@livelayer/react 0.12.6 → 0.14.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/README.md +23 -10
- package/dist/index.d.ts +42 -0
- package/dist/index.js +3 -3
- package/dist/index.mjs +1009 -962
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -331,21 +331,34 @@ All props are optional except `agentId`.
|
|
|
331
331
|
|
|
332
332
|
Renders a wrapper element with `data-ll-region` + `data-ll-intent` that the page-context extractor prioritizes.
|
|
333
333
|
|
|
334
|
-
###
|
|
334
|
+
### Forms (0.12.0 — no wrappers, just plain HTML)
|
|
335
335
|
|
|
336
336
|
```tsx
|
|
337
|
-
<
|
|
338
|
-
<
|
|
339
|
-
<
|
|
340
|
-
<
|
|
341
|
-
|
|
342
|
-
<
|
|
343
|
-
|
|
337
|
+
<form onSubmit={handleSubmit}>
|
|
338
|
+
<label>Email <input name="email" type="email" required /></label>
|
|
339
|
+
<label>Bio <textarea name="bio" /></label>
|
|
340
|
+
<label>
|
|
341
|
+
Role
|
|
342
|
+
<select name="role">
|
|
343
|
+
<option value="dev">Developer</option>
|
|
344
|
+
<option value="pm">PM</option>
|
|
345
|
+
</select>
|
|
346
|
+
</label>
|
|
344
347
|
<button type="submit">Sign up</button>
|
|
345
|
-
</
|
|
348
|
+
</form>
|
|
346
349
|
```
|
|
347
350
|
|
|
348
|
-
|
|
351
|
+
Every `<form>` is auto-discovered. The agent infers labels from the
|
|
352
|
+
wrapping `<label>` / `aria-label` / `placeholder`, infers kinds from
|
|
353
|
+
the input `type=`, and can either fill in one shot (`fill_form`) or
|
|
354
|
+
walk the visitor through it conversationally (`collect_from_page`).
|
|
355
|
+
|
|
356
|
+
**Opt out** with `data-ll-skip` on a form or `data-ll-private` on an
|
|
357
|
+
input. Browser-native private fields (`type="password"`, `autocomplete="cc-*"`,
|
|
358
|
+
`autocomplete="off"`) are always excluded.
|
|
359
|
+
|
|
360
|
+
See the *Structured data collection* section above for `onCollect` /
|
|
361
|
+
`useCollect`.
|
|
349
362
|
|
|
350
363
|
### Hooks (power users)
|
|
351
364
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,18 +1,25 @@
|
|
|
1
1
|
import { AgentConfig } from '@livelayer/sdk';
|
|
2
2
|
import { AgentState } from '@livelayer/sdk';
|
|
3
|
+
import { clearFieldRegistry } from '@livelayer/sdk';
|
|
3
4
|
import { Component } from 'react';
|
|
4
5
|
import { ConnectionState } from '@livelayer/sdk';
|
|
5
6
|
import { CSSProperties } from 'react';
|
|
6
7
|
import { ElementType } from 'react';
|
|
7
8
|
import { ErrorInfo } from 'react';
|
|
8
9
|
import { FC } from 'react';
|
|
10
|
+
import { FieldKind } from '@livelayer/sdk';
|
|
11
|
+
import { FieldManifest } from '@livelayer/sdk';
|
|
12
|
+
import { FieldOption } from '@livelayer/sdk';
|
|
9
13
|
import { ForwardRefExoticComponent } from 'react';
|
|
14
|
+
import { getRegisteredFields } from '@livelayer/sdk';
|
|
10
15
|
import { JSX } from 'react/jsx-runtime';
|
|
11
16
|
import { LiveKitSession } from '@livelayer/sdk';
|
|
12
17
|
import { ReactNode } from 'react';
|
|
13
18
|
import { RefAttributes } from 'react';
|
|
19
|
+
import { registerFields } from '@livelayer/sdk';
|
|
14
20
|
import { Room } from 'livekit-client';
|
|
15
21
|
import { SessionOptions } from '@livelayer/sdk';
|
|
22
|
+
import { setFieldValue } from '@livelayer/sdk';
|
|
16
23
|
import { TranscriptEntry } from '@livelayer/sdk';
|
|
17
24
|
|
|
18
25
|
/**
|
|
@@ -407,6 +414,8 @@ export declare interface CameraStateHandle {
|
|
|
407
414
|
clearError: () => void;
|
|
408
415
|
}
|
|
409
416
|
|
|
417
|
+
export { clearFieldRegistry }
|
|
418
|
+
|
|
410
419
|
export declare function clearPageContextCache(): void;
|
|
411
420
|
|
|
412
421
|
export declare function clearRoutesCache(): void;
|
|
@@ -527,10 +536,25 @@ export declare function extractPageContext(extras?: Record<string, unknown>, opt
|
|
|
527
536
|
|
|
528
537
|
export declare function extractRoutes(doc?: Document): ExtractedRoute[];
|
|
529
538
|
|
|
539
|
+
export { FieldKind }
|
|
540
|
+
|
|
541
|
+
export { FieldManifest }
|
|
542
|
+
|
|
543
|
+
export { FieldOption }
|
|
544
|
+
|
|
545
|
+
export declare function FieldProvider({ fields, children }: FieldProviderProps): JSX.Element;
|
|
546
|
+
|
|
547
|
+
export declare interface FieldProviderProps {
|
|
548
|
+
fields: FieldManifest[];
|
|
549
|
+
children: ReactNode;
|
|
550
|
+
}
|
|
551
|
+
|
|
530
552
|
export declare function getCachedPageContext(extras?: Record<string, unknown>, opts?: ExtractOptions): PageContext;
|
|
531
553
|
|
|
532
554
|
export declare function getCachedRoutes(): ExtractedRoute[];
|
|
533
555
|
|
|
556
|
+
export { getRegisteredFields }
|
|
557
|
+
|
|
534
558
|
export declare interface LegacyAgentEventDetail {
|
|
535
559
|
eventName: string;
|
|
536
560
|
data: Record<string, unknown>;
|
|
@@ -707,6 +731,13 @@ export declare interface PageContext {
|
|
|
707
731
|
id: string;
|
|
708
732
|
intent?: string;
|
|
709
733
|
fields: Array<{
|
|
734
|
+
/**
|
|
735
|
+
* Agent-callable identifier. Prefers the input's `name` attribute,
|
|
736
|
+
* falls back to `id`, then `field_<n>` positional index within the
|
|
737
|
+
* form. The agent passes this string back as the key in
|
|
738
|
+
* `fill_form({ values: { [name]: "..." } })`. Stable across renders
|
|
739
|
+
* as long as the form's input order doesn't change.
|
|
740
|
+
*/
|
|
710
741
|
name: string;
|
|
711
742
|
label: string;
|
|
712
743
|
type: string;
|
|
@@ -733,6 +764,8 @@ declare interface Props {
|
|
|
733
764
|
fallback?: ReactNode;
|
|
734
765
|
}
|
|
735
766
|
|
|
767
|
+
export { registerFields }
|
|
768
|
+
|
|
736
769
|
/**
|
|
737
770
|
* The shape consumers pass back from the `getRoutes` callback. Matches
|
|
738
771
|
* `ExtractedRoute` but every field except `href` is optional — defaults
|
|
@@ -772,6 +805,8 @@ export declare interface ScreenShareStateHandle {
|
|
|
772
805
|
clearError: () => void;
|
|
773
806
|
}
|
|
774
807
|
|
|
808
|
+
export { setFieldValue }
|
|
809
|
+
|
|
775
810
|
/**
|
|
776
811
|
* Pure: should the widget render at this pathname?
|
|
777
812
|
*
|
|
@@ -916,6 +951,13 @@ export declare function useMicrophoneState(): MicrophoneStateHandle;
|
|
|
916
951
|
*/
|
|
917
952
|
export declare function usePathname(controlledPathname?: string): string;
|
|
918
953
|
|
|
954
|
+
/**
|
|
955
|
+
* Register a set of fields with the LiveLayer SDK. Stable across
|
|
956
|
+
* re-renders by depending on the SERIALIZED field list (so consumers
|
|
957
|
+
* can inline the array literal without memoizing).
|
|
958
|
+
*/
|
|
959
|
+
export declare function useRegisterFields(fields: FieldManifest[]): void;
|
|
960
|
+
|
|
919
961
|
export declare function useRouteMatch(pathname: string | undefined, showOn: RoutePattern[] | undefined, hideOn: RoutePattern[] | undefined): boolean;
|
|
920
962
|
|
|
921
963
|
export declare function useScreenShareState(): ScreenShareStateHandle;
|
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"),Nt=require("react-dom"),rr=require("@livelayer/sdk"),gt=require("livekit-client");class hn extends n.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,o){var i,s;(s=(i=this.props).onError)==null||s.call(i,r,o)}render(){var r;return this.state.hasError?this.props.fallback?this.props.fallback:t.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[t.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),t.jsx("p",{className:"ll-error-boundary__message",children:((r=this.state.error)==null?void 0:r.message)||"Something went wrong."}),t.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function mn(e){const[r,o]=n.useState("idle"),[i,s]=n.useState("idle"),[a,c]=n.useState([]),[l,u]=n.useState(null),[h,x]=n.useState(null),[p,f]=n.useState(null),[L,C]=n.useState(!1),[w,m]=n.useState(null),b=n.useRef(null),S=n.useRef(e.onDataMessage);S.current=e.onDataMessage,n.useEffect(()=>{const y={onConnectionStateChange:D=>{o(D),D==="connected"&&m(null)},onAgentStateChange:s,onTranscript:D=>c([...D]),onAgentConfig:u,onAudioTrack:D=>f(D),onVideoTrack:D=>x(D),onVideoTrackRemoved:()=>x(null),onError:D=>m(D),onDataMessage:D=>{var z;(z=S.current)==null||z.call(S,D)},onResumabilityChange:C},A=new rr.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},y);return b.current=A,o("idle"),s("idle"),c([]),u(null),x(null),f(null),C(!1),m(null),()=>{var D;(D=A.destroy)==null||D.call(A),b.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const R=n.useCallback(async()=>{const y=b.current;if(y)try{await y.connect()}catch(A){throw m(A instanceof Error?A.message:String(A)),A}},[]),E=n.useCallback(()=>{const y=b.current;y&&y.disconnect()},[]),O=n.useCallback(()=>{var y;return((y=b.current)==null?void 0:y.getRoom())??null},[]);return{connectionState:r,agentState:i,transcript:a,agentConfig:l,videoElement:h,audioElement:p,canResume:L,error:w,connect:R,disconnect:E,getRoom:O,session:b.current}}function gn(){const e=n.useRef(null),r=n.useRef(null),o=n.useRef(null),i=n.useRef(null),s=n.useRef(new Set),a=n.useRef(null),c=n.useCallback(()=>{const p=r.current;if(!p){i.current=null;return}(!a.current||a.current.length!==p.frequencyBinCount)&&(a.current=new Uint8Array(new ArrayBuffer(p.frequencyBinCount)));const f=a.current;p.getByteFrequencyData(f);let L=0;for(let w=0;w<f.length;w++)L+=f[w];const C=L/f.length/255;for(const w of s.current)try{w(C)}catch(m){console.error("[useAudioLevel] subscriber threw:",m)}i.current=requestAnimationFrame(c)},[]),l=n.useCallback(()=>{if(e.current||typeof window>"u"||typeof AudioContext>"u")return;const p=new AudioContext,f=p.createAnalyser();f.fftSize=64,f.connect(p.destination),e.current=p,r.current=f},[]),u=n.useCallback(p=>{if(l(),!(!e.current||!r.current)){if(o.current){try{o.current.disconnect()}catch{}o.current=null}try{const f=e.current.createMediaElementSource(p);f.connect(r.current),o.current=f}catch(f){console.warn("[useAudioLevel] createMediaElementSource failed:",f);return}i.current===null&&(i.current=requestAnimationFrame(c))}},[l,c]),h=n.useCallback(()=>{if(i.current!==null&&(cancelAnimationFrame(i.current),i.current=null),o.current){try{o.current.disconnect()}catch{}o.current=null}},[]),x=n.useCallback(p=>(s.current.add(p),()=>{s.current.delete(p)}),[]);return n.useEffect(()=>()=>{if(h(),r.current){try{r.current.disconnect()}catch{}r.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}s.current.clear(),a.current=null},[h]),{attach:u,detach:h,subscribe:x}}function yn(){const[e,r]=n.useState(!1),[o,i]=n.useState(""),[s,a]=n.useState(null),c=n.useRef(null),l=n.useRef(null),u=n.useCallback(async C=>{var w,m;if(c.current&&l.current){try{await l.current.localParticipant.unpublishTrack(c.current)}catch{}c.current.stop(),c.current=null}l.current=C,a(null);try{const b=await gt.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await C.localParticipant.publishTrack(b),c.current=b,r(b.isMuted);const S=(m=(w=b.mediaStreamTrack)==null?void 0:w.getSettings)==null?void 0:m.call(w);S!=null&&S.deviceId&&i(S.deviceId)}catch(b){const S=b instanceof Error&&b.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw a(S),b}},[]),h=n.useCallback(C=>{l.current=C},[]),x=n.useCallback(async C=>{const w=l.current;if(w)try{await w.switchActiveDevice("audioinput",C),i(C)}catch(m){console.warn("[useMicrophoneState] switchDevice failed:",m)}},[]),p=n.useCallback(async()=>{const C=l.current,w=!e;if(r(w),!!C)try{await C.localParticipant.setMicrophoneEnabled(!w)}catch(m){console.warn("[useMicrophoneState] setMicrophoneEnabled failed:",m),r(!w)}},[e]),f=n.useCallback(()=>{const C=c.current,w=l.current;if(C&&w){try{w.localParticipant.unpublishTrack(C)}catch{}C.stop()}c.current=null,l.current=null,r(!1),i("")},[]),L=n.useCallback(()=>a(null),[]);return{isMuted:e,activeDeviceId:o,micError:s,toggleMute:p,setupMic:u,attachRoom:h,switchDevice:x,teardownMic:f,clearError:L}}const or={resolution:{width:640,height:480,frameRate:24}};function vn(){const[e,r]=n.useState(!1),[o,i]=n.useState(null),[s,a]=n.useState(null),[c,l]=n.useState(""),u=n.useRef(null),h=n.useRef(null),x=n.useCallback(b=>{u.current=b},[]),p=n.useCallback(()=>{var R;const b=u.current,S=h.current;if(S&&b){const E=b.localParticipant.getTrackPublication(gt.Track.Source.Camera),y=(E==null?void 0:E.track)??S;try{b.localParticipant.unpublishTrack(y)}catch{}try{(R=y.stop)==null||R.call(y)}catch{}}h.current=null,a(null),r(!1)},[]),f=n.useCallback(async b=>{const S=u.current;if(S){i(null);try{const R={...or};b&&(R.deviceId=b);const E=await gt.createLocalVideoTrack(R);await S.localParticipant.publishTrack(E),h.current=E;const O=E.attach();a(O),r(!0),b&&l(b);try{S.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(R){const E=R instanceof Error&&R.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";i(E)}}},[]),L=n.useCallback(async()=>{e?p():await f(c||void 0)},[e,c,p,f]),C=n.useCallback(async b=>{p(),await f(b)},[p,f]),w=n.useCallback(()=>{p(),u.current=null,i(null),l("")},[p]),m=n.useCallback(()=>i(null),[]);return n.useEffect(()=>()=>{h.current&&h.current.stop()},[]),{isEnabled:e,error:o,previewEl:s,activeDeviceId:c,toggle:L,switchDevice:C,attachRoom:x,teardown:w,clearError:m}}function xn(){const[e,r]=n.useState(!1),[o,i]=n.useState(null),[s,a]=n.useState(null),c=n.useRef(null),l=n.useCallback(f=>{c.current=f},[]),u=n.useCallback(()=>a(null),[]),h=n.useCallback(async()=>{const f=c.current;if(f){if(e){try{await f.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1);return}i(null);try{await f.localParticipant.setScreenShareEnabled(!0);let L=0;const C=()=>{const w=f.localParticipant.getTrackPublication(gt.Track.Source.ScreenShare);if(w!=null&&w.track){const m=w.track.attach();a(m),r(!0);try{f.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}L++<10?setTimeout(C,100):r(!0)};C()}catch(L){const C=L instanceof Error?L.name:"";C!=="NotAllowedError"&&C!=="AbortError"&&i("Screen share unavailable. Try again."),r(!1)}}},[e,u]),x=n.useCallback(()=>{const f=c.current;if(f&&e)try{f.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1),i(null),c.current=null},[e,u]),p=n.useCallback(()=>i(null),[]);return{isEnabled:e,error:o,previewEl:s,toggle:h,attachRoom:l,teardown:x,clearError:p}}function bn(){const[e,r]=n.useState([]),[o,i]=n.useState([]),s=n.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const a=await navigator.mediaDevices.enumerateDevices();r(a.filter(c=>c.kind==="audioinput")),i(a.filter(c=>c.kind==="videoinput"))}catch{}},[]);return n.useEffect(()=>{if(s(),typeof navigator>"u"||!navigator.mediaDevices)return;const a=()=>void s();return navigator.mediaDevices.addEventListener("devicechange",a),()=>navigator.mediaDevices.removeEventListener("devicechange",a)},[s]),{mics:e,cameras:o,refresh:s}}function wn(e,r,o=!1){const[i,s]=n.useState(null),[a,c]=n.useState(null),[l,u]=n.useState(!o&&!!e);return n.useEffect(()=>{if(o||!e){u(!1);return}const h=new AbortController,x=r||"https://app.livelayer.studio";return u(!0),c(null),fetch(`${x}/api/widget/agent/${encodeURIComponent(e)}`,{signal:h.signal}).then(async p=>{if(!p.ok){const f=await p.json().catch(()=>({}));throw new Error(f.error||`HTTP ${p.status}`)}return p.json()}).then(p=>{h.signal.aborted||(s(p),u(!1))}).catch(p=>{h.signal.aborted||(c(p instanceof Error?p.message:"Agent lookup failed"),u(!1))}),()=>h.abort()},[e,r,o]),{info:i,error:a,loading:l}}function ir(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function sr(e,r){if(!(typeof window>"u"))try{window.localStorage.setItem(e,r)}catch{}}function _n({value:e,defaultValue:r="expanded",onChange:o}={}){const i=e!==void 0,[s,a]=n.useState(r),c=i?e:s,l=n.useCallback(u=>{u!==c&&(i||a(u),o==null||o(u))},[c,i,o]);return[c,l]}const ar=["hidden","minimized","expanded"];function lr(e){return e&&ar.includes(e)?e:null}function kn({value:e,defaultValue:r="expanded",onChange:o,persistKey:i="ll-widget",disablePersistence:s=!1}={}){const a=`${i}:display-mode`,c=n.useRef(!1),[l,u]=_n({value:e,defaultValue:r,onChange:h=>{e===void 0&&!s&&sr(a,h),o==null||o(h)}});return n.useEffect(()=>{if(c.current||(c.current=!0,s||e!==void 0))return;const h=lr(ir(a));h&&h!==l&&u(h)},[]),[l,u]}const cr=640;function Cn(e=cr){const[r,o]=n.useState(!1);return n.useEffect(()=>{if(e===!1){o(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const i=`(max-width: ${e-1}px)`,s=window.matchMedia(i),a=()=>o(s.matches);return a(),typeof s.addEventListener=="function"?(s.addEventListener("change",a),()=>s.removeEventListener("change",a)):(s.addListener(a),()=>{s.removeListener(a)})},[e]),r}const Kt="__llHistoryPatched",yt="ll:pathname";function ur(){if(typeof window>"u"||window.history[Kt])return;const e=window.history.pushState,r=window.history.replaceState;window.history.pushState=function(...o){const i=e.apply(this,o);return window.dispatchEvent(new Event(yt)),i},window.history.replaceState=function(...o){const i=r.apply(this,o);return window.dispatchEvent(new Event(yt)),i},window.history[Kt]=!0}function Jt(){return typeof window>"u"?"/":window.location.pathname||"/"}function Sn(e){const[r,o]=n.useState(()=>e??Jt());return n.useEffect(()=>{if(e!==void 0)return;ur();const i=()=>o(Jt());return i(),window.addEventListener("popstate",i),window.addEventListener(yt,i),()=>{window.removeEventListener("popstate",i),window.removeEventListener(yt,i)}},[e]),e??r}const Xt=new Map,dr=/[\\^$+?.()|{}[\]]/g;function fr(e){return e.replace(dr,"\\$&")}function pr(e){const r=Xt.get(e);if(r)return r;const o=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,i="",s="",a=o.replace(/\*\*/g,i).replace(/\*/g,s),l=fr(a).replace(new RegExp(`\\/${i}`,"g"),"(?:\\/.*)?").replace(new RegExp(i,"g"),".*").replace(new RegExp(s,"g"),"[^/]+"),u=new RegExp(`^${l}\\/?$`);return Xt.set(e,u),u}function hr(e,r){const o=r.length>1&&r.endsWith("/")?r.slice(0,-1):r;return pr(e).test(o)}function En(e,r){return typeof e=="function"?e(r):e instanceof RegExp?e.test(r):hr(e,r)}function Qt(e,r){if(!e||e.length===0)return!1;for(const o of e)if(En(o,r))return!0;return!1}function Ln(e,r,o){return e===void 0?!0:Qt(o,e)?!1:r&&r.length>0?Qt(r,e):!0}function jn(e,r,o){return n.useMemo(()=>Ln(e,r,o),[e,r,o])}function mr(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 gr(e){const r=n.useMemo(()=>mr(e.config),[e.config]),o=e.baseUrl.replace(/\/+$/,""),i=n.useRef(null),s=n.useCallback(u=>{try{new Audio(`${o}${u}`).play().catch(()=>{})}catch{}},[o]),a=n.useCallback(()=>{r.navigate&&s("/audio/page-change-sound.mp3")},[r.navigate,s]),c=n.useCallback(()=>{r.action&&s("/audio/confirmation-sound.mp3")},[r.action,s]),l=n.useCallback(u=>{if(!r.thinking){if(i.current){try{i.current.pause()}catch{}i.current=null}return}if(u){if(i.current)return;try{const h=new Audio(`${o}/audio/thinking-sound.mp3`);h.loop=!0,h.volume=.3,h.play().catch(()=>{i.current=null}),i.current=h}catch{}}else if(i.current){try{i.current.pause()}catch{}i.current=null}},[o,r.thinking]);return n.useEffect(()=>()=>{if(i.current){try{i.current.pause()}catch{}i.current=null}},[]),n.useMemo(()=>({playPageChange:a,playConfirmation:c,setThinking:l}),[a,c,l])}const Zt=({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"})}),en=({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"})}),yr=({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"})}),vr={left:180,right:0,up:-90,down:90},tn=({direction:e="right",className:r})=>t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${vr[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function xr(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const Rn="ll-hidden-tab-center-y",br=5,nn=16;function wr(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(Rn);if(!e)return null;const r=Number.parseFloat(e);return Number.isFinite(r)?r:null}catch{return null}}function rn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Rn,String(e))}catch{}}const _r=({position:e,isMobile:r,isSpeaking:o,onExpand:i,label:s="Open widget",avatarImageUrl:a,agentName:c,containerEl:l})=>{const u=xr(e),h=u==="right"?"left":"right",x=r?80:72,p=!!a,f=!!l,[L,C]=n.useState(null),[w,m]=n.useState(!1),b=n.useRef(null),S=n.useRef(!1),R=n.useCallback(j=>{if(typeof window>"u")return j;const H=x/2,P=nn+H,U=window.innerHeight-nn-H;return U<P?Math.max(P,j):Math.max(P,Math.min(U,j))},[x]);n.useEffect(()=>{if(f){C(null);return}const j=wr();C(R(j??window.innerHeight/2));const H=()=>{C(P=>P===null?null:R(P))};return window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[R,f]);const E=n.useCallback(j=>{if(!f&&!(j.pointerType==="mouse"&&j.button!==0)&&L!==null){try{j.currentTarget.setPointerCapture(j.pointerId)}catch{}b.current={startClientY:j.clientY,startCenterY:L,moved:!1}}},[L,f]),O=n.useCallback(j=>{const H=b.current;if(!H)return;const P=j.clientY-H.startClientY;!H.moved&&Math.abs(P)>br&&(H.moved=!0,m(!0)),H.moved&&C(R(H.startCenterY+P))},[R]),y=n.useCallback(j=>{const H=b.current;if(H){try{j.currentTarget.releasePointerCapture(j.pointerId)}catch{}b.current=null,H.moved&&(m(!1),S.current=!0,C(P=>(P!==null&&rn(P),P)))}},[]),A=n.useCallback(()=>{if(S.current){S.current=!1;return}i()},[i]),D=n.useCallback(j=>{if(j.key==="ArrowUp"||j.key==="ArrowDown"){j.preventDefault();const H=j.key==="ArrowUp"?-8:8;C(P=>{if(P===null)return P;const U=R(P+H);return rn(U),U})}},[R]),z=["ll-hidden",`ll-hidden--${u}`,r?"ll-hidden--mobile":"ll-hidden--desktop",o?"ll-hidden--speaking":null,w?"is-dragging":null,p?"ll-hidden--with-avatar":null,f?"ll-hidden--scoped":null].filter(Boolean).join(" "),K=L===null?void 0:{top:`${L-x/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:z,onPointerDown:E,onPointerMove:O,onPointerUp:y,onPointerCancel:y,onClick:A,onKeyDown:D,"aria-label":s,"data-position":e,style:K,children:p?t.jsxs(t.Fragment,{children:[t.jsx(tn,{direction:h,className:"ll-hidden__chevron ll-hidden__chevron--mini"}),t.jsx("img",{src:a,alt:c?`${c} avatar`:"Agent avatar",className:"ll-hidden__avatar",draggable:!1})]}):t.jsx(tn,{direction:h,className:"ll-hidden__chevron"})})},kr=({audioLevel:e,bars:r=20,maxHeight:o=20,minHeight:i=4,className:s,barClassName:a})=>{const c=n.useRef(null),l=n.useRef([]),u=n.useMemo(()=>{const x=(Math.sqrt(5)-1)/2;return Array.from({length:r},(p,f)=>.5+f*x%1*.5)},[r]);n.useEffect(()=>e.subscribe(p=>{for(let f=0;f<r;f++){const L=l.current[f];if(!L)continue;const C=Math.max(i,p*o*u[f]);L.style.height=`${C}px`}}),[e,r,o,i,u]);const h=["ll-waveform",s].filter(Boolean).join(" ");return t.jsx("div",{ref:c,className:h,"aria-hidden":"true",children:Array.from({length:r},(x,p)=>t.jsx("div",{ref:f=>{l.current[p]=f},className:["ll-waveform__bar",a].filter(Boolean).join(" "),style:{height:`${i}px`}},p))})},Cr=({position:e,isMobile:r,agentName:o,avatarImageUrl:i,agentState:s,isMuted:a,audioLevel:c,onExpand:l,onToggleMute:u,onClose:h})=>r?t.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${o} widget`,children:t.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:l,"aria-label":`Expand ${o} widget`,children:[i?t.jsx("img",{src:i,alt:o,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsx(kr,{audioLevel:c,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),t.jsx("span",{className:"ll-minimized__name",children:o}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:x=>{x.stopPropagation(),u()},onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.stopPropagation(),x.preventDefault(),u())},"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(Zt,{muted:a,className:"ll-minimized__icon"})}),t.jsx(en,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):t.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":e,role:"region","aria-label":`${o} widget`,children:t.jsxs("div",{className:"ll-minimized__surface",children:[i?t.jsx("img",{src:i,alt:o,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsxs("div",{className:"ll-minimized__meta",children:[t.jsx("span",{className:"ll-minimized__name",children:o}),t.jsx("span",{className:"ll-minimized__state",children:s==="speaking"?"Speaking":s==="thinking"?"Thinking":"Listening"})]}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:u,"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(Zt,{muted:a,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:l,"aria-label":`Expand ${o} widget`,children:t.jsx(en,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:h,"aria-label":"Close widget",children:t.jsx(yr,{className:"ll-minimized__icon"})})]})]})}),Sr=({src:e,alt:r,preCannedPlaying:o=!1,className:i,style:s})=>{const[a,c]=n.useState(!1),l=n.useRef(e);if(n.useEffect(()=>{l.current!==e&&(l.current=e,c(!1))},[e]),!e)return null;const u={position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",objectPosition:"top",transition:"opacity 500ms ease, transform 500ms ease",transform:o?"scale(1.02)":"scale(1)",opacity:a?1:0,...s};return t.jsx("img",{src:e,alt:r,className:i,style:u,loading:"eager",fetchPriority:"high",onLoad:()=>c(!0)})},Er=8,on=8,Lr=({open:e,onClose:r,anchorRef:o,children:i})=>{const s=n.useRef(null),[a,c]=n.useState(null);return n.useLayoutEffect(()=>{if(!e){c(null);return}const l=o.current;if(!l)return;const u=()=>{const h=l.getBoundingClientRect(),x={top:h.top-Er,left:h.left+h.width/2},p=on+90,f=window.innerWidth-on-90;x.left<p&&(x.left=p),x.left>f&&(x.left=f),c(x)};return u(),window.addEventListener("scroll",u,!0),window.addEventListener("resize",u),()=>{window.removeEventListener("scroll",u,!0),window.removeEventListener("resize",u)}},[e,o]),n.useEffect(()=>{if(!e)return;const l=h=>{const x=h.target,p=s.current,f=o.current;p&&p.contains(x)||f&&f.contains(x)||r()},u=h=>{h.key==="Escape"&&(h.stopPropagation(),r())};return document.addEventListener("mousedown",l),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",l),document.removeEventListener("keydown",u)}},[e,r,o]),!e||a===null||typeof document>"u"?null:Nt.createPortal(t.jsx("div",{ref:s,className:"ll-overflow-popover",role:"menu",style:{position:"fixed",top:a.top,left:a.left,transform:"translate(-50%, -100%)"},children:i}),document.body)},jr=({isMuted:e,onToggleMute:r,isCameraEnabled:o,onToggleCamera:i,allowCamera:s,isScreenShareEnabled:a,onToggleScreenShare:c,allowScreenShare:l,isSpeakerMuted:u,onToggleSpeaker:h,allowTyping:x,isTypingOpen:p,onToggleTyping:f,onDisconnect:L})=>{const[C,w]=n.useState(!1),m=n.useRef(null);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"ll-toolbar ll-toolbar--compact","data-testid":"compact-toolbar",onClick:b=>b.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(In,{muted:e})}),t.jsx("button",{ref:m,type:"button",className:`ll-tool ${C?"is-on":""}`,onClick:()=>w(b=>!b),"aria-label":"More controls","aria-haspopup":"menu","aria-expanded":C,children:t.jsx(Rr,{})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:L,"aria-label":"End conversation",children:t.jsx(Tn,{})})]}),t.jsxs(Lr,{open:C,onClose:()=>w(!1),anchorRef:m,children:[s&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${o?"is-on":""}`,onClick:()=>{i(),w(!1)},children:[t.jsx(An,{}),t.jsx("span",{children:o?"Stop camera":"Start camera"})]}),l&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${a?"is-on":""}`,onClick:()=>{c(),w(!1)},children:[t.jsx(Nn,{}),t.jsx("span",{children:a?"Stop sharing":"Share screen"})]}),t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${u?"is-on":""}`,onClick:()=>{h(),w(!1)},children:[t.jsx(Mn,{muted:u}),t.jsx("span",{children:u?"Unmute speaker":"Mute speaker"})]}),x&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${p?"is-on":""}`,onClick:()=>{f(),w(!1)},children:[t.jsx(Nr,{}),t.jsx("span",{children:p?"Hide typing":"Type a message"})]}),t.jsxs("button",{type:"button",className:"ll-overflow-popover__item is-active",disabled:!0,"aria-current":"true",children:[t.jsx("span",{className:"ll-overflow-popover__lang-code",children:"EN"}),t.jsx("span",{children:"English"})]})]})]})};function Rr(){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 Nr(){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 Ar=({position:e,isMobile:r,agentName:o,avatarImageUrl:i,idleLoopUrl:s,greeting:a,branding:c,teamMembers:l,currentTeamMemberId:u,isSwitchingTeamMember:h,teamSwitcherOpen:x,onToggleTeamSwitcher:p,onSelectTeamMember:f,languageMenuOpen:L,onToggleLanguageMenu:C,connectionState:w,agentState:m,transcript:b,canResume:S,needsUserGesture:R,error:E,isMuted:O,micError:y,micDevices:A,activeMicId:D,isCameraEnabled:z,cameraPreviewEl:K,cameraDevices:j,activeCameraId:H,isScreenShareEnabled:P,screenPreviewEl:U,isSpeakerMuted:ee,allowCamera:ye,allowScreenShare:V,allowTyping:ve,showMinimize:pe=!0,showClose:xe=!0,chromeless:he=!1,compactControls:te=!1,transforming:ot,transformingLabel:We,avatarVideoContainerRef:it,agentVideoEl:oe,onConnect:Fe,onDisconnect:Ue,onRetry:st,onResumeAudio:Ve,onToggleMute:ke,onSwitchMicDevice:Ae,onToggleCamera:Ce,onSwitchCameraDevice:Ie,onToggleScreenShare:Se,onToggleSpeaker:Ee,onSendMessage:Le,onMinimize:je,onClose:I,onClearMicError:xt})=>{var ct;const Re=((l==null?void 0:l.length)??0)>1,Me=w==="connecting"||w==="connected",ie=w==="connected",Ye=w==="idle"||w==="disconnected"||w==="error",[Ne,Te]=n.useState(!1);n.useEffect(()=>{if(!oe){Te(!1);return}if(!oe.paused&&oe.readyState>=2){Te(!0);return}Te(!1);const g=()=>Te(!0);return oe.addEventListener("playing",g),oe.addEventListener("loadeddata",g),()=>{oe.removeEventListener("playing",g),oe.removeEventListener("loadeddata",g)}},[oe]);const[bt,be]=n.useState(!1);n.useEffect(()=>{if(!ie){be(!1);return}if(Ne)return;const g=setTimeout(()=>be(!0),8e3);return()=>clearTimeout(g)},[ie,Ne]);const J=w==="connecting"||ie&&!!i&&!Ne&&!bt,Ge=n.useRef(null),ae=n.useRef(null);n.useEffect(()=>{const g=Ge.current;g&&(g.innerHTML="",K&&(K.style.width="100%",K.style.height="100%",K.style.objectFit="cover",K.style.transform="scaleX(-1)",g.appendChild(K)))},[K]),n.useEffect(()=>{const g=ae.current;g&&(g.innerHTML="",U&&(U.style.width="100%",U.style.height="100%",U.style.objectFit="contain",g.appendChild(U)))},[U]);const[De,Pe]=n.useState(!1),[X,ne]=n.useState(!1),at=n.useRef(null),lt=n.useRef(null);n.useEffect(()=>{if(!De&&!X&&!L&&!x)return;const g=()=>{Pe(!1),ne(!1),L&&C(),x&&p()};return document.addEventListener("click",g),()=>document.removeEventListener("click",g)},[De,X,L,x,C,p]);const[we,Ke]=n.useState(!1),Z=n.useCallback(()=>Ke(g=>!g),[]),[re,_e]=n.useState(""),Je=n.useCallback(g=>{g.preventDefault();const W=re.trim();W&&(Le(W),_e(""))},[re,Le]),wt=c.productName||"Live Layer";let le=null,ce=null;for(let g=b.length-1;g>=0;g--){const W=b[g];if(!le&&W.role==="agent"?le=W:!ce&&W.role==="user"&&(ce=W),le&&ce)break}const Xe=ie?(le==null?void 0:le.text)||null:a||null,$e=ie&&(ce==null?void 0:ce.text)||null,Qe=["ll-expanded",r?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:Qe,"data-position":e,"data-state":ie?"connected":Me?"connecting":"idle",role:"dialog","aria-label":`${o} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[i?t.jsx(Sr,{src:i,alt:o,className:"ll-expanded__bg-img"}):t.jsx("div",{className:"ll-expanded__bg-fallback",children:t.jsx("span",{className:"ll-expanded__bg-initial",children:((ct=o==null?void 0:o.charAt(0))==null?void 0:ct.toUpperCase())||"A"})}),s&&!ie&&t.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:it,className:"ll-expanded__video"}),J&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--connecting",children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:h?"Switching...":"Connecting..."})]}),R&&ie&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:Ve,children:[t.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("path",{d:"M3 9v6h4l5 5V4L7 9H3zm13.54.12a5 5 0 0 1 0 5.76l-1.41-1.41a3 3 0 0 0 0-2.94L16.54 9.12z"})}),t.jsx("p",{className:"ll-expanded__overlay-text",children:"Tap to enable audio"})]}),ot&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--transforming",role:"status","aria-live":"polite","aria-label":We,children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:We})]}),Me?t.jsxs(t.Fragment,{children:[!te&&t.jsxs("div",{className:"ll-expanded__topbar",children:[!he&&t.jsxs("div",{className:"ll-expanded__topbar-left",children:[t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill",onClick:g=>{Re&&(g.stopPropagation(),p())},"aria-haspopup":Re?"listbox":void 0,"aria-expanded":Re?x:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:o}),Re&&t.jsx(pt,{})]}),Re&&x&&t.jsx("div",{className:"ll-hmenu",onClick:g=>g.stopPropagation(),role:"listbox",children:l==null?void 0:l.map(g=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${g.id===u?"is-active":""}`,onClick:()=>f(g.id),role:"option","aria-selected":g.id===u,children:[g.avatarImageUrl&&t.jsx("img",{src:g.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:g.name}),g.role&&t.jsx("span",{className:"ll-hmenu__role",children:g.role})]},g.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:g=>{g.stopPropagation(),C()},"aria-haspopup":"listbox","aria-expanded":L,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(pt,{})]}),L&&t.jsx("div",{className:"ll-hmenu",onClick:g=>g.stopPropagation(),role:"listbox",children:t.jsx("button",{type:"button",className:"ll-hmenu__item is-active",role:"option","aria-selected":!0,children:t.jsx("span",{className:"ll-hmenu__name",children:"English"})})})]}),t.jsx("span",{className:`ll-expanded__state ll-expanded__state--${m}`,children:m})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[pe!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn",onClick:je,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(an,{})}),xe!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:I,"aria-label":"End call",title:"End call",children:t.jsx(sn,{})})]})]}),te&&t.jsxs("div",{className:"ll-compact-status","data-state":m,children:[t.jsx("span",{className:"ll-compact-status__dot","aria-hidden":!0}),t.jsx("span",{className:"ll-compact-status__label",children:m})]})]}):!te&&t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:wt}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[pe!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:je,"aria-label":"Minimize widget",children:t.jsx(an,{})}),xe!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:I,"aria-label":"Close widget",children:t.jsx(sn,{})})]})]}),Ye&&(()=>{const g=S?"Resume session":w==="disconnected"?"Reconnect to agent":"Start video call",W=!E;return t.jsxs(t.Fragment,{children:[W&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:Fe,"aria-label":g,children:[t.jsx("div",{className:"ll-expanded__play-circle",children:t.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("polygon",{points:"6 3 20 12 6 21 6 3"})})}),te&&t.jsx("span",{className:"ll-expanded__play-label",children:g})]}),!te&&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:Fe,"aria-label":g,children:g})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${Me&&(z||P)?"is-visible":""}`,children:[t.jsx("div",{ref:ae,className:P?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:Ge,className:!P&&z?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),Me?t.jsxs("div",{className:"ll-expanded__bottom",children:[!te&&Xe&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--agent","data-role":"agent",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:Xe})}),!te&&$e&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--user","data-role":"user",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:$e})}),!he&&!te&&t.jsxs("div",{className:"ll-toolbar",onClick:g=>g.stopPropagation(),children:[V&&t.jsx("button",{type:"button",className:`ll-tool ${P?"is-on":""}`,onClick:Se,"aria-label":P?"Stop sharing screen":"Share screen",title:P?"Stop sharing":"Share screen",children:t.jsx(Nn,{})}),ye&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${z?"is-on":""}`,onClick:Ce,"aria-label":z?"Turn off camera":"Turn on camera",title:z?"Stop camera":"Start camera",children:t.jsx(An,{})}),t.jsx("button",{ref:lt,type:"button",className:`ll-tool ll-tool--right ${z?"is-on":""}`,onClick:g=>{g.stopPropagation(),ne(W=>!W),Pe(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":X,children:t.jsx(pt,{})}),X&&j.length>0&&t.jsx(ln,{label:"Camera",devices:j,activeId:H,anchorRef:lt,onPick:g=>{ne(!1),Ie(g)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${O?"is-muted":""}`,onClick:ke,"aria-label":O?"Unmute microphone":"Mute microphone",title:O?"Unmute":"Mute",children:t.jsx(In,{muted:O})}),t.jsx("button",{ref:at,type:"button",className:`ll-tool ll-tool--right ${O?"is-muted":""}`,onClick:g=>{g.stopPropagation(),Pe(W=>!W),ne(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":De,children:t.jsx(pt,{})}),De&&A.length>0&&t.jsx(ln,{label:"Microphone",devices:A,activeId:D,anchorRef:at,onPick:g=>{Pe(!1),Ae(g)}})]}),t.jsx("button",{type:"button",className:`ll-tool ${ee?"is-muted":""}`,onClick:Ee,"aria-label":ee?"Unmute speaker":"Mute speaker",title:ee?"Unmute speaker":"Mute speaker",children:t.jsx(Mn,{muted:ee})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:Ue,"aria-label":"End conversation",title:"End conversation",children:t.jsx(Tn,{})})]}),!he&&te&&t.jsx(jr,{isMuted:O,onToggleMute:ke,isCameraEnabled:z,onToggleCamera:Ce,allowCamera:ye,isScreenShareEnabled:P,onToggleScreenShare:Se,allowScreenShare:V,isSpeakerMuted:ee,onToggleSpeaker:Ee,allowTyping:ve,isTypingOpen:we,onToggleTyping:Z,onDisconnect:Ue}),!he&&ve&&(te?we:!0)&&t.jsxs("form",{className:"ll-message-input",onSubmit:Je,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:re,onChange:g=>_e(g.target.value),"aria-label":"Message the agent"}),re.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(Ir,{})})]})]}):null,(()=>{if(y&&w!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:y}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:xt,"aria-label":"Dismiss",children:"×"})]});if(!E||w!=="error")return null;let g="Failed to connect",W="Try again";return E==="MIC_PERMISSION_DENIED"?g="Microphone blocked. Allow access to talk.":E==="MIC_NOT_FOUND"?g="No microphone found. Plug one in + retry.":E==="MIC_UNAVAILABLE"?g="Mic unavailable. Check other apps using it.":E==="AGENT_TIMEOUT"?g="Agent didn't pick up. Try again.":E==="CONNECT_FAILED"?g="Connection failed. Check your network.":E.length<80&&(g=E),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:g}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:st,children:W})]})})()]})};function pt(){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 sn(){return t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function an(){return t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})})}function Nn(){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 An(){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 In({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 Mn({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 Ir(){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 Tn(){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 ln=({label:e,devices:r,activeId:o,onPick:i,anchorRef:s})=>{const[a,c]=n.useState(null);return n.useLayoutEffect(()=>{const l=()=>{const u=s.current;if(!u)return;const h=u.getBoundingClientRect(),x=126,p=window.innerWidth-16-110,f=h.left+h.width/2;c({top:h.top-8,left:Math.max(x,Math.min(p,f))})};return l(),window.addEventListener("scroll",l,!0),window.addEventListener("resize",l),()=>{window.removeEventListener("scroll",l,!0),window.removeEventListener("resize",l)}},[s]),a===null||typeof document>"u"?null:Nt.createPortal(t.jsxs("div",{className:"ll-device-menu ll-device-menu--floating",onClick:l=>l.stopPropagation(),role:"listbox",style:{position:"fixed",top:a.top,left:a.left,transform:"translate(-50%, -100%)"},children:[t.jsx("p",{className:"ll-device-menu__label",children:e}),r.map((l,u)=>{const h=o===l.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${h?"is-active":""}`,onClick:()=>i(l.deviceId),role:"option","aria-selected":h,children:[h&&t.jsx("span",{className:"ll-device-menu__dot",children:"●"}),t.jsx("span",{className:"ll-device-menu__name",children:l.label||`${e} ${u+1}`})]},l.deviceId||u)})]}),document.body)},Mr=["[data-ll-private]","[data-ll-skip]",".ll-widget"];function At(e){let r=e;for(;r;){for(const o of Mr)if(r.matches(o))return!0;r=r.parentElement}return!1}function vt(e){if(At(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 ht=4096,Tr=20,Dr=20,Pr=10,$r=10,zr=30,Or=20,cn=500,Hr=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function nt(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let r=e;for(;r;){for(const o of Hr)if(r.matches(o))return!0;r=r.parentElement}return!1}function rt(e){if(typeof window>"u")return!0;const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return!1;const o=window.innerHeight||document.documentElement.clientHeight,i=window.innerWidth||document.documentElement.clientWidth;return r.bottom>0&&r.right>0&&r.top<o&&r.left<i}function un(e){const r=e.getAttribute("id");if(r){const a=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/"/g,'\\"'),c=document.querySelector(`label[for="${a}"]`);if(c!=null&&c.textContent)return c.textContent.trim()}const o=e.getAttribute("aria-label");if(o)return o.trim();const i=e.getAttribute("placeholder");if(i)return i.trim();const s=e.closest("label");return s!=null&&s.textContent?s.textContent.trim():""}function ge(e,r){return e.length<=r?e:e.slice(0,r-1)+"…"}function Br(e){return e&&e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||null}function qr(e){const r=e.getAttribute("aria-label");if(r)return r.trim().slice(0,80);const o=e.getAttribute("aria-labelledby");if(o){const a=document.getElementById(o);if(a!=null&&a.textContent)return a.textContent.trim().slice(0,80)}const i=e.querySelector('button[type="submit"], input[type="submit"], button:not([type])');if(i){const a=i instanceof HTMLInputElement?i.value:(i.textContent??"").trim();if(a&&a.length<60&&!/^(submit|ok|continue)$/i.test(a))return a}let s=e.parentElement;for(let a=0;s&&a<4;a++,s=s.parentElement){const c=s.querySelector("h1, h2, h3, h4");if(c!=null&&c.textContent){const l=c.textContent.trim();if(l&&l.length<80)return l}}return null}function He(e){return e.length}function Dn(e,r={}){const o=r.doc??(typeof document<"u"?document:null);if(!o)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:e};const i=typeof window<"u"&&window.location.href||"",s=typeof window<"u"&&window.location.pathname||"/",a=o.title||"",c=Array.from(o.querySelectorAll("[data-ll-region]")),l=[];for(const y of c){if(l.length>=Pr)break;if(nt(y)||!rt(y))continue;const A=y.getAttribute("data-ll-region")??"",D=y.getAttribute("data-ll-intent")??void 0,z=ge((y.innerText||y.textContent||"").trim(),cn*2);!A||!z||l.push({id:A,intent:D,text:z})}const u=[],h=["H1","H2","H3","H4","H5","H6"],x=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const y of x){if(nt(y)||!rt(y))continue;const A=(y.textContent||"").trim();A&&u.push(`${y.tagName}: ${ge(A,200)}`)}const p=Array.from(o.querySelectorAll("p, li"));for(const y of p){if(nt(y)||!rt(y)||h.includes(y.tagName))continue;const A=(y.textContent||"").trim();A.length>10&&u.push(ge(A,cn))}const f=u.join(`
|
|
2
|
-
`),L=[],C=Array.from(o.querySelectorAll("a[href]"));for(const y of C){if(L.length>=Tr)break;if(nt(y)||!rt(y))continue;const A=y.getAttribute("href")||"",D=(y.textContent||"").trim();!A||!D||L.push({href:A,text:ge(D,100)})}const w=[],m=Array.from(o.querySelectorAll("input, textarea, select"));for(const y of m){if(w.length>=Dr)break;if(nt(y)||!vt(y)||!rt(y))continue;const A=un(y),D=y instanceof HTMLInputElement?y.type:y.tagName.toLowerCase();A&&w.push({label:ge(A,100),type:D})}const b=Array.from(o.querySelectorAll("form")),S=[];let R=0;for(const y of b){if(S.length>=$r)break;if(At(y)||y.matches(".ll-widget *, .ll-widget"))continue;const A=y.getAttribute("id")||y.getAttribute("name")||Br(y.getAttribute("data-ll-intent"))||`form_${R++}`,D=y.getAttribute("data-ll-intent")||qr(y)||void 0,z=Array.from(y.querySelectorAll("input[name], textarea[name], select[name]")),K=[];for(const j of z){if(K.length>=zr)break;if(!vt(j))continue;if(j instanceof HTMLInputElement){const V=j.type;if(V==="submit"||V==="button"||V==="reset"||V==="hidden"||V==="image"||V==="file")continue}const H=j.getAttribute("name")||"";if(!H)continue;const P=un(j)||H,U=j instanceof HTMLInputElement?j.type:j.tagName.toLowerCase(),ee={name:H,label:ge(P,100),type:U};if(j.required===!0&&(ee.required=!0),j instanceof HTMLSelectElement){const V=[];for(let ve=0;ve<j.options.length&&!(V.length>=Or);ve++){const pe=j.options[ve];if(!pe||pe.disabled)continue;const xe=pe.value||"",he=(pe.textContent||"").trim()||xe;!xe&&!he||V.push({value:xe,label:ge(he,60)})}V.length>0&&(ee.options=V)}const ye=typeof j.validationMessage=="string"?j.validationMessage:"";ye&&(ee.validationMessage=ge(ye,200)),K.push(ee)}S.push({id:A,intent:D,fields:K})}const E={url:i,title:a,pathname:s,regions:l,visibleText:f,visibleLinks:L,visibleFields:w,forms:S,extras:e};let O=He(JSON.stringify(E.regions))+He(E.visibleText)+He(JSON.stringify(E.visibleLinks))+He(JSON.stringify(E.visibleFields));for(;O>ht&&E.visibleFields.length>0;)E.visibleFields.pop(),O=He(JSON.stringify(E.visibleFields));for(;O>ht&&E.visibleLinks.length>0;)E.visibleLinks.pop(),O-=80;return He(E.visibleText)>ht&&(E.visibleText=ge(E.visibleText,ht-100)),E}let Be=null;function Rt(e,r={}){const o=Date.now(),s=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(Be&&Be.key===s&&o-Be.at<1e3)return Be.ctx;const a=Dn(e,r);return Be={key:s,at:o,ctx:a},a}function Pn(){Be=null}const Wr=200;function $n(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 Fr(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function zn(e){const r=e??(typeof document<"u"?document:null);if(!r)return[];const o=typeof window<"u"&&window.location.origin||"",i=new Set,s=[],a=Array.from(r.querySelectorAll("a[href]"));for(const c of a){if(s.length>=Wr)break;if(At(c))continue;const l=c.getAttribute("href")||"";if(!Fr(l))continue;let u=l,h=!0;try{if(typeof window<"u"){const p=new URL(l,o);h=p.origin===o,h&&l.startsWith("http")&&(u=p.pathname+p.search+p.hash)}}catch{continue}if(i.has(u))continue;i.add(u);const x=(c.textContent||"").trim().slice(0,120);s.push({href:u,text:x,internal:h})}return s}let qe=null;const Ur=5e3;function mt(){const e=Date.now(),r=typeof window<"u"&&window.location.pathname||"/";if(qe&&qe.pathname===r&&e-qe.at<Ur)return qe.routes;const o=zn();return qe={at:e,pathname:r,routes:o},o}function On(){qe=null}function Vr(e,r){const o=e instanceof HTMLInputElement?HTMLInputElement.prototype:e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLSelectElement.prototype,i=Object.getOwnPropertyDescriptor(o,"value"),s=i==null?void 0:i.set;s?s.call(e,r):e.value=r}function Yr(e,r,o={}){const i=o.triggerInput??!0,s=o.triggerChange??!0;if(e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")){const a=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"),c=a==null?void 0:a.set,l=r==="true"||r==="1"||r==="on";c?c.call(e,l):e.checked=l,i&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}Vr(e,r),i&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}))}function dn(e,r){if(!r)return null;const o=r.replace(/"/g,'\\"');try{const c=e.querySelector(`form#${CSS.escape(r)}`);if(c)return c}catch{}const i=e.querySelector(`form[name="${o}"]`);if(i)return i;const s=e.querySelector(`form[data-ll-intent="${o}"]`);if(s)return s;const a=Array.from(e.querySelectorAll("form"));for(const c of a){const l=c.getAttribute("data-ll-intent");if(l&&Gr(l)===r)return c}if(/^form_\d+$/.test(r)){const c=parseInt(r.slice(5),10);let l=0;for(const u of a)if(!(u.id||u.getAttribute("name")||u.getAttribute("data-ll-intent"))){if(l===c)return u;l++}}return null}function Gr(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||null}function Kr(){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 Jr(e){if(!(e instanceof HTMLElement))return!1;const o=window.getComputedStyle(e).overflowY;return!(o!=="auto"&&o!=="scroll"||e.scrollHeight<=e.clientHeight+2)}function Xr(){if(typeof document>"u")return null;const e=Array.from(document.querySelectorAll("body, body *"));let r=null,o=0;for(const i of e){if(!Jr(i))continue;const s=i.getBoundingClientRect();if(s.bottom<=0||s.top>=window.innerHeight||s.right<=0||s.left>=window.innerWidth||s.width<=0||s.height<=0||i.closest(".ll-widget"))continue;const a=s.width*s.height;a>o&&(o=a,r=i)}return r}function Qr(){if(typeof window>"u")return null;if(Kr())return window;const e=Xr();return e||window}function fn(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function Zr(e){var r,o;return e instanceof Window?typeof document>"u"?0:Math.max(((r=document.body)==null?void 0:r.scrollHeight)??0,((o=document.documentElement)==null?void 0:o.scrollHeight)??0):e.scrollHeight-e.clientHeight}const eo=new Set(["agent_state","avatar_stream_ready","avatar_active","avatar_idle","bot_ready","agent_error","idle_warning","idle_timeout","navigate","scroll_to","request_page_context","scroll_page","click","fill_form","focus_field","submit_form","request_routes","task_field_updated","task_completed"]),Hn=n.forwardRef(function(r,o){var qt,Wt,Ft,Ut,Vt,Yt,Gt;const{agentId:i,apiKey:s,baseUrl:a="https://app.livelayer.studio",sessionEndpoint:c,sessionBody:l,soundEffects:u,experienceMode:h="WIDGET",autoConnect:x=!1,displayMode:p,defaultDisplayMode:f="expanded",onDisplayModeChange:L,position:C="bottom-right",mobileBreakpoint:w=640,persistKey:m="ll-widget",disablePersistence:b=!1,teamMembers:S,currentTeamMemberId:R,onTeamMemberChange:E,idleLoopUrl:O,greeting:y,avatarImageUrl:A,agentName:D,branding:z={},allowCamera:K=!0,allowScreenShare:j=!0,allowTyping:H=!0,showMinimize:P,showClose:U,chromeless:ee=!1,floatingChromeContainer:ye=null,compactControls:V=!1,transforming:ve=!1,transformingLabel:pe="Transforming…",showOn:xe,hideOn:he,pathname:te,onNavigate:ot,onScrollToSelector:We,getPageContext:it,pageContextExtras:oe,getRoutes:Fe,onScrollPage:Ue,onClick:st,capabilities:Ve,onConnect:ke,onDisconnect:Ae,onTranscript:Ce,onAgentState:Ie,onConnectionStateChange:Se,onAgentEvent:Ee,onAgentCommand:Le,onCollect:je,controlledSession:I,className:xt,style:Re,zIndex:Me=2147483647}=r,ie=Sn(te),Ye=jn(ie,xe,he);n.useEffect(()=>{Pn(),On()},[ie]);const Ne=R!==void 0,[Te,bt]=n.useState(()=>{var v;return R??((v=S==null?void 0:S[0])==null?void 0:v.id)}),be=Ne?R:Te,J=n.useMemo(()=>(S==null?void 0:S.find(v=>v.id===be))??null,[S,be]),Ge=(J==null?void 0:J.agentId)??i,ae=h==="EMBEDDED",[De,Pe]=kn({value:p,defaultValue:f,onChange:L,persistKey:m,disablePersistence:ae||b}),X=ae?"expanded":De,ne=ae?()=>{}:Pe,at=P??!ae,lt=U??!ae,we=Cn(w),Ke=gn(),Z=yn(),re=vn(),_e=xn(),Je=bn(),[wt,le]=n.useState(!1),[ce,Xe]=n.useState(!1),[$e,Qe]=n.useState(!1),[ct,g]=n.useState(!1),[W,qn]=n.useState(!1),ut=gr({baseUrl:a,config:u}),dt=n.useRef(ut);dt.current=ut;const _t=n.useRef(ot),kt=n.useRef(We),Ct=n.useRef(Ue),St=n.useRef(st),It=n.useRef(it),Mt=n.useRef(oe),Tt=n.useRef(Fe),Et=n.useRef(Ve),ue=n.useRef(null);_t.current=ot,kt.current=We,Ct.current=Ue,St.current=st,It.current=it,Mt.current=oe,Tt.current=Fe,Et.current=Ve;function de(v){const d=Et.current;return d?d.includes(v):!0}function fe(v,d){console.warn(`[LiveLayer] Agent command "${v}" blocked — capability "${d}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const Ze=n.useCallback(v=>{var F,se,me,tt;const d=v;if(!(!d.type||typeof d.type!="string")){if(Ee==null||Ee({eventName:d.type,data:v}),d.type==="navigate"){if(!de("navigate")){fe("navigate","navigate");return}const _=typeof d.href=="string"?d.href:null;if(!_){console.warn(`[LiveLayer] Agent emitted "navigate" without href. Skipping. Check your agent's tool schema. See https://livelayer.studio/docs/errors/navigate-missing-href`);return}if(dt.current.playPageChange(),_t.current){try{_t.current(_)}catch(N){console.warn(`[LiveLayer] onNavigate threw for "${_}". Falling back. Error:`,N)}return}if(typeof document<"u"){const N=document.querySelector(`a[href="${_.replace(/"/g,'\\"')}"]`);if(N){N.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",_),window.dispatchEvent(new PopStateEvent("popstate"))}catch(N){console.warn(`[LiveLayer] history.pushState fallback failed for "${_}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,N)}return}if(d.type==="scroll_to"){if(!de("scroll")){fe("scroll_to","scroll");return}const _=typeof d.selector=="string"?d.selector:null;if(!_)return;const N=d.behavior==="instant"?"instant":"smooth";if(kt.current){try{kt.current(_,N)}catch($){console.warn("[LiveLayer] onScrollToSelector threw.",$)}return}if(typeof document<"u"){let $=null;try{$=document.querySelector(_)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${_}".`);return}if(!$){console.warn(`[LiveLayer] scroll_to: no element matched "${_}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}$.scrollIntoView({behavior:N,block:"start"})}return}if(d.type==="request_page_context"){if(!de("read_page")){fe("request_page_context","read_page");return}const _=typeof d.requestId=="string"?d.requestId:void 0,N=(F=ue.current)==null?void 0:F.call(ue),$=q=>{const M=N,G=M==null?void 0:M.localParticipant;if(G!=null&&G.publishData)try{const Q=_?{...q,requestId:_}:q,Oe=new TextEncoder().encode(JSON.stringify(Q));G.publishData(Oe,{reliable:!0})}catch(Q){console.warn("[LiveLayer] publishData failed.",Q)}},T=Mt.current,B=It.current;try{if(B){const q=B(T);if(q instanceof Promise){$({type:"page_context_pending"}),q.then(M=>$({type:"page_context",context:M})).catch(M=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",M),$({type:"page_context",context:Rt(T)})});return}$({type:"page_context",context:q});return}$({type:"page_context",context:Rt(T)})}catch(q){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",q),$({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:T}})}return}if(d.type==="scroll_page"){if(!de("scroll")){fe("scroll_page","scroll");return}const _=d.direction;if(_!=="up"&&_!=="down"&&_!=="top"&&_!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(_)}". Expected up | down | top | bottom.`);return}const N=d.behavior==="instant"?"instant":"smooth";if(Ct.current){try{Ct.current(_,N)}catch(M){console.warn("[LiveLayer] onScrollPage threw.",M)}return}if(typeof window>"u")return;const $={behavior:N},T=Qr(),B=M=>{T instanceof Window?T.scrollBy({top:M,...$}):T.scrollBy({top:M,...$})},q=M=>{T instanceof Window?T.scrollTo({top:M,...$}):T.scrollTo({top:M,...$})};_==="up"?B(-fn(T)):_==="down"?B(fn(T)):q(_==="top"?0:Zr(T));return}if(d.type==="click"){if(!de("click")){fe("click","click");return}const _=typeof d.selector=="string"?d.selector:null;if(!_){console.warn("[LiveLayer] click: missing selector.");return}if(St.current){try{St.current(_)}catch($){console.warn("[LiveLayer] onClick threw.",$)}return}if(typeof document>"u")return;let N=null;try{N=document.querySelector(_)}catch{console.warn(`[LiveLayer] click: invalid selector "${_}".`);return}if(!N){console.warn(`[LiveLayer] click: no element matched "${_}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(N.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(se=N.click)==null||se.call(N);return}if(d.type==="fill_form"||d.type==="focus_field"){if(!de("fill_forms")){fe(d.type,"fill_forms");return}if(typeof document>"u")return;d.type==="fill_form"&&dt.current.playConfirmation();const _=typeof d.formId=="string"?d.formId:null;if(!_){console.warn(`[LiveLayer] ${d.type}: missing formId.`);return}const N=dn(document,_);if(!N){console.warn(`[LiveLayer] ${d.type}: no <form> matched id="${_}" (or matching name / data-ll-intent slug). Forms are auto-discovered — make sure the form has an \`id\`, \`name\`, or \`data-ll-intent\` attribute the agent observed in PageContext.forms.`);return}if(N.closest('[data-ll-private="true"], [data-ll-skip], .ll-widget')){console.warn(`[LiveLayer] ${d.type}: refusing to touch a form in a private / opted-out subtree.`);return}if(d.type==="focus_field"){const T=typeof d.fieldName=="string"?d.fieldName:null;if(!T){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const B=N.querySelector(`[name="${T.replace(/"/g,'\\"')}"]`);if(!B){console.warn(`[LiveLayer] focus_field: no input with name="${T}" in form "${_}".`);return}if(!vt(B)){console.warn(`[LiveLayer] focus_field: field "${T}" is privacy-protected and not focusable.`);return}B.focus();return}const $=d.values&&typeof d.values=="object"?d.values:null;if(!$){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[T,B]of Object.entries($)){if(typeof B!="string")continue;const q=N.querySelector(`[name="${T.replace(/"/g,'\\"')}"]`);if(!q){console.warn(`[LiveLayer] fill_form: no input with name="${T}" in form "${_}". Skipping.`);continue}if(!vt(q)){console.warn(`[LiveLayer] fill_form: field "${T}" is privacy-protected (password / cc-* / private). Skipping.`);continue}try{Yr(q,B)}catch(M){console.warn(`[LiveLayer] fill_form: failed to set "${T}".`,M)}}return}if(d.type==="submit_form"){if(!de("submit_forms")){fe("submit_form","submit_forms");return}if(typeof document>"u")return;const _=typeof d.formId=="string"?d.formId:null;if(!_){console.warn("[LiveLayer] submit_form: missing formId.");return}dt.current.playConfirmation();const N=dn(document,_);if(!N){console.warn(`[LiveLayer] submit_form: no <form> matched id="${_}" (or matching name / data-ll-intent slug).`);return}if(N.closest('[data-ll-private="true"], [data-ll-skip], .ll-widget')){console.warn("[LiveLayer] submit_form: refusing to submit a form in a private / opted-out subtree.");return}const $=typeof d.requestId=="string"?d.requestId:void 0,T=(me=ue.current)==null?void 0:me.call(ue),B=G=>{const Q=T,Oe=Q==null?void 0:Q.localParticipant;if(Oe!=null&&Oe.publishData)try{const tr=$?{...G,requestId:$}:G,nr=new TextEncoder().encode(JSON.stringify(tr));Oe.publishData(nr,{reliable:!0})}catch{}};let q=!1;const M=()=>{q=!0,B({type:"form_submitted",formId:_})};N.addEventListener("submit",M,{once:!0});try{typeof N.requestSubmit=="function"?N.requestSubmit():N.submit()}catch(G){console.warn("[LiveLayer] submit_form: requestSubmit threw.",G),N.removeEventListener("submit",M),B({type:"form_submit_blocked",formId:_,reason:"exception"});return}setTimeout(()=>{q||(N.removeEventListener("submit",M),B({type:"form_submit_blocked",formId:_,reason:"validation"}))},500);return}if(d.type==="request_routes"){if(!de("read_page")){fe("request_routes","read_page");return}const _=typeof d.requestId=="string"?d.requestId:void 0,$=(tt=ue.current)==null?void 0:tt.call(ue),T=$==null?void 0:$.localParticipant;if(!(T!=null&&T.publishData))return;const B=M=>{try{const G=_?{type:"routes",routes:M,requestId:_}:{type:"routes",routes:M},Q=new TextEncoder().encode(JSON.stringify(G));T.publishData(Q,{reliable:!0})}catch(G){console.warn("[LiveLayer] request_routes: publishData failed.",G)}},q=Tt.current;if(q){try{const M=q(),G=Q=>{if(!Array.isArray(Q)){B([]);return}B(Q.map($n).slice(0,200))};M instanceof Promise?M.then(G).catch(Q=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",Q),B(mt())}):G(M)}catch(M){console.warn("[LiveLayer] getRoutes threw; falling back to DOM walker.",M),B(mt())}return}try{B(mt())}catch(M){console.warn("[LiveLayer] request_routes: extractRoutes threw.",M)}return}if(d.type==="task_field_updated"){if(!de("collect_data")){fe("task_field_updated","collect_data");return}const _={phase:"field",fieldId:typeof d.fieldId=="string"?d.fieldId:"",fieldName:typeof d.fieldName=="string"?d.fieldName:typeof d.fieldId=="string"?d.fieldId:"",value:typeof d.value=="string"?d.value:"",kind:typeof d.kind=="string"?d.kind:"text",source:d.source==="slide"?"slide":d.source==="page"?"page":"agent",...typeof d.slideId=="string"?{slideId:d.slideId}:{},...typeof d.formId=="string"?{formId:d.formId}:{}};if(typeof document<"u")try{document.dispatchEvent(new CustomEvent("ll-collected",{detail:_}))}catch{}return}if(d.type==="task_completed"){if(!de("collect_data")){fe("task_completed","collect_data");return}const _=d.result;if(!_||typeof _!="object"){console.warn("[LiveLayer] task_completed missing `result` payload.");return}if(typeof document<"u")try{document.dispatchEvent(new CustomEvent("ll-collected",{detail:{phase:"complete",result:_}}))}catch{}try{je==null||je(_)}catch(N){console.warn("[LiveLayer] onCollect threw.",N)}return}eo.has(d.type)||Le==null||Le(d)}},[Le,Ee,je]),Y=mn({agentId:I?"__controlled__":Ge,baseUrl:a,apiKey:s,sessionEndpoint:c,sessionBody:l,onDataMessage:I?void 0:Ze});n.useEffect(()=>{if(I!=null&&I.subscribeToDataMessages)return I.subscribeToDataMessages(Ze)},[I,Ze]),ue.current=()=>{var v;return(v=Y.getRoom)==null?void 0:v.call(Y)},n.useEffect(()=>{var F;if(typeof window>"u")return;const v=((F=window.location)==null?void 0:F.hostname)||"";if(v==="localhost"||v==="127.0.0.1"||v==="0.0.0.0"||v.endsWith(".local")||v.endsWith(".test"))return window.__livelayerSimulateCommand=se=>{try{Ze(se)}catch(me){console.warn("[LiveLayer] simulate-command threw:",me)}},()=>{delete window.__livelayerSimulateCommand}},[Ze]);const k=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:Y.getRoom,isControlled:!0}:{connectionState:Y.connectionState,agentState:Y.agentState,transcript:Y.transcript,videoElement:Y.videoElement,audioElement:Y.audioElement,canResume:Y.canResume,error:Y.error,agentConfig:Y.agentConfig,connect:Y.connect,disconnect:Y.disconnect,getRoom:Y.getRoom,isControlled:!1},[I,Y]),Dt=n.useRef(k);Dt.current=k;const Pt=n.useRef(I);Pt.current=I,n.useImperativeHandle(o,()=>({sendData:async v=>{var me,tt;const d=Pt.current;if(d!=null&&d.publishData){try{await d.publishData(v)}catch(_){console.warn("[AvatarWidget] sendData (controlled) failed:",_)}return}const F=(tt=(me=Dt.current)==null?void 0:me.getRoom)==null?void 0:tt.call(me),se=F==null?void 0:F.localParticipant;if(se!=null&&se.publishData)try{const _=new TextEncoder().encode(JSON.stringify(v));await se.publishData(_,{reliable:!0})}catch(_){console.warn("[AvatarWidget] sendData failed:",_)}}}),[]);const $t=n.useRef(null);n.useEffect(()=>{const v=k.videoElement,d=$t.current;if(!(!v||!d))return d.appendChild(v),()=>{v.parentNode===d&&d.removeChild(v)}},[k.videoElement]),n.useEffect(()=>{const v=k.audioElement;if(!v)return;Ke.attach(v);const d=v.play();return d&&typeof d.catch=="function"&&d.catch(F=>{(F==null?void 0:F.name)==="NotAllowedError"&&le(!0)}),()=>{Ke.detach()}},[k.audioElement]),n.useEffect(()=>{if(k.isControlled||k.connectionState!=="connected")return;const v=k.getRoom();if(v)return Z.setupMic(v).catch(()=>{}),()=>{Z.teardownMic()}},[k.isControlled,k.connectionState]),n.useEffect(()=>{var d;if(k.connectionState!=="connected")return;const v=k.isControlled?(d=I==null?void 0:I.getRoom)==null?void 0:d.call(I):k.getRoom();if(v)return re.attachRoom(v),_e.attachRoom(v),k.isControlled&&Z.attachRoom(v),Je.refresh(),()=>{re.teardown(),_e.teardown()}},[k.isControlled,k.connectionState,I]),n.useEffect(()=>{const v=k.audioElement;v&&(v.muted=W)},[k.audioElement,W]);const Wn=n.useCallback(v=>{const d={type:"user_message",text:v};if(I!=null&&I.publishData){try{I.publishData(d)}catch{}return}const F=k.getRoom();if(F)try{const se=new TextEncoder().encode(JSON.stringify(d));F.localParticipant.publishData(se,{reliable:!0})}catch{}},[k,I]),Fn=n.useCallback(()=>{qn(v=>!v)},[]);n.useEffect(()=>{Se==null||Se(k.connectionState),k.connectionState==="connected"?ke==null||ke():k.connectionState==="disconnected"&&(Ae==null||Ae())},[k.connectionState,ke,Ae,Se]),n.useEffect(()=>{Ce==null||Ce(k.transcript)},[k.transcript,Ce]),n.useEffect(()=>{Ie==null||Ie(k.agentState)},[k.agentState,Ie]),n.useEffect(()=>{ut.setThinking(k.agentState==="thinking")},[k.agentState,ut]);const zt=n.useRef(!1);n.useEffect(()=>{!x||zt.current||Ye&&k.connectionState==="idle"&&(zt.current=!0,k.connect())},[x,k.connectionState,k,Ye]);const Un=n.useCallback(v=>{const d=S==null?void 0:S.find(F=>F.id===v);d&&(Qe(!1),v!==be&&(Xe(!0),k.disconnect(),Ne||bt(v),E==null||E(d)))},[S,be,k,Ne,E]);n.useEffect(()=>{ce&&k.connectionState==="connected"&&Xe(!1)},[k.connectionState,ce]),n.useEffect(()=>{if(!$e)return;const v=d=>{d.key==="Escape"&&Qe(!1)};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[$e]);const Vn=!!A||!!(J!=null&&J.avatarImageUrl)||k.isControlled,et=wn(Ge,a,Vn);Ve===void 0&&((qt=et.info)!=null&&qt.capabilities)&&(Et.current=et.info.capabilities);const ft=(J==null?void 0:J.name)??D??((Wt=k.agentConfig)==null?void 0:Wt.name)??((Ft=et.info)==null?void 0:Ft.name)??"Live Layer",Lt=(J==null?void 0:J.avatarImageUrl)??A??((Ut=k.agentConfig)==null?void 0:Ut.avatarImageUrl)??((Vt=et.info)==null?void 0:Vt.avatarImageUrl)??null,Yn=O??((Yt=k.agentConfig)==null?void 0:Yt.idleLoopUrl)??((Gt=et.info)==null?void 0:Gt.idleLoopUrl)??null,Gn=y??null,Kn=n.useCallback(()=>ne("expanded"),[ne]),Jn=n.useCallback(()=>ne("minimized"),[ne]),Ot=n.useCallback(()=>{k.disconnect(),ne("hidden")},[k,ne]),Xn=n.useCallback(()=>{const v=k.audioElement;v&&v.play().then(()=>le(!1)).catch(()=>{})},[k.audioElement]),Qn=n.useCallback(()=>{le(!1),k.connect()},[k]),ze={...Re,...ae?{}:{zIndex:Me}};z.primaryColor&&(ze["--ll-color-primary"]=z.primaryColor),z.accentColor&&(ze["--ll-color-accent"]=z.accentColor),z.backgroundColor&&(ze["--ll-color-bg"]=z.backgroundColor),z.textColor&&(ze["--ll-color-fg"]=z.textColor);const Zn=["ll-widget",`ll-widget--${X}`,`ll-widget--${we?"mobile":"desktop"}`,xt].filter(Boolean).join(" ");if(!Ye)return null;const er=t.jsx("div",{className:Zn,style:ze,"data-display-mode":X,"data-position":C,"data-experience-mode":h==="EMBEDDED"?"embedded":"widget",children:X==="expanded"&&t.jsx(Ar,{position:C,isMobile:we,agentName:ft,avatarImageUrl:Lt,idleLoopUrl:Yn,greeting:Gn,branding:z,teamMembers:S,currentTeamMemberId:be,isSwitchingTeamMember:ce,teamSwitcherOpen:$e,onToggleTeamSwitcher:()=>Qe(v=>!v),onSelectTeamMember:Un,connectionState:k.connectionState,agentState:k.agentState,transcript:k.transcript,isMuted:Z.isMuted,micDevices:Je.mics,activeMicId:Z.activeDeviceId,isCameraEnabled:re.isEnabled,cameraPreviewEl:re.previewEl,cameraDevices:Je.cameras,activeCameraId:re.activeDeviceId,isScreenShareEnabled:_e.isEnabled,screenPreviewEl:_e.previewEl,isSpeakerMuted:W,allowCamera:K,allowScreenShare:j,allowTyping:H,showMinimize:at,showClose:lt,chromeless:ee,compactControls:V,transforming:ve,transformingLabel:pe,languageMenuOpen:ct,onToggleLanguageMenu:()=>g(v=>!v),needsUserGesture:wt,canResume:k.canResume,micError:Z.micError,error:k.error,avatarVideoContainerRef:$t,agentVideoEl:k.videoElement,onConnect:()=>void k.connect(),onDisconnect:()=>k.disconnect(),onRetry:Qn,onResumeAudio:Xn,onToggleMute:Z.toggleMute,onSwitchMicDevice:v=>void Z.switchDevice(v),onToggleCamera:()=>void re.toggle(),onSwitchCameraDevice:v=>void re.switchDevice(v),onToggleScreenShare:()=>void _e.toggle(),onToggleSpeaker:Fn,onSendMessage:Wn,onMinimize:Jn,onClose:Ot,onClearMicError:Z.clearError})}),Ht=!ae&&(X==="hidden"||X==="minimized")?t.jsxs("div",{className:["ll-widget","ll-widget--floating",`ll-widget--${X}`,`ll-widget--${we?"mobile":"desktop"}`].join(" "),style:ze,"data-display-mode":X,"data-position":C,children:[X==="hidden"&&t.jsx(_r,{position:C,isMobile:we,isSpeaking:k.agentState==="speaking",onExpand:()=>ne("expanded"),label:`Open ${ft} widget`,avatarImageUrl:Lt,agentName:ft,containerEl:ye}),X==="minimized"&&t.jsx(Cr,{position:C,isMobile:we,agentName:ft,avatarImageUrl:Lt,agentState:k.agentState,isMuted:Z.isMuted,audioLevel:Ke,onExpand:Kn,onToggleMute:Z.toggleMute,onClose:Ot})]}):null,Bt=ye??(typeof document<"u"?document.body:null);return t.jsxs(t.Fragment,{children:[er,Ht&&Bt&&Nt.createPortal(Ht,Bt)]})});Hn.displayName="AvatarWidgetInner";const Bn=n.forwardRef(function(r,o){return t.jsx(hn,{children:t.jsx(Hn,{...r,ref:o})})});Bn.displayName="AvatarWidget";const to=({agentId:e,baseUrl:r,apiKey:o,mode:i,onAgentEvent:s,className:a,style:c})=>{const l=n.useRef(null),u=n.useRef(null),h=n.useRef(s);h.current=s;const x=n.useCallback(p=>{var L;const f=p.detail;(L=h.current)==null||L.call(h,f)},[]);return n.useEffect(()=>{const p=l.current;if(!p)return;const f=document.createElement("livelayer-widget");return f.setAttribute("agent-id",e),r&&f.setAttribute("base-url",r),o&&f.setAttribute("api-key",o),i&&f.setAttribute("mode",i),f.addEventListener("agent-event",x),p.appendChild(f),u.current=f,()=>{f.removeEventListener("agent-event",x),p.removeChild(f),u.current=null}},[e]),n.useEffect(()=>{u.current&&(i?u.current.setAttribute("mode",i):u.current.removeAttribute("mode"))},[i]),t.jsx("div",{ref:l,className:a,style:c})},no=n.forwardRef(function({id:r,intent:o,as:i="div",className:s,style:a,children:c},l){return n.createElement(i,{ref:l,"data-ll-region":r,"data-ll-intent":o,className:s,style:a},c)});function ro(e={}){const{onFieldUpdate:r,onComplete:o,source:i="all"}=e,[s,a]=n.useState({}),[c,l]=n.useState(!1),[u,h]=n.useState(null),x=n.useRef(r),p=n.useRef(o),f=n.useRef(i);n.useEffect(()=>{x.current=r,p.current=o,f.current=i},[r,o,i]);const L=n.useCallback(()=>{a({}),l(!1)},[]);return n.useEffect(()=>{if(typeof window>"u")return;const C=w=>{var b,S;const m=w.detail;if(m){if(m.phase==="field"){if(f.current!=="all"&&m.source!==f.current)return;l(!0),a(R=>R[m.fieldName]===m.value?R:{...R,[m.fieldName]:m.value});try{(b=x.current)==null||b.call(x,m)}catch(R){console.warn("[LiveLayer] useCollect onFieldUpdate threw.",R)}return}if(m.phase==="complete"){const R=m.result;if(f.current!=="all"&&R.source!==f.current)return;h(R),l(!1);try{(S=p.current)==null||S.call(p,R)}catch(E){console.warn("[LiveLayer] useCollect onComplete threw.",E)}}}};return document.addEventListener("ll-collected",C),()=>document.removeEventListener("ll-collected",C)},[]),{fields:s,isCollecting:c,lastResult:u,reset:L}}let pn=1;function oo({onMount:e,defaultOpen:r=!1,storageKey:o="ll-debug-open"}){const[i,s]=n.useState(r),[a,c]=n.useState([]),[l,u]=n.useState(""),[h,x]=n.useState(!1),p=n.useRef(new Set),f=n.useRef([]),L=n.useRef(h);L.current=h,n.useEffect(()=>{try{const m=localStorage.getItem(o);m==="1"&&s(!0),m==="0"&&s(!1)}catch{}},[o]),n.useEffect(()=>{try{localStorage.setItem(o,i?"1":"0")}catch{}},[i,o]),n.useEffect(()=>{const m=b=>{(b.metaKey||b.ctrlKey)&&b.shiftKey&&b.key.toLowerCase()==="l"&&(b.preventDefault(),s(S=>!S))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[]),n.useEffect(()=>{const m=setInterval(()=>{if(f.current.length===0||L.current)return;const b=f.current.splice(0,f.current.length);c(S=>[...b.reverse(),...S].slice(0,200))},100);return()=>clearInterval(m)},[]);const C=n.useRef(!1);if(n.useEffect(()=>{!e||C.current||(C.current=!0,e(m=>{f.current.push({id:pn++,ts:Date.now(),kind:"event",type:m.eventName,data:m.data})}))},[e]),n.useEffect(()=>{const m=console.warn,b=console.log,S=(R,E)=>function(...O){try{const y=typeof O[0]=="string"?O[0]:"";y.startsWith("[LiveLayer]")&&f.current.push({id:pn++,ts:Date.now(),kind:R,type:y.slice(0,120),data:{args:O.slice(1).map(A=>so(A))}})}catch{}return E.apply(this,O)};return console.warn=S("warn",m),console.log=S("log",b),()=>{console.warn=m,console.log=b}},[]),!i)return t.jsx("button",{type:"button",onClick:()=>s(!0),title:"Open LiveLayer debug panel (Cmd/Ctrl + Shift + L)","aria-label":"Open LiveLayer debug panel",style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.18)",borderRadius:999,padding:"6px 10px",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",cursor:"pointer",boxShadow:"0 4px 12px rgba(0,0,0,0.35)",opacity:.85},children:"🛰 LL debug"});const w=a.filter(m=>{if(!l)return!0;const b=l.toLowerCase();return m.type.toLowerCase().includes(b)||JSON.stringify(m.data||{}).toLowerCase().includes(b)});return t.jsxs("div",{style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,width:380,maxHeight:"60vh",background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:12,boxShadow:"0 16px 48px rgba(0,0,0,0.5)",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"8px 10px",background:"rgba(255,255,255,0.04)",borderBottom:"1px solid rgba(255,255,255,0.1)",display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontWeight:600,fontSize:12},children:"LiveLayer debug"}),t.jsxs("span",{style:{fontSize:10,color:"rgba(255,255,255,0.4)"},children:[a.length," event",a.length===1?"":"s"]}),t.jsx("span",{style:{flex:1}}),t.jsx("button",{type:"button",onClick:()=>x(m=>!m),style:jt(h?"#f59e0b":"transparent"),title:"Pause / resume capture",children:h?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{c([]),f.current=[]},style:jt("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>s(!1),style:jt("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:l,onChange:m=>u(m.target.value),placeholder:"filter by type or data…",style:{margin:8,padding:"6px 8px",background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:11,outline:"none"}}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"0 8px 8px"},children:w.length===0?t.jsxs("div",{style:{padding:14,fontSize:11,color:"rgba(255,255,255,0.4)",lineHeight:1.5},children:["No events yet. Connect to the agent and trigger a tool call — the events will stream in here. You can also dispatch commands manually in DevTools:",t.jsx("pre",{style:{marginTop:6,background:"rgba(255,255,255,0.04)",padding:6,borderRadius:4,fontSize:10,whiteSpace:"pre-wrap"},children:`window.__livelayerSimulateCommand({
|
|
1
|
+
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),r=require("react"),At=require("react-dom"),Ve=require("@livelayer/sdk"),yt=require("livekit-client");class yn extends r.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,i){var o,l;(l=(o=this.props).onError)==null||l.call(o,n,i)}render(){var n;return this.state.hasError?this.props.fallback?this.props.fallback:t.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[t.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),t.jsx("p",{className:"ll-error-boundary__message",children:((n=this.state.error)==null?void 0:n.message)||"Something went wrong."}),t.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function vn(e){const[n,i]=r.useState("idle"),[o,l]=r.useState("idle"),[s,c]=r.useState([]),[a,u]=r.useState(null),[h,b]=r.useState(null),[p,f]=r.useState(null),[E,C]=r.useState(!1),[w,m]=r.useState(null),x=r.useRef(null),S=r.useRef(e.onDataMessage);S.current=e.onDataMessage,r.useEffect(()=>{const y={onConnectionStateChange:P=>{i(P),P==="connected"&&m(null)},onAgentStateChange:l,onTranscript:P=>c([...P]),onAgentConfig:u,onAudioTrack:P=>f(P),onVideoTrack:P=>b(P),onVideoTrackRemoved:()=>b(null),onError:P=>m(P),onDataMessage:P=>{var z;(z=S.current)==null||z.call(S,P)},onResumabilityChange:C},A=new Ve.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},y);return x.current=A,i("idle"),l("idle"),c([]),u(null),b(null),f(null),C(!1),m(null),()=>{var P;(P=A.destroy)==null||P.call(A),x.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const R=r.useCallback(async()=>{const y=x.current;if(y)try{await y.connect()}catch(A){throw m(A instanceof Error?A.message:String(A)),A}},[]),j=r.useCallback(()=>{const y=x.current;y&&y.disconnect()},[]),O=r.useCallback(()=>{var y;return((y=x.current)==null?void 0:y.getRoom())??null},[]);return{connectionState:n,agentState:o,transcript:s,agentConfig:a,videoElement:h,audioElement:p,canResume:E,error:w,connect:R,disconnect:j,getRoom:O,session:x.current}}function bn(){const e=r.useRef(null),n=r.useRef(null),i=r.useRef(null),o=r.useRef(null),l=r.useRef(new Set),s=r.useRef(null),c=r.useCallback(()=>{const p=n.current;if(!p){o.current=null;return}(!s.current||s.current.length!==p.frequencyBinCount)&&(s.current=new Uint8Array(new ArrayBuffer(p.frequencyBinCount)));const f=s.current;p.getByteFrequencyData(f);let E=0;for(let w=0;w<f.length;w++)E+=f[w];const C=E/f.length/255;for(const w of l.current)try{w(C)}catch(m){console.error("[useAudioLevel] subscriber threw:",m)}o.current=requestAnimationFrame(c)},[]),a=r.useCallback(()=>{if(e.current||typeof window>"u"||typeof AudioContext>"u")return;const p=new AudioContext,f=p.createAnalyser();f.fftSize=64,f.connect(p.destination),e.current=p,n.current=f},[]),u=r.useCallback(p=>{if(a(),!(!e.current||!n.current)){if(i.current){try{i.current.disconnect()}catch{}i.current=null}try{const f=e.current.createMediaElementSource(p);f.connect(n.current),i.current=f}catch(f){console.warn("[useAudioLevel] createMediaElementSource failed:",f);return}o.current===null&&(o.current=requestAnimationFrame(c))}},[a,c]),h=r.useCallback(()=>{if(o.current!==null&&(cancelAnimationFrame(o.current),o.current=null),i.current){try{i.current.disconnect()}catch{}i.current=null}},[]),b=r.useCallback(p=>(l.current.add(p),()=>{l.current.delete(p)}),[]);return r.useEffect(()=>()=>{if(h(),n.current){try{n.current.disconnect()}catch{}n.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}l.current.clear(),s.current=null},[h]),{attach:u,detach:h,subscribe:b}}function xn(){const[e,n]=r.useState(!1),[i,o]=r.useState(""),[l,s]=r.useState(null),c=r.useRef(null),a=r.useRef(null),u=r.useCallback(async C=>{var w,m;if(c.current&&a.current){try{await a.current.localParticipant.unpublishTrack(c.current)}catch{}c.current.stop(),c.current=null}a.current=C,s(null);try{const x=await yt.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await C.localParticipant.publishTrack(x),c.current=x,n(x.isMuted);const S=(m=(w=x.mediaStreamTrack)==null?void 0:w.getSettings)==null?void 0:m.call(w);S!=null&&S.deviceId&&o(S.deviceId)}catch(x){const S=x instanceof Error&&x.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw s(S),x}},[]),h=r.useCallback(C=>{a.current=C},[]),b=r.useCallback(async C=>{const w=a.current;if(w)try{await w.switchActiveDevice("audioinput",C),o(C)}catch(m){console.warn("[useMicrophoneState] switchDevice failed:",m)}},[]),p=r.useCallback(async()=>{const C=a.current,w=!e;if(n(w),!!C)try{await C.localParticipant.setMicrophoneEnabled(!w)}catch(m){console.warn("[useMicrophoneState] setMicrophoneEnabled failed:",m),n(!w)}},[e]),f=r.useCallback(()=>{const C=c.current,w=a.current;if(C&&w){try{w.localParticipant.unpublishTrack(C)}catch{}C.stop()}c.current=null,a.current=null,n(!1),o("")},[]),E=r.useCallback(()=>s(null),[]);return{isMuted:e,activeDeviceId:i,micError:l,toggleMute:p,setupMic:u,attachRoom:h,switchDevice:b,teardownMic:f,clearError:E}}const lr={resolution:{width:640,height:480,frameRate:24}};function wn(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),[l,s]=r.useState(null),[c,a]=r.useState(""),u=r.useRef(null),h=r.useRef(null),b=r.useCallback(x=>{u.current=x},[]),p=r.useCallback(()=>{var R;const x=u.current,S=h.current;if(S&&x){const j=x.localParticipant.getTrackPublication(yt.Track.Source.Camera),y=(j==null?void 0:j.track)??S;try{x.localParticipant.unpublishTrack(y)}catch{}try{(R=y.stop)==null||R.call(y)}catch{}}h.current=null,s(null),n(!1)},[]),f=r.useCallback(async x=>{const S=u.current;if(S){o(null);try{const R={...lr};x&&(R.deviceId=x);const j=await yt.createLocalVideoTrack(R);await S.localParticipant.publishTrack(j),h.current=j;const O=j.attach();s(O),n(!0),x&&a(x);try{S.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(R){const j=R instanceof Error&&R.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";o(j)}}},[]),E=r.useCallback(async()=>{e?p():await f(c||void 0)},[e,c,p,f]),C=r.useCallback(async x=>{p(),await f(x)},[p,f]),w=r.useCallback(()=>{p(),u.current=null,o(null),a("")},[p]),m=r.useCallback(()=>o(null),[]);return r.useEffect(()=>()=>{h.current&&h.current.stop()},[]),{isEnabled:e,error:i,previewEl:l,activeDeviceId:c,toggle:E,switchDevice:C,attachRoom:b,teardown:w,clearError:m}}function _n(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),[l,s]=r.useState(null),c=r.useRef(null),a=r.useCallback(f=>{c.current=f},[]),u=r.useCallback(()=>s(null),[]),h=r.useCallback(async()=>{const f=c.current;if(f){if(e){try{await f.localParticipant.setScreenShareEnabled(!1)}catch{}u(),n(!1);return}o(null);try{await f.localParticipant.setScreenShareEnabled(!0);let E=0;const C=()=>{const w=f.localParticipant.getTrackPublication(yt.Track.Source.ScreenShare);if(w!=null&&w.track){const m=w.track.attach();s(m),n(!0);try{f.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}E++<10?setTimeout(C,100):n(!0)};C()}catch(E){const C=E instanceof Error?E.name:"";C!=="NotAllowedError"&&C!=="AbortError"&&o("Screen share unavailable. Try again."),n(!1)}}},[e,u]),b=r.useCallback(()=>{const f=c.current;if(f&&e)try{f.localParticipant.setScreenShareEnabled(!1)}catch{}u(),n(!1),o(null),c.current=null},[e,u]),p=r.useCallback(()=>o(null),[]);return{isEnabled:e,error:i,previewEl:l,toggle:h,attachRoom:a,teardown:b,clearError:p}}function kn(){const[e,n]=r.useState([]),[i,o]=r.useState([]),l=r.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const s=await navigator.mediaDevices.enumerateDevices();n(s.filter(c=>c.kind==="audioinput")),o(s.filter(c=>c.kind==="videoinput"))}catch{}},[]);return r.useEffect(()=>{if(l(),typeof navigator>"u"||!navigator.mediaDevices)return;const s=()=>void l();return navigator.mediaDevices.addEventListener("devicechange",s),()=>navigator.mediaDevices.removeEventListener("devicechange",s)},[l]),{mics:e,cameras:i,refresh:l}}function Cn(e,n,i=!1){const[o,l]=r.useState(null),[s,c]=r.useState(null),[a,u]=r.useState(!i&&!!e);return r.useEffect(()=>{if(i||!e){u(!1);return}const h=new AbortController,b=n||"https://app.livelayer.studio";return u(!0),c(null),fetch(`${b}/api/widget/agent/${encodeURIComponent(e)}`,{signal:h.signal}).then(async p=>{if(!p.ok){const f=await p.json().catch(()=>({}));throw new Error(f.error||`HTTP ${p.status}`)}return p.json()}).then(p=>{h.signal.aborted||(l(p),u(!1))}).catch(p=>{h.signal.aborted||(c(p instanceof Error?p.message:"Agent lookup failed"),u(!1))}),()=>h.abort()},[e,n,i]),{info:o,error:s,loading:a}}function ar(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function cr(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n)}catch{}}function Sn({value:e,defaultValue:n="expanded",onChange:i}={}){const o=e!==void 0,[l,s]=r.useState(n),c=o?e:l,a=r.useCallback(u=>{u!==c&&(o||s(u),i==null||i(u))},[c,o,i]);return[c,a]}const ur=["hidden","minimized","expanded"];function dr(e){return e&&ur.includes(e)?e:null}function jn({value:e,defaultValue:n="expanded",onChange:i,persistKey:o="ll-widget",disablePersistence:l=!1}={}){const s=`${o}:display-mode`,c=r.useRef(!1),[a,u]=Sn({value:e,defaultValue:n,onChange:h=>{e===void 0&&!l&&cr(s,h),i==null||i(h)}});return r.useEffect(()=>{if(c.current||(c.current=!0,l||e!==void 0))return;const h=dr(ar(s));h&&h!==a&&u(h)},[]),[a,u]}const fr=640;function En(e=fr){const[n,i]=r.useState(!1);return r.useEffect(()=>{if(e===!1){i(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const o=`(max-width: ${e-1}px)`,l=window.matchMedia(o),s=()=>i(l.matches);return s(),typeof l.addEventListener=="function"?(l.addEventListener("change",s),()=>l.removeEventListener("change",s)):(l.addListener(s),()=>{l.removeListener(s)})},[e]),n}const Jt="__llHistoryPatched",vt="ll:pathname";function pr(){if(typeof window>"u"||window.history[Jt])return;const e=window.history.pushState,n=window.history.replaceState;window.history.pushState=function(...i){const o=e.apply(this,i);return window.dispatchEvent(new Event(vt)),o},window.history.replaceState=function(...i){const o=n.apply(this,i);return window.dispatchEvent(new Event(vt)),o},window.history[Jt]=!0}function Xt(){return typeof window>"u"?"/":window.location.pathname||"/"}function Ln(e){const[n,i]=r.useState(()=>e??Xt());return r.useEffect(()=>{if(e!==void 0)return;pr();const o=()=>i(Xt());return o(),window.addEventListener("popstate",o),window.addEventListener(vt,o),()=>{window.removeEventListener("popstate",o),window.removeEventListener(vt,o)}},[e]),e??n}const Qt=new Map,hr=/[\\^$+?.()|{}[\]]/g;function mr(e){return e.replace(hr,"\\$&")}function gr(e){const n=Qt.get(e);if(n)return n;const i=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,o="",l="",s=i.replace(/\*\*/g,o).replace(/\*/g,l),a=mr(s).replace(new RegExp(`\\/${o}`,"g"),"(?:\\/.*)?").replace(new RegExp(o,"g"),".*").replace(new RegExp(l,"g"),"[^/]+"),u=new RegExp(`^${a}\\/?$`);return Qt.set(e,u),u}function yr(e,n){const i=n.length>1&&n.endsWith("/")?n.slice(0,-1):n;return gr(e).test(i)}function Rn(e,n){return typeof e=="function"?e(n):e instanceof RegExp?e.test(n):yr(e,n)}function Zt(e,n){if(!e||e.length===0)return!1;for(const i of e)if(Rn(i,n))return!0;return!1}function Nn(e,n,i){return e===void 0?!0:Zt(i,e)?!1:n&&n.length>0?Zt(n,e):!0}function An(e,n,i){return r.useMemo(()=>Nn(e,n,i),[e,n,i])}function vr(e){return e===!1?{navigate:!1,thinking:!1,action:!1}:e===void 0||e===!0?{navigate:!0,thinking:!0,action:!0}:{navigate:e.navigate!==!1,thinking:e.thinking!==!1,action:e.action!==!1}}function br(e){const n=r.useMemo(()=>vr(e.config),[e.config]),i=e.baseUrl.replace(/\/+$/,""),o=r.useRef(null),l=r.useCallback(u=>{try{new Audio(`${i}${u}`).play().catch(()=>{})}catch{}},[i]),s=r.useCallback(()=>{n.navigate&&l("/audio/page-change-sound.mp3")},[n.navigate,l]),c=r.useCallback(()=>{n.action&&l("/audio/confirmation-sound.mp3")},[n.action,l]),a=r.useCallback(u=>{if(!n.thinking){if(o.current){try{o.current.pause()}catch{}o.current=null}return}if(u){if(o.current)return;try{const h=new Audio(`${i}/audio/thinking-sound.mp3`);h.loop=!0,h.volume=.3,h.play().catch(()=>{o.current=null}),o.current=h}catch{}}else if(o.current){try{o.current.pause()}catch{}o.current=null}},[i,n.thinking]);return r.useEffect(()=>()=>{if(o.current){try{o.current.pause()}catch{}o.current=null}},[]),r.useMemo(()=>({playPageChange:s,playConfirmation:c,setThinking:a}),[s,c,a])}const en=({muted:e=!1,className:n})=>e?t.jsxs("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):t.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),tn=({className:e})=>t.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})}),xr=({className:e})=>t.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),wr={left:180,right:0,up:-90,down:90},nn=({direction:e="right",className:n})=>t.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${wr[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function _r(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const In="ll-hidden-tab-center-y",kr=5,rn=16;function Cr(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(In);if(!e)return null;const n=Number.parseFloat(e);return Number.isFinite(n)?n:null}catch{return null}}function on(e){if(!(typeof window>"u"))try{window.localStorage.setItem(In,String(e))}catch{}}const Sr=({position:e,isMobile:n,isSpeaking:i,onExpand:o,label:l="Open widget",avatarImageUrl:s,agentName:c,containerEl:a})=>{const u=_r(e),h=u==="right"?"left":"right",b=n?80:72,p=!!s,f=!!a,[E,C]=r.useState(null),[w,m]=r.useState(!1),x=r.useRef(null),S=r.useRef(!1),R=r.useCallback(D=>{if(typeof window>"u")return D;const F=b/2,L=rn+F,V=window.innerHeight-rn-F;return V<L?Math.max(L,D):Math.max(L,Math.min(V,D))},[b]);r.useEffect(()=>{if(f){C(null);return}const D=Cr();C(R(D??window.innerHeight/2));const F=()=>{C(L=>L===null?null:R(L))};return window.addEventListener("resize",F),()=>window.removeEventListener("resize",F)},[R,f]);const j=r.useCallback(D=>{if(!f&&!(D.pointerType==="mouse"&&D.button!==0)&&E!==null){try{D.currentTarget.setPointerCapture(D.pointerId)}catch{}x.current={startClientY:D.clientY,startCenterY:E,moved:!1}}},[E,f]),O=r.useCallback(D=>{const F=x.current;if(!F)return;const L=D.clientY-F.startClientY;!F.moved&&Math.abs(L)>kr&&(F.moved=!0,m(!0)),F.moved&&C(R(F.startCenterY+L))},[R]),y=r.useCallback(D=>{const F=x.current;if(F){try{D.currentTarget.releasePointerCapture(D.pointerId)}catch{}x.current=null,F.moved&&(m(!1),S.current=!0,C(L=>(L!==null&&on(L),L)))}},[]),A=r.useCallback(()=>{if(S.current){S.current=!1;return}o()},[o]),P=r.useCallback(D=>{if(D.key==="ArrowUp"||D.key==="ArrowDown"){D.preventDefault();const F=D.key==="ArrowUp"?-8:8;C(L=>{if(L===null)return L;const V=R(L+F);return on(V),V})}},[R]),z=["ll-hidden",`ll-hidden--${u}`,n?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,w?"is-dragging":null,p?"ll-hidden--with-avatar":null,f?"ll-hidden--scoped":null].filter(Boolean).join(" "),J=E===null?void 0:{top:`${E-b/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:z,onPointerDown:j,onPointerMove:O,onPointerUp:y,onPointerCancel:y,onClick:A,onKeyDown:P,"aria-label":l,"data-position":e,style:J,children:p?t.jsxs(t.Fragment,{children:[t.jsx(nn,{direction:h,className:"ll-hidden__chevron ll-hidden__chevron--mini"}),t.jsx("img",{src:s,alt:c?`${c} avatar`:"Agent avatar",className:"ll-hidden__avatar",draggable:!1})]}):t.jsx(nn,{direction:h,className:"ll-hidden__chevron"})})},jr=({audioLevel:e,bars:n=20,maxHeight:i=20,minHeight:o=4,className:l,barClassName:s})=>{const c=r.useRef(null),a=r.useRef([]),u=r.useMemo(()=>{const b=(Math.sqrt(5)-1)/2;return Array.from({length:n},(p,f)=>.5+f*b%1*.5)},[n]);r.useEffect(()=>e.subscribe(p=>{for(let f=0;f<n;f++){const E=a.current[f];if(!E)continue;const C=Math.max(o,p*i*u[f]);E.style.height=`${C}px`}}),[e,n,i,o,u]);const h=["ll-waveform",l].filter(Boolean).join(" ");return t.jsx("div",{ref:c,className:h,"aria-hidden":"true",children:Array.from({length:n},(b,p)=>t.jsx("div",{ref:f=>{a.current[p]=f},className:["ll-waveform__bar",s].filter(Boolean).join(" "),style:{height:`${o}px`}},p))})},Er=({position:e,isMobile:n,agentName:i,avatarImageUrl:o,agentState:l,isMuted:s,audioLevel:c,onExpand:a,onToggleMute:u,onClose:h})=>n?t.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${i} widget`,children:t.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:a,"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(jr,{audioLevel:c,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),t.jsx("span",{className:"ll-minimized__name",children:i}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:b=>{b.stopPropagation(),u()},onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.stopPropagation(),b.preventDefault(),u())},"aria-label":s?"Unmute microphone":"Mute microphone",children:t.jsx(en,{muted:s,className:"ll-minimized__icon"})}),t.jsx(tn,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):t.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":e,role:"region","aria-label":`${i} widget`,children:t.jsxs("div",{className:"ll-minimized__surface",children:[o?t.jsx("img",{src:o,alt:i,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsxs("div",{className:"ll-minimized__meta",children:[t.jsx("span",{className:"ll-minimized__name",children:i}),t.jsx("span",{className:"ll-minimized__state",children:l==="speaking"?"Speaking":l==="thinking"?"Thinking":"Listening"})]}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:u,"aria-label":s?"Unmute microphone":"Mute microphone",children:t.jsx(en,{muted:s,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:a,"aria-label":`Expand ${i} widget`,children:t.jsx(tn,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:h,"aria-label":"Close widget",children:t.jsx(xr,{className:"ll-minimized__icon"})})]})]})}),Lr=({src:e,alt:n,preCannedPlaying:i=!1,className:o,style:l})=>{const[s,c]=r.useState(!1),a=r.useRef(e);if(r.useEffect(()=>{a.current!==e&&(a.current=e,c(!1))},[e]),!e)return null;const u={position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",objectPosition:"top",transition:"opacity 500ms ease, transform 500ms ease",transform:i?"scale(1.02)":"scale(1)",opacity:s?1:0,...l};return t.jsx("img",{src:e,alt:n,className:o,style:u,loading:"eager",fetchPriority:"high",onLoad:()=>c(!0)})},Rr=8,sn=8,Nr=({open:e,onClose:n,anchorRef:i,children:o})=>{const l=r.useRef(null),[s,c]=r.useState(null);return r.useLayoutEffect(()=>{if(!e){c(null);return}const a=i.current;if(!a)return;const u=()=>{const h=a.getBoundingClientRect(),b={top:h.top-Rr,left:h.left+h.width/2},p=sn+90,f=window.innerWidth-sn-90;b.left<p&&(b.left=p),b.left>f&&(b.left=f),c(b)};return u(),window.addEventListener("scroll",u,!0),window.addEventListener("resize",u),()=>{window.removeEventListener("scroll",u,!0),window.removeEventListener("resize",u)}},[e,i]),r.useEffect(()=>{if(!e)return;const a=h=>{const b=h.target,p=l.current,f=i.current;p&&p.contains(b)||f&&f.contains(b)||n()},u=h=>{h.key==="Escape"&&(h.stopPropagation(),n())};return document.addEventListener("mousedown",a),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",a),document.removeEventListener("keydown",u)}},[e,n,i]),!e||s===null||typeof document>"u"?null:At.createPortal(t.jsx("div",{ref:l,className:"ll-overflow-popover",role:"menu",style:{position:"fixed",top:s.top,left:s.left,transform:"translate(-50%, -100%)"},children:o}),document.body)},Ar=({isMuted:e,onToggleMute:n,isCameraEnabled:i,onToggleCamera:o,allowCamera:l,isScreenShareEnabled:s,onToggleScreenShare:c,allowScreenShare:a,isSpeakerMuted:u,onToggleSpeaker:h,allowTyping:b,isTypingOpen:p,onToggleTyping:f,onDisconnect:E})=>{const[C,w]=r.useState(!1),m=r.useRef(null);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"ll-toolbar ll-toolbar--compact","data-testid":"compact-toolbar",onClick:x=>x.stopPropagation(),children:[t.jsx("button",{type:"button",className:`ll-tool ${e?"is-muted":""}`,onClick:n,"aria-label":e?"Unmute microphone":"Mute microphone",children:t.jsx(Pn,{muted:e})}),t.jsx("button",{ref:m,type:"button",className:`ll-tool ${C?"is-on":""}`,onClick:()=>w(x=>!x),"aria-label":"More controls","aria-haspopup":"menu","aria-expanded":C,children:t.jsx(Ir,{})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:E,"aria-label":"End conversation",children:t.jsx($n,{})})]}),t.jsxs(Nr,{open:C,onClose:()=>w(!1),anchorRef:m,children:[l&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${i?"is-on":""}`,onClick:()=>{o(),w(!1)},children:[t.jsx(Tn,{}),t.jsx("span",{children:i?"Stop camera":"Start camera"})]}),a&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${s?"is-on":""}`,onClick:()=>{c(),w(!1)},children:[t.jsx(Mn,{}),t.jsx("span",{children:s?"Stop sharing":"Share screen"})]}),t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${u?"is-on":""}`,onClick:()=>{h(),w(!1)},children:[t.jsx(Dn,{muted:u}),t.jsx("span",{children:u?"Unmute speaker":"Mute speaker"})]}),b&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${p?"is-on":""}`,onClick:()=>{f(),w(!1)},children:[t.jsx(Mr,{}),t.jsx("span",{children:p?"Hide typing":"Type a message"})]}),t.jsxs("button",{type:"button",className:"ll-overflow-popover__item is-active",disabled:!0,"aria-current":"true",children:[t.jsx("span",{className:"ll-overflow-popover__lang-code",children:"EN"}),t.jsx("span",{children:"English"})]})]})]})};function Ir(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[t.jsx("circle",{cx:"6",cy:"12",r:"1.5"}),t.jsx("circle",{cx:"12",cy:"12",r:"1.5"}),t.jsx("circle",{cx:"18",cy:"12",r:"1.5"})]})}function Mr(){return t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:t.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}const Tr=({position:e,isMobile:n,agentName:i,avatarImageUrl:o,idleLoopUrl:l,greeting:s,branding:c,teamMembers:a,currentTeamMemberId:u,isSwitchingTeamMember:h,teamSwitcherOpen:b,onToggleTeamSwitcher:p,onSelectTeamMember:f,languageMenuOpen:E,onToggleLanguageMenu:C,connectionState:w,agentState:m,transcript:x,canResume:S,needsUserGesture:R,error:j,isMuted:O,micError:y,micDevices:A,activeMicId:P,isCameraEnabled:z,cameraPreviewEl:J,cameraDevices:D,activeCameraId:F,isScreenShareEnabled:L,screenPreviewEl:V,isSpeakerMuted:pe,allowCamera:te,allowScreenShare:Ie,allowTyping:Me,showMinimize:he=!0,showClose:_e=!0,chromeless:W=!1,compactControls:Y=!1,transforming:me,transformingLabel:ge,avatarVideoContainerRef:ke,agentVideoEl:ie,onConnect:Ye,onDisconnect:Ge,onRetry:lt,onResumeAudio:Ke,onToggleMute:Ce,onSwitchMicDevice:Te,onToggleCamera:Se,onSwitchCameraDevice:Pe,onToggleScreenShare:je,onToggleSpeaker:Ee,onSendMessage:Le,onMinimize:Re,onClose:I,onClearMicError:bt})=>{var ut;const Ne=((a==null?void 0:a.length)??0)>1,De=w==="connecting"||w==="connected",oe=w==="connected",Je=w==="idle"||w==="disconnected"||w==="error",[Ae,$e]=r.useState(!1);r.useEffect(()=>{if(!ie){$e(!1);return}if(!ie.paused&&ie.readyState>=2){$e(!0);return}$e(!1);const g=()=>$e(!0);return ie.addEventListener("playing",g),ie.addEventListener("loadeddata",g),()=>{ie.removeEventListener("playing",g),ie.removeEventListener("loadeddata",g)}},[ie]);const[xt,be]=r.useState(!1);r.useEffect(()=>{if(!oe){be(!1);return}if(Ae)return;const g=setTimeout(()=>be(!0),8e3);return()=>clearTimeout(g)},[oe,Ae]);const X=w==="connecting"||oe&&!!o&&!Ae&&!xt,Xe=r.useRef(null),le=r.useRef(null);r.useEffect(()=>{const g=Xe.current;g&&(g.innerHTML="",J&&(J.style.width="100%",J.style.height="100%",J.style.objectFit="cover",J.style.transform="scaleX(-1)",g.appendChild(J)))},[J]),r.useEffect(()=>{const g=le.current;g&&(g.innerHTML="",V&&(V.style.width="100%",V.style.height="100%",V.style.objectFit="contain",g.appendChild(V)))},[V]);const[ze,Oe]=r.useState(!1),[Q,ne]=r.useState(!1),at=r.useRef(null),ct=r.useRef(null);r.useEffect(()=>{if(!ze&&!Q&&!E&&!b)return;const g=()=>{Oe(!1),ne(!1),E&&C(),b&&p()};return document.addEventListener("click",g),()=>document.removeEventListener("click",g)},[ze,Q,E,b,C,p]);const[xe,Qe]=r.useState(!1),ee=r.useCallback(()=>Qe(g=>!g),[]),[re,we]=r.useState(""),Ze=r.useCallback(g=>{g.preventDefault();const q=re.trim();q&&(Le(q),we(""))},[re,Le]),wt=c.productName||"Live Layer";let ae=null,ce=null;for(let g=x.length-1;g>=0;g--){const q=x[g];if(!ae&&q.role==="agent"?ae=q:!ce&&q.role==="user"&&(ce=q),ae&&ce)break}const et=oe?(ae==null?void 0:ae.text)||null:s||null,Fe=oe&&(ce==null?void 0:ce.text)||null,tt=["ll-expanded",n?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:tt,"data-position":e,"data-state":oe?"connected":De?"connecting":"idle",role:"dialog","aria-label":`${i} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[o?t.jsx(Lr,{src:o,alt:i,className:"ll-expanded__bg-img"}):t.jsx("div",{className:"ll-expanded__bg-fallback",children:t.jsx("span",{className:"ll-expanded__bg-initial",children:((ut=i==null?void 0:i.charAt(0))==null?void 0:ut.toUpperCase())||"A"})}),l&&!oe&&t.jsx("video",{className:"ll-expanded__bg-idle",src:l,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:ke,className:"ll-expanded__video"}),X&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--connecting",children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:h?"Switching...":"Connecting..."})]}),R&&oe&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:Ke,children:[t.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("path",{d:"M3 9v6h4l5 5V4L7 9H3zm13.54.12a5 5 0 0 1 0 5.76l-1.41-1.41a3 3 0 0 0 0-2.94L16.54 9.12z"})}),t.jsx("p",{className:"ll-expanded__overlay-text",children:"Tap to enable audio"})]}),me&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--transforming",role:"status","aria-live":"polite","aria-label":ge,children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:ge})]}),De?t.jsxs(t.Fragment,{children:[!Y&&t.jsxs("div",{className:"ll-expanded__topbar",children:[!W&&t.jsxs("div",{className:"ll-expanded__topbar-left",children:[t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill",onClick:g=>{Ne&&(g.stopPropagation(),p())},"aria-haspopup":Ne?"listbox":void 0,"aria-expanded":Ne?b:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:i}),Ne&&t.jsx(ht,{})]}),Ne&&b&&t.jsx("div",{className:"ll-hmenu",onClick:g=>g.stopPropagation(),role:"listbox",children:a==null?void 0:a.map(g=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${g.id===u?"is-active":""}`,onClick:()=>f(g.id),role:"option","aria-selected":g.id===u,children:[g.avatarImageUrl&&t.jsx("img",{src:g.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:g.name}),g.role&&t.jsx("span",{className:"ll-hmenu__role",children:g.role})]},g.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:g=>{g.stopPropagation(),C()},"aria-haspopup":"listbox","aria-expanded":E,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(ht,{})]}),E&&t.jsx("div",{className:"ll-hmenu",onClick:g=>g.stopPropagation(),role:"listbox",children:t.jsx("button",{type:"button",className:"ll-hmenu__item is-active",role:"option","aria-selected":!0,children:t.jsx("span",{className:"ll-hmenu__name",children:"English"})})})]}),t.jsx("span",{className:`ll-expanded__state ll-expanded__state--${m}`,children:m})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[he!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn",onClick:Re,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(an,{})}),_e!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:I,"aria-label":"End call",title:"End call",children:t.jsx(ln,{})})]})]}),Y&&t.jsxs("div",{className:"ll-compact-status","data-state":m,children:[t.jsx("span",{className:"ll-compact-status__dot","aria-hidden":!0}),t.jsx("span",{className:"ll-compact-status__label",children:m})]})]}):!Y&&t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:wt}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[he!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:Re,"aria-label":"Minimize widget",children:t.jsx(an,{})}),_e!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:I,"aria-label":"Close widget",children:t.jsx(ln,{})})]})]}),Je&&(()=>{const g=S?"Resume session":w==="disconnected"?"Reconnect to agent":"Start video call",q=!j;return t.jsxs(t.Fragment,{children:[q&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:Ye,"aria-label":g,children:[t.jsx("div",{className:"ll-expanded__play-circle",children:t.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("polygon",{points:"6 3 20 12 6 21 6 3"})})}),Y&&t.jsx("span",{className:"ll-expanded__play-label",children:g})]}),!Y&&t.jsxs("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:[s&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:s})}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:Ye,"aria-label":g,children:g})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${De&&(z||L)?"is-visible":""}`,children:[t.jsx("div",{ref:le,className:L?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:Xe,className:!L&&z?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),De?t.jsxs("div",{className:"ll-expanded__bottom",children:[!Y&&et&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--agent","data-role":"agent",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:et})}),!Y&&Fe&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--user","data-role":"user",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:Fe})}),!W&&!Y&&t.jsxs("div",{className:"ll-toolbar",onClick:g=>g.stopPropagation(),children:[Ie&&t.jsx("button",{type:"button",className:`ll-tool ${L?"is-on":""}`,onClick:je,"aria-label":L?"Stop sharing screen":"Share screen",title:L?"Stop sharing":"Share screen",children:t.jsx(Mn,{})}),te&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${z?"is-on":""}`,onClick:Se,"aria-label":z?"Turn off camera":"Turn on camera",title:z?"Stop camera":"Start camera",children:t.jsx(Tn,{})}),t.jsx("button",{ref:ct,type:"button",className:`ll-tool ll-tool--right ${z?"is-on":""}`,onClick:g=>{g.stopPropagation(),ne(q=>!q),Oe(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":Q,children:t.jsx(ht,{})}),Q&&D.length>0&&t.jsx(cn,{label:"Camera",devices:D,activeId:F,anchorRef:ct,onPick:g=>{ne(!1),Pe(g)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${O?"is-muted":""}`,onClick:Ce,"aria-label":O?"Unmute microphone":"Mute microphone",title:O?"Unmute":"Mute",children:t.jsx(Pn,{muted:O})}),t.jsx("button",{ref:at,type:"button",className:`ll-tool ll-tool--right ${O?"is-muted":""}`,onClick:g=>{g.stopPropagation(),Oe(q=>!q),ne(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":ze,children:t.jsx(ht,{})}),ze&&A.length>0&&t.jsx(cn,{label:"Microphone",devices:A,activeId:P,anchorRef:at,onPick:g=>{Oe(!1),Te(g)}})]}),t.jsx("button",{type:"button",className:`ll-tool ${pe?"is-muted":""}`,onClick:Ee,"aria-label":pe?"Unmute speaker":"Mute speaker",title:pe?"Unmute speaker":"Mute speaker",children:t.jsx(Dn,{muted:pe})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:Ge,"aria-label":"End conversation",title:"End conversation",children:t.jsx($n,{})})]}),!W&&Y&&t.jsx(Ar,{isMuted:O,onToggleMute:Ce,isCameraEnabled:z,onToggleCamera:Se,allowCamera:te,isScreenShareEnabled:L,onToggleScreenShare:je,allowScreenShare:Ie,isSpeakerMuted:pe,onToggleSpeaker:Ee,allowTyping:Me,isTypingOpen:xe,onToggleTyping:ee,onDisconnect:Ge}),!W&&Me&&(Y?xe:!0)&&t.jsxs("form",{className:"ll-message-input",onSubmit:Ze,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:re,onChange:g=>we(g.target.value),"aria-label":"Message the agent"}),re.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(Pr,{})})]})]}):null,(()=>{if(y&&w!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:y}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:bt,"aria-label":"Dismiss",children:"×"})]});if(!j||w!=="error")return null;let g="Failed to connect",q="Try again";return j==="MIC_PERMISSION_DENIED"?g="Microphone blocked. Allow access to talk.":j==="MIC_NOT_FOUND"?g="No microphone found. Plug one in + retry.":j==="MIC_UNAVAILABLE"?g="Mic unavailable. Check other apps using it.":j==="AGENT_TIMEOUT"?g="Agent didn't pick up. Try again.":j==="CONNECT_FAILED"?g="Connection failed. Check your network.":j.length<80&&(g=j),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:g}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:lt,children:q})]})})()]})};function ht(){return t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":!0,children:t.jsx("polyline",{points:"6 9 12 15 18 9"})})}function ln(){return t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function an(){return t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})})}function Mn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Tn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M23 7l-7 5 7 5V7z"}),t.jsx("rect",{x:"1",y:"5",width:"15",height:"14",rx:"2"})]})}function Pn({muted:e}){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),t.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),t.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),e&&t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Dn({muted:e}){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e?t.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}):t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"}),t.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]})]})}function Pr(){return t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),t.jsx("polyline",{points:"12 5 19 12 12 19"})]})}function $n(){return t.jsx("svg",{width:"16",height:"16",viewBox:"-4 -4 32 32",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:t.jsx("path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.93.37 1.84.71 2.7a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.38-1.38a2 2 0 0 1 2.11-.45c.86.34 1.77.58 2.7.71A2 2 0 0 1 22 16.92z",transform:"rotate(135 12 12)"})})}const cn=({label:e,devices:n,activeId:i,onPick:o,anchorRef:l})=>{const[s,c]=r.useState(null);return r.useLayoutEffect(()=>{const a=()=>{const u=l.current;if(!u)return;const h=u.getBoundingClientRect(),b=126,p=window.innerWidth-16-110,f=h.left+h.width/2;c({top:h.top-8,left:Math.max(b,Math.min(p,f))})};return a(),window.addEventListener("scroll",a,!0),window.addEventListener("resize",a),()=>{window.removeEventListener("scroll",a,!0),window.removeEventListener("resize",a)}},[l]),s===null||typeof document>"u"?null:At.createPortal(t.jsxs("div",{className:"ll-device-menu ll-device-menu--floating",onClick:a=>a.stopPropagation(),role:"listbox",style:{position:"fixed",top:s.top,left:s.left,transform:"translate(-50%, -100%)"},children:[t.jsx("p",{className:"ll-device-menu__label",children:e}),n.map((a,u)=>{const h=i===a.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${h?"is-active":""}`,onClick:()=>o(a.deviceId),role:"option","aria-selected":h,children:[h&&t.jsx("span",{className:"ll-device-menu__dot",children:"●"}),t.jsx("span",{className:"ll-device-menu__name",children:a.label||`${e} ${u+1}`})]},a.deviceId||u)})]}),document.body)},Dr=["[data-ll-private]","[data-ll-skip]",".ll-widget"];function It(e){let n=e;for(;n;){for(const i of Dr)if(n.matches(i))return!0;n=n.parentElement}return!1}function Rt(e){if(It(e))return!1;if(e instanceof HTMLInputElement){if(e.type==="password")return!1;const n=(e.getAttribute("autocomplete")||"").toLowerCase();if(n==="off"||n.startsWith("cc-"))return!1}return!0}const mt=4096,$r=20,zr=20,Or=10,Fr=10,Hr=30,Br=20,un=500,qr=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function ot(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let n=e;for(;n;){for(const i of qr)if(n.matches(i))return!0;n=n.parentElement}return!1}function st(e){if(typeof window>"u")return!0;const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return!1;const i=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth;return n.bottom>0&&n.right>0&&n.top<i&&n.left<o}function dn(e){const n=e.getAttribute("id");if(n){const s=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(n):n.replace(/"/g,'\\"'),c=document.querySelector(`label[for="${s}"]`);if(c!=null&&c.textContent)return c.textContent.trim()}const i=e.getAttribute("aria-label");if(i)return i.trim();const o=e.getAttribute("placeholder");if(o)return o.trim();const l=e.closest("label");return l!=null&&l.textContent?l.textContent.trim():""}function ve(e,n){return e.length<=n?e:e.slice(0,n-1)+"…"}function Wr(e){return e&&e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||null}function Ur(e){const n=e.getAttribute("aria-label");if(n)return n.trim().slice(0,80);const i=e.getAttribute("aria-labelledby");if(i){const s=document.getElementById(i);if(s!=null&&s.textContent)return s.textContent.trim().slice(0,80)}const o=e.querySelector('button[type="submit"], input[type="submit"], button:not([type])');if(o){const s=o instanceof HTMLInputElement?o.value:(o.textContent??"").trim();if(s&&s.length<60&&!/^(submit|ok|continue)$/i.test(s))return s}let l=e.parentElement;for(let s=0;l&&s<4;s++,l=l.parentElement){const c=l.querySelector("h1, h2, h3, h4");if(c!=null&&c.textContent){const a=c.textContent.trim();if(a&&a.length<80)return a}}return null}function qe(e){return e.length}function zn(e,n={}){const i=n.doc??(typeof document<"u"?document:null);if(!i)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:e};const o=typeof window<"u"&&window.location.href||"",l=typeof window<"u"&&window.location.pathname||"/",s=i.title||"",c=Array.from(i.querySelectorAll("[data-ll-region]")),a=[];for(const y of c){if(a.length>=Or)break;if(ot(y)||!st(y))continue;const A=y.getAttribute("data-ll-region")??"",P=y.getAttribute("data-ll-intent")??void 0,z=ve((y.innerText||y.textContent||"").trim(),un*2);!A||!z||a.push({id:A,intent:P,text:z})}const u=[],h=["H1","H2","H3","H4","H5","H6"],b=Array.from(i.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const y of b){if(ot(y)||!st(y))continue;const A=(y.textContent||"").trim();A&&u.push(`${y.tagName}: ${ve(A,200)}`)}const p=Array.from(i.querySelectorAll("p, li"));for(const y of p){if(ot(y)||!st(y)||h.includes(y.tagName))continue;const A=(y.textContent||"").trim();A.length>10&&u.push(ve(A,un))}const f=u.join(`
|
|
2
|
+
`),E=[],C=Array.from(i.querySelectorAll("a[href]"));for(const y of C){if(E.length>=$r)break;if(ot(y)||!st(y))continue;const A=y.getAttribute("href")||"",P=(y.textContent||"").trim();!A||!P||E.push({href:A,text:ve(P,100)})}const w=[],m=Array.from(i.querySelectorAll("input, textarea, select"));for(const y of m){if(w.length>=zr)break;if(ot(y)||!Rt(y)||!st(y))continue;const A=dn(y),P=y instanceof HTMLInputElement?y.type:y.tagName.toLowerCase();A&&w.push({label:ve(A,100),type:P})}const x=Array.from(i.querySelectorAll("form")),S=[];let R=0;for(const y of x){if(S.length>=Fr)break;if(It(y)||y.matches(".ll-widget *, .ll-widget"))continue;const A=y.getAttribute("id")||y.getAttribute("name")||Wr(y.getAttribute("data-ll-intent"))||`form_${R++}`,P=y.getAttribute("data-ll-intent")||Ur(y)||void 0,z=Array.from(y.querySelectorAll("input, textarea, select")),J=[];let D=0;const F=new Set;for(const L of z){if(J.length>=Hr)break;if(!Rt(L))continue;if(L instanceof HTMLInputElement){const W=L.type;if(W==="submit"||W==="button"||W==="reset"||W==="hidden"||W==="image"||W==="file")continue}const V=L.getAttribute("name")||"",pe=L.getAttribute("id")||"";let te=V||pe||`field_${D}`;F.has(te)&&(te=`${te}__${D}`),F.add(te),D++;const Ie=dn(L)||te,Me=L instanceof HTMLInputElement?L.type:L.tagName.toLowerCase(),he={name:te,label:ve(Ie,100),type:Me};if(L.required===!0&&(he.required=!0),L instanceof HTMLSelectElement){const W=[];for(let Y=0;Y<L.options.length&&!(W.length>=Br);Y++){const me=L.options[Y];if(!me||me.disabled)continue;const ge=me.value||"",ke=(me.textContent||"").trim()||ge;!ge&&!ke||W.push({value:ge,label:ve(ke,60)})}W.length>0&&(he.options=W)}const _e=typeof L.validationMessage=="string"?L.validationMessage:"";_e&&(he.validationMessage=ve(_e,200)),J.push(he)}S.push({id:A,intent:P,fields:J})}const j={url:o,title:s,pathname:l,regions:a,visibleText:f,visibleLinks:E,visibleFields:w,forms:S,extras:e};let O=qe(JSON.stringify(j.regions))+qe(j.visibleText)+qe(JSON.stringify(j.visibleLinks))+qe(JSON.stringify(j.visibleFields));for(;O>mt&&j.visibleFields.length>0;)j.visibleFields.pop(),O=qe(JSON.stringify(j.visibleFields));for(;O>mt&&j.visibleLinks.length>0;)j.visibleLinks.pop(),O-=80;return qe(j.visibleText)>mt&&(j.visibleText=ve(j.visibleText,mt-100)),j}let We=null;function Nt(e,n={}){const i=Date.now(),l=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(We&&We.key===l&&i-We.at<1e3)return We.ctx;const s=zn(e,n);return We={key:l,at:i,ctx:s},s}function On(){We=null}const Vr=200;function Fn(e){const n=String(e.href||"");return{href:n,text:String(e.text??e.title??n),internal:e.internal??!0,title:e.title,description:e.description}}function Yr(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function Hn(e){const n=e??(typeof document<"u"?document:null);if(!n)return[];const i=typeof window<"u"&&window.location.origin||"",o=new Set,l=[],s=Array.from(n.querySelectorAll("a[href]"));for(const c of s){if(l.length>=Vr)break;if(It(c))continue;const a=c.getAttribute("href")||"";if(!Yr(a))continue;let u=a,h=!0;try{if(typeof window<"u"){const p=new URL(a,i);h=p.origin===i,h&&a.startsWith("http")&&(u=p.pathname+p.search+p.hash)}}catch{continue}if(o.has(u))continue;o.add(u);const b=(c.textContent||"").trim().slice(0,120);l.push({href:u,text:b,internal:h})}return l}let Ue=null;const Gr=5e3;function gt(){const e=Date.now(),n=typeof window<"u"&&window.location.pathname||"/";if(Ue&&Ue.pathname===n&&e-Ue.at<Gr)return Ue.routes;const i=Hn();return Ue={at:e,pathname:n,routes:i},i}function Bn(){Ue=null}function fn(e){if(e instanceof HTMLInputElement){const n=e.type;if(n==="submit"||n==="button"||n==="reset"||n==="hidden"||n==="image"||n==="file")return!1}return!0}function Kr(e,n){return e.getAttribute("name")||e.getAttribute("id")||`field_${n}`}function Jr(e,n){if(!n)return null;try{const s=e.querySelector(`[name="${n.replace(/"/g,'\\"')}"]`);if(s&&fn(s))return s}catch{}const i=Array.from(e.querySelectorAll("input, textarea, select"));let o=0;const l=new Map;for(const s of i){if(!fn(s))continue;const c=Kr(s,o);let a=c;if(l.has(c)&&(a=`${c}__${o}`),a===n)return s;l.set(c,s),o++}return null}function pn(e,n){const i=Jr(e,n);return i?Rt(i)?{el:i}:{el:null,reason:"private"}:{el:null,reason:"not_found"}}function Xr(e,n){const i=e instanceof HTMLInputElement?HTMLInputElement.prototype:e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLSelectElement.prototype,o=Object.getOwnPropertyDescriptor(i,"value"),l=o==null?void 0:o.set;l?l.call(e,n):e.value=n}function Qr(e,n,i={}){const o=i.triggerInput??!0,l=i.triggerChange??!0;if(e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")){const s=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"),c=s==null?void 0:s.set,a=n==="true"||n==="1"||n==="on";c?c.call(e,a):e.checked=a,o&&e.dispatchEvent(new Event("input",{bubbles:!0})),l&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}Xr(e,n),o&&e.dispatchEvent(new Event("input",{bubbles:!0})),l&&e.dispatchEvent(new Event("change",{bubbles:!0}))}function hn(e,n){if(!n)return null;const i=n.replace(/"/g,'\\"');try{const c=e.querySelector(`form#${CSS.escape(n)}`);if(c)return c}catch{}const o=e.querySelector(`form[name="${i}"]`);if(o)return o;const l=e.querySelector(`form[data-ll-intent="${i}"]`);if(l)return l;const s=Array.from(e.querySelectorAll("form"));for(const c of s){const a=c.getAttribute("data-ll-intent");if(a&&Zr(a)===n)return c}if(/^form_\d+$/.test(n)){const c=parseInt(n.slice(5),10);let a=0;for(const u of s)if(!(u.id||u.getAttribute("name")||u.getAttribute("data-ll-intent"))){if(a===c)return u;a++}}return null}function Zr(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||null}function ei(){if(typeof window>"u"||typeof document>"u")return!1;const e=document.scrollingElement||document.documentElement;if(!e||e.scrollHeight<=e.clientHeight+2)return!1;const n=window.getComputedStyle(e);return!(n.overflowY==="hidden"||n.overflowY==="clip")}function ti(e){if(!(e instanceof HTMLElement))return!1;const i=window.getComputedStyle(e).overflowY;return!(i!=="auto"&&i!=="scroll"||e.scrollHeight<=e.clientHeight+2)}function ni(){if(typeof document>"u")return null;const e=Array.from(document.querySelectorAll("body, body *"));let n=null,i=0;for(const o of e){if(!ti(o))continue;const l=o.getBoundingClientRect();if(l.bottom<=0||l.top>=window.innerHeight||l.right<=0||l.left>=window.innerWidth||l.width<=0||l.height<=0||o.closest(".ll-widget"))continue;const s=l.width*l.height;s>i&&(i=s,n=o)}return n}function ri(){if(typeof window>"u")return null;if(ei())return window;const e=ni();return e||window}function mn(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function ii(e){var n,i;return e instanceof Window?typeof document>"u"?0:Math.max(((n=document.body)==null?void 0:n.scrollHeight)??0,((i=document.documentElement)==null?void 0:i.scrollHeight)??0):e.scrollHeight-e.clientHeight}const oi=new Set(["agent_state","avatar_stream_ready","avatar_active","avatar_idle","bot_ready","agent_error","idle_warning","idle_timeout","navigate","scroll_to","request_page_context","scroll_page","click","fill_form","focus_field","submit_form","request_routes","task_field_updated","task_completed"]),qn=r.forwardRef(function(n,i){var qt,Wt,Ut,Vt,Yt,Gt,Kt;const{agentId:o,apiKey:l,baseUrl:s="https://app.livelayer.studio",sessionEndpoint:c,sessionBody:a,soundEffects:u,experienceMode:h="WIDGET",autoConnect:b=!1,displayMode:p,defaultDisplayMode:f="expanded",onDisplayModeChange:E,position:C="bottom-right",mobileBreakpoint:w=640,persistKey:m="ll-widget",disablePersistence:x=!1,teamMembers:S,currentTeamMemberId:R,onTeamMemberChange:j,idleLoopUrl:O,greeting:y,avatarImageUrl:A,agentName:P,branding:z={},allowCamera:J=!0,allowScreenShare:D=!0,allowTyping:F=!0,showMinimize:L,showClose:V,chromeless:pe=!1,floatingChromeContainer:te=null,compactControls:Ie=!1,transforming:Me=!1,transformingLabel:he="Transforming…",showOn:_e,hideOn:W,pathname:Y,onNavigate:me,onScrollToSelector:ge,getPageContext:ke,pageContextExtras:ie,getRoutes:Ye,onScrollPage:Ge,onClick:lt,capabilities:Ke,onConnect:Ce,onDisconnect:Te,onTranscript:Se,onAgentState:Pe,onConnectionStateChange:je,onAgentEvent:Ee,onAgentCommand:Le,onCollect:Re,controlledSession:I,className:bt,style:Ne,zIndex:De=2147483647}=n,oe=Ln(Y),Je=An(oe,_e,W);r.useEffect(()=>{On(),Bn()},[oe]);const Ae=R!==void 0,[$e,xt]=r.useState(()=>{var v;return R??((v=S==null?void 0:S[0])==null?void 0:v.id)}),be=Ae?R:$e,X=r.useMemo(()=>(S==null?void 0:S.find(v=>v.id===be))??null,[S,be]),Xe=(X==null?void 0:X.agentId)??o,le=h==="EMBEDDED",[ze,Oe]=jn({value:p,defaultValue:f,onChange:E,persistKey:m,disablePersistence:le||x}),Q=le?"expanded":ze,ne=le?()=>{}:Oe,at=L??!le,ct=V??!le,xe=En(w),Qe=bn(),ee=xn(),re=wn(),we=_n(),Ze=kn(),[wt,ae]=r.useState(!1),[ce,et]=r.useState(!1),[Fe,tt]=r.useState(!1),[ut,g]=r.useState(!1),[q,Vn]=r.useState(!1),dt=br({baseUrl:s,config:u}),ft=r.useRef(dt);ft.current=dt;const _t=r.useRef(me),kt=r.useRef(ge),Ct=r.useRef(Ge),St=r.useRef(lt),Mt=r.useRef(ke),Tt=r.useRef(ie),Pt=r.useRef(Ye),jt=r.useRef(Ke),ue=r.useRef(null);_t.current=me,kt.current=ge,Ct.current=Ge,St.current=lt,Mt.current=ke,Tt.current=ie,Pt.current=Ye,jt.current=Ke;function de(v){const d=jt.current;return d?d.includes(v):!0}function fe(v,d){console.warn(`[LiveLayer] Agent command "${v}" blocked — capability "${d}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const nt=r.useCallback(v=>{var U,se,ye,it;const d=v;if(!(!d.type||typeof d.type!="string")){if(Ee==null||Ee({eventName:d.type,data:v}),d.type==="navigate"){if(!de("navigate")){fe("navigate","navigate");return}const _=typeof d.href=="string"?d.href:null;if(!_){console.warn(`[LiveLayer] Agent emitted "navigate" without href. Skipping. Check your agent's tool schema. See https://livelayer.studio/docs/errors/navigate-missing-href`);return}if(ft.current.playPageChange(),_t.current){try{_t.current(_)}catch(N){console.warn(`[LiveLayer] onNavigate threw for "${_}". Falling back. Error:`,N)}return}if(typeof document<"u"){const N=document.querySelector(`a[href="${_.replace(/"/g,'\\"')}"]`);if(N){N.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",_),window.dispatchEvent(new PopStateEvent("popstate"))}catch(N){console.warn(`[LiveLayer] history.pushState fallback failed for "${_}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,N)}return}if(d.type==="scroll_to"){if(!de("scroll")){fe("scroll_to","scroll");return}const _=typeof d.selector=="string"?d.selector:null;if(!_)return;const N=d.behavior==="instant"?"instant":"smooth";if(kt.current){try{kt.current(_,N)}catch($){console.warn("[LiveLayer] onScrollToSelector threw.",$)}return}if(typeof document<"u"){let $=null;try{$=document.querySelector(_)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${_}".`);return}if(!$){console.warn(`[LiveLayer] scroll_to: no element matched "${_}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}$.scrollIntoView({behavior:N,block:"start"})}return}if(d.type==="request_page_context"){if(!de("read_page")){fe("request_page_context","read_page");return}const _=typeof d.requestId=="string"?d.requestId:void 0,N=(U=ue.current)==null?void 0:U.call(ue),$=B=>{const M=N,K=M==null?void 0:M.localParticipant;if(K!=null&&K.publishData)try{const Z=_?{...B,requestId:_}:B,Be=new TextEncoder().encode(JSON.stringify(Z));K.publishData(Be,{reliable:!0})}catch(Z){console.warn("[LiveLayer] publishData failed.",Z)}},T=Tt.current,H=Mt.current;try{if(H){const B=H(T);if(B instanceof Promise){$({type:"page_context_pending"}),B.then(M=>$({type:"page_context",context:M})).catch(M=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",M),$({type:"page_context",context:Nt(T)})});return}$({type:"page_context",context:B});return}$({type:"page_context",context:Nt(T)})}catch(B){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",B),$({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:T}})}return}if(d.type==="scroll_page"){if(!de("scroll")){fe("scroll_page","scroll");return}const _=d.direction;if(_!=="up"&&_!=="down"&&_!=="top"&&_!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(_)}". Expected up | down | top | bottom.`);return}const N=d.behavior==="instant"?"instant":"smooth";if(Ct.current){try{Ct.current(_,N)}catch(M){console.warn("[LiveLayer] onScrollPage threw.",M)}return}if(typeof window>"u")return;const $={behavior:N},T=ri(),H=M=>{T instanceof Window?T.scrollBy({top:M,...$}):T.scrollBy({top:M,...$})},B=M=>{T instanceof Window?T.scrollTo({top:M,...$}):T.scrollTo({top:M,...$})};_==="up"?H(-mn(T)):_==="down"?H(mn(T)):B(_==="top"?0:ii(T));return}if(d.type==="click"){if(!de("click")){fe("click","click");return}const _=typeof d.selector=="string"?d.selector:null;if(!_){console.warn("[LiveLayer] click: missing selector.");return}if(St.current){try{St.current(_)}catch($){console.warn("[LiveLayer] onClick threw.",$)}return}if(typeof document>"u")return;let N=null;try{N=document.querySelector(_)}catch{console.warn(`[LiveLayer] click: invalid selector "${_}".`);return}if(!N){console.warn(`[LiveLayer] click: no element matched "${_}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(N.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(se=N.click)==null||se.call(N);return}if(d.type==="fill_form"||d.type==="focus_field"){if(!de("fill_forms")){fe(d.type,"fill_forms");return}if(typeof document>"u")return;d.type==="fill_form"&&ft.current.playConfirmation();const _=typeof d.formId=="string"?d.formId:null;if(!_){console.warn(`[LiveLayer] ${d.type}: missing formId.`);return}const N=hn(document,_);if(!N){console.warn(`[LiveLayer] ${d.type}: no <form> matched id="${_}" (or matching name / data-ll-intent slug). Forms are auto-discovered — make sure the form has an \`id\`, \`name\`, or \`data-ll-intent\` attribute the agent observed in PageContext.forms.`);return}if(N.closest('[data-ll-private="true"], [data-ll-skip], .ll-widget')){console.warn(`[LiveLayer] ${d.type}: refusing to touch a form in a private / opted-out subtree.`);return}if(d.type==="focus_field"){const T=typeof d.fieldName=="string"?d.fieldName:null;if(!T){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const H=pn(N,T);if(H.el===null){H.reason==="private"?console.warn(`[LiveLayer] focus_field: field "${T}" is privacy-protected and not focusable.`):console.warn(`[LiveLayer] focus_field: no input matching key="${T}" in form "${_}". The agent should use the field.name it observed in PageContext.forms[].fields[].`);return}H.el.focus();return}const $=d.values&&typeof d.values=="object"?d.values:null;if(!$){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[T,H]of Object.entries($)){if(typeof H!="string")continue;const B=pn(N,T);if(B.el===null){B.reason==="private"?console.warn(`[LiveLayer] fill_form: field "${T}" is privacy-protected (password / cc-* / data-ll-private). Skipping.`):console.warn(`[LiveLayer] fill_form: no input matching key="${T}" in form "${_}". The agent should use the field.name it observed in PageContext.forms[].fields[]. Skipping.`);continue}try{Qr(B.el,H)}catch(M){console.warn(`[LiveLayer] fill_form: failed to set "${T}".`,M)}}return}if(d.type==="submit_form"){if(!de("submit_forms")){fe("submit_form","submit_forms");return}if(typeof document>"u")return;const _=typeof d.formId=="string"?d.formId:null;if(!_){console.warn("[LiveLayer] submit_form: missing formId.");return}ft.current.playConfirmation();const N=hn(document,_);if(!N){console.warn(`[LiveLayer] submit_form: no <form> matched id="${_}" (or matching name / data-ll-intent slug).`);return}if(N.closest('[data-ll-private="true"], [data-ll-skip], .ll-widget')){console.warn("[LiveLayer] submit_form: refusing to submit a form in a private / opted-out subtree.");return}const $=typeof d.requestId=="string"?d.requestId:void 0,T=(ye=ue.current)==null?void 0:ye.call(ue),H=K=>{const Z=T,Be=Z==null?void 0:Z.localParticipant;if(Be!=null&&Be.publishData)try{const or=$?{...K,requestId:$}:K,sr=new TextEncoder().encode(JSON.stringify(or));Be.publishData(sr,{reliable:!0})}catch{}};let B=!1;const M=()=>{B=!0,H({type:"form_submitted",formId:_})};N.addEventListener("submit",M,{once:!0});try{typeof N.requestSubmit=="function"?N.requestSubmit():N.submit()}catch(K){console.warn("[LiveLayer] submit_form: requestSubmit threw.",K),N.removeEventListener("submit",M),H({type:"form_submit_blocked",formId:_,reason:"exception"});return}setTimeout(()=>{B||(N.removeEventListener("submit",M),H({type:"form_submit_blocked",formId:_,reason:"validation"}))},500);return}if(d.type==="request_routes"){if(!de("read_page")){fe("request_routes","read_page");return}const _=typeof d.requestId=="string"?d.requestId:void 0,$=(it=ue.current)==null?void 0:it.call(ue),T=$==null?void 0:$.localParticipant;if(!(T!=null&&T.publishData))return;const H=M=>{try{const K=_?{type:"routes",routes:M,requestId:_}:{type:"routes",routes:M},Z=new TextEncoder().encode(JSON.stringify(K));T.publishData(Z,{reliable:!0})}catch(K){console.warn("[LiveLayer] request_routes: publishData failed.",K)}},B=Pt.current;if(B){try{const M=B(),K=Z=>{if(!Array.isArray(Z)){H([]);return}H(Z.map(Fn).slice(0,200))};M instanceof Promise?M.then(K).catch(Z=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",Z),H(gt())}):K(M)}catch(M){console.warn("[LiveLayer] getRoutes threw; falling back to DOM walker.",M),H(gt())}return}try{H(gt())}catch(M){console.warn("[LiveLayer] request_routes: extractRoutes threw.",M)}return}if(d.type==="task_field_updated"){if(!de("collect_data")){fe("task_field_updated","collect_data");return}const _={phase:"field",fieldId:typeof d.fieldId=="string"?d.fieldId:"",fieldName:typeof d.fieldName=="string"?d.fieldName:typeof d.fieldId=="string"?d.fieldId:"",value:typeof d.value=="string"?d.value:"",kind:typeof d.kind=="string"?d.kind:"text",source:d.source==="slide"?"slide":d.source==="page"?"page":"agent",...typeof d.slideId=="string"?{slideId:d.slideId}:{},...typeof d.formId=="string"?{formId:d.formId}:{}};if(typeof document<"u")try{document.dispatchEvent(new CustomEvent("ll-collected",{detail:_}))}catch{}return}if(d.type==="task_completed"){if(!de("collect_data")){fe("task_completed","collect_data");return}const _=d.result;if(!_||typeof _!="object"){console.warn("[LiveLayer] task_completed missing `result` payload.");return}if(typeof document<"u")try{document.dispatchEvent(new CustomEvent("ll-collected",{detail:{phase:"complete",result:_}}))}catch{}try{Re==null||Re(_)}catch(N){console.warn("[LiveLayer] onCollect threw.",N)}return}oi.has(d.type)||Le==null||Le(d)}},[Le,Ee,Re]),G=vn({agentId:I?"__controlled__":Xe,baseUrl:s,apiKey:l,sessionEndpoint:c,sessionBody:a,onDataMessage:I?void 0:nt});r.useEffect(()=>{if(I!=null&&I.subscribeToDataMessages)return I.subscribeToDataMessages(nt)},[I,nt]),ue.current=()=>{var v;return(v=G.getRoom)==null?void 0:v.call(G)},r.useEffect(()=>{var U;if(typeof window>"u")return;const v=((U=window.location)==null?void 0:U.hostname)||"";if(v==="localhost"||v==="127.0.0.1"||v==="0.0.0.0"||v.endsWith(".local")||v.endsWith(".test"))return window.__livelayerSimulateCommand=se=>{try{nt(se)}catch(ye){console.warn("[LiveLayer] simulate-command threw:",ye)}},()=>{delete window.__livelayerSimulateCommand}},[nt]);const k=r.useMemo(()=>I?{connectionState:I.connectionState,agentState:I.agentState,transcript:I.transcript,videoElement:I.videoElement,audioElement:I.audioElement,canResume:I.canResume,error:I.error,agentConfig:null,connect:async()=>{await I.onConnect()},disconnect:()=>I.onDisconnect(),getRoom:G.getRoom,isControlled:!0}:{connectionState:G.connectionState,agentState:G.agentState,transcript:G.transcript,videoElement:G.videoElement,audioElement:G.audioElement,canResume:G.canResume,error:G.error,agentConfig:G.agentConfig,connect:G.connect,disconnect:G.disconnect,getRoom:G.getRoom,isControlled:!1},[I,G]),Dt=r.useRef(k);Dt.current=k;const $t=r.useRef(I);$t.current=I,r.useImperativeHandle(i,()=>({sendData:async v=>{var ye,it;const d=$t.current;if(d!=null&&d.publishData){try{await d.publishData(v)}catch(_){console.warn("[AvatarWidget] sendData (controlled) failed:",_)}return}const U=(it=(ye=Dt.current)==null?void 0:ye.getRoom)==null?void 0:it.call(ye),se=U==null?void 0:U.localParticipant;if(se!=null&&se.publishData)try{const _=new TextEncoder().encode(JSON.stringify(v));await se.publishData(_,{reliable:!0})}catch(_){console.warn("[AvatarWidget] sendData failed:",_)}}}),[]);const zt=r.useRef(null);r.useEffect(()=>{const v=k.videoElement,d=zt.current;if(!(!v||!d))return d.appendChild(v),()=>{v.parentNode===d&&d.removeChild(v)}},[k.videoElement]),r.useEffect(()=>{const v=k.audioElement;if(!v)return;Qe.attach(v);const d=v.play();return d&&typeof d.catch=="function"&&d.catch(U=>{(U==null?void 0:U.name)==="NotAllowedError"&&ae(!0)}),()=>{Qe.detach()}},[k.audioElement]),r.useEffect(()=>{if(k.isControlled||k.connectionState!=="connected")return;const v=k.getRoom();if(v)return ee.setupMic(v).catch(()=>{}),()=>{ee.teardownMic()}},[k.isControlled,k.connectionState]),r.useEffect(()=>{var d;if(k.connectionState!=="connected")return;const v=k.isControlled?(d=I==null?void 0:I.getRoom)==null?void 0:d.call(I):k.getRoom();if(v)return re.attachRoom(v),we.attachRoom(v),k.isControlled&&ee.attachRoom(v),Ze.refresh(),()=>{re.teardown(),we.teardown()}},[k.isControlled,k.connectionState,I]),r.useEffect(()=>{const v=k.audioElement;v&&(v.muted=q)},[k.audioElement,q]);const Yn=r.useCallback(v=>{const d={type:"user_message",text:v};if(I!=null&&I.publishData){try{I.publishData(d)}catch{}return}const U=k.getRoom();if(U)try{const se=new TextEncoder().encode(JSON.stringify(d));U.localParticipant.publishData(se,{reliable:!0})}catch{}},[k,I]),Gn=r.useCallback(()=>{Vn(v=>!v)},[]);r.useEffect(()=>{je==null||je(k.connectionState),k.connectionState==="connected"?Ce==null||Ce():k.connectionState==="disconnected"&&(Te==null||Te())},[k.connectionState,Ce,Te,je]),r.useEffect(()=>{Se==null||Se(k.transcript)},[k.transcript,Se]),r.useEffect(()=>{Pe==null||Pe(k.agentState)},[k.agentState,Pe]),r.useEffect(()=>{dt.setThinking(k.agentState==="thinking")},[k.agentState,dt]);const Ot=r.useRef(!1);r.useEffect(()=>{!b||Ot.current||Je&&k.connectionState==="idle"&&(Ot.current=!0,k.connect())},[b,k.connectionState,k,Je]);const Kn=r.useCallback(v=>{const d=S==null?void 0:S.find(U=>U.id===v);d&&(tt(!1),v!==be&&(et(!0),k.disconnect(),Ae||xt(v),j==null||j(d)))},[S,be,k,Ae,j]);r.useEffect(()=>{ce&&k.connectionState==="connected"&&et(!1)},[k.connectionState,ce]),r.useEffect(()=>{if(!Fe)return;const v=d=>{d.key==="Escape"&&tt(!1)};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[Fe]);const Jn=!!A||!!(X!=null&&X.avatarImageUrl)||k.isControlled,rt=Cn(Xe,s,Jn);Ke===void 0&&((qt=rt.info)!=null&&qt.capabilities)&&(jt.current=rt.info.capabilities);const pt=(X==null?void 0:X.name)??P??((Wt=k.agentConfig)==null?void 0:Wt.name)??((Ut=rt.info)==null?void 0:Ut.name)??"Live Layer",Et=(X==null?void 0:X.avatarImageUrl)??A??((Vt=k.agentConfig)==null?void 0:Vt.avatarImageUrl)??((Yt=rt.info)==null?void 0:Yt.avatarImageUrl)??null,Xn=O??((Gt=k.agentConfig)==null?void 0:Gt.idleLoopUrl)??((Kt=rt.info)==null?void 0:Kt.idleLoopUrl)??null,Qn=y??null,Zn=r.useCallback(()=>ne("expanded"),[ne]),er=r.useCallback(()=>ne("minimized"),[ne]),Ft=r.useCallback(()=>{k.disconnect(),ne("hidden")},[k,ne]),tr=r.useCallback(()=>{const v=k.audioElement;v&&v.play().then(()=>ae(!1)).catch(()=>{})},[k.audioElement]),nr=r.useCallback(()=>{ae(!1),k.connect()},[k]),He={...Ne,...le?{}:{zIndex:De}};z.primaryColor&&(He["--ll-color-primary"]=z.primaryColor),z.accentColor&&(He["--ll-color-accent"]=z.accentColor),z.backgroundColor&&(He["--ll-color-bg"]=z.backgroundColor),z.textColor&&(He["--ll-color-fg"]=z.textColor);const rr=["ll-widget",`ll-widget--${Q}`,`ll-widget--${xe?"mobile":"desktop"}`,bt].filter(Boolean).join(" ");if(!Je)return null;const ir=t.jsx("div",{className:rr,style:He,"data-display-mode":Q,"data-position":C,"data-experience-mode":h==="EMBEDDED"?"embedded":"widget",children:Q==="expanded"&&t.jsx(Tr,{position:C,isMobile:xe,agentName:pt,avatarImageUrl:Et,idleLoopUrl:Xn,greeting:Qn,branding:z,teamMembers:S,currentTeamMemberId:be,isSwitchingTeamMember:ce,teamSwitcherOpen:Fe,onToggleTeamSwitcher:()=>tt(v=>!v),onSelectTeamMember:Kn,connectionState:k.connectionState,agentState:k.agentState,transcript:k.transcript,isMuted:ee.isMuted,micDevices:Ze.mics,activeMicId:ee.activeDeviceId,isCameraEnabled:re.isEnabled,cameraPreviewEl:re.previewEl,cameraDevices:Ze.cameras,activeCameraId:re.activeDeviceId,isScreenShareEnabled:we.isEnabled,screenPreviewEl:we.previewEl,isSpeakerMuted:q,allowCamera:J,allowScreenShare:D,allowTyping:F,showMinimize:at,showClose:ct,chromeless:pe,compactControls:Ie,transforming:Me,transformingLabel:he,languageMenuOpen:ut,onToggleLanguageMenu:()=>g(v=>!v),needsUserGesture:wt,canResume:k.canResume,micError:ee.micError,error:k.error,avatarVideoContainerRef:zt,agentVideoEl:k.videoElement,onConnect:()=>void k.connect(),onDisconnect:()=>k.disconnect(),onRetry:nr,onResumeAudio:tr,onToggleMute:ee.toggleMute,onSwitchMicDevice:v=>void ee.switchDevice(v),onToggleCamera:()=>void re.toggle(),onSwitchCameraDevice:v=>void re.switchDevice(v),onToggleScreenShare:()=>void we.toggle(),onToggleSpeaker:Gn,onSendMessage:Yn,onMinimize:er,onClose:Ft,onClearMicError:ee.clearError})}),Ht=!le&&(Q==="hidden"||Q==="minimized")?t.jsxs("div",{className:["ll-widget","ll-widget--floating",`ll-widget--${Q}`,`ll-widget--${xe?"mobile":"desktop"}`].join(" "),style:He,"data-display-mode":Q,"data-position":C,children:[Q==="hidden"&&t.jsx(Sr,{position:C,isMobile:xe,isSpeaking:k.agentState==="speaking",onExpand:()=>ne("expanded"),label:`Open ${pt} widget`,avatarImageUrl:Et,agentName:pt,containerEl:te}),Q==="minimized"&&t.jsx(Er,{position:C,isMobile:xe,agentName:pt,avatarImageUrl:Et,agentState:k.agentState,isMuted:ee.isMuted,audioLevel:Qe,onExpand:Zn,onToggleMute:ee.toggleMute,onClose:Ft})]}):null,Bt=te??(typeof document<"u"?document.body:null);return t.jsxs(t.Fragment,{children:[ir,Ht&&Bt&&At.createPortal(Ht,Bt)]})});qn.displayName="AvatarWidgetInner";const Wn=r.forwardRef(function(n,i){return t.jsx(yn,{children:t.jsx(qn,{...n,ref:i})})});Wn.displayName="AvatarWidget";const si=({agentId:e,baseUrl:n,apiKey:i,mode:o,onAgentEvent:l,className:s,style:c})=>{const a=r.useRef(null),u=r.useRef(null),h=r.useRef(l);h.current=l;const b=r.useCallback(p=>{var E;const f=p.detail;(E=h.current)==null||E.call(h,f)},[]);return r.useEffect(()=>{const p=a.current;if(!p)return;const f=document.createElement("livelayer-widget");return f.setAttribute("agent-id",e),n&&f.setAttribute("base-url",n),i&&f.setAttribute("api-key",i),o&&f.setAttribute("mode",o),f.addEventListener("agent-event",b),p.appendChild(f),u.current=f,()=>{f.removeEventListener("agent-event",b),p.removeChild(f),u.current=null}},[e]),r.useEffect(()=>{u.current&&(o?u.current.setAttribute("mode",o):u.current.removeAttribute("mode"))},[o]),t.jsx("div",{ref:a,className:s,style:c})},li=r.forwardRef(function({id:n,intent:i,as:o="div",className:l,style:s,children:c},a){return r.createElement(o,{ref:a,"data-ll-region":n,"data-ll-intent":i,className:l,style:s},c)});function ai(e={}){const{onFieldUpdate:n,onComplete:i,source:o="all"}=e,[l,s]=r.useState({}),[c,a]=r.useState(!1),[u,h]=r.useState(null),b=r.useRef(n),p=r.useRef(i),f=r.useRef(o);r.useEffect(()=>{b.current=n,p.current=i,f.current=o},[n,i,o]);const E=r.useCallback(()=>{s({}),a(!1)},[]);return r.useEffect(()=>{if(typeof window>"u")return;const C=w=>{var x,S;const m=w.detail;if(m){if(m.phase==="field"){if(f.current!=="all"&&m.source!==f.current)return;a(!0),s(R=>R[m.fieldName]===m.value?R:{...R,[m.fieldName]:m.value});try{(x=b.current)==null||x.call(b,m)}catch(R){console.warn("[LiveLayer] useCollect onFieldUpdate threw.",R)}return}if(m.phase==="complete"){const R=m.result;if(f.current!=="all"&&R.source!==f.current)return;h(R),a(!1);try{(S=p.current)==null||S.call(p,R)}catch(j){console.warn("[LiveLayer] useCollect onComplete threw.",j)}}}};return document.addEventListener("ll-collected",C),()=>document.removeEventListener("ll-collected",C)},[]),{fields:l,isCollecting:c,lastResult:u,reset:E}}let gn=1;function ci({onMount:e,defaultOpen:n=!1,storageKey:i="ll-debug-open"}){const[o,l]=r.useState(n),[s,c]=r.useState([]),[a,u]=r.useState(""),[h,b]=r.useState(!1),p=r.useRef(new Set),f=r.useRef([]),E=r.useRef(h);E.current=h,r.useEffect(()=>{try{const m=localStorage.getItem(i);m==="1"&&l(!0),m==="0"&&l(!1)}catch{}},[i]),r.useEffect(()=>{try{localStorage.setItem(i,o?"1":"0")}catch{}},[o,i]),r.useEffect(()=>{const m=x=>{(x.metaKey||x.ctrlKey)&&x.shiftKey&&x.key.toLowerCase()==="l"&&(x.preventDefault(),l(S=>!S))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[]),r.useEffect(()=>{const m=setInterval(()=>{if(f.current.length===0||E.current)return;const x=f.current.splice(0,f.current.length);c(S=>[...x.reverse(),...S].slice(0,200))},100);return()=>clearInterval(m)},[]);const C=r.useRef(!1);if(r.useEffect(()=>{!e||C.current||(C.current=!0,e(m=>{f.current.push({id:gn++,ts:Date.now(),kind:"event",type:m.eventName,data:m.data})}))},[e]),r.useEffect(()=>{const m=console.warn,x=console.log,S=(R,j)=>function(...O){try{const y=typeof O[0]=="string"?O[0]:"";y.startsWith("[LiveLayer]")&&f.current.push({id:gn++,ts:Date.now(),kind:R,type:y.slice(0,120),data:{args:O.slice(1).map(A=>di(A))}})}catch{}return j.apply(this,O)};return console.warn=S("warn",m),console.log=S("log",x),()=>{console.warn=m,console.log=x}},[]),!o)return t.jsx("button",{type:"button",onClick:()=>l(!0),title:"Open LiveLayer debug panel (Cmd/Ctrl + Shift + L)","aria-label":"Open LiveLayer debug panel",style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.18)",borderRadius:999,padding:"6px 10px",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",cursor:"pointer",boxShadow:"0 4px 12px rgba(0,0,0,0.35)",opacity:.85},children:"🛰 LL debug"});const w=s.filter(m=>{if(!a)return!0;const x=a.toLowerCase();return m.type.toLowerCase().includes(x)||JSON.stringify(m.data||{}).toLowerCase().includes(x)});return t.jsxs("div",{style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,width:380,maxHeight:"60vh",background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:12,boxShadow:"0 16px 48px rgba(0,0,0,0.5)",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"8px 10px",background:"rgba(255,255,255,0.04)",borderBottom:"1px solid rgba(255,255,255,0.1)",display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontWeight:600,fontSize:12},children:"LiveLayer debug"}),t.jsxs("span",{style:{fontSize:10,color:"rgba(255,255,255,0.4)"},children:[s.length," event",s.length===1?"":"s"]}),t.jsx("span",{style:{flex:1}}),t.jsx("button",{type:"button",onClick:()=>b(m=>!m),style:Lt(h?"#f59e0b":"transparent"),title:"Pause / resume capture",children:h?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{c([]),f.current=[]},style:Lt("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>l(!1),style:Lt("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:a,onChange:m=>u(m.target.value),placeholder:"filter by type or data…",style:{margin:8,padding:"6px 8px",background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:11,outline:"none"}}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"0 8px 8px"},children:w.length===0?t.jsxs("div",{style:{padding:14,fontSize:11,color:"rgba(255,255,255,0.4)",lineHeight:1.5},children:["No events yet. Connect to the agent and trigger a tool call — the events will stream in here. You can also dispatch commands manually in DevTools:",t.jsx("pre",{style:{marginTop:6,background:"rgba(255,255,255,0.04)",padding:6,borderRadius:4,fontSize:10,whiteSpace:"pre-wrap"},children:`window.__livelayerSimulateCommand({
|
|
3
3
|
type: "navigate",
|
|
4
4
|
href: "/about"
|
|
5
|
-
})`})]}):w.map(m=>t.jsx(
|
|
5
|
+
})`})]}):w.map(m=>t.jsx(ui,{entry:m,expanded:p.current.has(m.id),onToggle:()=>{p.current.has(m.id)?p.current.delete(m.id):p.current.add(m.id),c(x=>[...x])}},m.id))})]})}function ui({entry:e,expanded:n,onToggle:i}){const o=e.kind==="warn"?"#f59e0b":e.type.startsWith("[LiveLayer]")?"#94a3b8":e.type==="navigate"||e.type==="scroll_page"||e.type==="scroll_to"||e.type==="click"?"#22c55e":e.type==="fill_form"||e.type==="submit_form"||e.type==="focus_field"?"#a78bfa":e.type==="request_page_context"||e.type==="request_routes"?"#38bdf8":e.type==="agent_state"?"#facc15":"#cbd5e1",l=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:l}),t.jsx("span",{style:{color:o,fontWeight:600,flexShrink:0},children:e.type.length>50?e.type.slice(0,50)+"…":e.type})]}),n&&e.data&&t.jsx("pre",{style:{marginTop:6,padding:6,background:"rgba(255,255,255,0.04)",borderRadius:4,fontSize:10,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:JSON.stringify(e.data,null,2)})]})}function Lt(e){return{background:e,color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:999,padding:"3px 8px",fontSize:10,cursor:"pointer"}}function di(e){try{return e instanceof Error?{message:e.message,stack:e.stack}:(JSON.stringify(e),e)}catch{return String(e)}}function Un(e){const n=JSON.stringify(e);r.useEffect(()=>Ve.registerFields(e),[n])}function fi({fields:e,children:n}){return Un(e),t.jsx(t.Fragment,{children:n})}function pi(){const[e,n]=r.useState([]),i=r.useCallback(l=>{n(s=>{const c=s.findIndex(a=>a.id===l.id);if(c>=0){const a=s.slice();return a[c]=l,a}return[...s,l]})},[]),o=r.useCallback(()=>n([]),[]);return{entries:e,pushSegment:i,clear:o,latest:e.length>0?e[e.length-1]:null}}Object.defineProperty(exports,"clearFieldRegistry",{enumerable:!0,get:()=>Ve.clearFieldRegistry});Object.defineProperty(exports,"getRegisteredFields",{enumerable:!0,get:()=>Ve.getRegisteredFields});Object.defineProperty(exports,"registerFields",{enumerable:!0,get:()=>Ve.registerFields});Object.defineProperty(exports,"setFieldValue",{enumerable:!0,get:()=>Ve.setFieldValue});exports.AvatarWidget=Wn;exports.ErrorBoundary=yn;exports.FieldProvider=fi;exports.LiveLayerDebugPanel=ci;exports.LiveLayerRegion=li;exports.LiveLayerWidget=si;exports.clearPageContextCache=On;exports.clearRoutesCache=Bn;exports.extractPageContext=zn;exports.extractRoutes=Hn;exports.getCachedPageContext=Nt;exports.getCachedRoutes=gt;exports.matchesPattern=Rn;exports.normalizeRouteInput=Fn;exports.shouldRenderAtPath=Nn;exports.useAgentInfo=Cn;exports.useAudioLevel=bn;exports.useCameraState=wn;exports.useCollect=ai;exports.useDisplayMode=Sn;exports.useDisplayModePersistence=jn;exports.useIsMobile=En;exports.useLiveKitSession=vn;exports.useMediaDevices=kn;exports.useMicrophoneState=xn;exports.usePathname=Ln;exports.useRegisterFields=Un;exports.useRouteMatch=An;exports.useScreenShareState=_n;exports.useTranscript=pi;
|