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