@livelayer/react 0.14.1 → 0.15.1

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