@livelayer/react 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -331,6 +331,21 @@ export declare interface LegacyAgentEventDetail {
331
331
 
332
332
  declare type LevelSubscriber = (level: number) => void;
333
333
 
334
+ export declare function LiveLayerDebugPanel({ onMount, defaultOpen, storageKey, }: LiveLayerDebugPanelProps): JSX.Element;
335
+
336
+ export declare interface LiveLayerDebugPanelProps {
337
+ /**
338
+ * Receives a `push(event)` function the parent uses to forward
339
+ * AgentEvent payloads from `<AvatarWidget onAgentEvent>`. Called
340
+ * once on mount; the function reference stays stable.
341
+ */
342
+ onMount?: (push: (e: AgentEventDetail) => void) => void;
343
+ /** Force the panel open at startup. Default: hidden, toggle with kb shortcut. */
344
+ defaultOpen?: boolean;
345
+ /** Custom storage key suffix if you mount multiple panels (rare). */
346
+ storageKey?: string;
347
+ }
348
+
334
349
  export declare const LiveLayerField: ForwardRefExoticComponent<LiveLayerFieldProps & RefAttributes<FieldElement>>;
335
350
 
336
351
  export declare type LiveLayerFieldProps = (CommonFieldProps & {
package/dist/index.js CHANGED
@@ -1,2 +1,5 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),r=require("react"),gn=require("@livelayer/sdk"),We=require("livekit-client");class It extends r.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,i){var o,s;(s=(o=this.props).onError)==null||s.call(o,n,i)}render(){var n;return this.state.hasError?this.props.fallback?this.props.fallback:t.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[t.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),t.jsx("p",{className:"ll-error-boundary__message",children:((n=this.state.error)==null?void 0:n.message)||"Something went wrong."}),t.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function Tt(e){const[n,i]=r.useState("idle"),[o,s]=r.useState("idle"),[l,u]=r.useState([]),[d,f]=r.useState(null),[v,h]=r.useState(null),[a,c]=r.useState(null),[S,k]=r.useState(!1),[L,T]=r.useState(null),N=r.useRef(null),M=r.useRef(e.onDataMessage);M.current=e.onDataMessage,r.useEffect(()=>{const x={onConnectionStateChange:w=>{i(w),w==="connected"&&T(null)},onAgentStateChange:s,onTranscript:w=>u([...w]),onAgentConfig:f,onAudioTrack:w=>c(w),onVideoTrack:w=>h(w),onVideoTrackRemoved:()=>h(null),onError:w=>T(w),onDataMessage:w=>{var P;(P=M.current)==null||P.call(M,w)},onResumabilityChange:k},C=new gn.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},x);return N.current=C,i("idle"),s("idle"),u([]),f(null),h(null),c(null),k(!1),T(null),()=>{var w;(w=C.destroy)==null||w.call(C),N.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const j=r.useCallback(async()=>{const x=N.current;if(x)try{await x.connect()}catch(C){throw T(C instanceof Error?C.message:String(C)),C}},[]),A=r.useCallback(()=>{const x=N.current;x&&x.disconnect()},[]),y=r.useCallback(()=>{var x;return((x=N.current)==null?void 0:x.getRoom())??null},[]);return{connectionState:n,agentState:o,transcript:l,agentConfig:d,videoElement:v,audioElement:a,canResume:S,error:L,connect:j,disconnect:A,getRoom:y,session:N.current}}function Pt(){const e=r.useRef(null),n=r.useRef(null),i=r.useRef(null),o=r.useRef(null),s=r.useRef(new Set),l=r.useRef(null),u=r.useCallback(()=>{const a=n.current;if(!a){o.current=null;return}(!l.current||l.current.length!==a.frequencyBinCount)&&(l.current=new Uint8Array(new ArrayBuffer(a.frequencyBinCount)));const c=l.current;a.getByteFrequencyData(c);let S=0;for(let L=0;L<c.length;L++)S+=c[L];const k=S/c.length/255;for(const L of s.current)try{L(k)}catch(T){console.error("[useAudioLevel] subscriber threw:",T)}o.current=requestAnimationFrame(u)},[]),d=r.useCallback(()=>{if(e.current||typeof window>"u"||typeof AudioContext>"u")return;const a=new AudioContext,c=a.createAnalyser();c.fftSize=64,c.connect(a.destination),e.current=a,n.current=c},[]),f=r.useCallback(a=>{if(d(),!(!e.current||!n.current)){if(i.current){try{i.current.disconnect()}catch{}i.current=null}try{const c=e.current.createMediaElementSource(a);c.connect(n.current),i.current=c}catch(c){console.warn("[useAudioLevel] createMediaElementSource failed:",c);return}o.current===null&&(o.current=requestAnimationFrame(u))}},[d,u]),v=r.useCallback(()=>{if(o.current!==null&&(cancelAnimationFrame(o.current),o.current=null),i.current){try{i.current.disconnect()}catch{}i.current=null}},[]),h=r.useCallback(a=>(s.current.add(a),()=>{s.current.delete(a)}),[]);return r.useEffect(()=>()=>{if(v(),n.current){try{n.current.disconnect()}catch{}n.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}s.current.clear(),l.current=null},[v]),{attach:f,detach:v,subscribe:h}}function Dt(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),s=r.useRef(null),l=r.useRef(null),u=r.useCallback(async h=>{if(s.current&&l.current){try{await l.current.localParticipant.unpublishTrack(s.current)}catch{}s.current.stop(),s.current=null}l.current=h,o(null);try{const a=await We.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await h.localParticipant.publishTrack(a),s.current=a,n(a.isMuted)}catch(a){const c=a instanceof Error&&a.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw o(c),a}},[]),d=r.useCallback(()=>{const h=s.current;h&&(h.isMuted?(h.unmute(),n(!1)):(h.mute(),n(!0)))},[]),f=r.useCallback(()=>{const h=s.current,a=l.current;if(h&&a){try{a.localParticipant.unpublishTrack(h)}catch{}h.stop()}s.current=null,l.current=null,n(!1)},[]),v=r.useCallback(()=>o(null),[]);return{isMuted:e,micError:i,toggleMute:d,setupMic:u,teardownMic:f,clearError:v}}const yn={resolution:{width:640,height:480,frameRate:24}};function $t(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),[s,l]=r.useState(null),[u,d]=r.useState(""),f=r.useRef(null),v=r.useRef(null),h=r.useCallback(N=>{f.current=N},[]),a=r.useCallback(()=>{const N=f.current,M=v.current;if(M&&N){const j=N.localParticipant.getTrackPublication(We.Track.Source.Camera);if(j!=null&&j.track){try{N.localParticipant.unpublishTrack(j.track)}catch{}j.track.stop()}else M.stop()}v.current=null,l(null),n(!1)},[]),c=r.useCallback(async N=>{const M=f.current;if(M){o(null);try{const j={...yn};N&&(j.deviceId=N);const A=await We.createLocalVideoTrack(j);await M.localParticipant.publishTrack(A),v.current=A;const y=A.attach();l(y),n(!0),N&&d(N);try{M.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)}}},[]),S=r.useCallback(async()=>{e?a():await c(u||void 0)},[e,u,a,c]),k=r.useCallback(async N=>{a(),await c(N)},[a,c]),L=r.useCallback(()=>{a(),f.current=null,o(null),d("")},[a]),T=r.useCallback(()=>o(null),[]);return r.useEffect(()=>()=>{v.current&&v.current.stop()},[]),{isEnabled:e,error:i,previewEl:s,activeDeviceId:u,toggle:S,switchDevice:k,attachRoom:h,teardown:L,clearError:T}}function zt(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),[s,l]=r.useState(null),u=r.useRef(null),d=r.useCallback(c=>{u.current=c},[]),f=r.useCallback(()=>l(null),[]),v=r.useCallback(async()=>{const c=u.current;if(c){if(e){try{await c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),n(!1);return}o(null);try{await c.localParticipant.setScreenShareEnabled(!0);let S=0;const k=()=>{const L=c.localParticipant.getTrackPublication(We.Track.Source.ScreenShare);if(L!=null&&L.track){const T=L.track.attach();l(T),n(!0);try{c.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}S++<10?setTimeout(k,100):n(!0)};k()}catch(S){const k=S instanceof Error?S.name:"";k!=="NotAllowedError"&&k!=="AbortError"&&o("Screen share unavailable. Try again."),n(!1)}}},[e,f]),h=r.useCallback(()=>{const c=u.current;if(c&&e)try{c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),n(!1),o(null),u.current=null},[e,f]),a=r.useCallback(()=>o(null),[]);return{isEnabled:e,error:i,previewEl:s,toggle:v,attachRoom:d,teardown:h,clearError:a}}function qt(){const[e,n]=r.useState([]),[i,o]=r.useState([]),s=r.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const l=await navigator.mediaDevices.enumerateDevices();n(l.filter(u=>u.kind==="audioinput")),o(l.filter(u=>u.kind==="videoinput"))}catch{}},[]);return r.useEffect(()=>{if(s(),typeof navigator>"u"||!navigator.mediaDevices)return;const l=()=>void s();return navigator.mediaDevices.addEventListener("devicechange",l),()=>navigator.mediaDevices.removeEventListener("devicechange",l)},[s]),{mics:e,cameras:i,refresh:s}}function Ht(e,n,i=!1){const[o,s]=r.useState(null),[l,u]=r.useState(null),[d,f]=r.useState(!i&&!!e);return r.useEffect(()=>{if(i||!e){f(!1);return}const v=new AbortController,h=n||"https://app.livelayer.studio";return f(!0),u(null),fetch(`${h}/api/widget/agent/${encodeURIComponent(e)}`,{signal:v.signal}).then(async a=>{if(!a.ok){const c=await a.json().catch(()=>({}));throw new Error(c.error||`HTTP ${a.status}`)}return a.json()}).then(a=>{v.signal.aborted||(s(a),f(!1))}).catch(a=>{v.signal.aborted||(u(a instanceof Error?a.message:"Agent lookup failed"),f(!1))}),()=>v.abort()},[e,n,i]),{info:o,error:l,loading:d}}function vn(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function xn(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n)}catch{}}function Ot({value:e,defaultValue:n="expanded",onChange:i}={}){const o=e!==void 0,[s,l]=r.useState(n),u=o?e:s,d=r.useCallback(f=>{f!==u&&(o||l(f),i==null||i(f))},[u,o,i]);return[u,d]}const bn=["hidden","minimized","expanded"];function wn(e){return e&&bn.includes(e)?e:null}function Ft({value:e,defaultValue:n="expanded",onChange:i,persistKey:o="ll-widget",disablePersistence:s=!1}={}){const l=`${o}:display-mode`,u=r.useRef(!1),[d,f]=Ot({value:e,defaultValue:n,onChange:v=>{e===void 0&&!s&&xn(l,v),i==null||i(v)}});return r.useEffect(()=>{if(u.current||(u.current=!0,s||e!==void 0))return;const v=wn(vn(l));v&&v!==d&&f(v)},[]),[d,f]}const _n=640;function Bt(e=_n){const[n,i]=r.useState(!1);return r.useEffect(()=>{if(e===!1){i(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const o=`(max-width: ${e-1}px)`,s=window.matchMedia(o),l=()=>i(s.matches);return l(),typeof s.addEventListener=="function"?(s.addEventListener("change",l),()=>s.removeEventListener("change",l)):(s.addListener(l),()=>{s.removeListener(l)})},[e]),n}const bt="__llHistoryPatched",Ve="ll:pathname";function kn(){if(typeof window>"u"||window.history[bt])return;const e=window.history.pushState,n=window.history.replaceState;window.history.pushState=function(...i){const o=e.apply(this,i);return window.dispatchEvent(new Event(Ve)),o},window.history.replaceState=function(...i){const o=n.apply(this,i);return window.dispatchEvent(new Event(Ve)),o},window.history[bt]=!0}function wt(){return typeof window>"u"?"/":window.location.pathname||"/"}function Ut(e){const[n,i]=r.useState(()=>e??wt());return r.useEffect(()=>{if(e!==void 0)return;kn();const o=()=>i(wt());return o(),window.addEventListener("popstate",o),window.addEventListener(Ve,o),()=>{window.removeEventListener("popstate",o),window.removeEventListener(Ve,o)}},[e]),e??n}const _t=new Map,Cn=/[\\^$+?.()|{}[\]]/g;function Sn(e){return e.replace(Cn,"\\$&")}function Ln(e){const n=_t.get(e);if(n)return n;const i=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,o="",s="",l=i.replace(/\*\*/g,o).replace(/\*/g,s),d=Sn(l).replace(new RegExp(`\\/${o}`,"g"),"(?:\\/.*)?").replace(new RegExp(o,"g"),".*").replace(new RegExp(s,"g"),"[^/]+"),f=new RegExp(`^${d}\\/?$`);return _t.set(e,f),f}function En(e,n){const i=n.length>1&&n.endsWith("/")?n.slice(0,-1):n;return Ln(e).test(i)}function Wt(e,n){return typeof e=="function"?e(n):e instanceof RegExp?e.test(n):En(e,n)}function kt(e,n){if(!e||e.length===0)return!1;for(const i of e)if(Wt(i,n))return!0;return!1}function Vt(e,n,i){return e===void 0?!0:kt(i,e)?!1:n&&n.length>0?kt(n,e):!0}function Kt(e,n,i){return r.useMemo(()=>Vt(e,n,i),[e,n,i])}const Ct=({muted:e=!1,className:n})=>e?t.jsxs("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):t.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),St=({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"})}),jn=({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"})}),Nn={left:180,right:0,up:-90,down:90},Rn=({direction:e="right",className:n})=>t.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${Nn[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function An(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const Yt="ll-hidden-tab-center-y",Mn=5,Lt=16;function In(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(Yt);if(!e)return null;const n=Number.parseFloat(e);return Number.isFinite(n)?n:null}catch{return null}}function Et(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Yt,String(e))}catch{}}const Tn=({position:e,isMobile:n,isSpeaking:i,onExpand:o,label:s="Open widget"})=>{const l=An(e),u=l==="right"?"left":"right",d=n?80:72,[f,v]=r.useState(null),[h,a]=r.useState(!1),c=r.useRef(null),S=r.useRef(!1),k=r.useCallback(x=>{if(typeof window>"u")return x;const C=d/2,w=Lt+C,P=window.innerHeight-Lt-C;return P<w?Math.max(w,x):Math.max(w,Math.min(P,x))},[d]);r.useEffect(()=>{const x=In();v(k(x??window.innerHeight/2));const C=()=>{v(w=>w===null?null:k(w))};return window.addEventListener("resize",C),()=>window.removeEventListener("resize",C)},[k]);const L=r.useCallback(x=>{if(!(x.pointerType==="mouse"&&x.button!==0)&&f!==null){try{x.currentTarget.setPointerCapture(x.pointerId)}catch{}c.current={startClientY:x.clientY,startCenterY:f,moved:!1}}},[f]),T=r.useCallback(x=>{const C=c.current;if(!C)return;const w=x.clientY-C.startClientY;!C.moved&&Math.abs(w)>Mn&&(C.moved=!0,a(!0)),C.moved&&v(k(C.startCenterY+w))},[k]),N=r.useCallback(x=>{const C=c.current;if(C){try{x.currentTarget.releasePointerCapture(x.pointerId)}catch{}c.current=null,C.moved&&(a(!1),S.current=!0,v(w=>(w!==null&&Et(w),w)))}},[]),M=r.useCallback(()=>{if(S.current){S.current=!1;return}o()},[o]),j=r.useCallback(x=>{if(x.key==="ArrowUp"||x.key==="ArrowDown"){x.preventDefault();const C=x.key==="ArrowUp"?-8:8;v(w=>{if(w===null)return w;const P=k(w+C);return Et(P),P})}},[k]),A=["ll-hidden",`ll-hidden--${l}`,n?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,h?"is-dragging":null].filter(Boolean).join(" "),y=f===null?void 0:{top:`${f-d/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:A,onPointerDown:L,onPointerMove:T,onPointerUp:N,onPointerCancel:N,onClick:M,onKeyDown:j,"aria-label":s,"data-position":e,style:y,children:t.jsx(Rn,{direction:u,className:"ll-hidden__chevron"})})},Pn=({audioLevel:e,bars:n=20,maxHeight:i=20,minHeight:o=4,className:s,barClassName:l})=>{const u=r.useRef(null),d=r.useRef([]),f=r.useMemo(()=>{const h=(Math.sqrt(5)-1)/2;return Array.from({length:n},(a,c)=>.5+c*h%1*.5)},[n]);r.useEffect(()=>e.subscribe(a=>{for(let c=0;c<n;c++){const S=d.current[c];if(!S)continue;const k=Math.max(o,a*i*f[c]);S.style.height=`${k}px`}}),[e,n,i,o,f]);const v=["ll-waveform",s].filter(Boolean).join(" ");return t.jsx("div",{ref:u,className:v,"aria-hidden":"true",children:Array.from({length:n},(h,a)=>t.jsx("div",{ref:c=>{d.current[a]=c},className:["ll-waveform__bar",l].filter(Boolean).join(" "),style:{height:`${o}px`}},a))})},Dn=({position:e,isMobile:n,agentName:i,avatarImageUrl:o,agentState:s,isMuted:l,audioLevel:u,onExpand:d,onToggleMute:f,onClose:v})=>n?t.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${i} widget`,children:t.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick: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(Pn,{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:h=>{h.stopPropagation(),f()},onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.stopPropagation(),h.preventDefault(),f())},"aria-label":l?"Unmute microphone":"Mute microphone",children:t.jsx(Ct,{muted:l,className:"ll-minimized__icon"})}),t.jsx(St,{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":l?"Unmute microphone":"Mute microphone",children:t.jsx(Ct,{muted:l,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:d,"aria-label":`Expand ${i} widget`,children:t.jsx(St,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:v,"aria-label":"Close widget",children:t.jsx(jn,{className:"ll-minimized__icon"})})]})]})}),$n=({src:e,alt:n,preCannedPlaying:i=!1,className:o,style:s})=>{const[l,u]=r.useState(!1),d=r.useRef(e);if(r.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:l?1:0,...s};return t.jsx("img",{src:e,alt:n,className:o,style:f,loading:"eager",fetchpriority:"high",onLoad:()=>u(!0)})},zn=({position:e,isMobile:n,agentName:i,avatarImageUrl:o,idleLoopUrl:s,greeting:l,branding:u,teamMembers:d,currentTeamMemberId:f,isSwitchingTeamMember:v,teamSwitcherOpen:h,onToggleTeamSwitcher:a,onSelectTeamMember:c,languageMenuOpen:S,onToggleLanguageMenu:k,connectionState:L,agentState:T,transcript:N,canResume:M,needsUserGesture:j,error:A,isMuted:y,micError:x,micDevices:C,isCameraEnabled:w,cameraPreviewEl:P,cameraDevices:K,activeCameraId:se,isScreenShareEnabled:Y,screenPreviewEl:G,isSpeakerMuted:le,allowCamera:De,allowScreenShare:$e,allowTyping:ze,avatarVideoContainerRef:Ce,onConnect:ae,onDisconnect:fe,onRetry:pe,onResumeAudio:he,onToggleMute:me,onToggleCamera:ge,onSwitchCameraDevice:ye,onToggleScreenShare:D,onToggleSpeaker:Ye,onSendMessage:qe,onMinimize:He,onClose:Se,onClearMicError:Le})=>{var Re;const ee=N.length>0?N[N.length-1]:null,ce=((d==null?void 0:d.length)??0)>1,ve=L==="connecting"||L==="connected",X=L==="connected",F=L==="idle"||L==="disconnected"||L==="error",Ee=r.useRef(null),te=r.useRef(null);r.useEffect(()=>{const m=Ee.current;m&&(m.innerHTML="",P&&(P.style.width="100%",P.style.height="100%",P.style.objectFit="cover",P.style.transform="scaleX(-1)",m.appendChild(P)))},[P]),r.useEffect(()=>{const m=te.current;m&&(m.innerHTML="",G&&(G.style.width="100%",G.style.height="100%",G.style.objectFit="contain",m.appendChild(G)))},[G]);const[W,Q]=r.useState(!1),[ne,B]=r.useState(!1);r.useEffect(()=>{if(!W&&!ne&&!S&&!h)return;const m=()=>{Q(!1),B(!1),S&&k(),h&&a()};return document.addEventListener("click",m),()=>document.removeEventListener("click",m)},[W,ne,S,h,k,a]);const[V,re]=r.useState(""),je=r.useCallback(m=>{m.preventDefault();const H=V.trim();H&&(qe(H),re(""))},[V,qe]),Ge=u.productName||"Live Layer",xe=X&&(ee!=null&&ee.text)?ee.text:l||"",Ne=["ll-expanded",n?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:Ne,"data-position":e,"data-state":X?"connected":ve?"connecting":"idle",role:"dialog","aria-label":`${i} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[o?t.jsx($n,{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:((Re=i==null?void 0:i.charAt(0))==null?void 0:Re.toUpperCase())||"A"})}),s&&!X&&t.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:Ce,className:"ll-expanded__video"}),L==="connecting"&&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:v?"Switching...":"Connecting..."})]}),j&&X&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:he,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"})]}),ve?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:m=>{ce&&(m.stopPropagation(),a())},"aria-haspopup":ce?"listbox":void 0,"aria-expanded":ce?h:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:i}),ce&&t.jsx(Be,{})]}),ce&&h&&t.jsx("div",{className:"ll-hmenu",onClick:m=>m.stopPropagation(),role:"listbox",children:d==null?void 0:d.map(m=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${m.id===f?"is-active":""}`,onClick:()=>c(m.id),role:"option","aria-selected":m.id===f,children:[m.avatarImageUrl&&t.jsx("img",{src:m.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:m.name}),m.role&&t.jsx("span",{className:"ll-hmenu__role",children:m.role})]},m.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:m=>{m.stopPropagation(),k()},"aria-haspopup":"listbox","aria-expanded":S,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(Be,{})]}),S&&t.jsx("div",{className:"ll-hmenu",onClick:m=>m.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--${T}`,children:T})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn",onClick:He,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(Nt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Se,"aria-label":"End call",title:"End call",children:t.jsx(jt,{})})]})]}):t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:Ge}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:He,"aria-label":"Minimize widget",children:t.jsx(Nt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Se,"aria-label":"Close widget",children:t.jsx(jt,{})})]})]}),F&&(()=>{const m=M?"Restart paused session":L==="disconnected"?"Reconnect to agent":"Start video call",H=M?"Pick up where you left off":null,Xe=L==="idle"&&!M&&!A;return t.jsxs(t.Fragment,{children:[Xe&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:ae,"aria-label":m,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:m})]}),t.jsxs("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:[l&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:l})}),H&&t.jsx("p",{className:"ll-expanded__cta-sublabel",children:H}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:ae,"aria-label":m,children:m})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${ve&&(w||Y)?"is-visible":""}`,children:[t.jsx("div",{ref:te,className:Y?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:Ee,className:!Y&&w?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),ve?t.jsxs("div",{className:"ll-expanded__bottom",children:[xe&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:xe})}),t.jsxs("div",{className:"ll-toolbar",onClick:m=>m.stopPropagation(),children:[$e&&t.jsx("button",{type:"button",className:`ll-tool ${Y?"is-on":""}`,onClick:D,"aria-label":Y?"Stop sharing screen":"Share screen",title:Y?"Stop sharing":"Share screen",children:t.jsx(qn,{})}),De&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${w?"is-on":""}`,onClick:ge,"aria-label":w?"Turn off camera":"Turn on camera",title:w?"Stop camera":"Start camera",children:t.jsx(Hn,{})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${w?"is-on":""}`,onClick:m=>{m.stopPropagation(),B(H=>!H),Q(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":ne,children:t.jsx(Be,{})}),ne&&K.length>0&&t.jsx(Rt,{label:"Camera",devices:K,activeId:se,onPick:m=>{B(!1),ye(m)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${y?"is-muted":""}`,onClick:me,"aria-label":y?"Unmute microphone":"Mute microphone",title:y?"Unmute":"Mute",children:t.jsx(On,{muted:y})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${y?"is-muted":""}`,onClick:m=>{m.stopPropagation(),Q(H=>!H),B(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":W,children:t.jsx(Be,{})}),W&&C.length>0&&t.jsx(Rt,{label:"Microphone",devices:C,activeId:"",onPick:()=>Q(!1)})]}),t.jsx("button",{type:"button",className:`ll-tool ${le?"is-muted":""}`,onClick:Ye,"aria-label":le?"Unmute speaker":"Mute speaker",title:le?"Unmute speaker":"Mute speaker",children:t.jsx(Fn,{muted:le})})]}),ze&&t.jsxs("form",{className:"ll-message-input",onSubmit:je,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:V,onChange:m=>re(m.target.value),"aria-label":"Message the agent"}),V.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(Bn,{})})]}),t.jsx("button",{type:"button",className:"ll-expanded__end",onClick:fe,children:"End conversation"})]}):null,(()=>{if(x&&L!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:x}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:Le,"aria-label":"Dismiss",children:"×"})]});if(!A||L!=="error")return null;let m="Failed to connect",H="Try again";return A==="MIC_PERMISSION_DENIED"?m="Microphone blocked. Allow access to talk.":A==="MIC_NOT_FOUND"?m="No microphone found. Plug one in + retry.":A==="MIC_UNAVAILABLE"?m="Mic unavailable. Check other apps using it.":A==="AGENT_TIMEOUT"?m="Agent didn't pick up. Try again.":A==="CONNECT_FAILED"?m="Connection failed. Check your network.":A.length<80&&(m=A),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:m}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:pe,children:H})]})})()]})};function Be(){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 jt(){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 Nt(){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 qn(){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 Hn(){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 On({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 Fn({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 Bn(){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"})]})}const Rt=({label:e,devices:n,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}),n.map((s,l)=>{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} ${l+1}`})]},s.deviceId||l)})]}),Un=['[data-ll-private="true"]',".ll-widget"];function ot(e){let n=e;for(;n;){for(const i of Un)if(n.matches(i))return!0;n=n.parentElement}return!1}function Ke(e){if(ot(e))return!1;if(e instanceof HTMLInputElement){if(e.type==="password")return!1;const n=(e.getAttribute("autocomplete")||"").toLowerCase();if(n==="off"||n.startsWith("cc-"))return!1}return!0}const Ue=4096,Wn=20,Vn=20,Kn=10,Yn=10,Gn=30,At=500,Xn=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function Te(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let n=e;for(;n;){for(const i of Xn)if(n.matches(i))return!0;n=n.parentElement}return!1}function Pe(e){if(typeof window>"u")return!0;const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return!1;const i=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth;return n.bottom>0&&n.right>0&&n.top<i&&n.left<o}function Mt(e){const n=e.getAttribute("id");if(n){const l=document.querySelector(`label[for="${CSS.escape(n)}"]`);if(l!=null&&l.textContent)return l.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,n){return e.length<=n?e:e.slice(0,n-1)+"…"}function we(e){return e.length}function Gt(e,n={}){const i=n.doc??(typeof document<"u"?document:null);if(!i)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:e};const o=typeof window<"u"&&window.location.href||"",s=typeof window<"u"&&window.location.pathname||"/",l=i.title||"",u=Array.from(i.querySelectorAll("[data-ll-region]")),d=[];for(const y of u){if(d.length>=Kn)break;if(Te(y)||!Pe(y))continue;const x=y.getAttribute("data-ll-region")??"",C=y.getAttribute("data-ll-intent")??void 0,w=de((y.innerText||y.textContent||"").trim(),At*2);!x||!w||d.push({id:x,intent:C,text:w})}const f=[],v=["H1","H2","H3","H4","H5","H6"],h=Array.from(i.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const y of h){if(Te(y)||!Pe(y))continue;const x=(y.textContent||"").trim();x&&f.push(`${y.tagName}: ${de(x,200)}`)}const a=Array.from(i.querySelectorAll("p, li"));for(const y of a){if(Te(y)||!Pe(y)||v.includes(y.tagName))continue;const x=(y.textContent||"").trim();x.length>10&&f.push(de(x,At))}const c=f.join(`
2
- `),S=[],k=Array.from(i.querySelectorAll("a[href]"));for(const y of k){if(S.length>=Wn)break;if(Te(y)||!Pe(y))continue;const x=y.getAttribute("href")||"",C=(y.textContent||"").trim();!x||!C||S.push({href:x,text:de(C,100)})}const L=[],T=Array.from(i.querySelectorAll("input, textarea, select"));for(const y of T){if(L.length>=Vn)break;if(Te(y)||!Ke(y)||!Pe(y))continue;const x=Mt(y),C=y instanceof HTMLInputElement?y.type:y.tagName.toLowerCase();x&&L.push({label:de(x,100),type:C})}const N=Array.from(i.querySelectorAll("[data-ll-form]")),M=[];for(const y of N){if(M.length>=Yn)break;if(ot(y))continue;const x=y.getAttribute("data-ll-form")||"";if(!x)continue;const C=y.getAttribute("data-ll-intent")||void 0,w=Array.from(y.querySelectorAll("[data-ll-field]")),P=[];for(const K of w){if(P.length>=Gn)break;if(!Ke(K))continue;const se=K.getAttribute("data-ll-field")||"";if(!se)continue;const Y=Mt(K)||se,G=K instanceof HTMLInputElement?K.type:K.tagName.toLowerCase();P.push({name:se,label:de(Y,100),type:G})}M.push({id:x,intent:C,fields:P})}const j={url:o,title:l,pathname:s,regions:d,visibleText:c,visibleLinks:S,visibleFields:L,forms:M,extras:e};let A=we(JSON.stringify(j.regions))+we(j.visibleText)+we(JSON.stringify(j.visibleLinks))+we(JSON.stringify(j.visibleFields));for(;A>Ue&&j.visibleFields.length>0;)j.visibleFields.pop(),A=we(JSON.stringify(j.visibleFields));for(;A>Ue&&j.visibleLinks.length>0;)j.visibleLinks.pop(),A-=80;return we(j.visibleText)>Ue&&(j.visibleText=de(j.visibleText,Ue-100)),j}let _e=null;function it(e,n={}){const i=Date.now(),s=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(_e&&_e.key===s&&i-_e.at<1e3)return _e.ctx;const l=Gt(e,n);return _e={key:s,at:i,ctx:l},l}function Xt(){_e=null}const Jn=200;function Qn(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function Jt(e){const n=e??(typeof document<"u"?document:null);if(!n)return[];const i=typeof window<"u"&&window.location.origin||"",o=new Set,s=[],l=Array.from(n.querySelectorAll("a[href]"));for(const u of l){if(s.length>=Jn)break;if(ot(u))continue;const d=u.getAttribute("href")||"";if(!Qn(d))continue;let f=d,v=!0;try{if(typeof window<"u"){const a=new URL(d,i);v=a.origin===i,v&&d.startsWith("http")&&(f=a.pathname+a.search+a.hash)}}catch{continue}if(o.has(f))continue;o.add(f);const h=(u.textContent||"").trim().slice(0,120);s.push({href:f,text:h,internal:v})}return s}let ke=null;const Zn=5e3;function Qt(){const e=Date.now(),n=typeof window<"u"&&window.location.pathname||"/";if(ke&&ke.pathname===n&&e-ke.at<Zn)return ke.routes;const i=Jt();return ke={at:e,pathname:n,routes:i},i}function Zt(){ke=null}function er(e,n){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,n):e.value=n}function tr(e,n,i={}){const o=i.triggerInput??!0,s=i.triggerChange??!0;if(e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")){const l=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"),u=l==null?void 0:l.set,d=n==="true"||n==="1"||n==="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}er(e,n),o&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}))}const nr=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 rr(e){var ft,pt,ht,mt,gt,yt,vt;const{agentId:n,apiKey:i,baseUrl:o="https://app.livelayer.studio",sessionEndpoint:s,sessionBody:l,autoConnect:u=!1,displayMode:d,defaultDisplayMode:f="expanded",onDisplayModeChange:v,position:h="bottom-right",mobileBreakpoint:a=640,persistKey:c="ll-widget",disablePersistence:S=!1,teamMembers:k,currentTeamMemberId:L,onTeamMemberChange:T,idleLoopUrl:N,greeting:M,avatarImageUrl:j,agentName:A,branding:y={},allowCamera:x=!0,allowScreenShare:C=!0,allowTyping:w=!0,showOn:P,hideOn:K,pathname:se,onNavigate:Y,onScrollToSelector:G,getPageContext:le,pageContextExtras:De,onScrollPage:$e,onClick:ze,capabilities:Ce,onConnect:ae,onDisconnect:fe,onTranscript:pe,onAgentState:he,onConnectionStateChange:me,onAgentEvent:ge,onAgentCommand:ye,controlledSession:D,className:Ye,style:qe,zIndex:He=2147483647}=e,Se=Ut(se),Le=Kt(Se,P,K);r.useEffect(()=>{Xt(),Zt()},[Se]);const ee=L!==void 0,[ce,ve]=r.useState(()=>{var g;return L??((g=k==null?void 0:k[0])==null?void 0:g.id)}),X=ee?L:ce,F=r.useMemo(()=>(k==null?void 0:k.find(g=>g.id===X))??null,[k,X]),Ee=(F==null?void 0:F.agentId)??n,[te,W]=Ft({value:d,defaultValue:f,onChange:v,persistKey:c,disablePersistence:S}),Q=Bt(a),ne=Pt(),B=Dt(),V=$t(),re=zt(),je=qt(),[Ge,xe]=r.useState(!1),[Ne,Re]=r.useState(!1),[m,H]=r.useState(!1),[Xe,en]=r.useState(!1),[Je,tn]=r.useState(!1),Qe=r.useRef(Y),Ze=r.useRef(G),et=r.useRef($e),tt=r.useRef(ze),st=r.useRef(le),lt=r.useRef(De),nt=r.useRef(Ce),J=r.useRef(null);Qe.current=Y,Ze.current=G,et.current=$e,tt.current=ze,st.current=le,lt.current=De,nt.current=Ce;function ie(g){const p=nt.current;return p?p.includes(g):!0}function oe(g,p){console.warn(`[LiveLayer] Agent command "${g}" blocked — capability "${p}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const Ae=r.useCallback(g=>{var U,Oe,Fe,xt;const p=g;if(!(!p.type||typeof p.type!="string")){if(ge==null||ge({eventName:p.type,data:g}),p.type==="navigate"){if(!ie("navigate")){oe("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(Qe.current){try{Qe.current(_)}catch(E){console.warn(`[LiveLayer] onNavigate threw for "${_}". Falling back. Error:`,E)}return}if(typeof document<"u"){const E=document.querySelector(`a[href="${_.replace(/"/g,'\\"')}"]`);if(E){E.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",_),window.dispatchEvent(new PopStateEvent("popstate"))}catch(E){console.warn(`[LiveLayer] history.pushState fallback failed for "${_}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,E)}return}if(p.type==="scroll_to"){if(!ie("scroll")){oe("scroll_to","scroll");return}const _=typeof p.selector=="string"?p.selector:null;if(!_)return;const E=p.behavior==="instant"?"instant":"smooth";if(Ze.current){try{Ze.current(_,E)}catch(R){console.warn("[LiveLayer] onScrollToSelector threw.",R)}return}if(typeof document<"u"){let R=null;try{R=document.querySelector(_)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${_}".`);return}if(!R){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}R.scrollIntoView({behavior:E,block:"start"})}return}if(p.type==="request_page_context"){if(!ie("read_page")){oe("request_page_context","read_page");return}const _=typeof p.requestId=="string"?p.requestId:void 0,E=(U=J.current)==null?void 0:U.call(J),R=z=>{const O=E,Z=O==null?void 0:O.localParticipant;if(Z!=null&&Z.publishData)try{const ue=_?{...z,requestId:_}:z,be=new TextEncoder().encode(JSON.stringify(ue));Z.publishData(be,{reliable:!0})}catch(ue){console.warn("[LiveLayer] publishData failed.",ue)}},I=lt.current,$=st.current;try{if($){const z=$(I);if(z instanceof Promise){R({type:"page_context_pending"}),z.then(O=>R({type:"page_context",context:O})).catch(O=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",O),R({type:"page_context",context:it(I)})});return}R({type:"page_context",context:z});return}R({type:"page_context",context:it(I)})}catch(z){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",z),R({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:I}})}return}if(p.type==="scroll_page"){if(!ie("scroll")){oe("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 E=p.behavior==="instant"?"instant":"smooth";if(et.current){try{et.current(_,E)}catch(I){console.warn("[LiveLayer] onScrollPage threw.",I)}return}if(typeof window>"u")return;const R={behavior:E};_==="up"?window.scrollBy({top:-window.innerHeight,...R}):_==="down"?window.scrollBy({top:window.innerHeight,...R}):_==="top"?window.scrollTo({top:0,...R}):window.scrollTo({top:document.body.scrollHeight,...R});return}if(p.type==="click"){if(!ie("click")){oe("click","click");return}const _=typeof p.selector=="string"?p.selector:null;if(!_){console.warn("[LiveLayer] click: missing selector.");return}if(tt.current){try{tt.current(_)}catch(R){console.warn("[LiveLayer] onClick threw.",R)}return}if(typeof document>"u")return;let E=null;try{E=document.querySelector(_)}catch{console.warn(`[LiveLayer] click: invalid selector "${_}".`);return}if(!E){console.warn(`[LiveLayer] click: no element matched "${_}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(E.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(Oe=E.click)==null||Oe.call(E);return}if(p.type==="fill_form"||p.type==="focus_field"){if(!ie("fill_forms")){oe(p.type,"fill_forms");return}if(typeof document>"u")return;const _=typeof p.formId=="string"?p.formId:null;if(!_){console.warn(`[LiveLayer] ${p.type}: missing formId.`);return}const E=document.querySelector(`[data-ll-form="${_.replace(/"/g,'\\"')}"]`);if(!E){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(E.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 I=typeof p.fieldName=="string"?p.fieldName:null;if(!I){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const $=E.querySelector(`[data-ll-field="${I.replace(/"/g,'\\"')}"]`);if(!$){console.warn(`[LiveLayer] focus_field: no field "${I}" in form "${_}".`);return}if(!Ke($)){console.warn(`[LiveLayer] focus_field: field "${I}" is privacy-protected and not focusable.`);return}$.focus();return}const R=p.values&&typeof p.values=="object"?p.values:null;if(!R){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[I,$]of Object.entries(R)){if(typeof $!="string")continue;const z=E.querySelector(`[data-ll-field="${I.replace(/"/g,'\\"')}"]`);if(!z){console.warn(`[LiveLayer] fill_form: no field "${I}" in form "${_}". Skipping.`);continue}if(!Ke(z)){console.warn(`[LiveLayer] fill_form: field "${I}" is privacy-protected (password / cc-* / private). Skipping.`);continue}try{tr(z,$)}catch(O){console.warn(`[LiveLayer] fill_form: failed to set "${I}".`,O)}}return}if(p.type==="submit_form"){if(!ie("submit_forms")){oe("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}const E=document.querySelector(`[data-ll-form="${_.replace(/"/g,'\\"')}"]`);if(!E){console.warn(`[LiveLayer] submit_form: no form with data-ll-form="${_}".`);return}if(E.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] submit_form: refusing to submit a form in a private subtree.");return}const R=typeof p.requestId=="string"?p.requestId:void 0,I=(Fe=J.current)==null?void 0:Fe.call(J),$=Z=>{const ue=I,be=ue==null?void 0:ue.localParticipant;if(be!=null&&be.publishData)try{const hn=R?{...Z,requestId:R}:Z,mn=new TextEncoder().encode(JSON.stringify(hn));be.publishData(mn,{reliable:!0})}catch{}};let z=!1;const O=()=>{z=!0,$({type:"form_submitted",formId:_})};E.addEventListener("submit",O,{once:!0});try{typeof E.requestSubmit=="function"?E.requestSubmit():E.submit()}catch(Z){console.warn("[LiveLayer] submit_form: requestSubmit threw.",Z),E.removeEventListener("submit",O),$({type:"form_submit_blocked",formId:_,reason:"exception"});return}setTimeout(()=>{z||(E.removeEventListener("submit",O),$({type:"form_submit_blocked",formId:_,reason:"validation"}))},500);return}if(p.type==="request_routes"){if(!ie("read_page")){oe("request_routes","read_page");return}const _=typeof p.requestId=="string"?p.requestId:void 0,R=(xt=J.current)==null?void 0:xt.call(J),I=R==null?void 0:R.localParticipant;if(!(I!=null&&I.publishData))return;try{const $=Qt(),z=_?{type:"routes",routes:$,requestId:_}:{type:"routes",routes:$},O=new TextEncoder().encode(JSON.stringify(z));I.publishData(O,{reliable:!0})}catch($){console.warn("[LiveLayer] request_routes: extractRoutes threw.",$)}return}nr.has(p.type)||ye==null||ye(p)}},[ye,ge]),q=Tt({agentId:D?"__controlled__":Ee,baseUrl:o,apiKey:i,sessionEndpoint:s,sessionBody:l,onDataMessage:D?void 0:Ae});r.useEffect(()=>{if(D!=null&&D.subscribeToDataMessages)return D.subscribeToDataMessages(Ae)},[D,Ae]),J.current=()=>{var g;return(g=q.getRoom)==null?void 0:g.call(q)},r.useEffect(()=>{var U;if(typeof window>"u")return;const g=((U=window.location)==null?void 0:U.hostname)||"";if(g==="localhost"||g==="127.0.0.1"||g==="0.0.0.0"||g.endsWith(".local")||g.endsWith(".test"))return window.__livelayerSimulateCommand=Oe=>{try{Ae(Oe)}catch(Fe){console.warn("[LiveLayer] simulate-command threw:",Fe)}},()=>{delete window.__livelayerSimulateCommand}},[Ae]);const b=r.useMemo(()=>D?{connectionState:D.connectionState,agentState:D.agentState,transcript:D.transcript,videoElement:D.videoElement,audioElement:D.audioElement,canResume:D.canResume,error:D.error,agentConfig:null,connect:async()=>{await D.onConnect()},disconnect:()=>D.onDisconnect(),getRoom:q.getRoom,isControlled:!0}:{connectionState:q.connectionState,agentState:q.agentState,transcript:q.transcript,videoElement:q.videoElement,audioElement:q.audioElement,canResume:q.canResume,error:q.error,agentConfig:q.agentConfig,connect:q.connect,disconnect:q.disconnect,getRoom:q.getRoom,isControlled:!1},[D,q]),at=r.useRef(null);r.useEffect(()=>{const g=b.videoElement,p=at.current;if(!(!g||!p))return p.appendChild(g),()=>{g.parentNode===p&&p.removeChild(g)}},[b.videoElement]),r.useEffect(()=>{const g=b.audioElement;if(!g)return;ne.attach(g);const p=g.play();return p&&typeof p.catch=="function"&&p.catch(U=>{(U==null?void 0:U.name)==="NotAllowedError"&&xe(!0)}),()=>{ne.detach()}},[b.audioElement]),r.useEffect(()=>{if(b.isControlled||b.connectionState!=="connected")return;const g=b.getRoom();if(g)return B.setupMic(g).catch(()=>{}),V.attachRoom(g),re.attachRoom(g),je.refresh(),()=>{B.teardownMic(),V.teardown(),re.teardown()}},[b.isControlled,b.connectionState]),r.useEffect(()=>{const g=b.audioElement;g&&(g.muted=Je)},[b.audioElement,Je]);const nn=r.useCallback(g=>{const p=b.getRoom();if(p)try{const U=new TextEncoder().encode(JSON.stringify({type:"user_message",text:g}));p.localParticipant.publishData(U,{reliable:!0})}catch{}},[b]),rn=r.useCallback(()=>{tn(g=>!g)},[]);r.useEffect(()=>{me==null||me(b.connectionState),b.connectionState==="connected"?ae==null||ae():b.connectionState==="disconnected"&&(fe==null||fe())},[b.connectionState,ae,fe,me]),r.useEffect(()=>{pe==null||pe(b.transcript)},[b.transcript,pe]),r.useEffect(()=>{he==null||he(b.agentState)},[b.agentState,he]);const ct=r.useRef(!1);r.useEffect(()=>{b.isControlled||!u||ct.current||Le&&b.connectionState==="idle"&&(ct.current=!0,b.connect())},[u,b.connectionState,b,Le]);const on=r.useCallback(g=>{const p=k==null?void 0:k.find(U=>U.id===g);p&&(H(!1),g!==X&&(Re(!0),b.disconnect(),ee||ve(g),T==null||T(p)))},[k,X,b,ee,T]);r.useEffect(()=>{Ne&&b.connectionState==="connected"&&Re(!1)},[b.connectionState,Ne]),r.useEffect(()=>{if(!m)return;const g=p=>{p.key==="Escape"&&H(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[m]);const sn=!!j||!!(F!=null&&F.avatarImageUrl)||b.isControlled,Me=Ht(Ee,o,sn);Ce===void 0&&((ft=Me.info)!=null&&ft.capabilities)&&(nt.current=Me.info.capabilities);const rt=(F==null?void 0:F.name)??A??((pt=b.agentConfig)==null?void 0:pt.name)??((ht=Me.info)==null?void 0:ht.name)??"Live Layer",ut=(F==null?void 0:F.avatarImageUrl)??j??((mt=b.agentConfig)==null?void 0:mt.avatarImageUrl)??((gt=Me.info)==null?void 0:gt.avatarImageUrl)??null,ln=N??((yt=b.agentConfig)==null?void 0:yt.idleLoopUrl)??((vt=Me.info)==null?void 0:vt.idleLoopUrl)??null,an=M??null,cn=r.useCallback(()=>W("expanded"),[W]),un=r.useCallback(()=>W("minimized"),[W]),dt=r.useCallback(()=>{b.disconnect(),W("hidden")},[b,W]),dn=r.useCallback(()=>{const g=b.audioElement;g&&g.play().then(()=>xe(!1)).catch(()=>{})},[b.audioElement]),fn=r.useCallback(()=>{xe(!1),b.connect()},[b]),Ie={...qe,zIndex:He};y.primaryColor&&(Ie["--ll-color-primary"]=y.primaryColor),y.accentColor&&(Ie["--ll-color-accent"]=y.accentColor),y.backgroundColor&&(Ie["--ll-color-bg"]=y.backgroundColor),y.textColor&&(Ie["--ll-color-fg"]=y.textColor);const pn=["ll-widget",`ll-widget--${te}`,`ll-widget--${Q?"mobile":"desktop"}`,Ye].filter(Boolean).join(" ");return Le?t.jsxs("div",{className:pn,style:Ie,"data-display-mode":te,"data-position":h,children:[te==="hidden"&&t.jsx(Tn,{position:h,isMobile:Q,isSpeaking:b.agentState==="speaking",onExpand:()=>W("expanded"),label:`Open ${rt} widget`}),te==="minimized"&&t.jsx(Dn,{position:h,isMobile:Q,agentName:rt,avatarImageUrl:ut,agentState:b.agentState,isMuted:B.isMuted,audioLevel:ne,onExpand:cn,onToggleMute:B.toggleMute,onClose:dt}),te==="expanded"&&t.jsx(zn,{position:h,isMobile:Q,agentName:rt,avatarImageUrl:ut,idleLoopUrl:ln,greeting:an,branding:y,teamMembers:k,currentTeamMemberId:X,isSwitchingTeamMember:Ne,teamSwitcherOpen:m,onToggleTeamSwitcher:()=>H(g=>!g),onSelectTeamMember:on,connectionState:b.connectionState,agentState:b.agentState,transcript:b.transcript,isMuted:B.isMuted,micDevices:je.mics,isCameraEnabled:V.isEnabled,cameraPreviewEl:V.previewEl,cameraDevices:je.cameras,activeCameraId:V.activeDeviceId,isScreenShareEnabled:re.isEnabled,screenPreviewEl:re.previewEl,isSpeakerMuted:Je,allowCamera:x,allowScreenShare:C,allowTyping:w,languageMenuOpen:Xe,onToggleLanguageMenu:()=>en(g=>!g),needsUserGesture:Ge,canResume:b.canResume,micError:B.micError,error:b.error,avatarVideoContainerRef:at,onConnect:()=>void b.connect(),onDisconnect:()=>b.disconnect(),onRetry:fn,onResumeAudio:dn,onToggleMute:B.toggleMute,onToggleCamera:()=>void V.toggle(),onSwitchCameraDevice:g=>void V.switchDevice(g),onToggleScreenShare:()=>void re.toggle(),onToggleSpeaker:rn,onSendMessage:nn,onMinimize:un,onClose:dt,onClearMicError:B.clearError})]}):null}function ir(e){return t.jsx(It,{children:t.jsx(rr,{...e})})}const or=({agentId:e,baseUrl:n,apiKey:i,mode:o,onAgentEvent:s,className:l,style:u})=>{const d=r.useRef(null),f=r.useRef(null),v=r.useRef(s);v.current=s;const h=r.useCallback(a=>{var S;const c=a.detail;(S=v.current)==null||S.call(v,c)},[]);return r.useEffect(()=>{const a=d.current;if(!a)return;const c=document.createElement("livelayer-widget");return c.setAttribute("agent-id",e),n&&c.setAttribute("base-url",n),i&&c.setAttribute("api-key",i),o&&c.setAttribute("mode",o),c.addEventListener("agent-event",h),a.appendChild(c),f.current=c,()=>{c.removeEventListener("agent-event",h),a.removeChild(c),f.current=null}},[e]),r.useEffect(()=>{f.current&&(o?f.current.setAttribute("mode",o):f.current.removeAttribute("mode"))},[o]),t.jsx("div",{ref:d,className:l,style:u})},sr=r.forwardRef(function({id:n,intent:i,as:o="div",className:s,style:l,children:u},d){return r.createElement(o,{ref:d,"data-ll-region":n,"data-ll-intent":i,className:s,style:l},u)}),lr=r.forwardRef(function({id:n,intent:i,children:o,...s},l){return t.jsx("form",{ref:l,"data-ll-form":n,"data-ll-intent":i,...s,children:o})}),ar=r.forwardRef(function(n,i){const{name:o,label:s,labelClassName:l}=n,u={name:o,"data-ll-field":o};let d;if("as"in n&&n.as==="textarea"){const{name:f,label:v,labelClassName:h,as:a,...c}=n;d=t.jsx("textarea",{ref:i,...u,...c})}else if("as"in n&&n.as==="select"){const{name:f,label:v,labelClassName:h,as:a,children:c,...S}=n;d=t.jsx("select",{ref:i,...u,...S,children:c})}else{const{name:f,label:v,labelClassName:h,as:a,...c}=n;d=t.jsx("input",{ref:i,...u,...c})}return s===void 0?d:t.jsxs("label",{className:l,children:[s,d]})});function cr(){const[e,n]=r.useState([]),i=r.useCallback(s=>{n(l=>{const u=l.findIndex(d=>d.id===s.id);if(u>=0){const d=l.slice();return d[u]=s,d}return[...l,s]})},[]),o=r.useCallback(()=>n([]),[]);return{entries:e,pushSegment:i,clear:o,latest:e.length>0?e[e.length-1]:null}}exports.AvatarWidget=ir;exports.ErrorBoundary=It;exports.LiveLayerField=ar;exports.LiveLayerForm=lr;exports.LiveLayerRegion=sr;exports.LiveLayerWidget=or;exports.clearPageContextCache=Xt;exports.clearRoutesCache=Zt;exports.extractPageContext=Gt;exports.extractRoutes=Jt;exports.getCachedPageContext=it;exports.getCachedRoutes=Qt;exports.matchesPattern=Wt;exports.shouldRenderAtPath=Vt;exports.useAgentInfo=Ht;exports.useAudioLevel=Pt;exports.useCameraState=$t;exports.useDisplayMode=Ot;exports.useDisplayModePersistence=Ft;exports.useIsMobile=Bt;exports.useLiveKitSession=Tt;exports.useMediaDevices=qt;exports.useMicrophoneState=Dt;exports.usePathname=Ut;exports.useRouteMatch=Kt;exports.useScreenShareState=zt;exports.useTranscript=cr;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),r=require("react"),xn=require("@livelayer/sdk"),Ue=require("livekit-client");class Dt extends r.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,i){var o,s;(s=(o=this.props).onError)==null||s.call(o,n,i)}render(){var n;return this.state.hasError?this.props.fallback?this.props.fallback:t.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[t.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),t.jsx("p",{className:"ll-error-boundary__message",children:((n=this.state.error)==null?void 0:n.message)||"Something went wrong."}),t.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function $t(e){const[n,i]=r.useState("idle"),[o,s]=r.useState("idle"),[l,u]=r.useState([]),[d,f]=r.useState(null),[m,g]=r.useState(null),[a,c]=r.useState(null),[j,C]=r.useState(!1),[E,v]=r.useState(null),S=r.useRef(null),M=r.useRef(e.onDataMessage);M.current=e.onDataMessage,r.useEffect(()=>{const y={onConnectionStateChange:_=>{i(_),_==="connected"&&v(null)},onAgentStateChange:s,onTranscript:_=>u([..._]),onAgentConfig:f,onAudioTrack:_=>c(_),onVideoTrack:_=>g(_),onVideoTrackRemoved:()=>g(null),onError:_=>v(_),onDataMessage:_=>{var D;(D=M.current)==null||D.call(M,_)},onResumabilityChange:C},L=new xn.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},y);return S.current=L,i("idle"),s("idle"),u([]),f(null),g(null),c(null),C(!1),v(null),()=>{var _;(_=L.destroy)==null||_.call(L),S.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const N=r.useCallback(async()=>{const y=S.current;if(y)try{await y.connect()}catch(L){throw v(L instanceof Error?L.message:String(L)),L}},[]),T=r.useCallback(()=>{const y=S.current;y&&y.disconnect()},[]),h=r.useCallback(()=>{var y;return((y=S.current)==null?void 0:y.getRoom())??null},[]);return{connectionState:n,agentState:o,transcript:l,agentConfig:d,videoElement:m,audioElement:a,canResume:j,error:E,connect:N,disconnect:T,getRoom:h,session:S.current}}function zt(){const e=r.useRef(null),n=r.useRef(null),i=r.useRef(null),o=r.useRef(null),s=r.useRef(new Set),l=r.useRef(null),u=r.useCallback(()=>{const a=n.current;if(!a){o.current=null;return}(!l.current||l.current.length!==a.frequencyBinCount)&&(l.current=new Uint8Array(new ArrayBuffer(a.frequencyBinCount)));const c=l.current;a.getByteFrequencyData(c);let j=0;for(let E=0;E<c.length;E++)j+=c[E];const C=j/c.length/255;for(const E of s.current)try{E(C)}catch(v){console.error("[useAudioLevel] subscriber threw:",v)}o.current=requestAnimationFrame(u)},[]),d=r.useCallback(()=>{if(e.current||typeof window>"u"||typeof AudioContext>"u")return;const a=new AudioContext,c=a.createAnalyser();c.fftSize=64,c.connect(a.destination),e.current=a,n.current=c},[]),f=r.useCallback(a=>{if(d(),!(!e.current||!n.current)){if(i.current){try{i.current.disconnect()}catch{}i.current=null}try{const c=e.current.createMediaElementSource(a);c.connect(n.current),i.current=c}catch(c){console.warn("[useAudioLevel] createMediaElementSource failed:",c);return}o.current===null&&(o.current=requestAnimationFrame(u))}},[d,u]),m=r.useCallback(()=>{if(o.current!==null&&(cancelAnimationFrame(o.current),o.current=null),i.current){try{i.current.disconnect()}catch{}i.current=null}},[]),g=r.useCallback(a=>(s.current.add(a),()=>{s.current.delete(a)}),[]);return r.useEffect(()=>()=>{if(m(),n.current){try{n.current.disconnect()}catch{}n.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}s.current.clear(),l.current=null},[m]),{attach:f,detach:m,subscribe:g}}function Ht(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),s=r.useRef(null),l=r.useRef(null),u=r.useCallback(async g=>{if(s.current&&l.current){try{await l.current.localParticipant.unpublishTrack(s.current)}catch{}s.current.stop(),s.current=null}l.current=g,o(null);try{const a=await Ue.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await g.localParticipant.publishTrack(a),s.current=a,n(a.isMuted)}catch(a){const c=a instanceof Error&&a.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw o(c),a}},[]),d=r.useCallback(()=>{const g=s.current;g&&(g.isMuted?(g.unmute(),n(!1)):(g.mute(),n(!0)))},[]),f=r.useCallback(()=>{const g=s.current,a=l.current;if(g&&a){try{a.localParticipant.unpublishTrack(g)}catch{}g.stop()}s.current=null,l.current=null,n(!1)},[]),m=r.useCallback(()=>o(null),[]);return{isMuted:e,micError:i,toggleMute:d,setupMic:u,teardownMic:f,clearError:m}}const vn={resolution:{width:640,height:480,frameRate:24}};function qt(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),[s,l]=r.useState(null),[u,d]=r.useState(""),f=r.useRef(null),m=r.useRef(null),g=r.useCallback(S=>{f.current=S},[]),a=r.useCallback(()=>{const S=f.current,M=m.current;if(M&&S){const N=S.localParticipant.getTrackPublication(Ue.Track.Source.Camera);if(N!=null&&N.track){try{S.localParticipant.unpublishTrack(N.track)}catch{}N.track.stop()}else M.stop()}m.current=null,l(null),n(!1)},[]),c=r.useCallback(async S=>{const M=f.current;if(M){o(null);try{const N={...vn};S&&(N.deviceId=S);const T=await Ue.createLocalVideoTrack(N);await M.localParticipant.publishTrack(T),m.current=T;const h=T.attach();l(h),n(!0),S&&d(S);try{M.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(N){const T=N instanceof Error&&N.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";o(T)}}},[]),j=r.useCallback(async()=>{e?a():await c(u||void 0)},[e,u,a,c]),C=r.useCallback(async S=>{a(),await c(S)},[a,c]),E=r.useCallback(()=>{a(),f.current=null,o(null),d("")},[a]),v=r.useCallback(()=>o(null),[]);return r.useEffect(()=>()=>{m.current&&m.current.stop()},[]),{isEnabled:e,error:i,previewEl:s,activeDeviceId:u,toggle:j,switchDevice:C,attachRoom:g,teardown:E,clearError:v}}function Ot(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),[s,l]=r.useState(null),u=r.useRef(null),d=r.useCallback(c=>{u.current=c},[]),f=r.useCallback(()=>l(null),[]),m=r.useCallback(async()=>{const c=u.current;if(c){if(e){try{await c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),n(!1);return}o(null);try{await c.localParticipant.setScreenShareEnabled(!0);let j=0;const C=()=>{const E=c.localParticipant.getTrackPublication(Ue.Track.Source.ScreenShare);if(E!=null&&E.track){const v=E.track.attach();l(v),n(!0);try{c.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}j++<10?setTimeout(C,100):n(!0)};C()}catch(j){const C=j instanceof Error?j.name:"";C!=="NotAllowedError"&&C!=="AbortError"&&o("Screen share unavailable. Try again."),n(!1)}}},[e,f]),g=r.useCallback(()=>{const c=u.current;if(c&&e)try{c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),n(!1),o(null),u.current=null},[e,f]),a=r.useCallback(()=>o(null),[]);return{isEnabled:e,error:i,previewEl:s,toggle:m,attachRoom:d,teardown:g,clearError:a}}function Bt(){const[e,n]=r.useState([]),[i,o]=r.useState([]),s=r.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const l=await navigator.mediaDevices.enumerateDevices();n(l.filter(u=>u.kind==="audioinput")),o(l.filter(u=>u.kind==="videoinput"))}catch{}},[]);return r.useEffect(()=>{if(s(),typeof navigator>"u"||!navigator.mediaDevices)return;const l=()=>void s();return navigator.mediaDevices.addEventListener("devicechange",l),()=>navigator.mediaDevices.removeEventListener("devicechange",l)},[s]),{mics:e,cameras:i,refresh:s}}function Wt(e,n,i=!1){const[o,s]=r.useState(null),[l,u]=r.useState(null),[d,f]=r.useState(!i&&!!e);return r.useEffect(()=>{if(i||!e){f(!1);return}const m=new AbortController,g=n||"https://app.livelayer.studio";return f(!0),u(null),fetch(`${g}/api/widget/agent/${encodeURIComponent(e)}`,{signal:m.signal}).then(async a=>{if(!a.ok){const c=await a.json().catch(()=>({}));throw new Error(c.error||`HTTP ${a.status}`)}return a.json()}).then(a=>{m.signal.aborted||(s(a),f(!1))}).catch(a=>{m.signal.aborted||(u(a instanceof Error?a.message:"Agent lookup failed"),f(!1))}),()=>m.abort()},[e,n,i]),{info:o,error:l,loading:d}}function wn(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function _n(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n)}catch{}}function Ft({value:e,defaultValue:n="expanded",onChange:i}={}){const o=e!==void 0,[s,l]=r.useState(n),u=o?e:s,d=r.useCallback(f=>{f!==u&&(o||l(f),i==null||i(f))},[u,o,i]);return[u,d]}const kn=["hidden","minimized","expanded"];function Sn(e){return e&&kn.includes(e)?e:null}function Ut({value:e,defaultValue:n="expanded",onChange:i,persistKey:o="ll-widget",disablePersistence:s=!1}={}){const l=`${o}:display-mode`,u=r.useRef(!1),[d,f]=Ft({value:e,defaultValue:n,onChange:m=>{e===void 0&&!s&&_n(l,m),i==null||i(m)}});return r.useEffect(()=>{if(u.current||(u.current=!0,s||e!==void 0))return;const m=Sn(wn(l));m&&m!==d&&f(m)},[]),[d,f]}const Cn=640;function Vt(e=Cn){const[n,i]=r.useState(!1);return r.useEffect(()=>{if(e===!1){i(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const o=`(max-width: ${e-1}px)`,s=window.matchMedia(o),l=()=>i(s.matches);return l(),typeof s.addEventListener=="function"?(s.addEventListener("change",l),()=>s.removeEventListener("change",l)):(s.addListener(l),()=>{s.removeListener(l)})},[e]),n}const wt="__llHistoryPatched",Ve="ll:pathname";function Ln(){if(typeof window>"u"||window.history[wt])return;const e=window.history.pushState,n=window.history.replaceState;window.history.pushState=function(...i){const o=e.apply(this,i);return window.dispatchEvent(new Event(Ve)),o},window.history.replaceState=function(...i){const o=n.apply(this,i);return window.dispatchEvent(new Event(Ve)),o},window.history[wt]=!0}function _t(){return typeof window>"u"?"/":window.location.pathname||"/"}function Yt(e){const[n,i]=r.useState(()=>e??_t());return r.useEffect(()=>{if(e!==void 0)return;Ln();const o=()=>i(_t());return o(),window.addEventListener("popstate",o),window.addEventListener(Ve,o),()=>{window.removeEventListener("popstate",o),window.removeEventListener(Ve,o)}},[e]),e??n}const kt=new Map,jn=/[\\^$+?.()|{}[\]]/g;function En(e){return e.replace(jn,"\\$&")}function Nn(e){const n=kt.get(e);if(n)return n;const i=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,o="",s="",l=i.replace(/\*\*/g,o).replace(/\*/g,s),d=En(l).replace(new RegExp(`\\/${o}`,"g"),"(?:\\/.*)?").replace(new RegExp(o,"g"),".*").replace(new RegExp(s,"g"),"[^/]+"),f=new RegExp(`^${d}\\/?$`);return kt.set(e,f),f}function Rn(e,n){const i=n.length>1&&n.endsWith("/")?n.slice(0,-1):n;return Nn(e).test(i)}function Kt(e,n){return typeof e=="function"?e(n):e instanceof RegExp?e.test(n):Rn(e,n)}function St(e,n){if(!e||e.length===0)return!1;for(const i of e)if(Kt(i,n))return!0;return!1}function Gt(e,n,i){return e===void 0?!0:St(i,e)?!1:n&&n.length>0?St(n,e):!0}function Jt(e,n,i){return r.useMemo(()=>Gt(e,n,i),[e,n,i])}const Ct=({muted:e=!1,className:n})=>e?t.jsxs("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):t.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),Lt=({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"})}),An=({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"})}),Mn={left:180,right:0,up:-90,down:90},In=({direction:e="right",className:n})=>t.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${Mn[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function Tn(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const Xt="ll-hidden-tab-center-y",Pn=5,jt=16;function Dn(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(Xt);if(!e)return null;const n=Number.parseFloat(e);return Number.isFinite(n)?n:null}catch{return null}}function Et(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Xt,String(e))}catch{}}const $n=({position:e,isMobile:n,isSpeaking:i,onExpand:o,label:s="Open widget"})=>{const l=Tn(e),u=l==="right"?"left":"right",d=n?80:72,[f,m]=r.useState(null),[g,a]=r.useState(!1),c=r.useRef(null),j=r.useRef(!1),C=r.useCallback(y=>{if(typeof window>"u")return y;const L=d/2,_=jt+L,D=window.innerHeight-jt-L;return D<_?Math.max(_,y):Math.max(_,Math.min(D,y))},[d]);r.useEffect(()=>{const y=Dn();m(C(y??window.innerHeight/2));const L=()=>{m(_=>_===null?null:C(_))};return window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[C]);const E=r.useCallback(y=>{if(!(y.pointerType==="mouse"&&y.button!==0)&&f!==null){try{y.currentTarget.setPointerCapture(y.pointerId)}catch{}c.current={startClientY:y.clientY,startCenterY:f,moved:!1}}},[f]),v=r.useCallback(y=>{const L=c.current;if(!L)return;const _=y.clientY-L.startClientY;!L.moved&&Math.abs(_)>Pn&&(L.moved=!0,a(!0)),L.moved&&m(C(L.startCenterY+_))},[C]),S=r.useCallback(y=>{const L=c.current;if(L){try{y.currentTarget.releasePointerCapture(y.pointerId)}catch{}c.current=null,L.moved&&(a(!1),j.current=!0,m(_=>(_!==null&&Et(_),_)))}},[]),M=r.useCallback(()=>{if(j.current){j.current=!1;return}o()},[o]),N=r.useCallback(y=>{if(y.key==="ArrowUp"||y.key==="ArrowDown"){y.preventDefault();const L=y.key==="ArrowUp"?-8:8;m(_=>{if(_===null)return _;const D=C(_+L);return Et(D),D})}},[C]),T=["ll-hidden",`ll-hidden--${l}`,n?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,g?"is-dragging":null].filter(Boolean).join(" "),h=f===null?void 0:{top:`${f-d/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:T,onPointerDown:E,onPointerMove:v,onPointerUp:S,onPointerCancel:S,onClick:M,onKeyDown:N,"aria-label":s,"data-position":e,style:h,children:t.jsx(In,{direction:u,className:"ll-hidden__chevron"})})},zn=({audioLevel:e,bars:n=20,maxHeight:i=20,minHeight:o=4,className:s,barClassName:l})=>{const u=r.useRef(null),d=r.useRef([]),f=r.useMemo(()=>{const g=(Math.sqrt(5)-1)/2;return Array.from({length:n},(a,c)=>.5+c*g%1*.5)},[n]);r.useEffect(()=>e.subscribe(a=>{for(let c=0;c<n;c++){const j=d.current[c];if(!j)continue;const C=Math.max(o,a*i*f[c]);j.style.height=`${C}px`}}),[e,n,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:n},(g,a)=>t.jsx("div",{ref:c=>{d.current[a]=c},className:["ll-waveform__bar",l].filter(Boolean).join(" "),style:{height:`${o}px`}},a))})},Hn=({position:e,isMobile:n,agentName:i,avatarImageUrl:o,agentState:s,isMuted:l,audioLevel:u,onExpand:d,onToggleMute:f,onClose:m})=>n?t.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${i} widget`,children:t.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick: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(zn,{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":l?"Unmute microphone":"Mute microphone",children:t.jsx(Ct,{muted:l,className:"ll-minimized__icon"})}),t.jsx(Lt,{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":l?"Unmute microphone":"Mute microphone",children:t.jsx(Ct,{muted:l,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:d,"aria-label":`Expand ${i} widget`,children:t.jsx(Lt,{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(An,{className:"ll-minimized__icon"})})]})]})}),qn=({src:e,alt:n,preCannedPlaying:i=!1,className:o,style:s})=>{const[l,u]=r.useState(!1),d=r.useRef(e);if(r.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:l?1:0,...s};return t.jsx("img",{src:e,alt:n,className:o,style:f,loading:"eager",fetchpriority:"high",onLoad:()=>u(!0)})},On=({position:e,isMobile:n,agentName:i,avatarImageUrl:o,idleLoopUrl:s,greeting:l,branding:u,teamMembers:d,currentTeamMemberId:f,isSwitchingTeamMember:m,teamSwitcherOpen:g,onToggleTeamSwitcher:a,onSelectTeamMember:c,languageMenuOpen:j,onToggleLanguageMenu:C,connectionState:E,agentState:v,transcript:S,canResume:M,needsUserGesture:N,error:T,isMuted:h,micError:y,micDevices:L,isCameraEnabled:_,cameraPreviewEl:D,cameraDevices:Y,activeCameraId:se,isScreenShareEnabled:K,screenPreviewEl:G,isSpeakerMuted:le,allowCamera:De,allowScreenShare:$e,allowTyping:ze,avatarVideoContainerRef:Se,onConnect:ae,onDisconnect:fe,onRetry:pe,onResumeAudio:he,onToggleMute:me,onToggleCamera:ge,onSwitchCameraDevice:ye,onToggleScreenShare:z,onToggleSpeaker:Ke,onSendMessage:He,onMinimize:qe,onClose:Ce,onClearMicError:Le})=>{var Re;const ee=S.length>0?S[S.length-1]:null,ce=((d==null?void 0:d.length)??0)>1,be=E==="connecting"||E==="connected",J=E==="connected",B=E==="idle"||E==="disconnected"||E==="error",je=r.useRef(null),te=r.useRef(null);r.useEffect(()=>{const b=je.current;b&&(b.innerHTML="",D&&(D.style.width="100%",D.style.height="100%",D.style.objectFit="cover",D.style.transform="scaleX(-1)",b.appendChild(D)))},[D]),r.useEffect(()=>{const b=te.current;b&&(b.innerHTML="",G&&(G.style.width="100%",G.style.height="100%",G.style.objectFit="contain",b.appendChild(G)))},[G]);const[U,Q]=r.useState(!1),[ne,W]=r.useState(!1);r.useEffect(()=>{if(!U&&!ne&&!j&&!g)return;const b=()=>{Q(!1),W(!1),j&&C(),g&&a()};return document.addEventListener("click",b),()=>document.removeEventListener("click",b)},[U,ne,j,g,C,a]);const[V,re]=r.useState(""),Ee=r.useCallback(b=>{b.preventDefault();const O=V.trim();O&&(He(O),re(""))},[V,He]),Ge=u.productName||"Live Layer",xe=J&&(ee!=null&&ee.text)?ee.text:l||"",Ne=["ll-expanded",n?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:Ne,"data-position":e,"data-state":J?"connected":be?"connecting":"idle",role:"dialog","aria-label":`${i} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[o?t.jsx(qn,{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:((Re=i==null?void 0:i.charAt(0))==null?void 0:Re.toUpperCase())||"A"})}),s&&!J&&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"}),E==="connecting"&&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..."})]}),N&&J&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:he,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"})]}),be?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:b=>{ce&&(b.stopPropagation(),a())},"aria-haspopup":ce?"listbox":void 0,"aria-expanded":ce?g:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:i}),ce&&t.jsx(We,{})]}),ce&&g&&t.jsx("div",{className:"ll-hmenu",onClick:b=>b.stopPropagation(),role:"listbox",children:d==null?void 0:d.map(b=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${b.id===f?"is-active":""}`,onClick:()=>c(b.id),role:"option","aria-selected":b.id===f,children:[b.avatarImageUrl&&t.jsx("img",{src:b.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:b.name}),b.role&&t.jsx("span",{className:"ll-hmenu__role",children:b.role})]},b.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:b=>{b.stopPropagation(),C()},"aria-haspopup":"listbox","aria-expanded":j,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(We,{})]}),j&&t.jsx("div",{className:"ll-hmenu",onClick:b=>b.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--${v}`,children:v})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn",onClick:qe,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(Rt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ce,"aria-label":"End call",title:"End call",children:t.jsx(Nt,{})})]})]}):t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:Ge}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:qe,"aria-label":"Minimize widget",children:t.jsx(Rt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ce,"aria-label":"Close widget",children:t.jsx(Nt,{})})]})]}),B&&(()=>{const b=M?"Restart paused session":E==="disconnected"?"Reconnect to agent":"Start video call",O=M?"Pick up where you left off":null,Je=E==="idle"&&!M&&!T;return t.jsxs(t.Fragment,{children:[Je&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:ae,"aria-label":b,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:b})]}),t.jsxs("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:[l&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:l})}),O&&t.jsx("p",{className:"ll-expanded__cta-sublabel",children:O}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:ae,"aria-label":b,children:b})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${be&&(_||K)?"is-visible":""}`,children:[t.jsx("div",{ref:te,className:K?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:je,className:!K&&_?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),be?t.jsxs("div",{className:"ll-expanded__bottom",children:[xe&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:xe})}),t.jsxs("div",{className:"ll-toolbar",onClick:b=>b.stopPropagation(),children:[$e&&t.jsx("button",{type:"button",className:`ll-tool ${K?"is-on":""}`,onClick:z,"aria-label":K?"Stop sharing screen":"Share screen",title:K?"Stop sharing":"Share screen",children:t.jsx(Bn,{})}),De&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${_?"is-on":""}`,onClick:ge,"aria-label":_?"Turn off camera":"Turn on camera",title:_?"Stop camera":"Start camera",children:t.jsx(Wn,{})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${_?"is-on":""}`,onClick:b=>{b.stopPropagation(),W(O=>!O),Q(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":ne,children:t.jsx(We,{})}),ne&&Y.length>0&&t.jsx(At,{label:"Camera",devices:Y,activeId:se,onPick:b=>{W(!1),ye(b)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${h?"is-muted":""}`,onClick:me,"aria-label":h?"Unmute microphone":"Mute microphone",title:h?"Unmute":"Mute",children:t.jsx(Fn,{muted:h})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${h?"is-muted":""}`,onClick:b=>{b.stopPropagation(),Q(O=>!O),W(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":U,children:t.jsx(We,{})}),U&&L.length>0&&t.jsx(At,{label:"Microphone",devices:L,activeId:"",onPick:()=>Q(!1)})]}),t.jsx("button",{type:"button",className:`ll-tool ${le?"is-muted":""}`,onClick:Ke,"aria-label":le?"Unmute speaker":"Mute speaker",title:le?"Unmute speaker":"Mute speaker",children:t.jsx(Un,{muted:le})})]}),ze&&t.jsxs("form",{className:"ll-message-input",onSubmit:Ee,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:V,onChange:b=>re(b.target.value),"aria-label":"Message the agent"}),V.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(Vn,{})})]}),t.jsx("button",{type:"button",className:"ll-expanded__end",onClick:fe,children:"End conversation"})]}):null,(()=>{if(y&&E!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:y}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:Le,"aria-label":"Dismiss",children:"×"})]});if(!T||E!=="error")return null;let b="Failed to connect",O="Try again";return T==="MIC_PERMISSION_DENIED"?b="Microphone blocked. Allow access to talk.":T==="MIC_NOT_FOUND"?b="No microphone found. Plug one in + retry.":T==="MIC_UNAVAILABLE"?b="Mic unavailable. Check other apps using it.":T==="AGENT_TIMEOUT"?b="Agent didn't pick up. Try again.":T==="CONNECT_FAILED"?b="Connection failed. Check your network.":T.length<80&&(b=T),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:b}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:pe,children:O})]})})()]})};function We(){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 Nt(){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 Rt(){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 Bn(){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 Wn(){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 Fn({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 Un({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 Vn(){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"})]})}const At=({label:e,devices:n,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}),n.map((s,l)=>{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} ${l+1}`})]},s.deviceId||l)})]}),Yn=['[data-ll-private="true"]',".ll-widget"];function st(e){let n=e;for(;n;){for(const i of Yn)if(n.matches(i))return!0;n=n.parentElement}return!1}function Ye(e){if(st(e))return!1;if(e instanceof HTMLInputElement){if(e.type==="password")return!1;const n=(e.getAttribute("autocomplete")||"").toLowerCase();if(n==="off"||n.startsWith("cc-"))return!1}return!0}const Fe=4096,Kn=20,Gn=20,Jn=10,Xn=10,Qn=30,Mt=500,Zn=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function Te(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let n=e;for(;n;){for(const i of Zn)if(n.matches(i))return!0;n=n.parentElement}return!1}function Pe(e){if(typeof window>"u")return!0;const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return!1;const i=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth;return n.bottom>0&&n.right>0&&n.top<i&&n.left<o}function It(e){const n=e.getAttribute("id");if(n){const l=document.querySelector(`label[for="${CSS.escape(n)}"]`);if(l!=null&&l.textContent)return l.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,n){return e.length<=n?e:e.slice(0,n-1)+"…"}function we(e){return e.length}function Qt(e,n={}){const i=n.doc??(typeof document<"u"?document:null);if(!i)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:e};const o=typeof window<"u"&&window.location.href||"",s=typeof window<"u"&&window.location.pathname||"/",l=i.title||"",u=Array.from(i.querySelectorAll("[data-ll-region]")),d=[];for(const h of u){if(d.length>=Jn)break;if(Te(h)||!Pe(h))continue;const y=h.getAttribute("data-ll-region")??"",L=h.getAttribute("data-ll-intent")??void 0,_=de((h.innerText||h.textContent||"").trim(),Mt*2);!y||!_||d.push({id:y,intent:L,text:_})}const f=[],m=["H1","H2","H3","H4","H5","H6"],g=Array.from(i.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const h of g){if(Te(h)||!Pe(h))continue;const y=(h.textContent||"").trim();y&&f.push(`${h.tagName}: ${de(y,200)}`)}const a=Array.from(i.querySelectorAll("p, li"));for(const h of a){if(Te(h)||!Pe(h)||m.includes(h.tagName))continue;const y=(h.textContent||"").trim();y.length>10&&f.push(de(y,Mt))}const c=f.join(`
2
+ `),j=[],C=Array.from(i.querySelectorAll("a[href]"));for(const h of C){if(j.length>=Kn)break;if(Te(h)||!Pe(h))continue;const y=h.getAttribute("href")||"",L=(h.textContent||"").trim();!y||!L||j.push({href:y,text:de(L,100)})}const E=[],v=Array.from(i.querySelectorAll("input, textarea, select"));for(const h of v){if(E.length>=Gn)break;if(Te(h)||!Ye(h)||!Pe(h))continue;const y=It(h),L=h instanceof HTMLInputElement?h.type:h.tagName.toLowerCase();y&&E.push({label:de(y,100),type:L})}const S=Array.from(i.querySelectorAll("[data-ll-form]")),M=[];for(const h of S){if(M.length>=Xn)break;if(st(h))continue;const y=h.getAttribute("data-ll-form")||"";if(!y)continue;const L=h.getAttribute("data-ll-intent")||void 0,_=Array.from(h.querySelectorAll("[data-ll-field]")),D=[];for(const Y of _){if(D.length>=Qn)break;if(!Ye(Y))continue;const se=Y.getAttribute("data-ll-field")||"";if(!se)continue;const K=It(Y)||se,G=Y instanceof HTMLInputElement?Y.type:Y.tagName.toLowerCase();D.push({name:se,label:de(K,100),type:G})}M.push({id:y,intent:L,fields:D})}const N={url:o,title:l,pathname:s,regions:d,visibleText:c,visibleLinks:j,visibleFields:E,forms:M,extras:e};let T=we(JSON.stringify(N.regions))+we(N.visibleText)+we(JSON.stringify(N.visibleLinks))+we(JSON.stringify(N.visibleFields));for(;T>Fe&&N.visibleFields.length>0;)N.visibleFields.pop(),T=we(JSON.stringify(N.visibleFields));for(;T>Fe&&N.visibleLinks.length>0;)N.visibleLinks.pop(),T-=80;return we(N.visibleText)>Fe&&(N.visibleText=de(N.visibleText,Fe-100)),N}let _e=null;function ot(e,n={}){const i=Date.now(),s=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(_e&&_e.key===s&&i-_e.at<1e3)return _e.ctx;const l=Qt(e,n);return _e={key:s,at:i,ctx:l},l}function Zt(){_e=null}const er=200;function tr(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function en(e){const n=e??(typeof document<"u"?document:null);if(!n)return[];const i=typeof window<"u"&&window.location.origin||"",o=new Set,s=[],l=Array.from(n.querySelectorAll("a[href]"));for(const u of l){if(s.length>=er)break;if(st(u))continue;const d=u.getAttribute("href")||"";if(!tr(d))continue;let f=d,m=!0;try{if(typeof window<"u"){const a=new URL(d,i);m=a.origin===i,m&&d.startsWith("http")&&(f=a.pathname+a.search+a.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 ke=null;const nr=5e3;function tn(){const e=Date.now(),n=typeof window<"u"&&window.location.pathname||"/";if(ke&&ke.pathname===n&&e-ke.at<nr)return ke.routes;const i=en();return ke={at:e,pathname:n,routes:i},i}function nn(){ke=null}function rr(e,n){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,n):e.value=n}function ir(e,n,i={}){const o=i.triggerInput??!0,s=i.triggerChange??!0;if(e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")){const l=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"),u=l==null?void 0:l.set,d=n==="true"||n==="1"||n==="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}rr(e,n),o&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}))}function or(){if(typeof window>"u"||typeof document>"u")return!1;const e=document.scrollingElement||document.documentElement;if(!e||e.scrollHeight<=e.clientHeight+2)return!1;const n=window.getComputedStyle(e);return!(n.overflowY==="hidden"||n.overflowY==="clip")}function sr(e){if(!(e instanceof HTMLElement))return!1;const i=window.getComputedStyle(e).overflowY;return!(i!=="auto"&&i!=="scroll"||e.scrollHeight<=e.clientHeight+2)}function lr(){if(typeof document>"u")return null;const e=Array.from(document.querySelectorAll("body, body *"));let n=null,i=0;for(const o of e){if(!sr(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 l=s.width*s.height;l>i&&(i=l,n=o)}return n}function ar(){if(typeof window>"u")return null;if(or())return window;const e=lr();return e||window}function Tt(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function cr(e){var n,i;return e instanceof Window?typeof document>"u"?0:Math.max(((n=document.body)==null?void 0:n.scrollHeight)??0,((i=document.documentElement)==null?void 0:i.scrollHeight)??0):e.scrollHeight-e.clientHeight}const ur=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 dr(e){var pt,ht,mt,gt,yt,bt,xt;const{agentId:n,apiKey:i,baseUrl:o="https://app.livelayer.studio",sessionEndpoint:s,sessionBody:l,autoConnect:u=!1,displayMode:d,defaultDisplayMode:f="expanded",onDisplayModeChange:m,position:g="bottom-right",mobileBreakpoint:a=640,persistKey:c="ll-widget",disablePersistence:j=!1,teamMembers:C,currentTeamMemberId:E,onTeamMemberChange:v,idleLoopUrl:S,greeting:M,avatarImageUrl:N,agentName:T,branding:h={},allowCamera:y=!0,allowScreenShare:L=!0,allowTyping:_=!0,showOn:D,hideOn:Y,pathname:se,onNavigate:K,onScrollToSelector:G,getPageContext:le,pageContextExtras:De,onScrollPage:$e,onClick:ze,capabilities:Se,onConnect:ae,onDisconnect:fe,onTranscript:pe,onAgentState:he,onConnectionStateChange:me,onAgentEvent:ge,onAgentCommand:ye,controlledSession:z,className:Ke,style:He,zIndex:qe=2147483647}=e,Ce=Yt(se),Le=Jt(Ce,D,Y);r.useEffect(()=>{Zt(),nn()},[Ce]);const ee=E!==void 0,[ce,be]=r.useState(()=>{var x;return E??((x=C==null?void 0:C[0])==null?void 0:x.id)}),J=ee?E:ce,B=r.useMemo(()=>(C==null?void 0:C.find(x=>x.id===J))??null,[C,J]),je=(B==null?void 0:B.agentId)??n,[te,U]=Ut({value:d,defaultValue:f,onChange:m,persistKey:c,disablePersistence:j}),Q=Vt(a),ne=zt(),W=Ht(),V=qt(),re=Ot(),Ee=Bt(),[Ge,xe]=r.useState(!1),[Ne,Re]=r.useState(!1),[b,O]=r.useState(!1),[Je,rn]=r.useState(!1),[Xe,on]=r.useState(!1),Qe=r.useRef(K),Ze=r.useRef(G),et=r.useRef($e),tt=r.useRef(ze),lt=r.useRef(le),at=r.useRef(De),nt=r.useRef(Se),X=r.useRef(null);Qe.current=K,Ze.current=G,et.current=$e,tt.current=ze,lt.current=le,at.current=De,nt.current=Se;function ie(x){const p=nt.current;return p?p.includes(x):!0}function oe(x,p){console.warn(`[LiveLayer] Agent command "${x}" blocked — capability "${p}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const Ae=r.useCallback(x=>{var F,Oe,Be,vt;const p=x;if(!(!p.type||typeof p.type!="string")){if(ge==null||ge({eventName:p.type,data:x}),p.type==="navigate"){if(!ie("navigate")){oe("navigate","navigate");return}const k=typeof p.href=="string"?p.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(Qe.current){try{Qe.current(k)}catch(R){console.warn(`[LiveLayer] onNavigate threw for "${k}". Falling back. Error:`,R)}return}if(typeof document<"u"){const R=document.querySelector(`a[href="${k.replace(/"/g,'\\"')}"]`);if(R){R.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",k),window.dispatchEvent(new PopStateEvent("popstate"))}catch(R){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`,R)}return}if(p.type==="scroll_to"){if(!ie("scroll")){oe("scroll_to","scroll");return}const k=typeof p.selector=="string"?p.selector:null;if(!k)return;const R=p.behavior==="instant"?"instant":"smooth";if(Ze.current){try{Ze.current(k,R)}catch(I){console.warn("[LiveLayer] onScrollToSelector threw.",I)}return}if(typeof document<"u"){let I=null;try{I=document.querySelector(k)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${k}".`);return}if(!I){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}I.scrollIntoView({behavior:R,block:"start"})}return}if(p.type==="request_page_context"){if(!ie("read_page")){oe("request_page_context","read_page");return}const k=typeof p.requestId=="string"?p.requestId:void 0,R=(F=X.current)==null?void 0:F.call(X),I=H=>{const P=R,Z=P==null?void 0:P.localParticipant;if(Z!=null&&Z.publishData)try{const ue=k?{...H,requestId:k}:H,ve=new TextEncoder().encode(JSON.stringify(ue));Z.publishData(ve,{reliable:!0})}catch(ue){console.warn("[LiveLayer] publishData failed.",ue)}},A=at.current,$=lt.current;try{if($){const H=$(A);if(H instanceof Promise){I({type:"page_context_pending"}),H.then(P=>I({type:"page_context",context:P})).catch(P=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",P),I({type:"page_context",context:ot(A)})});return}I({type:"page_context",context:H});return}I({type:"page_context",context:ot(A)})}catch(H){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",H),I({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:A}})}return}if(p.type==="scroll_page"){if(!ie("scroll")){oe("scroll_page","scroll");return}const k=p.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 R=p.behavior==="instant"?"instant":"smooth";if(et.current){try{et.current(k,R)}catch(P){console.warn("[LiveLayer] onScrollPage threw.",P)}return}if(typeof window>"u")return;const I={behavior:R},A=ar(),$=P=>{A instanceof Window?A.scrollBy({top:P,...I}):A.scrollBy({top:P,...I})},H=P=>{A instanceof Window?A.scrollTo({top:P,...I}):A.scrollTo({top:P,...I})};k==="up"?$(-Tt(A)):k==="down"?$(Tt(A)):H(k==="top"?0:cr(A));return}if(p.type==="click"){if(!ie("click")){oe("click","click");return}const k=typeof p.selector=="string"?p.selector:null;if(!k){console.warn("[LiveLayer] click: missing selector.");return}if(tt.current){try{tt.current(k)}catch(I){console.warn("[LiveLayer] onClick threw.",I)}return}if(typeof document>"u")return;let R=null;try{R=document.querySelector(k)}catch{console.warn(`[LiveLayer] click: invalid selector "${k}".`);return}if(!R){console.warn(`[LiveLayer] click: no element matched "${k}". 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}(Oe=R.click)==null||Oe.call(R);return}if(p.type==="fill_form"||p.type==="focus_field"){if(!ie("fill_forms")){oe(p.type,"fill_forms");return}if(typeof document>"u")return;const k=typeof p.formId=="string"?p.formId:null;if(!k){console.warn(`[LiveLayer] ${p.type}: missing formId.`);return}const R=document.querySelector(`[data-ll-form="${k.replace(/"/g,'\\"')}"]`);if(!R){console.warn(`[LiveLayer] ${p.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(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 A=typeof p.fieldName=="string"?p.fieldName:null;if(!A){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const $=R.querySelector(`[data-ll-field="${A.replace(/"/g,'\\"')}"]`);if(!$){console.warn(`[LiveLayer] focus_field: no field "${A}" in form "${k}".`);return}if(!Ye($)){console.warn(`[LiveLayer] focus_field: field "${A}" is privacy-protected and not focusable.`);return}$.focus();return}const I=p.values&&typeof p.values=="object"?p.values:null;if(!I){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[A,$]of Object.entries(I)){if(typeof $!="string")continue;const H=R.querySelector(`[data-ll-field="${A.replace(/"/g,'\\"')}"]`);if(!H){console.warn(`[LiveLayer] fill_form: no field "${A}" in form "${k}". Skipping.`);continue}if(!Ye(H)){console.warn(`[LiveLayer] fill_form: field "${A}" is privacy-protected (password / cc-* / private). Skipping.`);continue}try{ir(H,$)}catch(P){console.warn(`[LiveLayer] fill_form: failed to set "${A}".`,P)}}return}if(p.type==="submit_form"){if(!ie("submit_forms")){oe("submit_form","submit_forms");return}if(typeof document>"u")return;const k=typeof p.formId=="string"?p.formId:null;if(!k){console.warn("[LiveLayer] submit_form: missing formId.");return}const R=document.querySelector(`[data-ll-form="${k.replace(/"/g,'\\"')}"]`);if(!R){console.warn(`[LiveLayer] submit_form: no form with data-ll-form="${k}".`);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 I=typeof p.requestId=="string"?p.requestId:void 0,A=(Be=X.current)==null?void 0:Be.call(X),$=Z=>{const ue=A,ve=ue==null?void 0:ue.localParticipant;if(ve!=null&&ve.publishData)try{const yn=I?{...Z,requestId:I}:Z,bn=new TextEncoder().encode(JSON.stringify(yn));ve.publishData(bn,{reliable:!0})}catch{}};let H=!1;const P=()=>{H=!0,$({type:"form_submitted",formId:k})};R.addEventListener("submit",P,{once:!0});try{typeof R.requestSubmit=="function"?R.requestSubmit():R.submit()}catch(Z){console.warn("[LiveLayer] submit_form: requestSubmit threw.",Z),R.removeEventListener("submit",P),$({type:"form_submit_blocked",formId:k,reason:"exception"});return}setTimeout(()=>{H||(R.removeEventListener("submit",P),$({type:"form_submit_blocked",formId:k,reason:"validation"}))},500);return}if(p.type==="request_routes"){if(!ie("read_page")){oe("request_routes","read_page");return}const k=typeof p.requestId=="string"?p.requestId:void 0,I=(vt=X.current)==null?void 0:vt.call(X),A=I==null?void 0:I.localParticipant;if(!(A!=null&&A.publishData))return;try{const $=tn(),H=k?{type:"routes",routes:$,requestId:k}:{type:"routes",routes:$},P=new TextEncoder().encode(JSON.stringify(H));A.publishData(P,{reliable:!0})}catch($){console.warn("[LiveLayer] request_routes: extractRoutes threw.",$)}return}ur.has(p.type)||ye==null||ye(p)}},[ye,ge]),q=$t({agentId:z?"__controlled__":je,baseUrl:o,apiKey:i,sessionEndpoint:s,sessionBody:l,onDataMessage:z?void 0:Ae});r.useEffect(()=>{if(z!=null&&z.subscribeToDataMessages)return z.subscribeToDataMessages(Ae)},[z,Ae]),X.current=()=>{var x;return(x=q.getRoom)==null?void 0:x.call(q)},r.useEffect(()=>{var F;if(typeof window>"u")return;const x=((F=window.location)==null?void 0:F.hostname)||"";if(x==="localhost"||x==="127.0.0.1"||x==="0.0.0.0"||x.endsWith(".local")||x.endsWith(".test"))return window.__livelayerSimulateCommand=Oe=>{try{Ae(Oe)}catch(Be){console.warn("[LiveLayer] simulate-command threw:",Be)}},()=>{delete window.__livelayerSimulateCommand}},[Ae]);const w=r.useMemo(()=>z?{connectionState:z.connectionState,agentState:z.agentState,transcript:z.transcript,videoElement:z.videoElement,audioElement:z.audioElement,canResume:z.canResume,error:z.error,agentConfig:null,connect:async()=>{await z.onConnect()},disconnect:()=>z.onDisconnect(),getRoom:q.getRoom,isControlled:!0}:{connectionState:q.connectionState,agentState:q.agentState,transcript:q.transcript,videoElement:q.videoElement,audioElement:q.audioElement,canResume:q.canResume,error:q.error,agentConfig:q.agentConfig,connect:q.connect,disconnect:q.disconnect,getRoom:q.getRoom,isControlled:!1},[z,q]),ct=r.useRef(null);r.useEffect(()=>{const x=w.videoElement,p=ct.current;if(!(!x||!p))return p.appendChild(x),()=>{x.parentNode===p&&p.removeChild(x)}},[w.videoElement]),r.useEffect(()=>{const x=w.audioElement;if(!x)return;ne.attach(x);const p=x.play();return p&&typeof p.catch=="function"&&p.catch(F=>{(F==null?void 0:F.name)==="NotAllowedError"&&xe(!0)}),()=>{ne.detach()}},[w.audioElement]),r.useEffect(()=>{if(w.isControlled||w.connectionState!=="connected")return;const x=w.getRoom();if(x)return W.setupMic(x).catch(()=>{}),V.attachRoom(x),re.attachRoom(x),Ee.refresh(),()=>{W.teardownMic(),V.teardown(),re.teardown()}},[w.isControlled,w.connectionState]),r.useEffect(()=>{const x=w.audioElement;x&&(x.muted=Xe)},[w.audioElement,Xe]);const sn=r.useCallback(x=>{const p=w.getRoom();if(p)try{const F=new TextEncoder().encode(JSON.stringify({type:"user_message",text:x}));p.localParticipant.publishData(F,{reliable:!0})}catch{}},[w]),ln=r.useCallback(()=>{on(x=>!x)},[]);r.useEffect(()=>{me==null||me(w.connectionState),w.connectionState==="connected"?ae==null||ae():w.connectionState==="disconnected"&&(fe==null||fe())},[w.connectionState,ae,fe,me]),r.useEffect(()=>{pe==null||pe(w.transcript)},[w.transcript,pe]),r.useEffect(()=>{he==null||he(w.agentState)},[w.agentState,he]);const ut=r.useRef(!1);r.useEffect(()=>{w.isControlled||!u||ut.current||Le&&w.connectionState==="idle"&&(ut.current=!0,w.connect())},[u,w.connectionState,w,Le]);const an=r.useCallback(x=>{const p=C==null?void 0:C.find(F=>F.id===x);p&&(O(!1),x!==J&&(Re(!0),w.disconnect(),ee||be(x),v==null||v(p)))},[C,J,w,ee,v]);r.useEffect(()=>{Ne&&w.connectionState==="connected"&&Re(!1)},[w.connectionState,Ne]),r.useEffect(()=>{if(!b)return;const x=p=>{p.key==="Escape"&&O(!1)};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[b]);const cn=!!N||!!(B!=null&&B.avatarImageUrl)||w.isControlled,Me=Wt(je,o,cn);Se===void 0&&((pt=Me.info)!=null&&pt.capabilities)&&(nt.current=Me.info.capabilities);const rt=(B==null?void 0:B.name)??T??((ht=w.agentConfig)==null?void 0:ht.name)??((mt=Me.info)==null?void 0:mt.name)??"Live Layer",dt=(B==null?void 0:B.avatarImageUrl)??N??((gt=w.agentConfig)==null?void 0:gt.avatarImageUrl)??((yt=Me.info)==null?void 0:yt.avatarImageUrl)??null,un=S??((bt=w.agentConfig)==null?void 0:bt.idleLoopUrl)??((xt=Me.info)==null?void 0:xt.idleLoopUrl)??null,dn=M??null,fn=r.useCallback(()=>U("expanded"),[U]),pn=r.useCallback(()=>U("minimized"),[U]),ft=r.useCallback(()=>{w.disconnect(),U("hidden")},[w,U]),hn=r.useCallback(()=>{const x=w.audioElement;x&&x.play().then(()=>xe(!1)).catch(()=>{})},[w.audioElement]),mn=r.useCallback(()=>{xe(!1),w.connect()},[w]),Ie={...He,zIndex:qe};h.primaryColor&&(Ie["--ll-color-primary"]=h.primaryColor),h.accentColor&&(Ie["--ll-color-accent"]=h.accentColor),h.backgroundColor&&(Ie["--ll-color-bg"]=h.backgroundColor),h.textColor&&(Ie["--ll-color-fg"]=h.textColor);const gn=["ll-widget",`ll-widget--${te}`,`ll-widget--${Q?"mobile":"desktop"}`,Ke].filter(Boolean).join(" ");return Le?t.jsxs("div",{className:gn,style:Ie,"data-display-mode":te,"data-position":g,children:[te==="hidden"&&t.jsx($n,{position:g,isMobile:Q,isSpeaking:w.agentState==="speaking",onExpand:()=>U("expanded"),label:`Open ${rt} widget`}),te==="minimized"&&t.jsx(Hn,{position:g,isMobile:Q,agentName:rt,avatarImageUrl:dt,agentState:w.agentState,isMuted:W.isMuted,audioLevel:ne,onExpand:fn,onToggleMute:W.toggleMute,onClose:ft}),te==="expanded"&&t.jsx(On,{position:g,isMobile:Q,agentName:rt,avatarImageUrl:dt,idleLoopUrl:un,greeting:dn,branding:h,teamMembers:C,currentTeamMemberId:J,isSwitchingTeamMember:Ne,teamSwitcherOpen:b,onToggleTeamSwitcher:()=>O(x=>!x),onSelectTeamMember:an,connectionState:w.connectionState,agentState:w.agentState,transcript:w.transcript,isMuted:W.isMuted,micDevices:Ee.mics,isCameraEnabled:V.isEnabled,cameraPreviewEl:V.previewEl,cameraDevices:Ee.cameras,activeCameraId:V.activeDeviceId,isScreenShareEnabled:re.isEnabled,screenPreviewEl:re.previewEl,isSpeakerMuted:Xe,allowCamera:y,allowScreenShare:L,allowTyping:_,languageMenuOpen:Je,onToggleLanguageMenu:()=>rn(x=>!x),needsUserGesture:Ge,canResume:w.canResume,micError:W.micError,error:w.error,avatarVideoContainerRef:ct,onConnect:()=>void w.connect(),onDisconnect:()=>w.disconnect(),onRetry:mn,onResumeAudio:hn,onToggleMute:W.toggleMute,onToggleCamera:()=>void V.toggle(),onSwitchCameraDevice:x=>void V.switchDevice(x),onToggleScreenShare:()=>void re.toggle(),onToggleSpeaker:ln,onSendMessage:sn,onMinimize:pn,onClose:ft,onClearMicError:W.clearError})]}):null}function fr(e){return t.jsx(Dt,{children:t.jsx(dr,{...e})})}const pr=({agentId:e,baseUrl:n,apiKey:i,mode:o,onAgentEvent:s,className:l,style:u})=>{const d=r.useRef(null),f=r.useRef(null),m=r.useRef(s);m.current=s;const g=r.useCallback(a=>{var j;const c=a.detail;(j=m.current)==null||j.call(m,c)},[]);return r.useEffect(()=>{const a=d.current;if(!a)return;const c=document.createElement("livelayer-widget");return c.setAttribute("agent-id",e),n&&c.setAttribute("base-url",n),i&&c.setAttribute("api-key",i),o&&c.setAttribute("mode",o),c.addEventListener("agent-event",g),a.appendChild(c),f.current=c,()=>{c.removeEventListener("agent-event",g),a.removeChild(c),f.current=null}},[e]),r.useEffect(()=>{f.current&&(o?f.current.setAttribute("mode",o):f.current.removeAttribute("mode"))},[o]),t.jsx("div",{ref:d,className:l,style:u})},hr=r.forwardRef(function({id:n,intent:i,as:o="div",className:s,style:l,children:u},d){return r.createElement(o,{ref:d,"data-ll-region":n,"data-ll-intent":i,className:s,style:l},u)}),mr=r.forwardRef(function({id:n,intent:i,children:o,...s},l){return t.jsx("form",{ref:l,"data-ll-form":n,"data-ll-intent":i,...s,children:o})}),gr=r.forwardRef(function(n,i){const{name:o,label:s,labelClassName:l}=n,u={name:o,"data-ll-field":o};let d;if("as"in n&&n.as==="textarea"){const{name:f,label:m,labelClassName:g,as:a,...c}=n;d=t.jsx("textarea",{ref:i,...u,...c})}else if("as"in n&&n.as==="select"){const{name:f,label:m,labelClassName:g,as:a,children:c,...j}=n;d=t.jsx("select",{ref:i,...u,...j,children:c})}else{const{name:f,label:m,labelClassName:g,as:a,...c}=n;d=t.jsx("input",{ref:i,...u,...c})}return s===void 0?d:t.jsxs("label",{className:l,children:[s,d]})});let Pt=1;function yr({onMount:e,defaultOpen:n=!1,storageKey:i="ll-debug-open"}){const[o,s]=r.useState(n),[l,u]=r.useState([]),[d,f]=r.useState(""),[m,g]=r.useState(!1),a=r.useRef(new Set),c=r.useRef([]),j=r.useRef(m);j.current=m,r.useEffect(()=>{try{const v=localStorage.getItem(i);v==="1"&&s(!0),v==="0"&&s(!1)}catch{}},[i]),r.useEffect(()=>{try{localStorage.setItem(i,o?"1":"0")}catch{}},[o,i]),r.useEffect(()=>{const v=S=>{(S.metaKey||S.ctrlKey)&&S.shiftKey&&S.key.toLowerCase()==="l"&&(S.preventDefault(),s(M=>!M))};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[]),r.useEffect(()=>{const v=setInterval(()=>{if(c.current.length===0||j.current)return;const S=c.current.splice(0,c.current.length);u(M=>[...S.reverse(),...M].slice(0,200))},100);return()=>clearInterval(v)},[]);const C=r.useRef(!1);if(r.useEffect(()=>{!e||C.current||(C.current=!0,e(v=>{c.current.push({id:Pt++,ts:Date.now(),kind:"event",type:v.eventName,data:v.data})}))},[e]),r.useEffect(()=>{const v=console.warn,S=console.log,M=(N,T)=>function(...h){try{const y=typeof h[0]=="string"?h[0]:"";y.startsWith("[LiveLayer]")&&c.current.push({id:Pt++,ts:Date.now(),kind:N,type:y.slice(0,120),data:{args:h.slice(1).map(L=>xr(L))}})}catch{}return T.apply(this,h)};return console.warn=M("warn",v),console.log=M("log",S),()=>{console.warn=v,console.log=S}},[]),!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 E=l.filter(v=>{if(!d)return!0;const S=d.toLowerCase();return v.type.toLowerCase().includes(S)||JSON.stringify(v.data||{}).toLowerCase().includes(S)});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:[l.length," event",l.length===1?"":"s"]}),t.jsx("span",{style:{flex:1}}),t.jsx("button",{type:"button",onClick:()=>g(v=>!v),style:it(m?"#f59e0b":"transparent"),title:"Pause / resume capture",children:m?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{u([]),c.current=[]},style:it("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>s(!1),style:it("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:d,onChange:v=>f(v.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:E.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
+ type: "navigate",
4
+ href: "/about"
5
+ })`})]}):E.map(v=>t.jsx(br,{entry:v,expanded:a.current.has(v.id),onToggle:()=>{a.current.has(v.id)?a.current.delete(v.id):a.current.add(v.id),u(S=>[...S])}},v.id))})]})}function br({entry:e,expanded:n,onToggle:i}){const o=e.kind==="warn"?"#f59e0b":e.type.startsWith("[LiveLayer]")?"#94a3b8":e.type==="navigate"||e.type==="scroll_page"||e.type==="scroll_to"||e.type==="click"?"#22c55e":e.type==="fill_form"||e.type==="submit_form"||e.type==="focus_field"?"#a78bfa":e.type==="request_page_context"||e.type==="request_routes"?"#38bdf8":e.type==="agent_state"?"#facc15":"#cbd5e1",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})]}),n&&e.data&&t.jsx("pre",{style:{marginTop:6,padding:6,background:"rgba(255,255,255,0.04)",borderRadius:4,fontSize:10,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:JSON.stringify(e.data,null,2)})]})}function it(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 xr(e){try{return e instanceof Error?{message:e.message,stack:e.stack}:(JSON.stringify(e),e)}catch{return String(e)}}function vr(){const[e,n]=r.useState([]),i=r.useCallback(s=>{n(l=>{const u=l.findIndex(d=>d.id===s.id);if(u>=0){const d=l.slice();return d[u]=s,d}return[...l,s]})},[]),o=r.useCallback(()=>n([]),[]);return{entries:e,pushSegment:i,clear:o,latest:e.length>0?e[e.length-1]:null}}exports.AvatarWidget=fr;exports.ErrorBoundary=Dt;exports.LiveLayerDebugPanel=yr;exports.LiveLayerField=gr;exports.LiveLayerForm=mr;exports.LiveLayerRegion=hr;exports.LiveLayerWidget=pr;exports.clearPageContextCache=Zt;exports.clearRoutesCache=nn;exports.extractPageContext=Qt;exports.extractRoutes=en;exports.getCachedPageContext=ot;exports.getCachedRoutes=tn;exports.matchesPattern=Kt;exports.shouldRenderAtPath=Gt;exports.useAgentInfo=Wt;exports.useAudioLevel=zt;exports.useCameraState=qt;exports.useDisplayMode=Ft;exports.useDisplayModePersistence=Ut;exports.useIsMobile=Vt;exports.useLiveKitSession=$t;exports.useMediaDevices=Bt;exports.useMicrophoneState=Ht;exports.usePathname=Yt;exports.useRouteMatch=Jt;exports.useScreenShareState=Ot;exports.useTranscript=vr;