@livelayer/react 0.10.1 → 0.10.2

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"),n=require("react"),Ct=require("react-dom"),Jn=require("@livelayer/sdk"),ht=require("livekit-client");class ln extends n.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,o){var i,s;(s=(i=this.props).onError)==null||s.call(i,r,o)}render(){var r;return this.state.hasError?this.props.fallback?this.props.fallback:t.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[t.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),t.jsx("p",{className:"ll-error-boundary__message",children:((r=this.state.error)==null?void 0:r.message)||"Something went wrong."}),t.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function cn(e){const[r,o]=n.useState("idle"),[i,s]=n.useState("idle"),[a,d]=n.useState([]),[l,u]=n.useState(null),[p,x]=n.useState(null),[f,c]=n.useState(null),[E,k]=n.useState(!1),[b,v]=n.useState(null),g=n.useRef(null),C=n.useRef(e.onDataMessage);C.current=e.onDataMessage,n.useEffect(()=>{const S={onConnectionStateChange:z=>{o(z),z==="connected"&&v(null)},onAgentStateChange:s,onTranscript:z=>d([...z]),onAgentConfig:u,onAudioTrack:z=>c(z),onVideoTrack:z=>x(z),onVideoTrackRemoved:()=>x(null),onError:z=>v(z),onDataMessage:z=>{var L;(L=C.current)==null||L.call(C,z)},onResumabilityChange:k},$=new Jn.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},S);return g.current=$,o("idle"),s("idle"),d([]),u(null),x(null),c(null),k(!1),v(null),()=>{var z;(z=$.destroy)==null||z.call($),g.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const M=n.useCallback(async()=>{const S=g.current;if(S)try{await S.connect()}catch($){throw v($ instanceof Error?$.message:String($)),$}},[]),N=n.useCallback(()=>{const S=g.current;S&&S.disconnect()},[]),_=n.useCallback(()=>{var S;return((S=g.current)==null?void 0:S.getRoom())??null},[]);return{connectionState:r,agentState:i,transcript:a,agentConfig:l,videoElement:p,audioElement:f,canResume:E,error:b,connect:M,disconnect:N,getRoom:_,session:g.current}}function un(){const e=n.useRef(null),r=n.useRef(null),o=n.useRef(null),i=n.useRef(null),s=n.useRef(new Set),a=n.useRef(null),d=n.useCallback(()=>{const f=r.current;if(!f){i.current=null;return}(!a.current||a.current.length!==f.frequencyBinCount)&&(a.current=new Uint8Array(new ArrayBuffer(f.frequencyBinCount)));const c=a.current;f.getByteFrequencyData(c);let E=0;for(let b=0;b<c.length;b++)E+=c[b];const k=E/c.length/255;for(const b of s.current)try{b(k)}catch(v){console.error("[useAudioLevel] subscriber threw:",v)}i.current=requestAnimationFrame(d)},[]),l=n.useCallback(()=>{if(e.current||typeof window>"u"||typeof AudioContext>"u")return;const f=new AudioContext,c=f.createAnalyser();c.fftSize=64,c.connect(f.destination),e.current=f,r.current=c},[]),u=n.useCallback(f=>{if(l(),!(!e.current||!r.current)){if(o.current){try{o.current.disconnect()}catch{}o.current=null}try{const c=e.current.createMediaElementSource(f);c.connect(r.current),o.current=c}catch(c){console.warn("[useAudioLevel] createMediaElementSource failed:",c);return}i.current===null&&(i.current=requestAnimationFrame(d))}},[l,d]),p=n.useCallback(()=>{if(i.current!==null&&(cancelAnimationFrame(i.current),i.current=null),o.current){try{o.current.disconnect()}catch{}o.current=null}},[]),x=n.useCallback(f=>(s.current.add(f),()=>{s.current.delete(f)}),[]);return n.useEffect(()=>()=>{if(p(),r.current){try{r.current.disconnect()}catch{}r.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}s.current.clear(),a.current=null},[p]),{attach:u,detach:p,subscribe:x}}function dn(){const[e,r]=n.useState(!1),[o,i]=n.useState(""),[s,a]=n.useState(null),d=n.useRef(null),l=n.useRef(null),u=n.useCallback(async k=>{var b,v;if(d.current&&l.current){try{await l.current.localParticipant.unpublishTrack(d.current)}catch{}d.current.stop(),d.current=null}l.current=k,a(null);try{const g=await ht.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await k.localParticipant.publishTrack(g),d.current=g,r(g.isMuted);const C=(v=(b=g.mediaStreamTrack)==null?void 0:b.getSettings)==null?void 0:v.call(b);C!=null&&C.deviceId&&i(C.deviceId)}catch(g){const C=g instanceof Error&&g.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw a(C),g}},[]),p=n.useCallback(k=>{l.current=k},[]),x=n.useCallback(async k=>{const b=l.current;if(b)try{await b.switchActiveDevice("audioinput",k),i(k)}catch(v){console.warn("[useMicrophoneState] switchDevice failed:",v)}},[]),f=n.useCallback(()=>{const k=d.current,b=l.current;if(k){k.isMuted?(k.unmute(),r(!1)):(k.mute(),r(!0));return}if(b){const v=!e;r(v);try{b.localParticipant.setMicrophoneEnabled(!v)}catch(g){console.warn("[useMicrophoneState] setMicrophoneEnabled failed:",g)}}},[e]),c=n.useCallback(()=>{const k=d.current,b=l.current;if(k&&b){try{b.localParticipant.unpublishTrack(k)}catch{}k.stop()}d.current=null,l.current=null,r(!1),i("")},[]),E=n.useCallback(()=>a(null),[]);return{isMuted:e,activeDeviceId:o,micError:s,toggleMute:f,setupMic:u,attachRoom:p,switchDevice:x,teardownMic:c,clearError:E}}const Xn={resolution:{width:640,height:480,frameRate:24}};function fn(){const[e,r]=n.useState(!1),[o,i]=n.useState(null),[s,a]=n.useState(null),[d,l]=n.useState(""),u=n.useRef(null),p=n.useRef(null),x=n.useCallback(g=>{u.current=g},[]),f=n.useCallback(()=>{var M;const g=u.current,C=p.current;if(C&&g){const N=g.localParticipant.getTrackPublication(ht.Track.Source.Camera),S=(N==null?void 0:N.track)??C;try{g.localParticipant.unpublishTrack(S)}catch{}try{(M=S.stop)==null||M.call(S)}catch{}}p.current=null,a(null),r(!1)},[]),c=n.useCallback(async g=>{const C=u.current;if(C){i(null);try{const M={...Xn};g&&(M.deviceId=g);const N=await ht.createLocalVideoTrack(M);await C.localParticipant.publishTrack(N),p.current=N;const _=N.attach();a(_),r(!0),g&&l(g);try{C.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(M){const N=M instanceof Error&&M.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";i(N)}}},[]),E=n.useCallback(async()=>{e?f():await c(d||void 0)},[e,d,f,c]),k=n.useCallback(async g=>{f(),await c(g)},[f,c]),b=n.useCallback(()=>{f(),u.current=null,i(null),l("")},[f]),v=n.useCallback(()=>i(null),[]);return n.useEffect(()=>()=>{p.current&&p.current.stop()},[]),{isEnabled:e,error:o,previewEl:s,activeDeviceId:d,toggle:E,switchDevice:k,attachRoom:x,teardown:b,clearError:v}}function pn(){const[e,r]=n.useState(!1),[o,i]=n.useState(null),[s,a]=n.useState(null),d=n.useRef(null),l=n.useCallback(c=>{d.current=c},[]),u=n.useCallback(()=>a(null),[]),p=n.useCallback(async()=>{const c=d.current;if(c){if(e){try{await c.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1);return}i(null);try{await c.localParticipant.setScreenShareEnabled(!0);let E=0;const k=()=>{const b=c.localParticipant.getTrackPublication(ht.Track.Source.ScreenShare);if(b!=null&&b.track){const v=b.track.attach();a(v),r(!0);try{c.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}E++<10?setTimeout(k,100):r(!0)};k()}catch(E){const k=E instanceof Error?E.name:"";k!=="NotAllowedError"&&k!=="AbortError"&&i("Screen share unavailable. Try again."),r(!1)}}},[e,u]),x=n.useCallback(()=>{const c=d.current;if(c&&e)try{c.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1),i(null),d.current=null},[e,u]),f=n.useCallback(()=>i(null),[]);return{isEnabled:e,error:o,previewEl:s,toggle:p,attachRoom:l,teardown:x,clearError:f}}function hn(){const[e,r]=n.useState([]),[o,i]=n.useState([]),s=n.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const a=await navigator.mediaDevices.enumerateDevices();r(a.filter(d=>d.kind==="audioinput")),i(a.filter(d=>d.kind==="videoinput"))}catch{}},[]);return n.useEffect(()=>{if(s(),typeof navigator>"u"||!navigator.mediaDevices)return;const a=()=>void s();return navigator.mediaDevices.addEventListener("devicechange",a),()=>navigator.mediaDevices.removeEventListener("devicechange",a)},[s]),{mics:e,cameras:o,refresh:s}}function mn(e,r,o=!1){const[i,s]=n.useState(null),[a,d]=n.useState(null),[l,u]=n.useState(!o&&!!e);return n.useEffect(()=>{if(o||!e){u(!1);return}const p=new AbortController,x=r||"https://app.livelayer.studio";return u(!0),d(null),fetch(`${x}/api/widget/agent/${encodeURIComponent(e)}`,{signal:p.signal}).then(async f=>{if(!f.ok){const c=await f.json().catch(()=>({}));throw new Error(c.error||`HTTP ${f.status}`)}return f.json()}).then(f=>{p.signal.aborted||(s(f),u(!1))}).catch(f=>{p.signal.aborted||(d(f instanceof Error?f.message:"Agent lookup failed"),u(!1))}),()=>p.abort()},[e,r,o]),{info:i,error:a,loading:l}}function Qn(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function Zn(e,r){if(!(typeof window>"u"))try{window.localStorage.setItem(e,r)}catch{}}function gn({value:e,defaultValue:r="expanded",onChange:o}={}){const i=e!==void 0,[s,a]=n.useState(r),d=i?e:s,l=n.useCallback(u=>{u!==d&&(i||a(u),o==null||o(u))},[d,i,o]);return[d,l]}const er=["hidden","minimized","expanded"];function tr(e){return e&&er.includes(e)?e:null}function yn({value:e,defaultValue:r="expanded",onChange:o,persistKey:i="ll-widget",disablePersistence:s=!1}={}){const a=`${i}:display-mode`,d=n.useRef(!1),[l,u]=gn({value:e,defaultValue:r,onChange:p=>{e===void 0&&!s&&Zn(a,p),o==null||o(p)}});return n.useEffect(()=>{if(d.current||(d.current=!0,s||e!==void 0))return;const p=tr(Qn(a));p&&p!==l&&u(p)},[]),[l,u]}const nr=640;function vn(e=nr){const[r,o]=n.useState(!1);return n.useEffect(()=>{if(e===!1){o(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const i=`(max-width: ${e-1}px)`,s=window.matchMedia(i),a=()=>o(s.matches);return a(),typeof s.addEventListener=="function"?(s.addEventListener("change",a),()=>s.removeEventListener("change",a)):(s.addListener(a),()=>{s.removeListener(a)})},[e]),r}const Ft="__llHistoryPatched",mt="ll:pathname";function rr(){if(typeof window>"u"||window.history[Ft])return;const e=window.history.pushState,r=window.history.replaceState;window.history.pushState=function(...o){const i=e.apply(this,o);return window.dispatchEvent(new Event(mt)),i},window.history.replaceState=function(...o){const i=r.apply(this,o);return window.dispatchEvent(new Event(mt)),i},window.history[Ft]=!0}function Ut(){return typeof window>"u"?"/":window.location.pathname||"/"}function xn(e){const[r,o]=n.useState(()=>e??Ut());return n.useEffect(()=>{if(e!==void 0)return;rr();const i=()=>o(Ut());return i(),window.addEventListener("popstate",i),window.addEventListener(mt,i),()=>{window.removeEventListener("popstate",i),window.removeEventListener(mt,i)}},[e]),e??r}const Vt=new Map,or=/[\\^$+?.()|{}[\]]/g;function ir(e){return e.replace(or,"\\$&")}function sr(e){const r=Vt.get(e);if(r)return r;const o=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,i="",s="",a=o.replace(/\*\*/g,i).replace(/\*/g,s),l=ir(a).replace(new RegExp(`\\/${i}`,"g"),"(?:\\/.*)?").replace(new RegExp(i,"g"),".*").replace(new RegExp(s,"g"),"[^/]+"),u=new RegExp(`^${l}\\/?$`);return Vt.set(e,u),u}function ar(e,r){const o=r.length>1&&r.endsWith("/")?r.slice(0,-1):r;return sr(e).test(o)}function bn(e,r){return typeof e=="function"?e(r):e instanceof RegExp?e.test(r):ar(e,r)}function Yt(e,r){if(!e||e.length===0)return!1;for(const o of e)if(bn(o,r))return!0;return!1}function wn(e,r,o){return e===void 0?!0:Yt(o,e)?!1:r&&r.length>0?Yt(r,e):!0}function _n(e,r,o){return n.useMemo(()=>wn(e,r,o),[e,r,o])}function lr(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 cr(e){const r=n.useMemo(()=>lr(e.config),[e.config]),o=e.baseUrl.replace(/\/+$/,""),i=n.useRef(null),s=n.useCallback(u=>{try{new Audio(`${o}${u}`).play().catch(()=>{})}catch{}},[o]),a=n.useCallback(()=>{r.navigate&&s("/audio/page-change-sound.mp3")},[r.navigate,s]),d=n.useCallback(()=>{r.action&&s("/audio/confirmation-sound.mp3")},[r.action,s]),l=n.useCallback(u=>{if(!r.thinking){if(i.current){try{i.current.pause()}catch{}i.current=null}return}if(u){if(i.current)return;try{const p=new Audio(`${o}/audio/thinking-sound.mp3`);p.loop=!0,p.volume=.3,p.play().catch(()=>{i.current=null}),i.current=p}catch{}}else if(i.current){try{i.current.pause()}catch{}i.current=null}},[o,r.thinking]);return n.useEffect(()=>()=>{if(i.current){try{i.current.pause()}catch{}i.current=null}},[]),n.useMemo(()=>({playPageChange:a,playConfirmation:d,setThinking:l}),[a,d,l])}const Gt=({muted:e=!1,className:r})=>e?t.jsxs("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),Kt=({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"})}),ur=({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"})}),dr={left:180,right:0,up:-90,down:90},Jt=({direction:e="right",className:r})=>t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${dr[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function fr(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const kn="ll-hidden-tab-center-y",pr=5,Xt=16;function hr(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(kn);if(!e)return null;const r=Number.parseFloat(e);return Number.isFinite(r)?r:null}catch{return null}}function Qt(e){if(!(typeof window>"u"))try{window.localStorage.setItem(kn,String(e))}catch{}}const mr=({position:e,isMobile:r,isSpeaking:o,onExpand:i,label:s="Open widget",avatarImageUrl:a,agentName:d})=>{const l=fr(e),u=l==="right"?"left":"right",p=r?80:72,x=!!a,[f,c]=n.useState(null),[E,k]=n.useState(!1),b=n.useRef(null),v=n.useRef(!1),g=n.useCallback(L=>{if(typeof window>"u")return L;const R=p/2,O=Xt+R,ee=window.innerHeight-Xt-R;return ee<O?Math.max(O,L):Math.max(O,Math.min(ee,L))},[p]);n.useEffect(()=>{const L=hr();c(g(L??window.innerHeight/2));const R=()=>{c(O=>O===null?null:g(O))};return window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[g]);const C=n.useCallback(L=>{if(!(L.pointerType==="mouse"&&L.button!==0)&&f!==null){try{L.currentTarget.setPointerCapture(L.pointerId)}catch{}b.current={startClientY:L.clientY,startCenterY:f,moved:!1}}},[f]),M=n.useCallback(L=>{const R=b.current;if(!R)return;const O=L.clientY-R.startClientY;!R.moved&&Math.abs(O)>pr&&(R.moved=!0,k(!0)),R.moved&&c(g(R.startCenterY+O))},[g]),N=n.useCallback(L=>{const R=b.current;if(R){try{L.currentTarget.releasePointerCapture(L.pointerId)}catch{}b.current=null,R.moved&&(k(!1),v.current=!0,c(O=>(O!==null&&Qt(O),O)))}},[]),_=n.useCallback(()=>{if(v.current){v.current=!1;return}i()},[i]),S=n.useCallback(L=>{if(L.key==="ArrowUp"||L.key==="ArrowDown"){L.preventDefault();const R=L.key==="ArrowUp"?-8:8;c(O=>{if(O===null)return O;const ee=g(O+R);return Qt(ee),ee})}},[g]),$=["ll-hidden",`ll-hidden--${l}`,r?"ll-hidden--mobile":"ll-hidden--desktop",o?"ll-hidden--speaking":null,E?"is-dragging":null,x?"ll-hidden--with-avatar":null].filter(Boolean).join(" "),z=f===null?void 0:{top:`${f-p/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:$,onPointerDown:C,onPointerMove:M,onPointerUp:N,onPointerCancel:N,onClick:_,onKeyDown:S,"aria-label":s,"data-position":e,style:z,children:x?t.jsxs(t.Fragment,{children:[t.jsx(Jt,{direction:u,className:"ll-hidden__chevron ll-hidden__chevron--mini"}),t.jsx("img",{src:a,alt:d?`${d} avatar`:"Agent avatar",className:"ll-hidden__avatar",draggable:!1})]}):t.jsx(Jt,{direction:u,className:"ll-hidden__chevron"})})},gr=({audioLevel:e,bars:r=20,maxHeight:o=20,minHeight:i=4,className:s,barClassName:a})=>{const d=n.useRef(null),l=n.useRef([]),u=n.useMemo(()=>{const x=(Math.sqrt(5)-1)/2;return Array.from({length:r},(f,c)=>.5+c*x%1*.5)},[r]);n.useEffect(()=>e.subscribe(f=>{for(let c=0;c<r;c++){const E=l.current[c];if(!E)continue;const k=Math.max(i,f*o*u[c]);E.style.height=`${k}px`}}),[e,r,o,i,u]);const p=["ll-waveform",s].filter(Boolean).join(" ");return t.jsx("div",{ref:d,className:p,"aria-hidden":"true",children:Array.from({length:r},(x,f)=>t.jsx("div",{ref:c=>{l.current[f]=c},className:["ll-waveform__bar",a].filter(Boolean).join(" "),style:{height:`${i}px`}},f))})},yr=({position:e,isMobile:r,agentName:o,avatarImageUrl:i,agentState:s,isMuted:a,audioLevel:d,onExpand:l,onToggleMute:u,onClose:p})=>r?t.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${o} widget`,children:t.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:l,"aria-label":`Expand ${o} widget`,children:[i?t.jsx("img",{src:i,alt:o,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsx(gr,{audioLevel:d,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),t.jsx("span",{className:"ll-minimized__name",children:o}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:x=>{x.stopPropagation(),u()},onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.stopPropagation(),x.preventDefault(),u())},"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(Gt,{muted:a,className:"ll-minimized__icon"})}),t.jsx(Kt,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):t.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":e,role:"region","aria-label":`${o} widget`,children:t.jsxs("div",{className:"ll-minimized__surface",children:[i?t.jsx("img",{src:i,alt:o,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:o}),t.jsx("span",{className:"ll-minimized__state",children:s==="speaking"?"Speaking":s==="thinking"?"Thinking":"Listening"})]}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:u,"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(Gt,{muted:a,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:l,"aria-label":`Expand ${o} widget`,children:t.jsx(Kt,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:p,"aria-label":"Close widget",children:t.jsx(ur,{className:"ll-minimized__icon"})})]})]})}),vr=({src:e,alt:r,preCannedPlaying:o=!1,className:i,style:s})=>{const[a,d]=n.useState(!1),l=n.useRef(e);if(n.useEffect(()=>{l.current!==e&&(l.current=e,d(!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:o?"scale(1.02)":"scale(1)",opacity:a?1:0,...s};return t.jsx("img",{src:e,alt:r,className:i,style:u,loading:"eager",fetchPriority:"high",onLoad:()=>d(!0)})},xr=8,Zt=8,br=({open:e,onClose:r,anchorRef:o,children:i})=>{const s=n.useRef(null),[a,d]=n.useState(null);return n.useLayoutEffect(()=>{if(!e){d(null);return}const l=o.current;if(!l)return;const u=()=>{const p=l.getBoundingClientRect(),x={top:p.top-xr,left:p.left+p.width/2},f=Zt+90,c=window.innerWidth-Zt-90;x.left<f&&(x.left=f),x.left>c&&(x.left=c),d(x)};return u(),window.addEventListener("scroll",u,!0),window.addEventListener("resize",u),()=>{window.removeEventListener("scroll",u,!0),window.removeEventListener("resize",u)}},[e,o]),n.useEffect(()=>{if(!e)return;const l=p=>{const x=p.target,f=s.current,c=o.current;f&&f.contains(x)||c&&c.contains(x)||r()},u=p=>{p.key==="Escape"&&(p.stopPropagation(),r())};return document.addEventListener("mousedown",l),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",l),document.removeEventListener("keydown",u)}},[e,r,o]),!e||a===null||typeof document>"u"?null:Ct.createPortal(t.jsx("div",{ref:s,className:"ll-overflow-popover",role:"menu",style:{position:"fixed",top:a.top,left:a.left,transform:"translate(-50%, -100%)"},children:i}),document.body)},wr=({isMuted:e,onToggleMute:r,isCameraEnabled:o,onToggleCamera:i,allowCamera:s,isScreenShareEnabled:a,onToggleScreenShare:d,allowScreenShare:l,isSpeakerMuted:u,onToggleSpeaker:p,allowTyping:x,isTypingOpen:f,onToggleTyping:c,onDisconnect:E})=>{const[k,b]=n.useState(!1),v=n.useRef(null);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"ll-toolbar ll-toolbar--compact","data-testid":"compact-toolbar",onClick:g=>g.stopPropagation(),children:[t.jsx("button",{type:"button",className:`ll-tool ${e?"is-muted":""}`,onClick:r,"aria-label":e?"Unmute microphone":"Mute microphone",children:t.jsx(Ln,{muted:e})}),t.jsx("button",{ref:v,type:"button",className:`ll-tool ${k?"is-on":""}`,onClick:()=>b(g=>!g),"aria-label":"More controls","aria-haspopup":"menu","aria-expanded":k,children:t.jsx(_r,{})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:E,"aria-label":"End conversation",children:t.jsx(En,{})})]}),t.jsxs(br,{open:k,onClose:()=>b(!1),anchorRef:v,children:[s&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${o?"is-on":""}`,onClick:()=>{i(),b(!1)},children:[t.jsx(Cn,{}),t.jsx("span",{children:o?"Stop camera":"Start camera"})]}),l&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${a?"is-on":""}`,onClick:()=>{d(),b(!1)},children:[t.jsx(jn,{}),t.jsx("span",{children:a?"Stop sharing":"Share screen"})]}),t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${u?"is-on":""}`,onClick:()=>{p(),b(!1)},children:[t.jsx(Sn,{muted:u}),t.jsx("span",{children:u?"Unmute speaker":"Mute speaker"})]}),x&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${f?"is-on":""}`,onClick:()=>{c(),b(!1)},children:[t.jsx(kr,{}),t.jsx("span",{children:f?"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 kr(){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 jr=({position:e,isMobile:r,agentName:o,avatarImageUrl:i,idleLoopUrl:s,greeting:a,branding:d,teamMembers:l,currentTeamMemberId:u,isSwitchingTeamMember:p,teamSwitcherOpen:x,onToggleTeamSwitcher:f,onSelectTeamMember:c,languageMenuOpen:E,onToggleLanguageMenu:k,connectionState:b,agentState:v,transcript:g,canResume:C,needsUserGesture:M,error:N,isMuted:_,micError:S,micDevices:$,activeMicId:z,isCameraEnabled:L,cameraPreviewEl:R,cameraDevices:O,activeCameraId:ee,isScreenShareEnabled:te,screenPreviewEl:K,isSpeakerMuted:oe,allowCamera:le,allowScreenShare:pe,allowTyping:ce,showMinimize:he=!0,chromeless:ue=!1,compactControls:J=!1,transforming:ot,transformingLabel:Be,avatarVideoContainerRef:it,agentVideoEl:ne,onConnect:qe,onDisconnect:Fe,onRetry:st,onResumeAudio:Ue,onToggleMute:_e,onSwitchMicDevice:Ae,onToggleCamera:ke,onSwitchCameraDevice:Me,onToggleScreenShare:je,onToggleSpeaker:Ce,onSendMessage:Le,onMinimize:I,onClose:at,onClearMicError:yt})=>{var Ne;const Se=((l==null?void 0:l.length)??0)>1,Ee=b==="connecting"||b==="connected",X=b==="connected",Ve=b==="idle"||b==="disconnected"||b==="error",[Ye,Ie]=n.useState(!1);n.useEffect(()=>{if(!ne){Ie(!1);return}if(!ne.paused&&ne.readyState>=2){Ie(!0);return}Ie(!1);const m=()=>Ie(!0);return ne.addEventListener("playing",m),ne.addEventListener("loadeddata",m),()=>{ne.removeEventListener("playing",m),ne.removeEventListener("loadeddata",m)}},[ne]);const[Re,Y]=n.useState(!1);n.useEffect(()=>{if(!X){Y(!1);return}if(Ye)return;const m=setTimeout(()=>Y(!0),8e3);return()=>clearTimeout(m)},[X,Ye]);const lt=b==="connecting"||X&&!!i&&!Ye&&!Re,Ge=n.useRef(null),Q=n.useRef(null);n.useEffect(()=>{const m=Ge.current;m&&(m.innerHTML="",R&&(R.style.width="100%",R.style.height="100%",R.style.objectFit="cover",R.style.transform="scaleX(-1)",m.appendChild(R)))},[R]),n.useEffect(()=>{const m=Q.current;m&&(m.innerHTML="",K&&(K.style.width="100%",K.style.height="100%",K.style.objectFit="contain",m.appendChild(K)))},[K]);const[Z,ie]=n.useState(!1),[me,F]=n.useState(!1),se=n.useRef(null),ge=n.useRef(null);n.useEffect(()=>{if(!Z&&!me&&!E&&!x)return;const m=()=>{ie(!1),F(!1),E&&k(),x&&f()};return document.addEventListener("click",m),()=>document.removeEventListener("click",m)},[Z,me,E,x,k,f]);const[Te,vt]=n.useState(!1),Ke=n.useCallback(()=>vt(m=>!m),[]),[ye,Je]=n.useState(""),Xe=n.useCallback(m=>{m.preventDefault();const B=ye.trim();B&&(Le(B),Je(""))},[ye,Le]),Qe=d.productName||"Live Layer";let ve=null,xe=null;for(let m=g.length-1;m>=0;m--){const B=g[m];if(!ve&&B.role==="agent"?ve=B:!xe&&B.role==="user"&&(xe=B),ve&&xe)break}const De=X?(ve==null?void 0:ve.text)||null:a||null,ct=X&&(xe==null?void 0:xe.text)||null,Pe=["ll-expanded",r?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:Pe,"data-position":e,"data-state":X?"connected":Ee?"connecting":"idle",role:"dialog","aria-label":`${o} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[i?t.jsx(vr,{src:i,alt:o,className:"ll-expanded__bg-img"}):t.jsx("div",{className:"ll-expanded__bg-fallback",children:t.jsx("span",{className:"ll-expanded__bg-initial",children:((Ne=o==null?void 0:o.charAt(0))==null?void 0:Ne.toUpperCase())||"A"})}),s&&!X&&t.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:it,className:"ll-expanded__video"}),lt&&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:p?"Switching...":"Connecting..."})]}),M&&X&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:Ue,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"})]}),ot&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--transforming",role:"status","aria-live":"polite","aria-label":Be,children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:Be})]}),Ee?t.jsxs(t.Fragment,{children:[!J&&t.jsxs("div",{className:"ll-expanded__topbar",children:[!ue&&t.jsxs("div",{className:"ll-expanded__topbar-left",children:[t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill",onClick:m=>{Se&&(m.stopPropagation(),f())},"aria-haspopup":Se?"listbox":void 0,"aria-expanded":Se?x:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:o}),Se&&t.jsx(dt,{})]}),Se&&x&&t.jsx("div",{className:"ll-hmenu",onClick:m=>m.stopPropagation(),role:"listbox",children:l==null?void 0:l.map(m=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${m.id===u?"is-active":""}`,onClick:()=>c(m.id),role:"option","aria-selected":m.id===u,children:[m.avatarImageUrl&&t.jsx("img",{src:m.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:m.name}),m.role&&t.jsx("span",{className:"ll-hmenu__role",children:m.role})]},m.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:m=>{m.stopPropagation(),k()},"aria-haspopup":"listbox","aria-expanded":E,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(dt,{})]}),E&&t.jsx("div",{className:"ll-hmenu",onClick:m=>m.stopPropagation(),role:"listbox",children:t.jsx("button",{type:"button",className:"ll-hmenu__item is-active",role:"option","aria-selected":!0,children:t.jsx("span",{className:"ll-hmenu__name",children:"English"})})})]}),t.jsx("span",{className:`ll-expanded__state ll-expanded__state--${v}`,children:v})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[he!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn",onClick:I,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(tn,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:at,"aria-label":"End call",title:"End call",children:t.jsx(en,{})})]})]}),J&&t.jsxs("div",{className:"ll-compact-status","data-state":v,children:[t.jsx("span",{className:"ll-compact-status__dot","aria-hidden":!0}),t.jsx("span",{className:"ll-compact-status__label",children:v})]})]}):!J&&t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:Qe}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[he!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:I,"aria-label":"Minimize widget",children:t.jsx(tn,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:at,"aria-label":"Close widget",children:t.jsx(en,{})})]})]}),Ve&&(()=>{const m=C?"Resume session":b==="disconnected"?"Reconnect to agent":"Start video call",B=!N;return t.jsxs(t.Fragment,{children:[B&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:qe,"aria-label":m,children:[t.jsx("div",{className:"ll-expanded__play-circle",children:t.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("polygon",{points:"6 3 20 12 6 21 6 3"})})}),J&&t.jsx("span",{className:"ll-expanded__play-label",children:m})]}),!J&&t.jsxs("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:[a&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:a})}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:qe,"aria-label":m,children:m})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${Ee&&(L||te)?"is-visible":""}`,children:[t.jsx("div",{ref:Q,className:te?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:Ge,className:!te&&L?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),Ee?t.jsxs("div",{className:"ll-expanded__bottom",children:[!J&&De&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--agent","data-role":"agent",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:De})}),!J&&ct&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--user","data-role":"user",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:ct})}),!ue&&!J&&t.jsxs("div",{className:"ll-toolbar",onClick:m=>m.stopPropagation(),children:[pe&&t.jsx("button",{type:"button",className:`ll-tool ${te?"is-on":""}`,onClick:je,"aria-label":te?"Stop sharing screen":"Share screen",title:te?"Stop sharing":"Share screen",children:t.jsx(jn,{})}),le&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${L?"is-on":""}`,onClick:ke,"aria-label":L?"Turn off camera":"Turn on camera",title:L?"Stop camera":"Start camera",children:t.jsx(Cn,{})}),t.jsx("button",{ref:ge,type:"button",className:`ll-tool ll-tool--right ${L?"is-on":""}`,onClick:m=>{m.stopPropagation(),F(B=>!B),ie(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":me,children:t.jsx(dt,{})}),me&&O.length>0&&t.jsx(nn,{label:"Camera",devices:O,activeId:ee,anchorRef:ge,onPick:m=>{F(!1),Me(m)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${_?"is-muted":""}`,onClick:_e,"aria-label":_?"Unmute microphone":"Mute microphone",title:_?"Unmute":"Mute",children:t.jsx(Ln,{muted:_})}),t.jsx("button",{ref:se,type:"button",className:`ll-tool ll-tool--right ${_?"is-muted":""}`,onClick:m=>{m.stopPropagation(),ie(B=>!B),F(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":Z,children:t.jsx(dt,{})}),Z&&$.length>0&&t.jsx(nn,{label:"Microphone",devices:$,activeId:z,anchorRef:se,onPick:m=>{ie(!1),Ae(m)}})]}),t.jsx("button",{type:"button",className:`ll-tool ${oe?"is-muted":""}`,onClick:Ce,"aria-label":oe?"Unmute speaker":"Mute speaker",title:oe?"Unmute speaker":"Mute speaker",children:t.jsx(Sn,{muted:oe})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:Fe,"aria-label":"End conversation",title:"End conversation",children:t.jsx(En,{})})]}),!ue&&J&&t.jsx(wr,{isMuted:_,onToggleMute:_e,isCameraEnabled:L,onToggleCamera:ke,allowCamera:le,isScreenShareEnabled:te,onToggleScreenShare:je,allowScreenShare:pe,isSpeakerMuted:oe,onToggleSpeaker:Ce,allowTyping:ce,isTypingOpen:Te,onToggleTyping:Ke,onDisconnect:Fe}),!ue&&ce&&(J?Te:!0)&&t.jsxs("form",{className:"ll-message-input",onSubmit:Xe,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:ye,onChange:m=>Je(m.target.value),"aria-label":"Message the agent"}),ye.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(Cr,{})})]})]}):null,(()=>{if(S&&b!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:S}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:yt,"aria-label":"Dismiss",children:"×"})]});if(!N||b!=="error")return null;let m="Failed to connect",B="Try again";return N==="MIC_PERMISSION_DENIED"?m="Microphone blocked. Allow access to talk.":N==="MIC_NOT_FOUND"?m="No microphone found. Plug one in + retry.":N==="MIC_UNAVAILABLE"?m="Mic unavailable. Check other apps using it.":N==="AGENT_TIMEOUT"?m="Agent didn't pick up. Try again.":N==="CONNECT_FAILED"?m="Connection failed. Check your network.":N.length<80&&(m=N),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:m}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:st,children:B})]})})()]})};function dt(){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 en(){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 tn(){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 jn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("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 Cn(){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 Ln({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 Sn({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 Cr(){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 En(){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 nn=({label:e,devices:r,activeId:o,onPick:i,anchorRef:s})=>{const[a,d]=n.useState(null);return n.useLayoutEffect(()=>{const l=()=>{const u=s.current;if(!u)return;const p=u.getBoundingClientRect(),x=126,f=window.innerWidth-16-110,c=p.left+p.width/2;d({top:p.top-8,left:Math.max(x,Math.min(f,c))})};return l(),window.addEventListener("scroll",l,!0),window.addEventListener("resize",l),()=>{window.removeEventListener("scroll",l,!0),window.removeEventListener("resize",l)}},[s]),a===null||typeof document>"u"?null:Ct.createPortal(t.jsxs("div",{className:"ll-device-menu ll-device-menu--floating",onClick:l=>l.stopPropagation(),role:"listbox",style:{position:"fixed",top:a.top,left:a.left,transform:"translate(-50%, -100%)"},children:[t.jsx("p",{className:"ll-device-menu__label",children:e}),r.map((l,u)=>{const p=o===l.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${p?"is-active":""}`,onClick:()=>i(l.deviceId),role:"option","aria-selected":p,children:[p&&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)},Lr=['[data-ll-private="true"]',".ll-widget"];function Lt(e){let r=e;for(;r;){for(const o of Lr)if(r.matches(o))return!0;r=r.parentElement}return!1}function gt(e){if(Lt(e))return!1;if(e instanceof HTMLInputElement){if(e.type==="password")return!1;const r=(e.getAttribute("autocomplete")||"").toLowerCase();if(r==="off"||r.startsWith("cc-"))return!1}return!0}const ft=4096,Sr=20,Er=20,Rr=10,Nr=10,Ar=30,Mr=20,rn=500,Ir=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function nt(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let r=e;for(;r;){for(const o of Ir)if(r.matches(o))return!0;r=r.parentElement}return!1}function rt(e){if(typeof window>"u")return!0;const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return!1;const o=window.innerHeight||document.documentElement.clientHeight,i=window.innerWidth||document.documentElement.clientWidth;return r.bottom>0&&r.right>0&&r.top<o&&r.left<i}function on(e){const r=e.getAttribute("id");if(r){const a=document.querySelector(`label[for="${CSS.escape(r)}"]`);if(a!=null&&a.textContent)return a.textContent.trim()}const o=e.getAttribute("aria-label");if(o)return o.trim();const i=e.getAttribute("placeholder");if(i)return i.trim();const s=e.closest("label");return s!=null&&s.textContent?s.textContent.trim():""}function fe(e,r){return e.length<=r?e:e.slice(0,r-1)+"…"}function Oe(e){return e.length}function Rn(e,r={}){const o=r.doc??(typeof document<"u"?document:null);if(!o)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:e};const i=typeof window<"u"&&window.location.href||"",s=typeof window<"u"&&window.location.pathname||"/",a=o.title||"",d=Array.from(o.querySelectorAll("[data-ll-region]")),l=[];for(const _ of d){if(l.length>=Rr)break;if(nt(_)||!rt(_))continue;const S=_.getAttribute("data-ll-region")??"",$=_.getAttribute("data-ll-intent")??void 0,z=fe((_.innerText||_.textContent||"").trim(),rn*2);!S||!z||l.push({id:S,intent:$,text:z})}const u=[],p=["H1","H2","H3","H4","H5","H6"],x=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const _ of x){if(nt(_)||!rt(_))continue;const S=(_.textContent||"").trim();S&&u.push(`${_.tagName}: ${fe(S,200)}`)}const f=Array.from(o.querySelectorAll("p, li"));for(const _ of f){if(nt(_)||!rt(_)||p.includes(_.tagName))continue;const S=(_.textContent||"").trim();S.length>10&&u.push(fe(S,rn))}const c=u.join(`
2
- `),E=[],k=Array.from(o.querySelectorAll("a[href]"));for(const _ of k){if(E.length>=Sr)break;if(nt(_)||!rt(_))continue;const S=_.getAttribute("href")||"",$=(_.textContent||"").trim();!S||!$||E.push({href:S,text:fe($,100)})}const b=[],v=Array.from(o.querySelectorAll("input, textarea, select"));for(const _ of v){if(b.length>=Er)break;if(nt(_)||!gt(_)||!rt(_))continue;const S=on(_),$=_ instanceof HTMLInputElement?_.type:_.tagName.toLowerCase();S&&b.push({label:fe(S,100),type:$})}const g=Array.from(o.querySelectorAll("[data-ll-form]")),C=[];for(const _ of g){if(C.length>=Nr)break;if(Lt(_))continue;const S=_.getAttribute("data-ll-form")||"";if(!S)continue;const $=_.getAttribute("data-ll-intent")||void 0,z=Array.from(_.querySelectorAll("[data-ll-field]")),L=[];for(const R of z){if(L.length>=Ar)break;if(!gt(R))continue;const O=R.getAttribute("data-ll-field")||"";if(!O)continue;const ee=on(R)||O,te=R instanceof HTMLInputElement?R.type:R.tagName.toLowerCase(),K={name:O,label:fe(ee,100),type:te};if(R.required===!0&&(K.required=!0),R instanceof HTMLSelectElement){const le=[];for(let pe=0;pe<R.options.length&&!(le.length>=Mr);pe++){const ce=R.options[pe];if(!ce||ce.disabled)continue;const he=ce.value||"",ue=(ce.textContent||"").trim()||he;!he&&!ue||le.push({value:he,label:fe(ue,60)})}le.length>0&&(K.options=le)}const oe=typeof R.validationMessage=="string"?R.validationMessage:"";oe&&(K.validationMessage=fe(oe,200)),L.push(K)}C.push({id:S,intent:$,fields:L})}const M={url:i,title:a,pathname:s,regions:l,visibleText:c,visibleLinks:E,visibleFields:b,forms:C,extras:e};let N=Oe(JSON.stringify(M.regions))+Oe(M.visibleText)+Oe(JSON.stringify(M.visibleLinks))+Oe(JSON.stringify(M.visibleFields));for(;N>ft&&M.visibleFields.length>0;)M.visibleFields.pop(),N=Oe(JSON.stringify(M.visibleFields));for(;N>ft&&M.visibleLinks.length>0;)M.visibleLinks.pop(),N-=80;return Oe(M.visibleText)>ft&&(M.visibleText=fe(M.visibleText,ft-100)),M}let He=null;function jt(e,r={}){const o=Date.now(),s=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(He&&He.key===s&&o-He.at<1e3)return He.ctx;const a=Rn(e,r);return He={key:s,at:o,ctx:a},a}function Nn(){He=null}const Tr=200;function An(e){const r=String(e.href||"");return{href:r,text:String(e.text??e.title??r),internal:e.internal??!0,title:e.title,description:e.description}}function Dr(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function Mn(e){const r=e??(typeof document<"u"?document:null);if(!r)return[];const o=typeof window<"u"&&window.location.origin||"",i=new Set,s=[],a=Array.from(r.querySelectorAll("a[href]"));for(const d of a){if(s.length>=Tr)break;if(Lt(d))continue;const l=d.getAttribute("href")||"";if(!Dr(l))continue;let u=l,p=!0;try{if(typeof window<"u"){const f=new URL(l,o);p=f.origin===o,p&&l.startsWith("http")&&(u=f.pathname+f.search+f.hash)}}catch{continue}if(i.has(u))continue;i.add(u);const x=(d.textContent||"").trim().slice(0,120);s.push({href:u,text:x,internal:p})}return s}let We=null;const Pr=5e3;function pt(){const e=Date.now(),r=typeof window<"u"&&window.location.pathname||"/";if(We&&We.pathname===r&&e-We.at<Pr)return We.routes;const o=Mn();return We={at:e,pathname:r,routes:o},o}function In(){We=null}function $r(e,r){const o=e instanceof HTMLInputElement?HTMLInputElement.prototype:e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLSelectElement.prototype,i=Object.getOwnPropertyDescriptor(o,"value"),s=i==null?void 0:i.set;s?s.call(e,r):e.value=r}function zr(e,r,o={}){const i=o.triggerInput??!0,s=o.triggerChange??!0;if(e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")){const a=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"),d=a==null?void 0:a.set,l=r==="true"||r==="1"||r==="on";d?d.call(e,l):e.checked=l,i&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}$r(e,r),i&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}))}function Or(){if(typeof window>"u"||typeof document>"u")return!1;const e=document.scrollingElement||document.documentElement;if(!e||e.scrollHeight<=e.clientHeight+2)return!1;const r=window.getComputedStyle(e);return!(r.overflowY==="hidden"||r.overflowY==="clip")}function Hr(e){if(!(e instanceof HTMLElement))return!1;const o=window.getComputedStyle(e).overflowY;return!(o!=="auto"&&o!=="scroll"||e.scrollHeight<=e.clientHeight+2)}function Wr(){if(typeof document>"u")return null;const e=Array.from(document.querySelectorAll("body, body *"));let r=null,o=0;for(const i of e){if(!Hr(i))continue;const s=i.getBoundingClientRect();if(s.bottom<=0||s.top>=window.innerHeight||s.right<=0||s.left>=window.innerWidth||s.width<=0||s.height<=0||i.closest(".ll-widget"))continue;const a=s.width*s.height;a>o&&(o=a,r=i)}return r}function Br(){if(typeof window>"u")return null;if(Or())return window;const e=Wr();return e||window}function sn(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function qr(e){var r,o;return e instanceof Window?typeof document>"u"?0:Math.max(((r=document.body)==null?void 0:r.scrollHeight)??0,((o=document.documentElement)==null?void 0:o.scrollHeight)??0):e.scrollHeight-e.clientHeight}const Fr=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"]),Tn=n.forwardRef(function(r,o){var $t,zt,Ot,Ht,Wt,Bt,qt;const{agentId:i,apiKey:s,baseUrl:a="https://app.livelayer.studio",sessionEndpoint:d,sessionBody:l,soundEffects:u,experienceMode:p="WIDGET",autoConnect:x=!1,displayMode:f,defaultDisplayMode:c="expanded",onDisplayModeChange:E,position:k="bottom-right",mobileBreakpoint:b=640,persistKey:v="ll-widget",disablePersistence:g=!1,teamMembers:C,currentTeamMemberId:M,onTeamMemberChange:N,idleLoopUrl:_,greeting:S,avatarImageUrl:$,agentName:z,branding:L={},allowCamera:R=!0,allowScreenShare:O=!0,allowTyping:ee=!0,showMinimize:te=!0,chromeless:K=!1,floatingChromeContainer:oe=null,compactControls:le=!1,transforming:pe=!1,transformingLabel:ce="Transforming…",showOn:he,hideOn:ue,pathname:J,onNavigate:ot,onScrollToSelector:Be,getPageContext:it,pageContextExtras:ne,getRoutes:qe,onScrollPage:Fe,onClick:st,capabilities:Ue,onConnect:_e,onDisconnect:Ae,onTranscript:ke,onAgentState:Me,onConnectionStateChange:je,onAgentEvent:Ce,onAgentCommand:Le,controlledSession:I,className:at,style:yt,zIndex:Se=2147483647}=r,Ee=xn(J),X=_n(Ee,he,ue);n.useEffect(()=>{Nn(),In()},[Ee]);const Ve=M!==void 0,[Ye,Ie]=n.useState(()=>{var y;return M??((y=C==null?void 0:C[0])==null?void 0:y.id)}),Re=Ve?M:Ye,Y=n.useMemo(()=>(C==null?void 0:C.find(y=>y.id===Re))??null,[C,Re]),lt=(Y==null?void 0:Y.agentId)??i,Ge=p==="EMBEDDED",[Q,Z]=yn({value:f,defaultValue:c,onChange:E,persistKey:v,disablePersistence:Ge||g}),ie=vn(b),me=un(),F=dn(),se=fn(),ge=pn(),Te=hn(),[vt,Ke]=n.useState(!1),[ye,Je]=n.useState(!1),[Xe,Qe]=n.useState(!1),[ve,xe]=n.useState(!1),[De,ct]=n.useState(!1),Pe=cr({baseUrl:a,config:u}),Ne=n.useRef(Pe);Ne.current=Pe;const m=n.useRef(ot),B=n.useRef(Be),xt=n.useRef(Fe),bt=n.useRef(st),St=n.useRef(it),Et=n.useRef(ne),Rt=n.useRef(qe),wt=n.useRef(Ue),ae=n.useRef(null);m.current=ot,B.current=Be,xt.current=Fe,bt.current=st,St.current=it,Et.current=ne,Rt.current=qe,wt.current=Ue;function be(y){const h=wt.current;return h?h.includes(y):!0}function we(y,h){console.warn(`[LiveLayer] Agent command "${y}" blocked — capability "${h}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const Ze=n.useCallback(y=>{var q,re,de,tt;const h=y;if(!(!h.type||typeof h.type!="string")){if(Ce==null||Ce({eventName:h.type,data:y}),h.type==="navigate"){if(!be("navigate")){we("navigate","navigate");return}const j=typeof h.href=="string"?h.href:null;if(!j){console.warn(`[LiveLayer] Agent emitted "navigate" without href. Skipping. Check your agent's tool schema. See https://livelayer.studio/docs/errors/navigate-missing-href`);return}if(Ne.current.playPageChange(),m.current){try{m.current(j)}catch(A){console.warn(`[LiveLayer] onNavigate threw for "${j}". Falling back. Error:`,A)}return}if(typeof document<"u"){const A=document.querySelector(`a[href="${j.replace(/"/g,'\\"')}"]`);if(A){A.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",j),window.dispatchEvent(new PopStateEvent("popstate"))}catch(A){console.warn(`[LiveLayer] history.pushState fallback failed for "${j}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,A)}return}if(h.type==="scroll_to"){if(!be("scroll")){we("scroll_to","scroll");return}const j=typeof h.selector=="string"?h.selector:null;if(!j)return;const A=h.behavior==="instant"?"instant":"smooth";if(B.current){try{B.current(j,A)}catch(P){console.warn("[LiveLayer] onScrollToSelector threw.",P)}return}if(typeof document<"u"){let P=null;try{P=document.querySelector(j)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${j}".`);return}if(!P){console.warn(`[LiveLayer] scroll_to: no element matched "${j}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}P.scrollIntoView({behavior:A,block:"start"})}return}if(h.type==="request_page_context"){if(!be("read_page")){we("request_page_context","read_page");return}const j=typeof h.requestId=="string"?h.requestId:void 0,A=(q=ae.current)==null?void 0:q.call(ae),P=W=>{const T=A,V=T==null?void 0:T.localParticipant;if(V!=null&&V.publishData)try{const G=j?{...W,requestId:j}:W,ze=new TextEncoder().encode(JSON.stringify(G));V.publishData(ze,{reliable:!0})}catch(G){console.warn("[LiveLayer] publishData failed.",G)}},D=Et.current,H=St.current;try{if(H){const W=H(D);if(W instanceof Promise){P({type:"page_context_pending"}),W.then(T=>P({type:"page_context",context:T})).catch(T=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",T),P({type:"page_context",context:jt(D)})});return}P({type:"page_context",context:W});return}P({type:"page_context",context:jt(D)})}catch(W){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",W),P({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:D}})}return}if(h.type==="scroll_page"){if(!be("scroll")){we("scroll_page","scroll");return}const j=h.direction;if(j!=="up"&&j!=="down"&&j!=="top"&&j!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(j)}". Expected up | down | top | bottom.`);return}const A=h.behavior==="instant"?"instant":"smooth";if(xt.current){try{xt.current(j,A)}catch(T){console.warn("[LiveLayer] onScrollPage threw.",T)}return}if(typeof window>"u")return;const P={behavior:A},D=Br(),H=T=>{D instanceof Window?D.scrollBy({top:T,...P}):D.scrollBy({top:T,...P})},W=T=>{D instanceof Window?D.scrollTo({top:T,...P}):D.scrollTo({top:T,...P})};j==="up"?H(-sn(D)):j==="down"?H(sn(D)):W(j==="top"?0:qr(D));return}if(h.type==="click"){if(!be("click")){we("click","click");return}const j=typeof h.selector=="string"?h.selector:null;if(!j){console.warn("[LiveLayer] click: missing selector.");return}if(bt.current){try{bt.current(j)}catch(P){console.warn("[LiveLayer] onClick threw.",P)}return}if(typeof document>"u")return;let A=null;try{A=document.querySelector(j)}catch{console.warn(`[LiveLayer] click: invalid selector "${j}".`);return}if(!A){console.warn(`[LiveLayer] click: no element matched "${j}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(A.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(re=A.click)==null||re.call(A);return}if(h.type==="fill_form"||h.type==="focus_field"){if(!be("fill_forms")){we(h.type,"fill_forms");return}if(typeof document>"u")return;h.type==="fill_form"&&Ne.current.playConfirmation();const j=typeof h.formId=="string"?h.formId:null;if(!j){console.warn(`[LiveLayer] ${h.type}: missing formId.`);return}const A=document.querySelector(`[data-ll-form="${j.replace(/"/g,'\\"')}"]`);if(!A){console.warn(`[LiveLayer] ${h.type}: no form with data-ll-form="${j}". Tag your form with <LiveLayerForm id> or data-ll-form. See https://livelayer.studio/docs/react/forms`);return}if(A.closest('[data-ll-private="true"], .ll-widget')){console.warn(`[LiveLayer] ${h.type}: refusing to touch a form in a private subtree.`);return}if(h.type==="focus_field"){const D=typeof h.fieldName=="string"?h.fieldName:null;if(!D){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const H=A.querySelector(`[data-ll-field="${D.replace(/"/g,'\\"')}"]`);if(!H){console.warn(`[LiveLayer] focus_field: no field "${D}" in form "${j}".`);return}if(!gt(H)){console.warn(`[LiveLayer] focus_field: field "${D}" is privacy-protected and not focusable.`);return}H.focus();return}const P=h.values&&typeof h.values=="object"?h.values:null;if(!P){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[D,H]of Object.entries(P)){if(typeof H!="string")continue;const W=A.querySelector(`[data-ll-field="${D.replace(/"/g,'\\"')}"]`);if(!W){console.warn(`[LiveLayer] fill_form: no field "${D}" in form "${j}". Skipping.`);continue}if(!gt(W)){console.warn(`[LiveLayer] fill_form: field "${D}" is privacy-protected (password / cc-* / private). Skipping.`);continue}try{zr(W,H)}catch(T){console.warn(`[LiveLayer] fill_form: failed to set "${D}".`,T)}}return}if(h.type==="submit_form"){if(!be("submit_forms")){we("submit_form","submit_forms");return}if(typeof document>"u")return;const j=typeof h.formId=="string"?h.formId:null;if(!j){console.warn("[LiveLayer] submit_form: missing formId.");return}Ne.current.playConfirmation();const A=document.querySelector(`[data-ll-form="${j.replace(/"/g,'\\"')}"]`);if(!A){console.warn(`[LiveLayer] submit_form: no form with data-ll-form="${j}".`);return}if(A.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] submit_form: refusing to submit a form in a private subtree.");return}const P=typeof h.requestId=="string"?h.requestId:void 0,D=(de=ae.current)==null?void 0:de.call(ae),H=V=>{const G=D,ze=G==null?void 0:G.localParticipant;if(ze!=null&&ze.publishData)try{const Gn=P?{...V,requestId:P}:V,Kn=new TextEncoder().encode(JSON.stringify(Gn));ze.publishData(Kn,{reliable:!0})}catch{}};let W=!1;const T=()=>{W=!0,H({type:"form_submitted",formId:j})};A.addEventListener("submit",T,{once:!0});try{typeof A.requestSubmit=="function"?A.requestSubmit():A.submit()}catch(V){console.warn("[LiveLayer] submit_form: requestSubmit threw.",V),A.removeEventListener("submit",T),H({type:"form_submit_blocked",formId:j,reason:"exception"});return}setTimeout(()=>{W||(A.removeEventListener("submit",T),H({type:"form_submit_blocked",formId:j,reason:"validation"}))},500);return}if(h.type==="request_routes"){if(!be("read_page")){we("request_routes","read_page");return}const j=typeof h.requestId=="string"?h.requestId:void 0,P=(tt=ae.current)==null?void 0:tt.call(ae),D=P==null?void 0:P.localParticipant;if(!(D!=null&&D.publishData))return;const H=T=>{try{const V=j?{type:"routes",routes:T,requestId:j}:{type:"routes",routes:T},G=new TextEncoder().encode(JSON.stringify(V));D.publishData(G,{reliable:!0})}catch(V){console.warn("[LiveLayer] request_routes: publishData failed.",V)}},W=Rt.current;if(W){try{const T=W(),V=G=>{if(!Array.isArray(G)){H([]);return}H(G.map(An).slice(0,200))};T instanceof Promise?T.then(V).catch(G=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",G),H(pt())}):V(T)}catch(T){console.warn("[LiveLayer] getRoutes threw; falling back to DOM walker.",T),H(pt())}return}try{H(pt())}catch(T){console.warn("[LiveLayer] request_routes: extractRoutes threw.",T)}return}Fr.has(h.type)||Le==null||Le(h)}},[Le,Ce]),U=cn({agentId:I?"__controlled__":lt,baseUrl:a,apiKey:s,sessionEndpoint:d,sessionBody:l,onDataMessage:I?void 0:Ze});n.useEffect(()=>{if(I!=null&&I.subscribeToDataMessages)return I.subscribeToDataMessages(Ze)},[I,Ze]),ae.current=()=>{var y;return(y=U.getRoom)==null?void 0:y.call(U)},n.useEffect(()=>{var q;if(typeof window>"u")return;const y=((q=window.location)==null?void 0:q.hostname)||"";if(y==="localhost"||y==="127.0.0.1"||y==="0.0.0.0"||y.endsWith(".local")||y.endsWith(".test"))return window.__livelayerSimulateCommand=re=>{try{Ze(re)}catch(de){console.warn("[LiveLayer] simulate-command threw:",de)}},()=>{delete window.__livelayerSimulateCommand}},[Ze]);const w=n.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:U.getRoom,isControlled:!0}:{connectionState:U.connectionState,agentState:U.agentState,transcript:U.transcript,videoElement:U.videoElement,audioElement:U.audioElement,canResume:U.canResume,error:U.error,agentConfig:U.agentConfig,connect:U.connect,disconnect:U.disconnect,getRoom:U.getRoom,isControlled:!1},[I,U]),Nt=n.useRef(w);Nt.current=w;const At=n.useRef(I);At.current=I,n.useImperativeHandle(o,()=>({sendData:async y=>{var de,tt;const h=At.current;if(h!=null&&h.publishData){try{await h.publishData(y)}catch(j){console.warn("[AvatarWidget] sendData (controlled) failed:",j)}return}const q=(tt=(de=Nt.current)==null?void 0:de.getRoom)==null?void 0:tt.call(de),re=q==null?void 0:q.localParticipant;if(re!=null&&re.publishData)try{const j=new TextEncoder().encode(JSON.stringify(y));await re.publishData(j,{reliable:!0})}catch(j){console.warn("[AvatarWidget] sendData failed:",j)}}}),[]);const Mt=n.useRef(null);n.useEffect(()=>{const y=w.videoElement,h=Mt.current;if(!(!y||!h))return h.appendChild(y),()=>{y.parentNode===h&&h.removeChild(y)}},[w.videoElement]),n.useEffect(()=>{const y=w.audioElement;if(!y)return;me.attach(y);const h=y.play();return h&&typeof h.catch=="function"&&h.catch(q=>{(q==null?void 0:q.name)==="NotAllowedError"&&Ke(!0)}),()=>{me.detach()}},[w.audioElement]),n.useEffect(()=>{if(w.isControlled||w.connectionState!=="connected")return;const y=w.getRoom();if(y)return F.setupMic(y).catch(()=>{}),()=>{F.teardownMic()}},[w.isControlled,w.connectionState]),n.useEffect(()=>{var h;if(w.connectionState!=="connected")return;const y=w.isControlled?(h=I==null?void 0:I.getRoom)==null?void 0:h.call(I):w.getRoom();if(y)return se.attachRoom(y),ge.attachRoom(y),w.isControlled&&F.attachRoom(y),Te.refresh(),()=>{se.teardown(),ge.teardown()}},[w.isControlled,w.connectionState,I]),n.useEffect(()=>{const y=w.audioElement;y&&(y.muted=De)},[w.audioElement,De]);const Pn=n.useCallback(y=>{const h={type:"user_message",text:y};if(I!=null&&I.publishData){try{I.publishData(h)}catch{}return}const q=w.getRoom();if(q)try{const re=new TextEncoder().encode(JSON.stringify(h));q.localParticipant.publishData(re,{reliable:!0})}catch{}},[w,I]),$n=n.useCallback(()=>{ct(y=>!y)},[]);n.useEffect(()=>{je==null||je(w.connectionState),w.connectionState==="connected"?_e==null||_e():w.connectionState==="disconnected"&&(Ae==null||Ae())},[w.connectionState,_e,Ae,je]),n.useEffect(()=>{ke==null||ke(w.transcript)},[w.transcript,ke]),n.useEffect(()=>{Me==null||Me(w.agentState)},[w.agentState,Me]),n.useEffect(()=>{Pe.setThinking(w.agentState==="thinking")},[w.agentState,Pe]);const It=n.useRef(!1);n.useEffect(()=>{w.isControlled||!x||It.current||X&&w.connectionState==="idle"&&(It.current=!0,w.connect())},[x,w.connectionState,w,X]);const zn=n.useCallback(y=>{const h=C==null?void 0:C.find(q=>q.id===y);h&&(Qe(!1),y!==Re&&(Je(!0),w.disconnect(),Ve||Ie(y),N==null||N(h)))},[C,Re,w,Ve,N]);n.useEffect(()=>{ye&&w.connectionState==="connected"&&Je(!1)},[w.connectionState,ye]),n.useEffect(()=>{if(!Xe)return;const y=h=>{h.key==="Escape"&&Qe(!1)};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[Xe]);const On=!!$||!!(Y!=null&&Y.avatarImageUrl)||w.isControlled,et=mn(lt,a,On);Ue===void 0&&(($t=et.info)!=null&&$t.capabilities)&&(wt.current=et.info.capabilities);const ut=(Y==null?void 0:Y.name)??z??((zt=w.agentConfig)==null?void 0:zt.name)??((Ot=et.info)==null?void 0:Ot.name)??"Live Layer",_t=(Y==null?void 0:Y.avatarImageUrl)??$??((Ht=w.agentConfig)==null?void 0:Ht.avatarImageUrl)??((Wt=et.info)==null?void 0:Wt.avatarImageUrl)??null,Hn=_??((Bt=w.agentConfig)==null?void 0:Bt.idleLoopUrl)??((qt=et.info)==null?void 0:qt.idleLoopUrl)??null,Wn=S??null,Bn=n.useCallback(()=>Z("expanded"),[Z]),qn=n.useCallback(()=>Z("minimized"),[Z]),Tt=n.useCallback(()=>{w.disconnect(),Z("hidden")},[w,Z]),Fn=n.useCallback(()=>{const y=w.audioElement;y&&y.play().then(()=>Ke(!1)).catch(()=>{})},[w.audioElement]),Un=n.useCallback(()=>{Ke(!1),w.connect()},[w]),$e={...yt,...Ge?{}:{zIndex:Se}};L.primaryColor&&($e["--ll-color-primary"]=L.primaryColor),L.accentColor&&($e["--ll-color-accent"]=L.accentColor),L.backgroundColor&&($e["--ll-color-bg"]=L.backgroundColor),L.textColor&&($e["--ll-color-fg"]=L.textColor);const Vn=["ll-widget",`ll-widget--${Q}`,`ll-widget--${ie?"mobile":"desktop"}`,at].filter(Boolean).join(" ");if(!X)return null;const Yn=t.jsx("div",{className:Vn,style:$e,"data-display-mode":Q,"data-position":k,"data-experience-mode":p==="EMBEDDED"?"embedded":"widget",children:Q==="expanded"&&t.jsx(jr,{position:k,isMobile:ie,agentName:ut,avatarImageUrl:_t,idleLoopUrl:Hn,greeting:Wn,branding:L,teamMembers:C,currentTeamMemberId:Re,isSwitchingTeamMember:ye,teamSwitcherOpen:Xe,onToggleTeamSwitcher:()=>Qe(y=>!y),onSelectTeamMember:zn,connectionState:w.connectionState,agentState:w.agentState,transcript:w.transcript,isMuted:F.isMuted,micDevices:Te.mics,activeMicId:F.activeDeviceId,isCameraEnabled:se.isEnabled,cameraPreviewEl:se.previewEl,cameraDevices:Te.cameras,activeCameraId:se.activeDeviceId,isScreenShareEnabled:ge.isEnabled,screenPreviewEl:ge.previewEl,isSpeakerMuted:De,allowCamera:R,allowScreenShare:O,allowTyping:ee,showMinimize:te,chromeless:K,compactControls:le,transforming:pe,transformingLabel:ce,languageMenuOpen:ve,onToggleLanguageMenu:()=>xe(y=>!y),needsUserGesture:vt,canResume:w.canResume,micError:F.micError,error:w.error,avatarVideoContainerRef:Mt,agentVideoEl:w.videoElement,onConnect:()=>void w.connect(),onDisconnect:()=>w.disconnect(),onRetry:Un,onResumeAudio:Fn,onToggleMute:F.toggleMute,onSwitchMicDevice:y=>void F.switchDevice(y),onToggleCamera:()=>void se.toggle(),onSwitchCameraDevice:y=>void se.switchDevice(y),onToggleScreenShare:()=>void ge.toggle(),onToggleSpeaker:$n,onSendMessage:Pn,onMinimize:qn,onClose:Tt,onClearMicError:F.clearError})}),Dt=Q==="hidden"||Q==="minimized"?t.jsxs("div",{className:["ll-widget","ll-widget--floating",`ll-widget--${Q}`,`ll-widget--${ie?"mobile":"desktop"}`].join(" "),style:$e,"data-display-mode":Q,"data-position":k,children:[Q==="hidden"&&t.jsx(mr,{position:k,isMobile:ie,isSpeaking:w.agentState==="speaking",onExpand:()=>Z("expanded"),label:`Open ${ut} widget`,avatarImageUrl:_t,agentName:ut}),Q==="minimized"&&t.jsx(yr,{position:k,isMobile:ie,agentName:ut,avatarImageUrl:_t,agentState:w.agentState,isMuted:F.isMuted,audioLevel:me,onExpand:Bn,onToggleMute:F.toggleMute,onClose:Tt})]}):null,Pt=oe??(typeof document<"u"?document.body:null);return t.jsxs(t.Fragment,{children:[Yn,Dt&&Pt&&Ct.createPortal(Dt,Pt)]})});Tn.displayName="AvatarWidgetInner";const Dn=n.forwardRef(function(r,o){return t.jsx(ln,{children:t.jsx(Tn,{...r,ref:o})})});Dn.displayName="AvatarWidget";const Ur=({agentId:e,baseUrl:r,apiKey:o,mode:i,onAgentEvent:s,className:a,style:d})=>{const l=n.useRef(null),u=n.useRef(null),p=n.useRef(s);p.current=s;const x=n.useCallback(f=>{var E;const c=f.detail;(E=p.current)==null||E.call(p,c)},[]);return n.useEffect(()=>{const f=l.current;if(!f)return;const c=document.createElement("livelayer-widget");return c.setAttribute("agent-id",e),r&&c.setAttribute("base-url",r),o&&c.setAttribute("api-key",o),i&&c.setAttribute("mode",i),c.addEventListener("agent-event",x),f.appendChild(c),u.current=c,()=>{c.removeEventListener("agent-event",x),f.removeChild(c),u.current=null}},[e]),n.useEffect(()=>{u.current&&(i?u.current.setAttribute("mode",i):u.current.removeAttribute("mode"))},[i]),t.jsx("div",{ref:l,className:a,style:d})},Vr=n.forwardRef(function({id:r,intent:o,as:i="div",className:s,style:a,children:d},l){return n.createElement(i,{ref:l,"data-ll-region":r,"data-ll-intent":o,className:s,style:a},d)}),Yr=n.forwardRef(function({id:r,intent:o,children:i,...s},a){return t.jsx("form",{ref:a,"data-ll-form":r,"data-ll-intent":o,...s,children:i})}),Gr=n.forwardRef(function(r,o){const{name:i,label:s,labelClassName:a}=r,d={name:i,"data-ll-field":i};let l;if("as"in r&&r.as==="textarea"){const{name:u,label:p,labelClassName:x,as:f,...c}=r;l=t.jsx("textarea",{ref:o,...d,...c})}else if("as"in r&&r.as==="select"){const{name:u,label:p,labelClassName:x,as:f,children:c,...E}=r;l=t.jsx("select",{ref:o,...d,...E,children:c})}else{const{name:u,label:p,labelClassName:x,as:f,...c}=r;l=t.jsx("input",{ref:o,...d,...c})}return s===void 0?l:t.jsxs("label",{className:a,children:[s,l]})});let an=1;function Kr({onMount:e,defaultOpen:r=!1,storageKey:o="ll-debug-open"}){const[i,s]=n.useState(r),[a,d]=n.useState([]),[l,u]=n.useState(""),[p,x]=n.useState(!1),f=n.useRef(new Set),c=n.useRef([]),E=n.useRef(p);E.current=p,n.useEffect(()=>{try{const v=localStorage.getItem(o);v==="1"&&s(!0),v==="0"&&s(!1)}catch{}},[o]),n.useEffect(()=>{try{localStorage.setItem(o,i?"1":"0")}catch{}},[i,o]),n.useEffect(()=>{const v=g=>{(g.metaKey||g.ctrlKey)&&g.shiftKey&&g.key.toLowerCase()==="l"&&(g.preventDefault(),s(C=>!C))};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[]),n.useEffect(()=>{const v=setInterval(()=>{if(c.current.length===0||E.current)return;const g=c.current.splice(0,c.current.length);d(C=>[...g.reverse(),...C].slice(0,200))},100);return()=>clearInterval(v)},[]);const k=n.useRef(!1);if(n.useEffect(()=>{!e||k.current||(k.current=!0,e(v=>{c.current.push({id:an++,ts:Date.now(),kind:"event",type:v.eventName,data:v.data})}))},[e]),n.useEffect(()=>{const v=console.warn,g=console.log,C=(M,N)=>function(..._){try{const S=typeof _[0]=="string"?_[0]:"";S.startsWith("[LiveLayer]")&&c.current.push({id:an++,ts:Date.now(),kind:M,type:S.slice(0,120),data:{args:_.slice(1).map($=>Xr($))}})}catch{}return N.apply(this,_)};return console.warn=C("warn",v),console.log=C("log",g),()=>{console.warn=v,console.log=g}},[]),!i)return t.jsx("button",{type:"button",onClick:()=>s(!0),title:"Open LiveLayer debug panel (Cmd/Ctrl + Shift + L)","aria-label":"Open LiveLayer debug panel",style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.18)",borderRadius:999,padding:"6px 10px",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",cursor:"pointer",boxShadow:"0 4px 12px rgba(0,0,0,0.35)",opacity:.85},children:"🛰 LL debug"});const b=a.filter(v=>{if(!l)return!0;const g=l.toLowerCase();return v.type.toLowerCase().includes(g)||JSON.stringify(v.data||{}).toLowerCase().includes(g)});return t.jsxs("div",{style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,width:380,maxHeight:"60vh",background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:12,boxShadow:"0 16px 48px rgba(0,0,0,0.5)",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"8px 10px",background:"rgba(255,255,255,0.04)",borderBottom:"1px solid rgba(255,255,255,0.1)",display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontWeight:600,fontSize:12},children:"LiveLayer debug"}),t.jsxs("span",{style:{fontSize:10,color:"rgba(255,255,255,0.4)"},children:[a.length," event",a.length===1?"":"s"]}),t.jsx("span",{style:{flex:1}}),t.jsx("button",{type:"button",onClick:()=>x(v=>!v),style:kt(p?"#f59e0b":"transparent"),title:"Pause / resume capture",children:p?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{d([]),c.current=[]},style:kt("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>s(!1),style:kt("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:l,onChange:v=>u(v.target.value),placeholder:"filter by type or data…",style:{margin:8,padding:"6px 8px",background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:11,outline:"none"}}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"0 8px 8px"},children:b.length===0?t.jsxs("div",{style:{padding:14,fontSize:11,color:"rgba(255,255,255,0.4)",lineHeight:1.5},children:["No events yet. Connect to the agent and trigger a tool call — the events will stream in here. You can also dispatch commands manually in DevTools:",t.jsx("pre",{style:{marginTop:6,background:"rgba(255,255,255,0.04)",padding:6,borderRadius:4,fontSize:10,whiteSpace:"pre-wrap"},children:`window.__livelayerSimulateCommand({
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),n=require("react"),Ct=require("react-dom"),Jn=require("@livelayer/sdk"),ht=require("livekit-client");class ln extends n.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,o){var i,s;(s=(i=this.props).onError)==null||s.call(i,r,o)}render(){var r;return this.state.hasError?this.props.fallback?this.props.fallback:t.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[t.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),t.jsx("p",{className:"ll-error-boundary__message",children:((r=this.state.error)==null?void 0:r.message)||"Something went wrong."}),t.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function cn(e){const[r,o]=n.useState("idle"),[i,s]=n.useState("idle"),[a,d]=n.useState([]),[l,u]=n.useState(null),[f,y]=n.useState(null),[p,c]=n.useState(null),[L,w]=n.useState(!1),[_,x]=n.useState(null),v=n.useRef(null),C=n.useRef(e.onDataMessage);C.current=e.onDataMessage,n.useEffect(()=>{const S={onConnectionStateChange:z=>{o(z),z==="connected"&&x(null)},onAgentStateChange:s,onTranscript:z=>d([...z]),onAgentConfig:u,onAudioTrack:z=>c(z),onVideoTrack:z=>y(z),onVideoTrackRemoved:()=>y(null),onError:z=>x(z),onDataMessage:z=>{var O;(O=C.current)==null||O.call(C,z)},onResumabilityChange:w},$=new Jn.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},S);return v.current=$,o("idle"),s("idle"),d([]),u(null),y(null),c(null),w(!1),x(null),()=>{var z;(z=$.destroy)==null||z.call($),v.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const E=n.useCallback(async()=>{const S=v.current;if(S)try{await S.connect()}catch($){throw x($ instanceof Error?$.message:String($)),$}},[]),N=n.useCallback(()=>{const S=v.current;S&&S.disconnect()},[]),k=n.useCallback(()=>{var S;return((S=v.current)==null?void 0:S.getRoom())??null},[]);return{connectionState:r,agentState:i,transcript:a,agentConfig:l,videoElement:f,audioElement:p,canResume:L,error:_,connect:E,disconnect:N,getRoom:k,session:v.current}}function un(){const e=n.useRef(null),r=n.useRef(null),o=n.useRef(null),i=n.useRef(null),s=n.useRef(new Set),a=n.useRef(null),d=n.useCallback(()=>{const p=r.current;if(!p){i.current=null;return}(!a.current||a.current.length!==p.frequencyBinCount)&&(a.current=new Uint8Array(new ArrayBuffer(p.frequencyBinCount)));const c=a.current;p.getByteFrequencyData(c);let L=0;for(let _=0;_<c.length;_++)L+=c[_];const w=L/c.length/255;for(const _ of s.current)try{_(w)}catch(x){console.error("[useAudioLevel] subscriber threw:",x)}i.current=requestAnimationFrame(d)},[]),l=n.useCallback(()=>{if(e.current||typeof window>"u"||typeof AudioContext>"u")return;const p=new AudioContext,c=p.createAnalyser();c.fftSize=64,c.connect(p.destination),e.current=p,r.current=c},[]),u=n.useCallback(p=>{if(l(),!(!e.current||!r.current)){if(o.current){try{o.current.disconnect()}catch{}o.current=null}try{const c=e.current.createMediaElementSource(p);c.connect(r.current),o.current=c}catch(c){console.warn("[useAudioLevel] createMediaElementSource failed:",c);return}i.current===null&&(i.current=requestAnimationFrame(d))}},[l,d]),f=n.useCallback(()=>{if(i.current!==null&&(cancelAnimationFrame(i.current),i.current=null),o.current){try{o.current.disconnect()}catch{}o.current=null}},[]),y=n.useCallback(p=>(s.current.add(p),()=>{s.current.delete(p)}),[]);return n.useEffect(()=>()=>{if(f(),r.current){try{r.current.disconnect()}catch{}r.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}s.current.clear(),a.current=null},[f]),{attach:u,detach:f,subscribe:y}}function dn(){const[e,r]=n.useState(!1),[o,i]=n.useState(""),[s,a]=n.useState(null),d=n.useRef(null),l=n.useRef(null),u=n.useCallback(async w=>{var _,x;if(d.current&&l.current){try{await l.current.localParticipant.unpublishTrack(d.current)}catch{}d.current.stop(),d.current=null}l.current=w,a(null);try{const v=await ht.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await w.localParticipant.publishTrack(v),d.current=v,r(v.isMuted);const C=(x=(_=v.mediaStreamTrack)==null?void 0:_.getSettings)==null?void 0:x.call(_);C!=null&&C.deviceId&&i(C.deviceId)}catch(v){const C=v instanceof Error&&v.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw a(C),v}},[]),f=n.useCallback(w=>{l.current=w},[]),y=n.useCallback(async w=>{const _=l.current;if(_)try{await _.switchActiveDevice("audioinput",w),i(w)}catch(x){console.warn("[useMicrophoneState] switchDevice failed:",x)}},[]),p=n.useCallback(()=>{const w=d.current,_=l.current;if(w){w.isMuted?(w.unmute(),r(!1)):(w.mute(),r(!0));return}if(_){const x=!e;r(x);try{_.localParticipant.setMicrophoneEnabled(!x)}catch(v){console.warn("[useMicrophoneState] setMicrophoneEnabled failed:",v)}}},[e]),c=n.useCallback(()=>{const w=d.current,_=l.current;if(w&&_){try{_.localParticipant.unpublishTrack(w)}catch{}w.stop()}d.current=null,l.current=null,r(!1),i("")},[]),L=n.useCallback(()=>a(null),[]);return{isMuted:e,activeDeviceId:o,micError:s,toggleMute:p,setupMic:u,attachRoom:f,switchDevice:y,teardownMic:c,clearError:L}}const Xn={resolution:{width:640,height:480,frameRate:24}};function fn(){const[e,r]=n.useState(!1),[o,i]=n.useState(null),[s,a]=n.useState(null),[d,l]=n.useState(""),u=n.useRef(null),f=n.useRef(null),y=n.useCallback(v=>{u.current=v},[]),p=n.useCallback(()=>{var E;const v=u.current,C=f.current;if(C&&v){const N=v.localParticipant.getTrackPublication(ht.Track.Source.Camera),S=(N==null?void 0:N.track)??C;try{v.localParticipant.unpublishTrack(S)}catch{}try{(E=S.stop)==null||E.call(S)}catch{}}f.current=null,a(null),r(!1)},[]),c=n.useCallback(async v=>{const C=u.current;if(C){i(null);try{const E={...Xn};v&&(E.deviceId=v);const N=await ht.createLocalVideoTrack(E);await C.localParticipant.publishTrack(N),f.current=N;const k=N.attach();a(k),r(!0),v&&l(v);try{C.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(E){const N=E instanceof Error&&E.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";i(N)}}},[]),L=n.useCallback(async()=>{e?p():await c(d||void 0)},[e,d,p,c]),w=n.useCallback(async v=>{p(),await c(v)},[p,c]),_=n.useCallback(()=>{p(),u.current=null,i(null),l("")},[p]),x=n.useCallback(()=>i(null),[]);return n.useEffect(()=>()=>{f.current&&f.current.stop()},[]),{isEnabled:e,error:o,previewEl:s,activeDeviceId:d,toggle:L,switchDevice:w,attachRoom:y,teardown:_,clearError:x}}function pn(){const[e,r]=n.useState(!1),[o,i]=n.useState(null),[s,a]=n.useState(null),d=n.useRef(null),l=n.useCallback(c=>{d.current=c},[]),u=n.useCallback(()=>a(null),[]),f=n.useCallback(async()=>{const c=d.current;if(c){if(e){try{await c.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1);return}i(null);try{await c.localParticipant.setScreenShareEnabled(!0);let L=0;const w=()=>{const _=c.localParticipant.getTrackPublication(ht.Track.Source.ScreenShare);if(_!=null&&_.track){const x=_.track.attach();a(x),r(!0);try{c.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}L++<10?setTimeout(w,100):r(!0)};w()}catch(L){const w=L instanceof Error?L.name:"";w!=="NotAllowedError"&&w!=="AbortError"&&i("Screen share unavailable. Try again."),r(!1)}}},[e,u]),y=n.useCallback(()=>{const c=d.current;if(c&&e)try{c.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1),i(null),d.current=null},[e,u]),p=n.useCallback(()=>i(null),[]);return{isEnabled:e,error:o,previewEl:s,toggle:f,attachRoom:l,teardown:y,clearError:p}}function hn(){const[e,r]=n.useState([]),[o,i]=n.useState([]),s=n.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const a=await navigator.mediaDevices.enumerateDevices();r(a.filter(d=>d.kind==="audioinput")),i(a.filter(d=>d.kind==="videoinput"))}catch{}},[]);return n.useEffect(()=>{if(s(),typeof navigator>"u"||!navigator.mediaDevices)return;const a=()=>void s();return navigator.mediaDevices.addEventListener("devicechange",a),()=>navigator.mediaDevices.removeEventListener("devicechange",a)},[s]),{mics:e,cameras:o,refresh:s}}function mn(e,r,o=!1){const[i,s]=n.useState(null),[a,d]=n.useState(null),[l,u]=n.useState(!o&&!!e);return n.useEffect(()=>{if(o||!e){u(!1);return}const f=new AbortController,y=r||"https://app.livelayer.studio";return u(!0),d(null),fetch(`${y}/api/widget/agent/${encodeURIComponent(e)}`,{signal:f.signal}).then(async p=>{if(!p.ok){const c=await p.json().catch(()=>({}));throw new Error(c.error||`HTTP ${p.status}`)}return p.json()}).then(p=>{f.signal.aborted||(s(p),u(!1))}).catch(p=>{f.signal.aborted||(d(p instanceof Error?p.message:"Agent lookup failed"),u(!1))}),()=>f.abort()},[e,r,o]),{info:i,error:a,loading:l}}function Qn(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function Zn(e,r){if(!(typeof window>"u"))try{window.localStorage.setItem(e,r)}catch{}}function gn({value:e,defaultValue:r="expanded",onChange:o}={}){const i=e!==void 0,[s,a]=n.useState(r),d=i?e:s,l=n.useCallback(u=>{u!==d&&(i||a(u),o==null||o(u))},[d,i,o]);return[d,l]}const er=["hidden","minimized","expanded"];function tr(e){return e&&er.includes(e)?e:null}function yn({value:e,defaultValue:r="expanded",onChange:o,persistKey:i="ll-widget",disablePersistence:s=!1}={}){const a=`${i}:display-mode`,d=n.useRef(!1),[l,u]=gn({value:e,defaultValue:r,onChange:f=>{e===void 0&&!s&&Zn(a,f),o==null||o(f)}});return n.useEffect(()=>{if(d.current||(d.current=!0,s||e!==void 0))return;const f=tr(Qn(a));f&&f!==l&&u(f)},[]),[l,u]}const nr=640;function vn(e=nr){const[r,o]=n.useState(!1);return n.useEffect(()=>{if(e===!1){o(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const i=`(max-width: ${e-1}px)`,s=window.matchMedia(i),a=()=>o(s.matches);return a(),typeof s.addEventListener=="function"?(s.addEventListener("change",a),()=>s.removeEventListener("change",a)):(s.addListener(a),()=>{s.removeListener(a)})},[e]),r}const Ft="__llHistoryPatched",mt="ll:pathname";function rr(){if(typeof window>"u"||window.history[Ft])return;const e=window.history.pushState,r=window.history.replaceState;window.history.pushState=function(...o){const i=e.apply(this,o);return window.dispatchEvent(new Event(mt)),i},window.history.replaceState=function(...o){const i=r.apply(this,o);return window.dispatchEvent(new Event(mt)),i},window.history[Ft]=!0}function Ut(){return typeof window>"u"?"/":window.location.pathname||"/"}function xn(e){const[r,o]=n.useState(()=>e??Ut());return n.useEffect(()=>{if(e!==void 0)return;rr();const i=()=>o(Ut());return i(),window.addEventListener("popstate",i),window.addEventListener(mt,i),()=>{window.removeEventListener("popstate",i),window.removeEventListener(mt,i)}},[e]),e??r}const Vt=new Map,or=/[\\^$+?.()|{}[\]]/g;function ir(e){return e.replace(or,"\\$&")}function sr(e){const r=Vt.get(e);if(r)return r;const o=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,i="",s="",a=o.replace(/\*\*/g,i).replace(/\*/g,s),l=ir(a).replace(new RegExp(`\\/${i}`,"g"),"(?:\\/.*)?").replace(new RegExp(i,"g"),".*").replace(new RegExp(s,"g"),"[^/]+"),u=new RegExp(`^${l}\\/?$`);return Vt.set(e,u),u}function ar(e,r){const o=r.length>1&&r.endsWith("/")?r.slice(0,-1):r;return sr(e).test(o)}function bn(e,r){return typeof e=="function"?e(r):e instanceof RegExp?e.test(r):ar(e,r)}function Yt(e,r){if(!e||e.length===0)return!1;for(const o of e)if(bn(o,r))return!0;return!1}function wn(e,r,o){return e===void 0?!0:Yt(o,e)?!1:r&&r.length>0?Yt(r,e):!0}function _n(e,r,o){return n.useMemo(()=>wn(e,r,o),[e,r,o])}function lr(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 cr(e){const r=n.useMemo(()=>lr(e.config),[e.config]),o=e.baseUrl.replace(/\/+$/,""),i=n.useRef(null),s=n.useCallback(u=>{try{new Audio(`${o}${u}`).play().catch(()=>{})}catch{}},[o]),a=n.useCallback(()=>{r.navigate&&s("/audio/page-change-sound.mp3")},[r.navigate,s]),d=n.useCallback(()=>{r.action&&s("/audio/confirmation-sound.mp3")},[r.action,s]),l=n.useCallback(u=>{if(!r.thinking){if(i.current){try{i.current.pause()}catch{}i.current=null}return}if(u){if(i.current)return;try{const f=new Audio(`${o}/audio/thinking-sound.mp3`);f.loop=!0,f.volume=.3,f.play().catch(()=>{i.current=null}),i.current=f}catch{}}else if(i.current){try{i.current.pause()}catch{}i.current=null}},[o,r.thinking]);return n.useEffect(()=>()=>{if(i.current){try{i.current.pause()}catch{}i.current=null}},[]),n.useMemo(()=>({playPageChange:a,playConfirmation:d,setThinking:l}),[a,d,l])}const Gt=({muted:e=!1,className:r})=>e?t.jsxs("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),Kt=({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"})}),ur=({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"})}),dr={left:180,right:0,up:-90,down:90},Jt=({direction:e="right",className:r})=>t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${dr[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function fr(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const kn="ll-hidden-tab-center-y",pr=5,Xt=16;function hr(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(kn);if(!e)return null;const r=Number.parseFloat(e);return Number.isFinite(r)?r:null}catch{return null}}function Qt(e){if(!(typeof window>"u"))try{window.localStorage.setItem(kn,String(e))}catch{}}const mr=({position:e,isMobile:r,isSpeaking:o,onExpand:i,label:s="Open widget",avatarImageUrl:a,agentName:d,containerEl:l})=>{const u=fr(e),f=u==="right"?"left":"right",y=r?80:72,p=!!a,c=!!l,[L,w]=n.useState(null),[_,x]=n.useState(!1),v=n.useRef(null),C=n.useRef(!1),E=n.useCallback(T=>{if(typeof window>"u")return T;const W=y/2,D=Xt+W,F=window.innerHeight-Xt-W;return F<D?Math.max(D,T):Math.max(D,Math.min(F,T))},[y]);n.useEffect(()=>{if(c){w(null);return}const T=hr();w(E(T??window.innerHeight/2));const W=()=>{w(D=>D===null?null:E(D))};return window.addEventListener("resize",W),()=>window.removeEventListener("resize",W)},[E,c]);const N=n.useCallback(T=>{if(!c&&!(T.pointerType==="mouse"&&T.button!==0)&&L!==null){try{T.currentTarget.setPointerCapture(T.pointerId)}catch{}v.current={startClientY:T.clientY,startCenterY:L,moved:!1}}},[L,c]),k=n.useCallback(T=>{const W=v.current;if(!W)return;const D=T.clientY-W.startClientY;!W.moved&&Math.abs(D)>pr&&(W.moved=!0,x(!0)),W.moved&&w(E(W.startCenterY+D))},[E]),S=n.useCallback(T=>{const W=v.current;if(W){try{T.currentTarget.releasePointerCapture(T.pointerId)}catch{}v.current=null,W.moved&&(x(!1),C.current=!0,w(D=>(D!==null&&Qt(D),D)))}},[]),$=n.useCallback(()=>{if(C.current){C.current=!1;return}i()},[i]),z=n.useCallback(T=>{if(T.key==="ArrowUp"||T.key==="ArrowDown"){T.preventDefault();const W=T.key==="ArrowUp"?-8:8;w(D=>{if(D===null)return D;const F=E(D+W);return Qt(F),F})}},[E]),O=["ll-hidden",`ll-hidden--${u}`,r?"ll-hidden--mobile":"ll-hidden--desktop",o?"ll-hidden--speaking":null,_?"is-dragging":null,p?"ll-hidden--with-avatar":null,c?"ll-hidden--scoped":null].filter(Boolean).join(" "),H=L===null?void 0:{top:`${L-y/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:O,onPointerDown:N,onPointerMove:k,onPointerUp:S,onPointerCancel:S,onClick:$,onKeyDown:z,"aria-label":s,"data-position":e,style:H,children:p?t.jsxs(t.Fragment,{children:[t.jsx(Jt,{direction:f,className:"ll-hidden__chevron ll-hidden__chevron--mini"}),t.jsx("img",{src:a,alt:d?`${d} avatar`:"Agent avatar",className:"ll-hidden__avatar",draggable:!1})]}):t.jsx(Jt,{direction:f,className:"ll-hidden__chevron"})})},gr=({audioLevel:e,bars:r=20,maxHeight:o=20,minHeight:i=4,className:s,barClassName:a})=>{const d=n.useRef(null),l=n.useRef([]),u=n.useMemo(()=>{const y=(Math.sqrt(5)-1)/2;return Array.from({length:r},(p,c)=>.5+c*y%1*.5)},[r]);n.useEffect(()=>e.subscribe(p=>{for(let c=0;c<r;c++){const L=l.current[c];if(!L)continue;const w=Math.max(i,p*o*u[c]);L.style.height=`${w}px`}}),[e,r,o,i,u]);const f=["ll-waveform",s].filter(Boolean).join(" ");return t.jsx("div",{ref:d,className:f,"aria-hidden":"true",children:Array.from({length:r},(y,p)=>t.jsx("div",{ref:c=>{l.current[p]=c},className:["ll-waveform__bar",a].filter(Boolean).join(" "),style:{height:`${i}px`}},p))})},yr=({position:e,isMobile:r,agentName:o,avatarImageUrl:i,agentState:s,isMuted:a,audioLevel:d,onExpand:l,onToggleMute:u,onClose:f})=>r?t.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${o} widget`,children:t.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:l,"aria-label":`Expand ${o} widget`,children:[i?t.jsx("img",{src:i,alt:o,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsx(gr,{audioLevel:d,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),t.jsx("span",{className:"ll-minimized__name",children:o}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:y=>{y.stopPropagation(),u()},onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.stopPropagation(),y.preventDefault(),u())},"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(Gt,{muted:a,className:"ll-minimized__icon"})}),t.jsx(Kt,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):t.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":e,role:"region","aria-label":`${o} widget`,children:t.jsxs("div",{className:"ll-minimized__surface",children:[i?t.jsx("img",{src:i,alt:o,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:o}),t.jsx("span",{className:"ll-minimized__state",children:s==="speaking"?"Speaking":s==="thinking"?"Thinking":"Listening"})]}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:u,"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(Gt,{muted:a,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:l,"aria-label":`Expand ${o} widget`,children:t.jsx(Kt,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:f,"aria-label":"Close widget",children:t.jsx(ur,{className:"ll-minimized__icon"})})]})]})}),vr=({src:e,alt:r,preCannedPlaying:o=!1,className:i,style:s})=>{const[a,d]=n.useState(!1),l=n.useRef(e);if(n.useEffect(()=>{l.current!==e&&(l.current=e,d(!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:o?"scale(1.02)":"scale(1)",opacity:a?1:0,...s};return t.jsx("img",{src:e,alt:r,className:i,style:u,loading:"eager",fetchPriority:"high",onLoad:()=>d(!0)})},xr=8,Zt=8,br=({open:e,onClose:r,anchorRef:o,children:i})=>{const s=n.useRef(null),[a,d]=n.useState(null);return n.useLayoutEffect(()=>{if(!e){d(null);return}const l=o.current;if(!l)return;const u=()=>{const f=l.getBoundingClientRect(),y={top:f.top-xr,left:f.left+f.width/2},p=Zt+90,c=window.innerWidth-Zt-90;y.left<p&&(y.left=p),y.left>c&&(y.left=c),d(y)};return u(),window.addEventListener("scroll",u,!0),window.addEventListener("resize",u),()=>{window.removeEventListener("scroll",u,!0),window.removeEventListener("resize",u)}},[e,o]),n.useEffect(()=>{if(!e)return;const l=f=>{const y=f.target,p=s.current,c=o.current;p&&p.contains(y)||c&&c.contains(y)||r()},u=f=>{f.key==="Escape"&&(f.stopPropagation(),r())};return document.addEventListener("mousedown",l),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",l),document.removeEventListener("keydown",u)}},[e,r,o]),!e||a===null||typeof document>"u"?null:Ct.createPortal(t.jsx("div",{ref:s,className:"ll-overflow-popover",role:"menu",style:{position:"fixed",top:a.top,left:a.left,transform:"translate(-50%, -100%)"},children:i}),document.body)},wr=({isMuted:e,onToggleMute:r,isCameraEnabled:o,onToggleCamera:i,allowCamera:s,isScreenShareEnabled:a,onToggleScreenShare:d,allowScreenShare:l,isSpeakerMuted:u,onToggleSpeaker:f,allowTyping:y,isTypingOpen:p,onToggleTyping:c,onDisconnect:L})=>{const[w,_]=n.useState(!1),x=n.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:r,"aria-label":e?"Unmute microphone":"Mute microphone",children:t.jsx(Ln,{muted:e})}),t.jsx("button",{ref:x,type:"button",className:`ll-tool ${w?"is-on":""}`,onClick:()=>_(v=>!v),"aria-label":"More controls","aria-haspopup":"menu","aria-expanded":w,children:t.jsx(_r,{})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:L,"aria-label":"End conversation",children:t.jsx(En,{})})]}),t.jsxs(br,{open:w,onClose:()=>_(!1),anchorRef:x,children:[s&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${o?"is-on":""}`,onClick:()=>{i(),_(!1)},children:[t.jsx(Cn,{}),t.jsx("span",{children:o?"Stop camera":"Start camera"})]}),l&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${a?"is-on":""}`,onClick:()=>{d(),_(!1)},children:[t.jsx(jn,{}),t.jsx("span",{children:a?"Stop sharing":"Share screen"})]}),t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${u?"is-on":""}`,onClick:()=>{f(),_(!1)},children:[t.jsx(Sn,{muted:u}),t.jsx("span",{children:u?"Unmute speaker":"Mute speaker"})]}),y&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${p?"is-on":""}`,onClick:()=>{c(),_(!1)},children:[t.jsx(kr,{}),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 kr(){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 jr=({position:e,isMobile:r,agentName:o,avatarImageUrl:i,idleLoopUrl:s,greeting:a,branding:d,teamMembers:l,currentTeamMemberId:u,isSwitchingTeamMember:f,teamSwitcherOpen:y,onToggleTeamSwitcher:p,onSelectTeamMember:c,languageMenuOpen:L,onToggleLanguageMenu:w,connectionState:_,agentState:x,transcript:v,canResume:C,needsUserGesture:E,error:N,isMuted:k,micError:S,micDevices:$,activeMicId:z,isCameraEnabled:O,cameraPreviewEl:H,cameraDevices:T,activeCameraId:W,isScreenShareEnabled:D,screenPreviewEl:F,isSpeakerMuted:ne,allowCamera:le,allowScreenShare:pe,allowTyping:ce,showMinimize:he=!0,chromeless:ue=!1,compactControls:Q=!1,transforming:ot,transformingLabel:Be,avatarVideoContainerRef:it,agentVideoEl:re,onConnect:qe,onDisconnect:Fe,onRetry:st,onResumeAudio:Ue,onToggleMute:_e,onSwitchMicDevice:Ae,onToggleCamera:ke,onSwitchCameraDevice:Me,onToggleScreenShare:je,onToggleSpeaker:Ce,onSendMessage:Le,onMinimize:A,onClose:at,onClearMicError:yt})=>{var Ne;const Se=((l==null?void 0:l.length)??0)>1,Ee=_==="connecting"||_==="connected",Z=_==="connected",Ve=_==="idle"||_==="disconnected"||_==="error",[Ye,Ie]=n.useState(!1);n.useEffect(()=>{if(!re){Ie(!1);return}if(!re.paused&&re.readyState>=2){Ie(!0);return}Ie(!1);const m=()=>Ie(!0);return re.addEventListener("playing",m),re.addEventListener("loadeddata",m),()=>{re.removeEventListener("playing",m),re.removeEventListener("loadeddata",m)}},[re]);const[Re,J]=n.useState(!1);n.useEffect(()=>{if(!Z){J(!1);return}if(Ye)return;const m=setTimeout(()=>J(!0),8e3);return()=>clearTimeout(m)},[Z,Ye]);const lt=_==="connecting"||Z&&!!i&&!Ye&&!Re,Ge=n.useRef(null),ee=n.useRef(null);n.useEffect(()=>{const m=Ge.current;m&&(m.innerHTML="",H&&(H.style.width="100%",H.style.height="100%",H.style.objectFit="cover",H.style.transform="scaleX(-1)",m.appendChild(H)))},[H]),n.useEffect(()=>{const m=ee.current;m&&(m.innerHTML="",F&&(F.style.width="100%",F.style.height="100%",F.style.objectFit="contain",m.appendChild(F)))},[F]);const[te,ie]=n.useState(!1),[me,Y]=n.useState(!1),se=n.useRef(null),ge=n.useRef(null);n.useEffect(()=>{if(!te&&!me&&!L&&!y)return;const m=()=>{ie(!1),Y(!1),L&&w(),y&&p()};return document.addEventListener("click",m),()=>document.removeEventListener("click",m)},[te,me,L,y,w,p]);const[Te,vt]=n.useState(!1),Ke=n.useCallback(()=>vt(m=>!m),[]),[ye,Je]=n.useState(""),Xe=n.useCallback(m=>{m.preventDefault();const U=ye.trim();U&&(Le(U),Je(""))},[ye,Le]),Qe=d.productName||"Live Layer";let ve=null,xe=null;for(let m=v.length-1;m>=0;m--){const U=v[m];if(!ve&&U.role==="agent"?ve=U:!xe&&U.role==="user"&&(xe=U),ve&&xe)break}const De=Z?(ve==null?void 0:ve.text)||null:a||null,ct=Z&&(xe==null?void 0:xe.text)||null,Pe=["ll-expanded",r?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:Pe,"data-position":e,"data-state":Z?"connected":Ee?"connecting":"idle",role:"dialog","aria-label":`${o} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[i?t.jsx(vr,{src:i,alt:o,className:"ll-expanded__bg-img"}):t.jsx("div",{className:"ll-expanded__bg-fallback",children:t.jsx("span",{className:"ll-expanded__bg-initial",children:((Ne=o==null?void 0:o.charAt(0))==null?void 0:Ne.toUpperCase())||"A"})}),s&&!Z&&t.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:it,className:"ll-expanded__video"}),lt&&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:f?"Switching...":"Connecting..."})]}),E&&Z&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:Ue,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"})]}),ot&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--transforming",role:"status","aria-live":"polite","aria-label":Be,children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:Be})]}),Ee?t.jsxs(t.Fragment,{children:[!Q&&t.jsxs("div",{className:"ll-expanded__topbar",children:[!ue&&t.jsxs("div",{className:"ll-expanded__topbar-left",children:[t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill",onClick:m=>{Se&&(m.stopPropagation(),p())},"aria-haspopup":Se?"listbox":void 0,"aria-expanded":Se?y:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:o}),Se&&t.jsx(dt,{})]}),Se&&y&&t.jsx("div",{className:"ll-hmenu",onClick:m=>m.stopPropagation(),role:"listbox",children:l==null?void 0:l.map(m=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${m.id===u?"is-active":""}`,onClick:()=>c(m.id),role:"option","aria-selected":m.id===u,children:[m.avatarImageUrl&&t.jsx("img",{src:m.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:m.name}),m.role&&t.jsx("span",{className:"ll-hmenu__role",children:m.role})]},m.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:m=>{m.stopPropagation(),w()},"aria-haspopup":"listbox","aria-expanded":L,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(dt,{})]}),L&&t.jsx("div",{className:"ll-hmenu",onClick:m=>m.stopPropagation(),role:"listbox",children:t.jsx("button",{type:"button",className:"ll-hmenu__item is-active",role:"option","aria-selected":!0,children:t.jsx("span",{className:"ll-hmenu__name",children:"English"})})})]}),t.jsx("span",{className:`ll-expanded__state ll-expanded__state--${x}`,children:x})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[he!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn",onClick:A,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(tn,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:at,"aria-label":"End call",title:"End call",children:t.jsx(en,{})})]})]}),Q&&t.jsxs("div",{className:"ll-compact-status","data-state":x,children:[t.jsx("span",{className:"ll-compact-status__dot","aria-hidden":!0}),t.jsx("span",{className:"ll-compact-status__label",children:x})]})]}):!Q&&t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:Qe}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[he!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:A,"aria-label":"Minimize widget",children:t.jsx(tn,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:at,"aria-label":"Close widget",children:t.jsx(en,{})})]})]}),Ve&&(()=>{const m=C?"Resume session":_==="disconnected"?"Reconnect to agent":"Start video call",U=!N;return t.jsxs(t.Fragment,{children:[U&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:qe,"aria-label":m,children:[t.jsx("div",{className:"ll-expanded__play-circle",children:t.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("polygon",{points:"6 3 20 12 6 21 6 3"})})}),Q&&t.jsx("span",{className:"ll-expanded__play-label",children:m})]}),!Q&&t.jsxs("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:[a&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:a})}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:qe,"aria-label":m,children:m})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${Ee&&(O||D)?"is-visible":""}`,children:[t.jsx("div",{ref:ee,className:D?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:Ge,className:!D&&O?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),Ee?t.jsxs("div",{className:"ll-expanded__bottom",children:[!Q&&De&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--agent","data-role":"agent",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:De})}),!Q&&ct&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--user","data-role":"user",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:ct})}),!ue&&!Q&&t.jsxs("div",{className:"ll-toolbar",onClick:m=>m.stopPropagation(),children:[pe&&t.jsx("button",{type:"button",className:`ll-tool ${D?"is-on":""}`,onClick:je,"aria-label":D?"Stop sharing screen":"Share screen",title:D?"Stop sharing":"Share screen",children:t.jsx(jn,{})}),le&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${O?"is-on":""}`,onClick:ke,"aria-label":O?"Turn off camera":"Turn on camera",title:O?"Stop camera":"Start camera",children:t.jsx(Cn,{})}),t.jsx("button",{ref:ge,type:"button",className:`ll-tool ll-tool--right ${O?"is-on":""}`,onClick:m=>{m.stopPropagation(),Y(U=>!U),ie(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":me,children:t.jsx(dt,{})}),me&&T.length>0&&t.jsx(nn,{label:"Camera",devices:T,activeId:W,anchorRef:ge,onPick:m=>{Y(!1),Me(m)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${k?"is-muted":""}`,onClick:_e,"aria-label":k?"Unmute microphone":"Mute microphone",title:k?"Unmute":"Mute",children:t.jsx(Ln,{muted:k})}),t.jsx("button",{ref:se,type:"button",className:`ll-tool ll-tool--right ${k?"is-muted":""}`,onClick:m=>{m.stopPropagation(),ie(U=>!U),Y(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":te,children:t.jsx(dt,{})}),te&&$.length>0&&t.jsx(nn,{label:"Microphone",devices:$,activeId:z,anchorRef:se,onPick:m=>{ie(!1),Ae(m)}})]}),t.jsx("button",{type:"button",className:`ll-tool ${ne?"is-muted":""}`,onClick:Ce,"aria-label":ne?"Unmute speaker":"Mute speaker",title:ne?"Unmute speaker":"Mute speaker",children:t.jsx(Sn,{muted:ne})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:Fe,"aria-label":"End conversation",title:"End conversation",children:t.jsx(En,{})})]}),!ue&&Q&&t.jsx(wr,{isMuted:k,onToggleMute:_e,isCameraEnabled:O,onToggleCamera:ke,allowCamera:le,isScreenShareEnabled:D,onToggleScreenShare:je,allowScreenShare:pe,isSpeakerMuted:ne,onToggleSpeaker:Ce,allowTyping:ce,isTypingOpen:Te,onToggleTyping:Ke,onDisconnect:Fe}),!ue&&ce&&(Q?Te:!0)&&t.jsxs("form",{className:"ll-message-input",onSubmit:Xe,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:ye,onChange:m=>Je(m.target.value),"aria-label":"Message the agent"}),ye.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(Cr,{})})]})]}):null,(()=>{if(S&&_!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:S}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:yt,"aria-label":"Dismiss",children:"×"})]});if(!N||_!=="error")return null;let m="Failed to connect",U="Try again";return N==="MIC_PERMISSION_DENIED"?m="Microphone blocked. Allow access to talk.":N==="MIC_NOT_FOUND"?m="No microphone found. Plug one in + retry.":N==="MIC_UNAVAILABLE"?m="Mic unavailable. Check other apps using it.":N==="AGENT_TIMEOUT"?m="Agent didn't pick up. Try again.":N==="CONNECT_FAILED"?m="Connection failed. Check your network.":N.length<80&&(m=N),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:m}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:st,children:U})]})})()]})};function dt(){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 en(){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 tn(){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 jn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("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 Cn(){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 Ln({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 Sn({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 Cr(){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 En(){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 nn=({label:e,devices:r,activeId:o,onPick:i,anchorRef:s})=>{const[a,d]=n.useState(null);return n.useLayoutEffect(()=>{const l=()=>{const u=s.current;if(!u)return;const f=u.getBoundingClientRect(),y=126,p=window.innerWidth-16-110,c=f.left+f.width/2;d({top:f.top-8,left:Math.max(y,Math.min(p,c))})};return l(),window.addEventListener("scroll",l,!0),window.addEventListener("resize",l),()=>{window.removeEventListener("scroll",l,!0),window.removeEventListener("resize",l)}},[s]),a===null||typeof document>"u"?null:Ct.createPortal(t.jsxs("div",{className:"ll-device-menu ll-device-menu--floating",onClick:l=>l.stopPropagation(),role:"listbox",style:{position:"fixed",top:a.top,left:a.left,transform:"translate(-50%, -100%)"},children:[t.jsx("p",{className:"ll-device-menu__label",children:e}),r.map((l,u)=>{const f=o===l.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${f?"is-active":""}`,onClick:()=>i(l.deviceId),role:"option","aria-selected":f,children:[f&&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)},Lr=['[data-ll-private="true"]',".ll-widget"];function Lt(e){let r=e;for(;r;){for(const o of Lr)if(r.matches(o))return!0;r=r.parentElement}return!1}function gt(e){if(Lt(e))return!1;if(e instanceof HTMLInputElement){if(e.type==="password")return!1;const r=(e.getAttribute("autocomplete")||"").toLowerCase();if(r==="off"||r.startsWith("cc-"))return!1}return!0}const ft=4096,Sr=20,Er=20,Rr=10,Nr=10,Ar=30,Mr=20,rn=500,Ir=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function nt(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let r=e;for(;r;){for(const o of Ir)if(r.matches(o))return!0;r=r.parentElement}return!1}function rt(e){if(typeof window>"u")return!0;const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return!1;const o=window.innerHeight||document.documentElement.clientHeight,i=window.innerWidth||document.documentElement.clientWidth;return r.bottom>0&&r.right>0&&r.top<o&&r.left<i}function on(e){const r=e.getAttribute("id");if(r){const a=document.querySelector(`label[for="${CSS.escape(r)}"]`);if(a!=null&&a.textContent)return a.textContent.trim()}const o=e.getAttribute("aria-label");if(o)return o.trim();const i=e.getAttribute("placeholder");if(i)return i.trim();const s=e.closest("label");return s!=null&&s.textContent?s.textContent.trim():""}function fe(e,r){return e.length<=r?e:e.slice(0,r-1)+"…"}function Oe(e){return e.length}function Rn(e,r={}){const o=r.doc??(typeof document<"u"?document:null);if(!o)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:e};const i=typeof window<"u"&&window.location.href||"",s=typeof window<"u"&&window.location.pathname||"/",a=o.title||"",d=Array.from(o.querySelectorAll("[data-ll-region]")),l=[];for(const k of d){if(l.length>=Rr)break;if(nt(k)||!rt(k))continue;const S=k.getAttribute("data-ll-region")??"",$=k.getAttribute("data-ll-intent")??void 0,z=fe((k.innerText||k.textContent||"").trim(),rn*2);!S||!z||l.push({id:S,intent:$,text:z})}const u=[],f=["H1","H2","H3","H4","H5","H6"],y=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const k of y){if(nt(k)||!rt(k))continue;const S=(k.textContent||"").trim();S&&u.push(`${k.tagName}: ${fe(S,200)}`)}const p=Array.from(o.querySelectorAll("p, li"));for(const k of p){if(nt(k)||!rt(k)||f.includes(k.tagName))continue;const S=(k.textContent||"").trim();S.length>10&&u.push(fe(S,rn))}const c=u.join(`
2
+ `),L=[],w=Array.from(o.querySelectorAll("a[href]"));for(const k of w){if(L.length>=Sr)break;if(nt(k)||!rt(k))continue;const S=k.getAttribute("href")||"",$=(k.textContent||"").trim();!S||!$||L.push({href:S,text:fe($,100)})}const _=[],x=Array.from(o.querySelectorAll("input, textarea, select"));for(const k of x){if(_.length>=Er)break;if(nt(k)||!gt(k)||!rt(k))continue;const S=on(k),$=k instanceof HTMLInputElement?k.type:k.tagName.toLowerCase();S&&_.push({label:fe(S,100),type:$})}const v=Array.from(o.querySelectorAll("[data-ll-form]")),C=[];for(const k of v){if(C.length>=Nr)break;if(Lt(k))continue;const S=k.getAttribute("data-ll-form")||"";if(!S)continue;const $=k.getAttribute("data-ll-intent")||void 0,z=Array.from(k.querySelectorAll("[data-ll-field]")),O=[];for(const H of z){if(O.length>=Ar)break;if(!gt(H))continue;const T=H.getAttribute("data-ll-field")||"";if(!T)continue;const W=on(H)||T,D=H instanceof HTMLInputElement?H.type:H.tagName.toLowerCase(),F={name:T,label:fe(W,100),type:D};if(H.required===!0&&(F.required=!0),H instanceof HTMLSelectElement){const le=[];for(let pe=0;pe<H.options.length&&!(le.length>=Mr);pe++){const ce=H.options[pe];if(!ce||ce.disabled)continue;const he=ce.value||"",ue=(ce.textContent||"").trim()||he;!he&&!ue||le.push({value:he,label:fe(ue,60)})}le.length>0&&(F.options=le)}const ne=typeof H.validationMessage=="string"?H.validationMessage:"";ne&&(F.validationMessage=fe(ne,200)),O.push(F)}C.push({id:S,intent:$,fields:O})}const E={url:i,title:a,pathname:s,regions:l,visibleText:c,visibleLinks:L,visibleFields:_,forms:C,extras:e};let N=Oe(JSON.stringify(E.regions))+Oe(E.visibleText)+Oe(JSON.stringify(E.visibleLinks))+Oe(JSON.stringify(E.visibleFields));for(;N>ft&&E.visibleFields.length>0;)E.visibleFields.pop(),N=Oe(JSON.stringify(E.visibleFields));for(;N>ft&&E.visibleLinks.length>0;)E.visibleLinks.pop(),N-=80;return Oe(E.visibleText)>ft&&(E.visibleText=fe(E.visibleText,ft-100)),E}let He=null;function jt(e,r={}){const o=Date.now(),s=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(He&&He.key===s&&o-He.at<1e3)return He.ctx;const a=Rn(e,r);return He={key:s,at:o,ctx:a},a}function Nn(){He=null}const Tr=200;function An(e){const r=String(e.href||"");return{href:r,text:String(e.text??e.title??r),internal:e.internal??!0,title:e.title,description:e.description}}function Dr(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function Mn(e){const r=e??(typeof document<"u"?document:null);if(!r)return[];const o=typeof window<"u"&&window.location.origin||"",i=new Set,s=[],a=Array.from(r.querySelectorAll("a[href]"));for(const d of a){if(s.length>=Tr)break;if(Lt(d))continue;const l=d.getAttribute("href")||"";if(!Dr(l))continue;let u=l,f=!0;try{if(typeof window<"u"){const p=new URL(l,o);f=p.origin===o,f&&l.startsWith("http")&&(u=p.pathname+p.search+p.hash)}}catch{continue}if(i.has(u))continue;i.add(u);const y=(d.textContent||"").trim().slice(0,120);s.push({href:u,text:y,internal:f})}return s}let We=null;const Pr=5e3;function pt(){const e=Date.now(),r=typeof window<"u"&&window.location.pathname||"/";if(We&&We.pathname===r&&e-We.at<Pr)return We.routes;const o=Mn();return We={at:e,pathname:r,routes:o},o}function In(){We=null}function $r(e,r){const o=e instanceof HTMLInputElement?HTMLInputElement.prototype:e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLSelectElement.prototype,i=Object.getOwnPropertyDescriptor(o,"value"),s=i==null?void 0:i.set;s?s.call(e,r):e.value=r}function zr(e,r,o={}){const i=o.triggerInput??!0,s=o.triggerChange??!0;if(e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")){const a=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"),d=a==null?void 0:a.set,l=r==="true"||r==="1"||r==="on";d?d.call(e,l):e.checked=l,i&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}$r(e,r),i&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}))}function Or(){if(typeof window>"u"||typeof document>"u")return!1;const e=document.scrollingElement||document.documentElement;if(!e||e.scrollHeight<=e.clientHeight+2)return!1;const r=window.getComputedStyle(e);return!(r.overflowY==="hidden"||r.overflowY==="clip")}function Hr(e){if(!(e instanceof HTMLElement))return!1;const o=window.getComputedStyle(e).overflowY;return!(o!=="auto"&&o!=="scroll"||e.scrollHeight<=e.clientHeight+2)}function Wr(){if(typeof document>"u")return null;const e=Array.from(document.querySelectorAll("body, body *"));let r=null,o=0;for(const i of e){if(!Hr(i))continue;const s=i.getBoundingClientRect();if(s.bottom<=0||s.top>=window.innerHeight||s.right<=0||s.left>=window.innerWidth||s.width<=0||s.height<=0||i.closest(".ll-widget"))continue;const a=s.width*s.height;a>o&&(o=a,r=i)}return r}function Br(){if(typeof window>"u")return null;if(Or())return window;const e=Wr();return e||window}function sn(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function qr(e){var r,o;return e instanceof Window?typeof document>"u"?0:Math.max(((r=document.body)==null?void 0:r.scrollHeight)??0,((o=document.documentElement)==null?void 0:o.scrollHeight)??0):e.scrollHeight-e.clientHeight}const Fr=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"]),Tn=n.forwardRef(function(r,o){var $t,zt,Ot,Ht,Wt,Bt,qt;const{agentId:i,apiKey:s,baseUrl:a="https://app.livelayer.studio",sessionEndpoint:d,sessionBody:l,soundEffects:u,experienceMode:f="WIDGET",autoConnect:y=!1,displayMode:p,defaultDisplayMode:c="expanded",onDisplayModeChange:L,position:w="bottom-right",mobileBreakpoint:_=640,persistKey:x="ll-widget",disablePersistence:v=!1,teamMembers:C,currentTeamMemberId:E,onTeamMemberChange:N,idleLoopUrl:k,greeting:S,avatarImageUrl:$,agentName:z,branding:O={},allowCamera:H=!0,allowScreenShare:T=!0,allowTyping:W=!0,showMinimize:D=!0,chromeless:F=!1,floatingChromeContainer:ne=null,compactControls:le=!1,transforming:pe=!1,transformingLabel:ce="Transforming…",showOn:he,hideOn:ue,pathname:Q,onNavigate:ot,onScrollToSelector:Be,getPageContext:it,pageContextExtras:re,getRoutes:qe,onScrollPage:Fe,onClick:st,capabilities:Ue,onConnect:_e,onDisconnect:Ae,onTranscript:ke,onAgentState:Me,onConnectionStateChange:je,onAgentEvent:Ce,onAgentCommand:Le,controlledSession:A,className:at,style:yt,zIndex:Se=2147483647}=r,Ee=xn(Q),Z=_n(Ee,he,ue);n.useEffect(()=>{Nn(),In()},[Ee]);const Ve=E!==void 0,[Ye,Ie]=n.useState(()=>{var g;return E??((g=C==null?void 0:C[0])==null?void 0:g.id)}),Re=Ve?E:Ye,J=n.useMemo(()=>(C==null?void 0:C.find(g=>g.id===Re))??null,[C,Re]),lt=(J==null?void 0:J.agentId)??i,Ge=f==="EMBEDDED",[ee,te]=yn({value:p,defaultValue:c,onChange:L,persistKey:x,disablePersistence:Ge||v}),ie=vn(_),me=un(),Y=dn(),se=fn(),ge=pn(),Te=hn(),[vt,Ke]=n.useState(!1),[ye,Je]=n.useState(!1),[Xe,Qe]=n.useState(!1),[ve,xe]=n.useState(!1),[De,ct]=n.useState(!1),Pe=cr({baseUrl:a,config:u}),Ne=n.useRef(Pe);Ne.current=Pe;const m=n.useRef(ot),U=n.useRef(Be),xt=n.useRef(Fe),bt=n.useRef(st),St=n.useRef(it),Et=n.useRef(re),Rt=n.useRef(qe),wt=n.useRef(Ue),ae=n.useRef(null);m.current=ot,U.current=Be,xt.current=Fe,bt.current=st,St.current=it,Et.current=re,Rt.current=qe,wt.current=Ue;function be(g){const h=wt.current;return h?h.includes(g):!0}function we(g,h){console.warn(`[LiveLayer] Agent command "${g}" blocked — capability "${h}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const Ze=n.useCallback(g=>{var V,oe,de,tt;const h=g;if(!(!h.type||typeof h.type!="string")){if(Ce==null||Ce({eventName:h.type,data:g}),h.type==="navigate"){if(!be("navigate")){we("navigate","navigate");return}const j=typeof h.href=="string"?h.href:null;if(!j){console.warn(`[LiveLayer] Agent emitted "navigate" without href. Skipping. Check your agent's tool schema. See https://livelayer.studio/docs/errors/navigate-missing-href`);return}if(Ne.current.playPageChange(),m.current){try{m.current(j)}catch(R){console.warn(`[LiveLayer] onNavigate threw for "${j}". Falling back. Error:`,R)}return}if(typeof document<"u"){const R=document.querySelector(`a[href="${j.replace(/"/g,'\\"')}"]`);if(R){R.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",j),window.dispatchEvent(new PopStateEvent("popstate"))}catch(R){console.warn(`[LiveLayer] history.pushState fallback failed for "${j}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,R)}return}if(h.type==="scroll_to"){if(!be("scroll")){we("scroll_to","scroll");return}const j=typeof h.selector=="string"?h.selector:null;if(!j)return;const R=h.behavior==="instant"?"instant":"smooth";if(U.current){try{U.current(j,R)}catch(P){console.warn("[LiveLayer] onScrollToSelector threw.",P)}return}if(typeof document<"u"){let P=null;try{P=document.querySelector(j)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${j}".`);return}if(!P){console.warn(`[LiveLayer] scroll_to: no element matched "${j}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}P.scrollIntoView({behavior:R,block:"start"})}return}if(h.type==="request_page_context"){if(!be("read_page")){we("request_page_context","read_page");return}const j=typeof h.requestId=="string"?h.requestId:void 0,R=(V=ae.current)==null?void 0:V.call(ae),P=q=>{const M=R,K=M==null?void 0:M.localParticipant;if(K!=null&&K.publishData)try{const X=j?{...q,requestId:j}:q,ze=new TextEncoder().encode(JSON.stringify(X));K.publishData(ze,{reliable:!0})}catch(X){console.warn("[LiveLayer] publishData failed.",X)}},I=Et.current,B=St.current;try{if(B){const q=B(I);if(q instanceof Promise){P({type:"page_context_pending"}),q.then(M=>P({type:"page_context",context:M})).catch(M=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",M),P({type:"page_context",context:jt(I)})});return}P({type:"page_context",context:q});return}P({type:"page_context",context:jt(I)})}catch(q){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",q),P({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:I}})}return}if(h.type==="scroll_page"){if(!be("scroll")){we("scroll_page","scroll");return}const j=h.direction;if(j!=="up"&&j!=="down"&&j!=="top"&&j!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(j)}". Expected up | down | top | bottom.`);return}const R=h.behavior==="instant"?"instant":"smooth";if(xt.current){try{xt.current(j,R)}catch(M){console.warn("[LiveLayer] onScrollPage threw.",M)}return}if(typeof window>"u")return;const P={behavior:R},I=Br(),B=M=>{I instanceof Window?I.scrollBy({top:M,...P}):I.scrollBy({top:M,...P})},q=M=>{I instanceof Window?I.scrollTo({top:M,...P}):I.scrollTo({top:M,...P})};j==="up"?B(-sn(I)):j==="down"?B(sn(I)):q(j==="top"?0:qr(I));return}if(h.type==="click"){if(!be("click")){we("click","click");return}const j=typeof h.selector=="string"?h.selector:null;if(!j){console.warn("[LiveLayer] click: missing selector.");return}if(bt.current){try{bt.current(j)}catch(P){console.warn("[LiveLayer] onClick threw.",P)}return}if(typeof document>"u")return;let R=null;try{R=document.querySelector(j)}catch{console.warn(`[LiveLayer] click: invalid selector "${j}".`);return}if(!R){console.warn(`[LiveLayer] click: no element matched "${j}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(R.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(oe=R.click)==null||oe.call(R);return}if(h.type==="fill_form"||h.type==="focus_field"){if(!be("fill_forms")){we(h.type,"fill_forms");return}if(typeof document>"u")return;h.type==="fill_form"&&Ne.current.playConfirmation();const j=typeof h.formId=="string"?h.formId:null;if(!j){console.warn(`[LiveLayer] ${h.type}: missing formId.`);return}const R=document.querySelector(`[data-ll-form="${j.replace(/"/g,'\\"')}"]`);if(!R){console.warn(`[LiveLayer] ${h.type}: no form with data-ll-form="${j}". Tag your form with <LiveLayerForm id> or data-ll-form. See https://livelayer.studio/docs/react/forms`);return}if(R.closest('[data-ll-private="true"], .ll-widget')){console.warn(`[LiveLayer] ${h.type}: refusing to touch a form in a private subtree.`);return}if(h.type==="focus_field"){const I=typeof h.fieldName=="string"?h.fieldName:null;if(!I){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const B=R.querySelector(`[data-ll-field="${I.replace(/"/g,'\\"')}"]`);if(!B){console.warn(`[LiveLayer] focus_field: no field "${I}" in form "${j}".`);return}if(!gt(B)){console.warn(`[LiveLayer] focus_field: field "${I}" is privacy-protected and not focusable.`);return}B.focus();return}const P=h.values&&typeof h.values=="object"?h.values:null;if(!P){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[I,B]of Object.entries(P)){if(typeof B!="string")continue;const q=R.querySelector(`[data-ll-field="${I.replace(/"/g,'\\"')}"]`);if(!q){console.warn(`[LiveLayer] fill_form: no field "${I}" in form "${j}". Skipping.`);continue}if(!gt(q)){console.warn(`[LiveLayer] fill_form: field "${I}" is privacy-protected (password / cc-* / private). Skipping.`);continue}try{zr(q,B)}catch(M){console.warn(`[LiveLayer] fill_form: failed to set "${I}".`,M)}}return}if(h.type==="submit_form"){if(!be("submit_forms")){we("submit_form","submit_forms");return}if(typeof document>"u")return;const j=typeof h.formId=="string"?h.formId:null;if(!j){console.warn("[LiveLayer] submit_form: missing formId.");return}Ne.current.playConfirmation();const R=document.querySelector(`[data-ll-form="${j.replace(/"/g,'\\"')}"]`);if(!R){console.warn(`[LiveLayer] submit_form: no form with data-ll-form="${j}".`);return}if(R.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] submit_form: refusing to submit a form in a private subtree.");return}const P=typeof h.requestId=="string"?h.requestId:void 0,I=(de=ae.current)==null?void 0:de.call(ae),B=K=>{const X=I,ze=X==null?void 0:X.localParticipant;if(ze!=null&&ze.publishData)try{const Gn=P?{...K,requestId:P}:K,Kn=new TextEncoder().encode(JSON.stringify(Gn));ze.publishData(Kn,{reliable:!0})}catch{}};let q=!1;const M=()=>{q=!0,B({type:"form_submitted",formId:j})};R.addEventListener("submit",M,{once:!0});try{typeof R.requestSubmit=="function"?R.requestSubmit():R.submit()}catch(K){console.warn("[LiveLayer] submit_form: requestSubmit threw.",K),R.removeEventListener("submit",M),B({type:"form_submit_blocked",formId:j,reason:"exception"});return}setTimeout(()=>{q||(R.removeEventListener("submit",M),B({type:"form_submit_blocked",formId:j,reason:"validation"}))},500);return}if(h.type==="request_routes"){if(!be("read_page")){we("request_routes","read_page");return}const j=typeof h.requestId=="string"?h.requestId:void 0,P=(tt=ae.current)==null?void 0:tt.call(ae),I=P==null?void 0:P.localParticipant;if(!(I!=null&&I.publishData))return;const B=M=>{try{const K=j?{type:"routes",routes:M,requestId:j}:{type:"routes",routes:M},X=new TextEncoder().encode(JSON.stringify(K));I.publishData(X,{reliable:!0})}catch(K){console.warn("[LiveLayer] request_routes: publishData failed.",K)}},q=Rt.current;if(q){try{const M=q(),K=X=>{if(!Array.isArray(X)){B([]);return}B(X.map(An).slice(0,200))};M instanceof Promise?M.then(K).catch(X=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",X),B(pt())}):K(M)}catch(M){console.warn("[LiveLayer] getRoutes threw; falling back to DOM walker.",M),B(pt())}return}try{B(pt())}catch(M){console.warn("[LiveLayer] request_routes: extractRoutes threw.",M)}return}Fr.has(h.type)||Le==null||Le(h)}},[Le,Ce]),G=cn({agentId:A?"__controlled__":lt,baseUrl:a,apiKey:s,sessionEndpoint:d,sessionBody:l,onDataMessage:A?void 0:Ze});n.useEffect(()=>{if(A!=null&&A.subscribeToDataMessages)return A.subscribeToDataMessages(Ze)},[A,Ze]),ae.current=()=>{var g;return(g=G.getRoom)==null?void 0:g.call(G)},n.useEffect(()=>{var V;if(typeof window>"u")return;const g=((V=window.location)==null?void 0:V.hostname)||"";if(g==="localhost"||g==="127.0.0.1"||g==="0.0.0.0"||g.endsWith(".local")||g.endsWith(".test"))return window.__livelayerSimulateCommand=oe=>{try{Ze(oe)}catch(de){console.warn("[LiveLayer] simulate-command threw:",de)}},()=>{delete window.__livelayerSimulateCommand}},[Ze]);const b=n.useMemo(()=>A?{connectionState:A.connectionState,agentState:A.agentState,transcript:A.transcript,videoElement:A.videoElement,audioElement:A.audioElement,canResume:A.canResume,error:A.error,agentConfig:null,connect:async()=>{await A.onConnect()},disconnect:()=>A.onDisconnect(),getRoom:G.getRoom,isControlled:!0}:{connectionState:G.connectionState,agentState:G.agentState,transcript:G.transcript,videoElement:G.videoElement,audioElement:G.audioElement,canResume:G.canResume,error:G.error,agentConfig:G.agentConfig,connect:G.connect,disconnect:G.disconnect,getRoom:G.getRoom,isControlled:!1},[A,G]),Nt=n.useRef(b);Nt.current=b;const At=n.useRef(A);At.current=A,n.useImperativeHandle(o,()=>({sendData:async g=>{var de,tt;const h=At.current;if(h!=null&&h.publishData){try{await h.publishData(g)}catch(j){console.warn("[AvatarWidget] sendData (controlled) failed:",j)}return}const V=(tt=(de=Nt.current)==null?void 0:de.getRoom)==null?void 0:tt.call(de),oe=V==null?void 0:V.localParticipant;if(oe!=null&&oe.publishData)try{const j=new TextEncoder().encode(JSON.stringify(g));await oe.publishData(j,{reliable:!0})}catch(j){console.warn("[AvatarWidget] sendData failed:",j)}}}),[]);const Mt=n.useRef(null);n.useEffect(()=>{const g=b.videoElement,h=Mt.current;if(!(!g||!h))return h.appendChild(g),()=>{g.parentNode===h&&h.removeChild(g)}},[b.videoElement]),n.useEffect(()=>{const g=b.audioElement;if(!g)return;me.attach(g);const h=g.play();return h&&typeof h.catch=="function"&&h.catch(V=>{(V==null?void 0:V.name)==="NotAllowedError"&&Ke(!0)}),()=>{me.detach()}},[b.audioElement]),n.useEffect(()=>{if(b.isControlled||b.connectionState!=="connected")return;const g=b.getRoom();if(g)return Y.setupMic(g).catch(()=>{}),()=>{Y.teardownMic()}},[b.isControlled,b.connectionState]),n.useEffect(()=>{var h;if(b.connectionState!=="connected")return;const g=b.isControlled?(h=A==null?void 0:A.getRoom)==null?void 0:h.call(A):b.getRoom();if(g)return se.attachRoom(g),ge.attachRoom(g),b.isControlled&&Y.attachRoom(g),Te.refresh(),()=>{se.teardown(),ge.teardown()}},[b.isControlled,b.connectionState,A]),n.useEffect(()=>{const g=b.audioElement;g&&(g.muted=De)},[b.audioElement,De]);const Pn=n.useCallback(g=>{const h={type:"user_message",text:g};if(A!=null&&A.publishData){try{A.publishData(h)}catch{}return}const V=b.getRoom();if(V)try{const oe=new TextEncoder().encode(JSON.stringify(h));V.localParticipant.publishData(oe,{reliable:!0})}catch{}},[b,A]),$n=n.useCallback(()=>{ct(g=>!g)},[]);n.useEffect(()=>{je==null||je(b.connectionState),b.connectionState==="connected"?_e==null||_e():b.connectionState==="disconnected"&&(Ae==null||Ae())},[b.connectionState,_e,Ae,je]),n.useEffect(()=>{ke==null||ke(b.transcript)},[b.transcript,ke]),n.useEffect(()=>{Me==null||Me(b.agentState)},[b.agentState,Me]),n.useEffect(()=>{Pe.setThinking(b.agentState==="thinking")},[b.agentState,Pe]);const It=n.useRef(!1);n.useEffect(()=>{b.isControlled||!y||It.current||Z&&b.connectionState==="idle"&&(It.current=!0,b.connect())},[y,b.connectionState,b,Z]);const zn=n.useCallback(g=>{const h=C==null?void 0:C.find(V=>V.id===g);h&&(Qe(!1),g!==Re&&(Je(!0),b.disconnect(),Ve||Ie(g),N==null||N(h)))},[C,Re,b,Ve,N]);n.useEffect(()=>{ye&&b.connectionState==="connected"&&Je(!1)},[b.connectionState,ye]),n.useEffect(()=>{if(!Xe)return;const g=h=>{h.key==="Escape"&&Qe(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[Xe]);const On=!!$||!!(J!=null&&J.avatarImageUrl)||b.isControlled,et=mn(lt,a,On);Ue===void 0&&(($t=et.info)!=null&&$t.capabilities)&&(wt.current=et.info.capabilities);const ut=(J==null?void 0:J.name)??z??((zt=b.agentConfig)==null?void 0:zt.name)??((Ot=et.info)==null?void 0:Ot.name)??"Live Layer",_t=(J==null?void 0:J.avatarImageUrl)??$??((Ht=b.agentConfig)==null?void 0:Ht.avatarImageUrl)??((Wt=et.info)==null?void 0:Wt.avatarImageUrl)??null,Hn=k??((Bt=b.agentConfig)==null?void 0:Bt.idleLoopUrl)??((qt=et.info)==null?void 0:qt.idleLoopUrl)??null,Wn=S??null,Bn=n.useCallback(()=>te("expanded"),[te]),qn=n.useCallback(()=>te("minimized"),[te]),Tt=n.useCallback(()=>{b.disconnect(),te("hidden")},[b,te]),Fn=n.useCallback(()=>{const g=b.audioElement;g&&g.play().then(()=>Ke(!1)).catch(()=>{})},[b.audioElement]),Un=n.useCallback(()=>{Ke(!1),b.connect()},[b]),$e={...yt,...Ge?{}:{zIndex:Se}};O.primaryColor&&($e["--ll-color-primary"]=O.primaryColor),O.accentColor&&($e["--ll-color-accent"]=O.accentColor),O.backgroundColor&&($e["--ll-color-bg"]=O.backgroundColor),O.textColor&&($e["--ll-color-fg"]=O.textColor);const Vn=["ll-widget",`ll-widget--${ee}`,`ll-widget--${ie?"mobile":"desktop"}`,at].filter(Boolean).join(" ");if(!Z)return null;const Yn=t.jsx("div",{className:Vn,style:$e,"data-display-mode":ee,"data-position":w,"data-experience-mode":f==="EMBEDDED"?"embedded":"widget",children:ee==="expanded"&&t.jsx(jr,{position:w,isMobile:ie,agentName:ut,avatarImageUrl:_t,idleLoopUrl:Hn,greeting:Wn,branding:O,teamMembers:C,currentTeamMemberId:Re,isSwitchingTeamMember:ye,teamSwitcherOpen:Xe,onToggleTeamSwitcher:()=>Qe(g=>!g),onSelectTeamMember:zn,connectionState:b.connectionState,agentState:b.agentState,transcript:b.transcript,isMuted:Y.isMuted,micDevices:Te.mics,activeMicId:Y.activeDeviceId,isCameraEnabled:se.isEnabled,cameraPreviewEl:se.previewEl,cameraDevices:Te.cameras,activeCameraId:se.activeDeviceId,isScreenShareEnabled:ge.isEnabled,screenPreviewEl:ge.previewEl,isSpeakerMuted:De,allowCamera:H,allowScreenShare:T,allowTyping:W,showMinimize:D,chromeless:F,compactControls:le,transforming:pe,transformingLabel:ce,languageMenuOpen:ve,onToggleLanguageMenu:()=>xe(g=>!g),needsUserGesture:vt,canResume:b.canResume,micError:Y.micError,error:b.error,avatarVideoContainerRef:Mt,agentVideoEl:b.videoElement,onConnect:()=>void b.connect(),onDisconnect:()=>b.disconnect(),onRetry:Un,onResumeAudio:Fn,onToggleMute:Y.toggleMute,onSwitchMicDevice:g=>void Y.switchDevice(g),onToggleCamera:()=>void se.toggle(),onSwitchCameraDevice:g=>void se.switchDevice(g),onToggleScreenShare:()=>void ge.toggle(),onToggleSpeaker:$n,onSendMessage:Pn,onMinimize:qn,onClose:Tt,onClearMicError:Y.clearError})}),Dt=ee==="hidden"||ee==="minimized"?t.jsxs("div",{className:["ll-widget","ll-widget--floating",`ll-widget--${ee}`,`ll-widget--${ie?"mobile":"desktop"}`].join(" "),style:$e,"data-display-mode":ee,"data-position":w,children:[ee==="hidden"&&t.jsx(mr,{position:w,isMobile:ie,isSpeaking:b.agentState==="speaking",onExpand:()=>te("expanded"),label:`Open ${ut} widget`,avatarImageUrl:_t,agentName:ut,containerEl:ne}),ee==="minimized"&&t.jsx(yr,{position:w,isMobile:ie,agentName:ut,avatarImageUrl:_t,agentState:b.agentState,isMuted:Y.isMuted,audioLevel:me,onExpand:Bn,onToggleMute:Y.toggleMute,onClose:Tt})]}):null,Pt=ne??(typeof document<"u"?document.body:null);return t.jsxs(t.Fragment,{children:[Yn,Dt&&Pt&&Ct.createPortal(Dt,Pt)]})});Tn.displayName="AvatarWidgetInner";const Dn=n.forwardRef(function(r,o){return t.jsx(ln,{children:t.jsx(Tn,{...r,ref:o})})});Dn.displayName="AvatarWidget";const Ur=({agentId:e,baseUrl:r,apiKey:o,mode:i,onAgentEvent:s,className:a,style:d})=>{const l=n.useRef(null),u=n.useRef(null),f=n.useRef(s);f.current=s;const y=n.useCallback(p=>{var L;const c=p.detail;(L=f.current)==null||L.call(f,c)},[]);return n.useEffect(()=>{const p=l.current;if(!p)return;const c=document.createElement("livelayer-widget");return c.setAttribute("agent-id",e),r&&c.setAttribute("base-url",r),o&&c.setAttribute("api-key",o),i&&c.setAttribute("mode",i),c.addEventListener("agent-event",y),p.appendChild(c),u.current=c,()=>{c.removeEventListener("agent-event",y),p.removeChild(c),u.current=null}},[e]),n.useEffect(()=>{u.current&&(i?u.current.setAttribute("mode",i):u.current.removeAttribute("mode"))},[i]),t.jsx("div",{ref:l,className:a,style:d})},Vr=n.forwardRef(function({id:r,intent:o,as:i="div",className:s,style:a,children:d},l){return n.createElement(i,{ref:l,"data-ll-region":r,"data-ll-intent":o,className:s,style:a},d)}),Yr=n.forwardRef(function({id:r,intent:o,children:i,...s},a){return t.jsx("form",{ref:a,"data-ll-form":r,"data-ll-intent":o,...s,children:i})}),Gr=n.forwardRef(function(r,o){const{name:i,label:s,labelClassName:a}=r,d={name:i,"data-ll-field":i};let l;if("as"in r&&r.as==="textarea"){const{name:u,label:f,labelClassName:y,as:p,...c}=r;l=t.jsx("textarea",{ref:o,...d,...c})}else if("as"in r&&r.as==="select"){const{name:u,label:f,labelClassName:y,as:p,children:c,...L}=r;l=t.jsx("select",{ref:o,...d,...L,children:c})}else{const{name:u,label:f,labelClassName:y,as:p,...c}=r;l=t.jsx("input",{ref:o,...d,...c})}return s===void 0?l:t.jsxs("label",{className:a,children:[s,l]})});let an=1;function Kr({onMount:e,defaultOpen:r=!1,storageKey:o="ll-debug-open"}){const[i,s]=n.useState(r),[a,d]=n.useState([]),[l,u]=n.useState(""),[f,y]=n.useState(!1),p=n.useRef(new Set),c=n.useRef([]),L=n.useRef(f);L.current=f,n.useEffect(()=>{try{const x=localStorage.getItem(o);x==="1"&&s(!0),x==="0"&&s(!1)}catch{}},[o]),n.useEffect(()=>{try{localStorage.setItem(o,i?"1":"0")}catch{}},[i,o]),n.useEffect(()=>{const x=v=>{(v.metaKey||v.ctrlKey)&&v.shiftKey&&v.key.toLowerCase()==="l"&&(v.preventDefault(),s(C=>!C))};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[]),n.useEffect(()=>{const x=setInterval(()=>{if(c.current.length===0||L.current)return;const v=c.current.splice(0,c.current.length);d(C=>[...v.reverse(),...C].slice(0,200))},100);return()=>clearInterval(x)},[]);const w=n.useRef(!1);if(n.useEffect(()=>{!e||w.current||(w.current=!0,e(x=>{c.current.push({id:an++,ts:Date.now(),kind:"event",type:x.eventName,data:x.data})}))},[e]),n.useEffect(()=>{const x=console.warn,v=console.log,C=(E,N)=>function(...k){try{const S=typeof k[0]=="string"?k[0]:"";S.startsWith("[LiveLayer]")&&c.current.push({id:an++,ts:Date.now(),kind:E,type:S.slice(0,120),data:{args:k.slice(1).map($=>Xr($))}})}catch{}return N.apply(this,k)};return console.warn=C("warn",x),console.log=C("log",v),()=>{console.warn=x,console.log=v}},[]),!i)return t.jsx("button",{type:"button",onClick:()=>s(!0),title:"Open LiveLayer debug panel (Cmd/Ctrl + Shift + L)","aria-label":"Open LiveLayer debug panel",style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.18)",borderRadius:999,padding:"6px 10px",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",cursor:"pointer",boxShadow:"0 4px 12px rgba(0,0,0,0.35)",opacity:.85},children:"🛰 LL debug"});const _=a.filter(x=>{if(!l)return!0;const v=l.toLowerCase();return x.type.toLowerCase().includes(v)||JSON.stringify(x.data||{}).toLowerCase().includes(v)});return t.jsxs("div",{style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,width:380,maxHeight:"60vh",background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:12,boxShadow:"0 16px 48px rgba(0,0,0,0.5)",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"8px 10px",background:"rgba(255,255,255,0.04)",borderBottom:"1px solid rgba(255,255,255,0.1)",display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontWeight:600,fontSize:12},children:"LiveLayer debug"}),t.jsxs("span",{style:{fontSize:10,color:"rgba(255,255,255,0.4)"},children:[a.length," event",a.length===1?"":"s"]}),t.jsx("span",{style:{flex:1}}),t.jsx("button",{type:"button",onClick:()=>y(x=>!x),style:kt(f?"#f59e0b":"transparent"),title:"Pause / resume capture",children:f?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{d([]),c.current=[]},style:kt("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>s(!1),style:kt("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:l,onChange:x=>u(x.target.value),placeholder:"filter by type or data…",style:{margin:8,padding:"6px 8px",background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:11,outline:"none"}}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"0 8px 8px"},children:_.length===0?t.jsxs("div",{style:{padding:14,fontSize:11,color:"rgba(255,255,255,0.4)",lineHeight:1.5},children:["No events yet. Connect to the agent and trigger a tool call — the events will stream in here. You can also dispatch commands manually in DevTools:",t.jsx("pre",{style:{marginTop:6,background:"rgba(255,255,255,0.04)",padding:6,borderRadius:4,fontSize:10,whiteSpace:"pre-wrap"},children:`window.__livelayerSimulateCommand({
3
3
  type: "navigate",
4
4
  href: "/about"
5
- })`})]}):b.map(v=>t.jsx(Jr,{entry:v,expanded:f.current.has(v.id),onToggle:()=>{f.current.has(v.id)?f.current.delete(v.id):f.current.add(v.id),d(g=>[...g])}},v.id))})]})}function Jr({entry:e,expanded:r,onToggle:o}){const i=e.kind==="warn"?"#f59e0b":e.type.startsWith("[LiveLayer]")?"#94a3b8":e.type==="navigate"||e.type==="scroll_page"||e.type==="scroll_to"||e.type==="click"?"#22c55e":e.type==="fill_form"||e.type==="submit_form"||e.type==="focus_field"?"#a78bfa":e.type==="request_page_context"||e.type==="request_routes"?"#38bdf8":e.type==="agent_state"?"#facc15":"#cbd5e1",s=new Date(e.ts).toLocaleTimeString("en-US",{hour12:!1});return t.jsxs("button",{type:"button",onClick:o,style:{textAlign:"left",background:"transparent",border:0,color:"#fff",width:"100%",padding:"6px 4px",cursor:"pointer",borderBottom:"1px solid rgba(255,255,255,0.04)",fontSize:11,lineHeight:1.4},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:{color:"rgba(255,255,255,0.4)",fontVariantNumeric:"tabular-nums",fontSize:10},children:s}),t.jsx("span",{style:{color:i,fontWeight:600,flexShrink:0},children:e.type.length>50?e.type.slice(0,50)+"…":e.type})]}),r&&e.data&&t.jsx("pre",{style:{marginTop:6,padding:6,background:"rgba(255,255,255,0.04)",borderRadius:4,fontSize:10,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:JSON.stringify(e.data,null,2)})]})}function kt(e){return{background:e,color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:999,padding:"3px 8px",fontSize:10,cursor:"pointer"}}function Xr(e){try{return e instanceof Error?{message:e.message,stack:e.stack}:(JSON.stringify(e),e)}catch{return String(e)}}function Qr(){const[e,r]=n.useState([]),o=n.useCallback(s=>{r(a=>{const d=a.findIndex(l=>l.id===s.id);if(d>=0){const l=a.slice();return l[d]=s,l}return[...a,s]})},[]),i=n.useCallback(()=>r([]),[]);return{entries:e,pushSegment:o,clear:i,latest:e.length>0?e[e.length-1]:null}}exports.AvatarWidget=Dn;exports.ErrorBoundary=ln;exports.LiveLayerDebugPanel=Kr;exports.LiveLayerField=Gr;exports.LiveLayerForm=Yr;exports.LiveLayerRegion=Vr;exports.LiveLayerWidget=Ur;exports.clearPageContextCache=Nn;exports.clearRoutesCache=In;exports.extractPageContext=Rn;exports.extractRoutes=Mn;exports.getCachedPageContext=jt;exports.getCachedRoutes=pt;exports.matchesPattern=bn;exports.normalizeRouteInput=An;exports.shouldRenderAtPath=wn;exports.useAgentInfo=mn;exports.useAudioLevel=un;exports.useCameraState=fn;exports.useDisplayMode=gn;exports.useDisplayModePersistence=yn;exports.useIsMobile=vn;exports.useLiveKitSession=cn;exports.useMediaDevices=hn;exports.useMicrophoneState=dn;exports.usePathname=xn;exports.useRouteMatch=_n;exports.useScreenShareState=pn;exports.useTranscript=Qr;
5
+ })`})]}):_.map(x=>t.jsx(Jr,{entry:x,expanded:p.current.has(x.id),onToggle:()=>{p.current.has(x.id)?p.current.delete(x.id):p.current.add(x.id),d(v=>[...v])}},x.id))})]})}function Jr({entry:e,expanded:r,onToggle:o}){const i=e.kind==="warn"?"#f59e0b":e.type.startsWith("[LiveLayer]")?"#94a3b8":e.type==="navigate"||e.type==="scroll_page"||e.type==="scroll_to"||e.type==="click"?"#22c55e":e.type==="fill_form"||e.type==="submit_form"||e.type==="focus_field"?"#a78bfa":e.type==="request_page_context"||e.type==="request_routes"?"#38bdf8":e.type==="agent_state"?"#facc15":"#cbd5e1",s=new Date(e.ts).toLocaleTimeString("en-US",{hour12:!1});return t.jsxs("button",{type:"button",onClick:o,style:{textAlign:"left",background:"transparent",border:0,color:"#fff",width:"100%",padding:"6px 4px",cursor:"pointer",borderBottom:"1px solid rgba(255,255,255,0.04)",fontSize:11,lineHeight:1.4},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:{color:"rgba(255,255,255,0.4)",fontVariantNumeric:"tabular-nums",fontSize:10},children:s}),t.jsx("span",{style:{color:i,fontWeight:600,flexShrink:0},children:e.type.length>50?e.type.slice(0,50)+"…":e.type})]}),r&&e.data&&t.jsx("pre",{style:{marginTop:6,padding:6,background:"rgba(255,255,255,0.04)",borderRadius:4,fontSize:10,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:JSON.stringify(e.data,null,2)})]})}function kt(e){return{background:e,color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:999,padding:"3px 8px",fontSize:10,cursor:"pointer"}}function Xr(e){try{return e instanceof Error?{message:e.message,stack:e.stack}:(JSON.stringify(e),e)}catch{return String(e)}}function Qr(){const[e,r]=n.useState([]),o=n.useCallback(s=>{r(a=>{const d=a.findIndex(l=>l.id===s.id);if(d>=0){const l=a.slice();return l[d]=s,l}return[...a,s]})},[]),i=n.useCallback(()=>r([]),[]);return{entries:e,pushSegment:o,clear:i,latest:e.length>0?e[e.length-1]:null}}exports.AvatarWidget=Dn;exports.ErrorBoundary=ln;exports.LiveLayerDebugPanel=Kr;exports.LiveLayerField=Gr;exports.LiveLayerForm=Yr;exports.LiveLayerRegion=Vr;exports.LiveLayerWidget=Ur;exports.clearPageContextCache=Nn;exports.clearRoutesCache=In;exports.extractPageContext=Rn;exports.extractRoutes=Mn;exports.getCachedPageContext=jt;exports.getCachedRoutes=pt;exports.matchesPattern=bn;exports.normalizeRouteInput=An;exports.shouldRenderAtPath=wn;exports.useAgentInfo=mn;exports.useAudioLevel=un;exports.useCameraState=fn;exports.useDisplayMode=gn;exports.useDisplayModePersistence=yn;exports.useIsMobile=vn;exports.useLiveKitSession=cn;exports.useMediaDevices=hn;exports.useMicrophoneState=dn;exports.usePathname=xn;exports.useRouteMatch=_n;exports.useScreenShareState=pn;exports.useTranscript=Qr;