@livelayer/react 0.5.5-pr66c.5 → 0.5.5-pr66c.7

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