@livelayer/react 0.5.15 → 0.5.17

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