@voxket-ai/voxket-live 1.1.61 → 1.1.62

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.
Files changed (3) hide show
  1. package/dist/index.cjs +2 -10
  2. package/dist/index.js +1734 -1796
  3. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -45,7 +45,7 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
45
45
  }
46
46
  `),()=>{v.contains(S)&&v.removeChild(S)}},[t]),m.jsx(kD,{isPresent:t,childRef:o,sizeRef:a,children:D.cloneElement(e,{ref:u})})}const wD=({children:e,initial:t,isPresent:n,onExitComplete:i,custom:r,presenceAffectsLayout:s,mode:o,anchorX:a,anchorY:c,root:l})=>{const u=mp(CD),d=M.useId();let h=!0,f=M.useMemo(()=>(h=!1,{id:d,initial:t,isPresent:n,custom:r,onExitComplete:g=>{u.set(g,!0);for(const p of u.values())if(!p)return;i&&i()},register:g=>(u.set(g,!1),()=>u.delete(g))}),[n,u,i]);return s&&h&&(f={...f}),M.useMemo(()=>{u.forEach((g,p)=>u.set(p,!1))},[n]),D.useEffect(()=>{!n&&!u.size&&i&&i()},[n]),o==="popLayout"&&(e=m.jsx(ED,{isPresent:n,anchorX:a,anchorY:c,root:l,children:e})),m.jsx(Kl.Provider,{value:f,children:e})};function CD(){return new Map}function VE(e=!0){const t=M.useContext(Kl);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:r}=t,s=M.useId();M.useEffect(()=>{if(e)return r(s)},[e]);const o=M.useCallback(()=>e&&i&&i(s),[s,i,e]);return!n&&i?[!1,o]:[!0]}const Xa=e=>e.key||"";function my(e){const t=[];return M.Children.forEach(e,n=>{M.isValidElement(n)&&t.push(n)}),t}const Ys=({children:e,custom:t,initial:n=!0,onExitComplete:i,presenceAffectsLayout:r=!0,mode:s="sync",propagate:o=!1,anchorX:a="left",anchorY:c="top",root:l})=>{const[u,d]=VE(o),h=M.useMemo(()=>my(e),[e]),f=o&&!u?[]:h.map(Xa),g=M.useRef(!0),p=M.useRef(h),x=mp(()=>new Map),y=M.useRef(new Set),[E,w]=M.useState(h),[S,v]=M.useState(h);vk(()=>{g.current=!1,p.current=h;for(let T=0;T<S.length;T++){const I=Xa(S[T]);f.includes(I)?(x.delete(I),y.current.delete(I)):x.get(I)!==!0&&x.set(I,!1)}},[S,f.length,f.join("-")]);const k=[];if(h!==E){let T=[...h];for(let I=0;I<S.length;I++){const b=S[I],A=Xa(b);f.includes(A)||(T.splice(I,0,b),k.push(b))}return s==="wait"&&k.length&&(T=k),v(my(T)),w(h),null}process.env.NODE_ENV!=="production"&&s==="wait"&&S.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:_}=M.useContext(pp);return m.jsx(m.Fragment,{children:S.map(T=>{const I=Xa(T),b=o&&!u?!1:h===S||f.includes(I),A=()=>{if(y.current.has(I))return;if(y.current.add(I),x.has(I))x.set(I,!0);else return;let P=!0;x.forEach(B=>{B||(P=!1)}),P&&(_==null||_(),v(p.current),o&&(d==null||d()),i&&i())};return m.jsx(wD,{isPresent:b,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:s,root:l,onExitComplete:b?void 0:A,anchorX:a,anchorY:c,children:T},I)})})},zE=M.createContext({strict:!1}),gy={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let by=!1;function TD(){if(by)return;const e={};for(const t in gy)e[t]={isEnabled:n=>gy[t].some(i=>!!n[i])};bE(e),by=!0}function GE(){return TD(),hO()}function AD(e){const t=GE();for(const n in e)t[n]={...t[n],...e[n]};bE(t)}const RD=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function bl(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||RD.has(e)}let HE=e=>!bl(e);function _D(e){typeof e=="function"&&(HE=t=>t.startsWith("on")?!bl(t):e(t))}try{_D(require("@emotion/is-prop-valid").default)}catch{}function ID(e,t,n){const i={};for(const r in e)r==="values"&&typeof e.values=="object"||(HE(r)||n===!0&&bl(r)||!t&&!bl(r)||e.draggable&&r.startsWith("onDrag"))&&(i[r]=e[r]);return i}const Ql=M.createContext({});function ND(e,t){if(ql(e)){const{initial:n,animate:i}=e;return{initial:n===!1||la(n)?n:void 0,animate:la(i)?i:void 0}}return e.inherit!==!1?t:{}}function MD(e){const{initial:t,animate:n}=ND(e,M.useContext(Ql));return M.useMemo(()=>({initial:t,animate:n}),[yy(t),yy(n)])}function yy(e){return Array.isArray(e)?e.join(" "):e}const Hp=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function KE(e,t,n){for(const i in t)!hn(t[i])&&!wE(i,n)&&(e[i]=t[i])}function PD({transformTemplate:e},t){return M.useMemo(()=>{const n=Hp();return Vp(n,t,e),Object.assign({},n.vars,n.style)},[t])}function OD(e,t){const n=e.style||{},i={};return KE(i,n,e),Object.assign(i,PD(e,t)),i}function DD(e,t){const n={},i=OD(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=i,n}const WE=()=>({...Hp(),attrs:{}});function LD(e,t,n,i){const r=M.useMemo(()=>{const s=WE();return CE(s,t,AE(i),e.transformTemplate,e.style),{...s.attrs,style:{...s.style}}},[t]);if(e.style){const s={};KE(s,e.style,e),r.style={...s,...r.style}}return r}const BD=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Kp(e){return typeof e!="string"||e.includes("-")?!1:!!(BD.indexOf(e)>-1||/[A-Z]/u.test(e))}function FD(e,t,n,{latestValues:i},r,s=!1,o){const c=(o??Kp(e)?LD:DD)(t,i,r,e),l=ID(t,typeof e=="string",s),u=e!==M.Fragment?{...l,...c,ref:n}:{},{children:d}=t,h=M.useMemo(()=>hn(d)?d.get():d,[d]);return M.createElement(e,{...u,children:h})}function UD({scrapeMotionValuesFromProps:e,createRenderState:t},n,i,r){return{latestValues:jD(n,i,r,e),renderState:t()}}function jD(e,t,n,i){const r={},s=i(e,{});for(const h in s)r[h]=Fc(s[h]);let{initial:o,animate:a}=e;const c=ql(e),l=gE(e);t&&l&&!c&&e.inherit!==!1&&(o===void 0&&(o=t.initial),a===void 0&&(a=t.animate));let u=n?n.initial===!1:!1;u=u||o===!1;const d=u?a:o;if(d&&typeof d!="boolean"&&!Wl(d)){const h=Array.isArray(d)?d:[d];for(let f=0;f<h.length;f++){const g=Op(e,h[f]);if(g){const{transitionEnd:p,transition:x,...y}=g;for(const E in y){let w=y[E];if(Array.isArray(w)){const S=u?w.length-1:0;w=w[S]}w!==null&&(r[E]=w)}for(const E in p)r[E]=p[E]}}}return r}const qE=e=>(t,n)=>{const i=M.useContext(Ql),r=M.useContext(Kl),s=()=>UD(e,t,i,r);return n?s():mp(s)},VD=qE({scrapeMotionValuesFromProps:zp,createRenderState:Hp}),zD=qE({scrapeMotionValuesFromProps:RE,createRenderState:WE}),GD=Symbol.for("motionComponentSymbol");function HD(e,t,n){const i=M.useRef(n);M.useInsertionEffect(()=>{i.current=n});const r=M.useRef(null);return M.useCallback(s=>{var a;s&&((a=e.onMount)==null||a.call(e,s)),t&&(s?t.mount(s):t.unmount());const o=i.current;if(typeof o=="function")if(s){const c=o(s);typeof c=="function"&&(r.current=c)}else r.current?(r.current(),r.current=null):o(s);else o&&(o.current=s)},[t])}const QE=M.createContext({});function Uo(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function KD(e,t,n,i,r,s){var y,E;const{visualElement:o}=M.useContext(Ql),a=M.useContext(zE),c=M.useContext(Kl),l=M.useContext(Gp).reducedMotion,u=M.useRef(null),d=M.useRef(!1);i=i||a.renderer,!u.current&&i&&(u.current=i(e,{visualState:t,parent:o,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:l,isSVG:s}),d.current&&u.current&&(u.current.manuallyAnimateOnMount=!0));const h=u.current,f=M.useContext(QE);h&&!h.projection&&r&&(h.type==="html"||h.type==="svg")&&WD(u.current,n,r,f);const g=M.useRef(!1);M.useInsertionEffect(()=>{h&&g.current&&h.update(n,c)});const p=n[nE],x=M.useRef(!!p&&!((y=window.MotionHandoffIsComplete)!=null&&y.call(window,p))&&((E=window.MotionHasOptimisedAnimation)==null?void 0:E.call(window,p)));return vk(()=>{d.current=!0,h&&(g.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),h.scheduleRenderMicrotask(),x.current&&h.animationState&&h.animationState.animateChanges())}),M.useEffect(()=>{h&&(!x.current&&h.animationState&&h.animationState.animateChanges(),x.current&&(queueMicrotask(()=>{var w;(w=window.MotionHandoffMarkAsComplete)==null||w.call(window,p)}),x.current=!1),h.enteringChildren=void 0)}),h}function WD(e,t,n,i){const{layoutId:r,layout:s,drag:o,dragConstraints:a,layoutScroll:c,layoutRoot:l,layoutCrossfade:u}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:YE(e.parent)),e.projection.setOptions({layoutId:r,layout:s,alwaysMeasureLayout:!!o||a&&Uo(a),visualElement:e,animationType:typeof s=="string"?s:"both",initialPromotionConfig:i,crossfade:u,layoutScroll:c,layoutRoot:l})}function YE(e){if(e)return e.options.allowProjection!==!1?e.projection:YE(e.parent)}function ad(e,{forwardMotionProps:t=!1,type:n}={},i,r){i&&AD(i);const s=n?n==="svg":Kp(e),o=s?zD:VD;function a(l,u){let d;const h={...M.useContext(Gp),...l,layoutId:qD(l)},{isStatic:f}=h,g=MD(l),p=o(l,f);if(!f&&yk){QD(h,i);const x=YD(h);d=x.MeasureLayout,g.visualElement=KD(e,p,h,r,x.ProjectionNode,s)}return m.jsxs(Ql.Provider,{value:g,children:[d&&g.visualElement?m.jsx(d,{visualElement:g.visualElement,...h}):null,FD(e,l,HD(p,g.visualElement,u),p,f,t,s)]})}a.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const c=M.forwardRef(a);return c[GD]=e,c}function qD({layoutId:e}){const t=M.useContext(pp).id;return t&&e!==void 0?t+"-"+e:e}function QD(e,t){const n=M.useContext(zE).strict;if(process.env.NODE_ENV!=="production"&&t&&n){const i="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?ro(!1,i,"lazy-strict-mode"):Yi(!1,i,"lazy-strict-mode")}}function YD(e){const t=GE(),{drag:n,layout:i}=t;if(!n&&!i)return{};const r={...n,...i};return{MeasureLayout:n!=null&&n.isEnabled(e)||i!=null&&i.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function JD(e,t){if(typeof Proxy>"u")return ad;const n=new Map,i=(s,o)=>ad(s,o,e,t),r=(s,o)=>(process.env.NODE_ENV!=="production"&&xp(!1,"motion() is deprecated. Use motion.create() instead."),i(s,o));return new Proxy(r,{get:(s,o)=>o==="create"?i:(n.has(o)||n.set(o,ad(o,void 0,e,t)),n.get(o))})}const XD=(e,t)=>t.isSVG??Kp(e)?new _O(t):new EO(t,{allowProjection:e!==M.Fragment});class ZD extends Ir{constructor(t){super(t),t.animationState||(t.animationState=OO(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Wl(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){var t;this.node.animationState.reset(),(t=this.unmountControls)==null||t.call(this)}}let $D=0;class e2 extends Ir{constructor(){super(...arguments),this.id=$D++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===i)return;const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const t2={animation:{Feature:ZD},exit:{Feature:e2}};function ka(e){return{point:{x:e.pageX,y:e.pageY}}}const n2=e=>t=>Fp(t)&&e(t,ka(t));function Yo(e,t,n,i){return ua(e,t,n2(n),i)}const JE=({current:e})=>e?e.ownerDocument.defaultView:null,vy=(e,t)=>Math.abs(e-t);function i2(e,t){const n=vy(e.x,t.x),i=vy(e.y,t.y);return Math.sqrt(n**2+i**2)}const xy=new Set(["auto","scroll"]);class XE{constructor(t,n,{transformPagePoint:i,contextWindow:r=window,dragSnapToOrigin:s=!1,distanceThreshold:o=3,element:a}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=f=>{this.handleScroll(f.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=ld(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,p=i2(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!p)return;const{point:x}=f,{timestamp:y}=on;this.history.push({...x,timestamp:y});const{onStart:E,onMove:w}=this.handlers;g||(E&&E(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),w&&w(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=cd(g,this.transformPagePoint),Rt.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:p,onSessionEnd:x,resumeAnimation:y}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&y&&y(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const E=ld(f.type==="pointercancel"?this.lastMoveEventInfo:cd(g,this.transformPagePoint),this.history);this.startEvent&&p&&p(f,E),x&&x(f,E)},!Fp(t))return;this.dragSnapToOrigin=s,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=o,this.contextWindow=r||window;const c=ka(t),l=cd(c,this.transformPagePoint),{point:u}=l,{timestamp:d}=on;this.history=[{...u,timestamp:d}];const{onSessionStart:h}=n;h&&h(t,ld(l,this.history)),this.removeListeners=va(Yo(this.contextWindow,"pointermove",this.handlePointerMove),Yo(this.contextWindow,"pointerup",this.handlePointerUp),Yo(this.contextWindow,"pointercancel",this.handlePointerUp)),a&&this.startScrollTracking(a)}startScrollTracking(t){let n=t.parentElement;for(;n;){const i=getComputedStyle(n);(xy.has(i.overflowX)||xy.has(i.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0,passive:!0}),window.addEventListener("scroll",this.onWindowScroll,{passive:!0}),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(t){const n=this.scrollPositions.get(t);if(!n)return;const i=t===window,r=i?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},s={x:r.x-n.x,y:r.y-n.y};s.x===0&&s.y===0||(i?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=s.x,this.lastMoveEventInfo.point.y+=s.y):this.history.length>0&&(this.history[0].x-=s.x,this.history[0].y-=s.y),this.scrollPositions.set(t,r),Rt.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),xr(this.updatePoint)}}function cd(e,t){return t?{point:t(e.point)}:e}function Sy(e,t){return{x:e.x-t.x,y:e.y-t.y}}function ld({point:e},t){return{point:e,delta:Sy(e,ZE(t)),offset:Sy(e,r2(t)),velocity:s2(t,.1)}}function r2(e){return e[0]}function ZE(e){return e[e.length-1]}function s2(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,i=null;const r=ZE(e);for(;n>=0&&(i=e[n],!(r.timestamp-i.timestamp>xi(t)));)n--;if(!i)return{x:0,y:0};const s=Wn(r.timestamp-i.timestamp);if(s===0)return{x:0,y:0};const o={x:(r.x-i.x)/s,y:(r.y-i.y)/s};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function o2(e,{min:t,max:n},i){return t!==void 0&&e<t?e=i?Dt(t,e,i.min):Math.max(e,t):n!==void 0&&e>n&&(e=i?Dt(n,e,i.max):Math.min(e,n)),e}function ky(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function a2(e,{top:t,left:n,bottom:i,right:r}){return{x:ky(e.x,n,r),y:ky(e.y,t,i)}}function Ey(e,t){let n=t.min-e.min,i=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,i]=[i,n]),{min:n,max:i}}function c2(e,t){return{x:Ey(e.x,t.x),y:Ey(e.y,t.y)}}function l2(e,t){let n=.5;const i=xn(e),r=xn(t);return r>i?n=oa(t.min,t.max-i,e.min):i>r&&(n=oa(e.min,e.max-r,t.min)),wi(0,1,n)}function u2(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const Zh=.35;function d2(e=Zh){return e===!1?e=0:e===!0&&(e=Zh),{x:wy(e,"left","right"),y:wy(e,"top","bottom")}}function wy(e,t,n){return{min:Cy(e,t),max:Cy(e,n)}}function Cy(e,t){return typeof e=="number"?e:e[t]||0}const h2=new WeakMap;class f2{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Xt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:i}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const s=d=>{n?(this.stopAnimation(),this.snapToCursor(ka(d).point)):this.pauseAnimation()},o=(d,h)=>{this.stopAnimation();const{drag:f,dragPropagation:g,onDragStart:p}=this.getProps();if(f&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=eO(f),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Vn(y=>{let E=this.getAxisMotionValue(y).get()||0;if(Si.test(E)){const{projection:w}=this.visualElement;if(w&&w.layout){const S=w.layout.layoutBox[y];S&&(E=xn(S)*(parseFloat(E)/100))}}this.originPoint[y]=E}),p&&Rt.postRender(()=>p(d,h)),Hh(this.visualElement,"transform");const{animationState:x}=this.visualElement;x&&x.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:f,dragDirectionLock:g,onDirectionLock:p,onDrag:x}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:y}=h;if(g&&this.currentDirection===null){this.currentDirection=p2(y),this.currentDirection!==null&&p&&p(this.currentDirection);return}this.updateAxis("x",h.point,y),this.updateAxis("y",h.point,y),this.visualElement.render(),x&&x(d,h)},c=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h,this.stop(d,h),this.latestPointerEvent=null,this.latestPanInfo=null},l=()=>Vn(d=>{var h;return this.getAnimationState(d)==="paused"&&((h=this.getAxisMotionValue(d).animation)==null?void 0:h.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new XE(t,{onSessionStart:s,onStart:o,onMove:a,onSessionEnd:c,resumeAnimation:l},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:i,contextWindow:JE(this.visualElement),element:this.visualElement.current})}stop(t,n){const i=t||this.latestPointerEvent,r=n||this.latestPanInfo,s=this.isDragging;if(this.cancel(),!s||!r||!i)return;const{velocity:o}=r;this.startAnimation(o);const{onDragEnd:a}=this.getProps();a&&Rt.postRender(()=>a(i,r))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:i}=this.getProps();!i&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,n,i){const{drag:r}=this.getProps();if(!i||!Za(t,r,this.currentDirection))return;const s=this.getAxisMotionValue(t);let o=this.originPoint[t]+i[t];this.constraints&&this.constraints[t]&&(o=o2(o,this.constraints[t],this.elastic[t])),s.set(o)}resolveConstraints(){var s;const{dragConstraints:t,dragElastic:n}=this.getProps(),i=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(s=this.visualElement.projection)==null?void 0:s.layout,r=this.constraints;t&&Uo(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&i?this.constraints=a2(i.layoutBox,t):this.constraints=!1,this.elastic=d2(n),r!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&Vn(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=u2(i.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Uo(t))return!1;const i=t.current;Yi(i!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const s=bO(i,r.root,this.visualElement.getTransformPagePoint());let o=c2(r.layout.layoutBox,s);if(n){const a=n(pO(o));this.hasMutatedConstraints=!!a,a&&(o=vE(a))}return o}startAnimation(t){const{drag:n,dragMomentum:i,dragElastic:r,dragTransition:s,dragSnapToOrigin:o,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},l=Vn(u=>{if(!Za(u,n,this.currentDirection))return;let d=c&&c[u]||{};o&&(d={min:0,max:0});const h=r?200:1e6,f=r?40:1e7,g={type:"inertia",velocity:i?t[u]:0,bounceStiffness:h,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...s,...d};return this.startAxisValueAnimation(u,g)});return Promise.all(l).then(a)}startAxisValueAnimation(t,n){const i=this.getAxisMotionValue(t);return Hh(this.visualElement,t),i.start(Pp(t,i,0,n,this.visualElement,!1))}stopAnimation(){Vn(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Vn(t=>{var n;return(n=this.getAxisMotionValue(t).animation)==null?void 0:n.pause()})}getAnimationState(t){var n;return(n=this.getAxisMotionValue(t).animation)==null?void 0:n.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,i=this.visualElement.getProps(),r=i[n];return r||this.visualElement.getValue(t,(i.initial?i.initial[t]:void 0)||0)}snapToCursor(t){Vn(n=>{const{drag:i}=this.getProps();if(!Za(n,i,this.currentDirection))return;const{projection:r}=this.visualElement,s=this.getAxisMotionValue(n);if(r&&r.layout){const{min:o,max:a}=r.layout.layoutBox[n],c=s.get()||0;s.set(t[n]-Dt(o,a,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!Uo(n)||!i||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Vn(o=>{const a=this.getAxisMotionValue(o);if(a&&this.constraints!==!1){const c=a.get();r[o]=l2({min:c,max:c},this.constraints[o])}});const{transformTemplate:s}=this.visualElement.getProps();this.visualElement.current.style.transform=s?s({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),Vn(o=>{if(!Za(o,t,null))return;const a=this.getAxisMotionValue(o),{min:c,max:l}=this.constraints[o];a.set(Dt(c,l,r[o]))})}addListeners(){if(!this.visualElement.current)return;h2.set(this.visualElement,this);const t=this.visualElement.current,n=Yo(t,"pointerdown",c=>{const{drag:l,dragListener:u=!0}=this.getProps(),d=c.target,h=d!==t&&fE(d);l&&u&&!h&&this.start(c)}),i=()=>{const{dragConstraints:c}=this.getProps();Uo(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:r}=this.visualElement,s=r.addEventListener("measure",i);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),Rt.read(i);const o=ua(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",(({delta:c,hasLayoutChanged:l})=>{this.isDragging&&l&&(Vn(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=c[u].translate,d.set(d.get()+c[u].translate))}),this.visualElement.render())}));return()=>{o(),n(),s(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:i=!1,dragPropagation:r=!1,dragConstraints:s=!1,dragElastic:o=Zh,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:i,dragPropagation:r,dragConstraints:s,dragElastic:o,dragMomentum:a}}}function Za(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function p2(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class m2 extends Ir{constructor(t){super(t),this.removeGroupControls=qn,this.removeListeners=qn,this.controls=new f2(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||qn}update(){const{dragControls:t}=this.node.getProps(),{dragControls:n}=this.node.prevProps||{};t!==n&&(this.removeGroupControls(),t&&(this.removeGroupControls=t.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const Ty=e=>(t,n)=>{e&&Rt.postRender(()=>e(t,n))};class g2 extends Ir{constructor(){super(...arguments),this.removePointerDownListener=qn}onPointerDown(t){this.session=new XE(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:JE(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:i,onPanEnd:r}=this.node.getProps();return{onSessionStart:Ty(t),onStart:Ty(n),onMove:i,onEnd:(s,o)=>{delete this.session,r&&Rt.postRender(()=>r(s,o))}}}mount(){this.removePointerDownListener=Yo(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let ud=!1;class b2 extends M.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:i,layoutId:r}=this.props,{projection:s}=t;s&&(n.group&&n.group.add(s),i&&i.register&&r&&i.register(s),ud&&s.root.didUpdate(),s.addEventListener("animationComplete",()=>{this.safeToRemove()}),s.setOptions({...s.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Uc.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:i,drag:r,isPresent:s}=this.props,{projection:o}=i;return o&&(o.isPresent=s,t.layoutDependency!==n&&o.setOptions({...o.options,layoutDependency:n}),ud=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==s?o.willUpdate():this.safeToRemove(),t.isPresent!==s&&(s?o.promote():o.relegate()||Rt.postRender(()=>{const a=o.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Bp.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:i}=this.props,{projection:r}=t;ud=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),i&&i.deregister&&i.deregister(r))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function $E(e){const[t,n]=VE(),i=M.useContext(pp);return m.jsx(b2,{...e,layoutGroup:i,switchLayoutGroup:M.useContext(QE),isPresent:t,safeToRemove:n})}const y2={pan:{Feature:g2},drag:{Feature:m2,ProjectionNode:jE,MeasureLayout:$E}};function Ay(e,t,n){const{props:i}=e;e.animationState&&i.whileHover&&e.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,s=i[r];s&&Rt.postRender(()=>s(t,ka(t)))}class v2 extends Ir{mount(){const{current:t}=this.node;t&&(this.unmount=tO(t,(n,i)=>(Ay(this.node,i,"Start"),r=>Ay(this.node,r,"End"))))}unmount(){}}class x2 extends Ir{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=va(ua(this.node.current,"focus",()=>this.onFocus()),ua(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Ry(e,t,n){const{props:i}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&i.whileTap&&e.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),s=i[r];s&&Rt.postRender(()=>s(t,ka(t)))}class S2 extends Ir{mount(){const{current:t}=this.node;t&&(this.unmount=rO(t,(n,i)=>(Ry(this.node,i,"Start"),(r,{success:s})=>Ry(this.node,r,s?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const $h=new WeakMap,dd=new WeakMap,k2=e=>{const t=$h.get(e.target);t&&t(e)},E2=e=>{e.forEach(k2)};function w2({root:e,...t}){const n=e||document;dd.has(n)||dd.set(n,{});const i=dd.get(n),r=JSON.stringify(t);return i[r]||(i[r]=new IntersectionObserver(E2,{root:e,...t})),i[r]}function C2(e,t,n){const i=w2(t);return $h.set(e,n),i.observe(e),()=>{$h.delete(e),i.unobserve(e)}}const T2={some:0,all:1};class A2 extends Ir{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:i,amount:r="some",once:s}=t,o={root:n?n.current:void 0,rootMargin:i,threshold:typeof r=="number"?r:T2[r]},a=c=>{const{isIntersecting:l}=c;if(this.isInView===l||(this.isInView=l,s&&!l&&this.hasEnteredView))return;l&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",l);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),h=l?u:d;h&&h(c)};return C2(this.node.current,o,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(R2(t,n))&&this.startObserver()}unmount(){}}function R2({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const _2={inView:{Feature:A2},tap:{Feature:S2},focus:{Feature:x2},hover:{Feature:v2}},I2={layout:{ProjectionNode:jE,MeasureLayout:$E}},N2={...t2,..._2,...y2,...I2},Ve=JD(N2,XD);var $a=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ew(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ef={exports:{}},M2=ef.exports,_y;function P2(){return _y||(_y=1,(function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(M2,function(){var t=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},o=null;function a(p,x){var y=p[x];if(typeof y.bind=="function")return y.bind(p);try{return Function.prototype.bind.call(y,p)}catch{return function(){return Function.prototype.apply.apply(y,[p,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(p){return p==="debug"&&(p="log"),typeof console===n?!1:p==="trace"&&i?c:console[p]!==void 0?a(console,p):console.log!==void 0?a(console,"log"):t}function u(){for(var p=this.getLevel(),x=0;x<r.length;x++){var y=r[x];this[y]=x<p?t:this.methodFactory(y,p,this.name)}if(this.log=this.debug,typeof console===n&&p<this.levels.SILENT)return"No console available for logging"}function d(p){return function(){typeof console!==n&&(u.call(this),this[p].apply(this,arguments))}}function h(p,x,y){return l(p)||d.apply(this,arguments)}function f(p,x){var y=this,E,w,S,v="loglevel";typeof p=="string"?v+=":"+p:typeof p=="symbol"&&(v=void 0);function k(A){var P=(r[A]||"silent").toUpperCase();if(!(typeof window===n||!v)){try{window.localStorage[v]=P;return}catch{}try{window.document.cookie=encodeURIComponent(v)+"="+P+";"}catch{}}}function _(){var A;if(!(typeof window===n||!v)){try{A=window.localStorage[v]}catch{}if(typeof A===n)try{var P=window.document.cookie,B=encodeURIComponent(v),L=P.indexOf(B+"=");L!==-1&&(A=/^([^;]+)/.exec(P.slice(L+B.length+1))[1])}catch{}return y.levels[A]===void 0&&(A=void 0),A}}function T(){if(!(typeof window===n||!v)){try{window.localStorage.removeItem(v)}catch{}try{window.document.cookie=encodeURIComponent(v)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function I(A){var P=A;if(typeof P=="string"&&y.levels[P.toUpperCase()]!==void 0&&(P=y.levels[P.toUpperCase()]),typeof P=="number"&&P>=0&&P<=y.levels.SILENT)return P;throw new TypeError("log.setLevel() called with invalid level: "+A)}y.name=p,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=x||h,y.getLevel=function(){return S??w??E},y.setLevel=function(A,P){return S=I(A),P!==!1&&k(S),u.call(y)},y.setDefaultLevel=function(A){w=I(A),_()||y.setLevel(A,!1)},y.resetLevel=function(){S=null,T(),u.call(y)},y.enableAll=function(A){y.setLevel(y.levels.TRACE,A)},y.disableAll=function(A){y.setLevel(y.levels.SILENT,A)},y.rebuild=function(){if(o!==y&&(E=I(o.getLevel())),u.call(y),o===y)for(var A in s)s[A].rebuild()},E=I(o?o.getLevel():"WARN");var b=_();b!=null&&(S=I(b)),u.call(y)}o=new f,o.getLogger=function(p){if(typeof p!="symbol"&&typeof p!="string"||p==="")throw new TypeError("You must supply a name when creating a logger.");var x=s[p];return x||(x=s[p]=new f(p,o.methodFactory)),x};var g=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=g),o},o.getLoggers=function(){return s},o.default=o,o})})(ef)),ef.exports}var O2=P2();const D2=ew(O2);var tf=function(e,t){return tf=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(n[r]=i[r])},tf(e,t)};function Zi(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");tf(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function L2(e,t,n,i){function r(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(u){try{l(i.next(u))}catch(d){o(d)}}function c(u){try{l(i.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((i=i.apply(e,[])).next())})}function tw(e,t){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,r,s,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(n=0)),n;)try{if(i=1,r&&(s=l[0]&2?r.return:l[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,l[1])).done)return s;switch(r=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,r=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){n.label=l[1];break}if(l[0]===6&&n.label<s[1]){n.label=s[1],s=l;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(l);break}s[2]&&n.ops.pop(),n.trys.pop();continue}l=t.call(e,n)}catch(u){l=[6,u],r=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Js(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function yl(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,s=[],o;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function vl(e,t,n){if(arguments.length===2)for(var i=0,r=t.length,s;i<r;i++)(s||!(i in t))&&(s||(s=Array.prototype.slice.call(t,0,i)),s[i]=t[i]);return e.concat(s||Array.prototype.slice.call(t))}function Gs(e){return this instanceof Gs?(this.v=e,this):new Gs(e)}function B2(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(e,t||[]),r,s=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),r[Symbol.asyncIterator]=function(){return this},r;function o(f){return function(g){return Promise.resolve(g).then(f,d)}}function a(f,g){i[f]&&(r[f]=function(p){return new Promise(function(x,y){s.push([f,p,x,y])>1||c(f,p)})},g&&(r[f]=g(r[f])))}function c(f,g){try{l(i[f](g))}catch(p){h(s[0][3],p)}}function l(f){f.value instanceof Gs?Promise.resolve(f.value.v).then(u,d):h(s[0][2],f)}function u(f){c("next",f)}function d(f){c("throw",f)}function h(f,g){f(g),s.shift(),s.length&&c(s[0][0],s[0][1])}}function F2(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof Js=="function"?Js(e):e[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(s){n[s]=e[s]&&function(o){return new Promise(function(a,c){o=e[s](o),r(a,c,o.done,o.value)})}}function r(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function $t(e){return typeof e=="function"}function Wp(e){var t=function(i){Error.call(i),i.stack=new Error().stack},n=e(t);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var hd=Wp(function(e){return function(t){e(this),this.message=t?t.length+` errors occurred during unsubscription:
47
47
  `+t.map(function(n,i){return i+1+") "+n.toString()}).join(`
48
- `):"",this.name="UnsubscriptionError",this.errors=t}});function xl(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var Ea=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,n,i,r,s;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=Js(o),c=a.next();!c.done;c=a.next()){var l=c.value;l.remove(this)}}catch(p){t={error:p}}finally{try{c&&!c.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}else o.remove(this);var u=this.initialTeardown;if($t(u))try{u()}catch(p){s=p instanceof hd?p.errors:[p]}var d=this._finalizers;if(d){this._finalizers=null;try{for(var h=Js(d),f=h.next();!f.done;f=h.next()){var g=f.value;try{Iy(g)}catch(p){s=s??[],p instanceof hd?s=vl(vl([],yl(s)),yl(p.errors)):s.push(p)}}}catch(p){i={error:p}}finally{try{f&&!f.done&&(r=h.return)&&r.call(h)}finally{if(i)throw i.error}}}if(s)throw new hd(s)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Iy(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(t)}},e.prototype._hasParent=function(t){var n=this._parentage;return n===t||Array.isArray(n)&&n.includes(t)},e.prototype._addParent=function(t){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(t),n):n?[n,t]:t},e.prototype._removeParent=function(t){var n=this._parentage;n===t?this._parentage=null:Array.isArray(n)&&xl(n,t)},e.prototype.remove=function(t){var n=this._finalizers;n&&xl(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),nw=Ea.EMPTY;function iw(e){return e instanceof Ea||e&&"closed"in e&&$t(e.remove)&&$t(e.add)&&$t(e.unsubscribe)}function Iy(e){$t(e)?e():e.unsubscribe()}var U2={Promise:void 0},j2={setTimeout:function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];return setTimeout.apply(void 0,vl([e,t],yl(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function rw(e){j2.setTimeout(function(){throw e})}function Ny(){}function jc(e){e()}var qp=(function(e){Zi(t,e);function t(n){var i=e.call(this)||this;return i.isStopped=!1,n?(i.destination=n,iw(n)&&n.add(i)):i.destination=G2,i}return t.create=function(n,i,r){return new nf(n,i,r)},t.prototype.next=function(n){this.isStopped||this._next(n)},t.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(n){this.destination.next(n)},t.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(Ea),V2=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var n=this.partialObserver;if(n.next)try{n.next(t)}catch(i){ec(i)}},e.prototype.error=function(t){var n=this.partialObserver;if(n.error)try{n.error(t)}catch(i){ec(i)}else ec(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(n){ec(n)}},e})(),nf=(function(e){Zi(t,e);function t(n,i,r){var s=e.call(this)||this,o;return $t(n)||!n?o={next:n??void 0,error:i??void 0,complete:r??void 0}:o=n,s.destination=new V2(o),s}return t})(qp);function ec(e){rw(e)}function z2(e){throw e}var G2={closed:!0,next:Ny,error:z2,complete:Ny},Qp=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function sw(e){return e}function H2(e){return e.length===0?sw:e.length===1?e[0]:function(t){return e.reduce(function(n,i){return i(n)},t)}}var Fn=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(t,n,i){var r=this,s=W2(t)?t:new nf(t,n,i);return jc(function(){var o=r,a=o.operator,c=o.source;s.add(a?a.call(s,c):c?r._subscribe(s):r._trySubscribe(s))}),s},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(n){t.error(n)}},e.prototype.forEach=function(t,n){var i=this;return n=My(n),new n(function(r,s){var o=new nf({next:function(a){try{t(a)}catch(c){s(c),o.unsubscribe()}},error:s,complete:r});i.subscribe(o)})},e.prototype._subscribe=function(t){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(t)},e.prototype[Qp]=function(){return this},e.prototype.pipe=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return H2(t)(this)},e.prototype.toPromise=function(t){var n=this;return t=My(t),new t(function(i,r){var s;n.subscribe(function(o){return s=o},function(o){return r(o)},function(){return i(s)})})},e.create=function(t){return new e(t)},e})();function My(e){var t;return(t=e??U2.Promise)!==null&&t!==void 0?t:Promise}function K2(e){return e&&$t(e.next)&&$t(e.error)&&$t(e.complete)}function W2(e){return e&&e instanceof qp||K2(e)&&iw(e)}function q2(e){return $t(e==null?void 0:e.lift)}function wa(e){return function(t){if(q2(t))return t.lift(function(n){try{return e(n,this)}catch(i){this.error(i)}});throw new TypeError("Unable to lift unknown Observable type")}}function Sl(e,t,n,i,r){return new Q2(e,t,n,i,r)}var Q2=(function(e){Zi(t,e);function t(n,i,r,s,o,a){var c=e.call(this,n)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=i?function(l){try{i(l)}catch(u){n.error(u)}}:e.prototype._next,c._error=s?function(l){try{s(l)}catch(u){n.error(u)}finally{this.unsubscribe()}}:e.prototype._error,c._complete=r?function(){try{r()}catch(l){n.error(l)}finally{this.unsubscribe()}}:e.prototype._complete,c}return t.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var i=this.closed;e.prototype.unsubscribe.call(this),!i&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},t})(qp),Y2=Wp(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),ow=(function(e){Zi(t,e);function t(){var n=e.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return t.prototype.lift=function(n){var i=new Py(this,this);return i.operator=n,i},t.prototype._throwIfClosed=function(){if(this.closed)throw new Y2},t.prototype.next=function(n){var i=this;jc(function(){var r,s;if(i._throwIfClosed(),!i.isStopped){i.currentObservers||(i.currentObservers=Array.from(i.observers));try{for(var o=Js(i.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(n)}}catch(l){r={error:l}}finally{try{a&&!a.done&&(s=o.return)&&s.call(o)}finally{if(r)throw r.error}}}})},t.prototype.error=function(n){var i=this;jc(function(){if(i._throwIfClosed(),!i.isStopped){i.hasError=i.isStopped=!0,i.thrownError=n;for(var r=i.observers;r.length;)r.shift().error(n)}})},t.prototype.complete=function(){var n=this;jc(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var i=n.observers;i.length;)i.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(n){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,n)},t.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},t.prototype._innerSubscribe=function(n){var i=this,r=this,s=r.hasError,o=r.isStopped,a=r.observers;return s||o?nw:(this.currentObservers=null,a.push(n),new Ea(function(){i.currentObservers=null,xl(a,n)}))},t.prototype._checkFinalizedStatuses=function(n){var i=this,r=i.hasError,s=i.thrownError,o=i.isStopped;r?n.error(s):o&&n.complete()},t.prototype.asObservable=function(){var n=new Fn;return n.source=this,n},t.create=function(n,i){return new Py(n,i)},t})(Fn),Py=(function(e){Zi(t,e);function t(n,i){var r=e.call(this)||this;return r.destination=n,r.source=i,r}return t.prototype.next=function(n){var i,r;(r=(i=this.destination)===null||i===void 0?void 0:i.next)===null||r===void 0||r.call(i,n)},t.prototype.error=function(n){var i,r;(r=(i=this.destination)===null||i===void 0?void 0:i.error)===null||r===void 0||r.call(i,n)},t.prototype.complete=function(){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||i===void 0||i.call(n)},t.prototype._subscribe=function(n){var i,r;return(r=(i=this.source)===null||i===void 0?void 0:i.subscribe(n))!==null&&r!==void 0?r:nw},t})(ow);(function(e){Zi(t,e);function t(n){var i=e.call(this)||this;return i._value=n,i}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(n){var i=e.prototype._subscribe.call(this,n);return!i.closed&&n.next(this._value),i},t.prototype.getValue=function(){var n=this,i=n.hasError,r=n.thrownError,s=n._value;if(i)throw r;return this._throwIfClosed(),s},t.prototype.next=function(n){e.prototype.next.call(this,this._value=n)},t})(ow);var J2={now:function(){return Date.now()}},X2=(function(e){Zi(t,e);function t(n,i){return e.call(this)||this}return t.prototype.schedule=function(n,i){return this},t})(Ea),Oy={setInterval:function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];return setInterval.apply(void 0,vl([e,t],yl(n)))},clearInterval:function(e){return clearInterval(e)},delegate:void 0},Z2=(function(e){Zi(t,e);function t(n,i){var r=e.call(this,n,i)||this;return r.scheduler=n,r.work=i,r.pending=!1,r}return t.prototype.schedule=function(n,i){var r;if(i===void 0&&(i=0),this.closed)return this;this.state=n;var s=this.id,o=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(o,s,i)),this.pending=!0,this.delay=i,this.id=(r=this.id)!==null&&r!==void 0?r:this.requestAsyncId(o,this.id,i),this},t.prototype.requestAsyncId=function(n,i,r){return r===void 0&&(r=0),Oy.setInterval(n.flush.bind(n,this),r)},t.prototype.recycleAsyncId=function(n,i,r){if(r===void 0&&(r=0),r!=null&&this.delay===r&&this.pending===!1)return i;i!=null&&Oy.clearInterval(i)},t.prototype.execute=function(n,i){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(n,i);if(r)return r;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(n,i){var r=!1,s;try{this.work(n)}catch(o){r=!0,s=o||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),s},t.prototype.unsubscribe=function(){if(!this.closed){var n=this,i=n.id,r=n.scheduler,s=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,xl(s,this),i!=null&&(this.id=this.recycleAsyncId(r,i,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t})(X2),Dy=(function(){function e(t,n){n===void 0&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(t,n,i){return n===void 0&&(n=0),new this.schedulerActionCtor(this,t).schedule(i,n)},e.now=J2.now,e})(),$2=(function(e){Zi(t,e);function t(n,i){i===void 0&&(i=Dy.now);var r=e.call(this,n,i)||this;return r.actions=[],r._active=!1,r}return t.prototype.flush=function(n){var i=this.actions;if(this._active){i.push(n);return}var r;this._active=!0;do if(r=n.execute(n.state,n.delay))break;while(n=i.shift());if(this._active=!1,r){for(;n=i.shift();)n.unsubscribe();throw r}},t})(Dy);new $2(Z2);function eL(e){return e&&$t(e.schedule)}function tL(e){return e[e.length-1]}function aw(e){return eL(tL(e))?e.pop():void 0}var cw=(function(e){return e&&typeof e.length=="number"&&typeof e!="function"});function lw(e){return $t(e==null?void 0:e.then)}function uw(e){return $t(e[Qp])}function dw(e){return Symbol.asyncIterator&&$t(e==null?void 0:e[Symbol.asyncIterator])}function hw(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function nL(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var fw=nL();function pw(e){return $t(e==null?void 0:e[fw])}function mw(e){return B2(this,arguments,function(){var t,n,i,r;return tw(this,function(s){switch(s.label){case 0:t=e.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,Gs(t.read())];case 3:return n=s.sent(),i=n.value,r=n.done,r?[4,Gs(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,Gs(i)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function gw(e){return $t(e==null?void 0:e.getReader)}function Ca(e){if(e instanceof Fn)return e;if(e!=null){if(uw(e))return iL(e);if(cw(e))return rL(e);if(lw(e))return sL(e);if(dw(e))return bw(e);if(pw(e))return oL(e);if(gw(e))return aL(e)}throw hw(e)}function iL(e){return new Fn(function(t){var n=e[Qp]();if($t(n.subscribe))return n.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function rL(e){return new Fn(function(t){for(var n=0;n<e.length&&!t.closed;n++)t.next(e[n]);t.complete()})}function sL(e){return new Fn(function(t){e.then(function(n){t.closed||(t.next(n),t.complete())},function(n){return t.error(n)}).then(null,rw)})}function oL(e){return new Fn(function(t){var n,i;try{for(var r=Js(e),s=r.next();!s.done;s=r.next()){var o=s.value;if(t.next(o),t.closed)return}}catch(a){n={error:a}}finally{try{s&&!s.done&&(i=r.return)&&i.call(r)}finally{if(n)throw n.error}}t.complete()})}function bw(e){return new Fn(function(t){cL(e,t).catch(function(n){return t.error(n)})})}function aL(e){return bw(mw(e))}function cL(e,t){var n,i,r,s;return L2(this,void 0,void 0,function(){var o,a;return tw(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=F2(e),c.label=1;case 1:return[4,n.next()];case 2:if(i=c.sent(),!!i.done)return[3,4];if(o=i.value,t.next(o),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),r={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),i&&!i.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(r)throw r.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function Kr(e,t,n,i,r){i===void 0&&(i=0),r===void 0&&(r=!1);var s=t.schedule(function(){n(),r?e.add(this.schedule(null,i)):this.unsubscribe()},i);if(e.add(s),!r)return s}function yw(e,t){return t===void 0&&(t=0),wa(function(n,i){n.subscribe(Sl(i,function(r){return Kr(i,e,function(){return i.next(r)},t)},function(){return Kr(i,e,function(){return i.complete()},t)},function(r){return Kr(i,e,function(){return i.error(r)},t)}))})}function vw(e,t){return t===void 0&&(t=0),wa(function(n,i){i.add(e.schedule(function(){return n.subscribe(i)},t))})}function lL(e,t){return Ca(e).pipe(vw(t),yw(t))}function uL(e,t){return Ca(e).pipe(vw(t),yw(t))}function dL(e,t){return new Fn(function(n){var i=0;return t.schedule(function(){i===e.length?n.complete():(n.next(e[i++]),n.closed||this.schedule())})})}function hL(e,t){return new Fn(function(n){var i;return Kr(n,t,function(){i=e[fw](),Kr(n,t,function(){var r,s,o;try{r=i.next(),s=r.value,o=r.done}catch(a){n.error(a);return}o?n.complete():n.next(s)},0,!0)}),function(){return $t(i==null?void 0:i.return)&&i.return()}})}function xw(e,t){if(!e)throw new Error("Iterable cannot be null");return new Fn(function(n){Kr(n,t,function(){var i=e[Symbol.asyncIterator]();Kr(n,t,function(){i.next().then(function(r){r.done?n.complete():n.next(r.value)})},0,!0)})})}function fL(e,t){return xw(mw(e),t)}function pL(e,t){if(e!=null){if(uw(e))return lL(e,t);if(cw(e))return dL(e,t);if(lw(e))return uL(e,t);if(dw(e))return xw(e,t);if(pw(e))return hL(e,t);if(gw(e))return fL(e,t)}throw hw(e)}function mL(e,t){return t?pL(e,t):Ca(e)}Wp(function(e){return function(t){t===void 0&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Ta(e,t){return wa(function(n,i){var r=0;n.subscribe(Sl(i,function(s){i.next(e.call(t,s,r++))}))})}function gL(e,t,n,i,r,s,o,a){var c=[],l=0,u=0,d=!1,h=function(){d&&!c.length&&!l&&t.complete()},f=function(p){return l<i?g(p):c.push(p)},g=function(p){l++;var x=!1;Ca(n(p,u++)).subscribe(Sl(t,function(y){t.next(y)},function(){x=!0},void 0,function(){if(x)try{l--;for(var y=function(){var E=c.shift();o||g(E)};c.length&&l<i;)y();h()}catch(E){t.error(E)}}))};return e.subscribe(Sl(t,f,function(){d=!0,h()})),function(){}}function Sw(e,t,n){return n===void 0&&(n=1/0),$t(t)?Sw(function(i,r){return Ta(function(s,o){return t(i,s,r,o)})(Ca(e(i,r)))},n):(typeof t=="number"&&(n=t),wa(function(i,r){return gL(i,r,e,n)}))}function bL(e){return Sw(sw,e)}function yL(){return bL(1)}function Ly(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return yL()(mL(e,aw(e)))}function Yl(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=aw(e);return wa(function(i,r){(n?Ly(e,i,n):Ly(e,i)).subscribe(r)})}var vL=(e,t,n)=>new Promise((i,r)=>{var s=c=>{try{a(n.next(c))}catch(l){r(l)}},o=c=>{try{a(n.throw(c))}catch(l){r(l)}},a=c=>c.done?i(c.value):Promise.resolve(c.value).then(s,o);a((n=n.apply(e,t)).next())}),xL="lk";function Yp(e){return typeof e>"u"?!1:SL(e)||kL(e)}function SL(e){var t;return e?e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&e.hasOwnProperty("track")&&typeof((t=e.publication)==null?void 0:t.track)<"u":!1}function kL(e){return e?e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&e.hasOwnProperty("publication")&&typeof e.publication<"u":!1}function EL(e){return e?e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&typeof e.publication>"u":!1}function wL(e){if(typeof e=="string"||typeof e=="number")return`${e}`;if(EL(e))return`${e.participant.identity}_${e.source}_placeholder`;if(Yp(e))return`${e.participant.identity}_${e.publication.source}_${e.publication.trackSid}`;throw new Error(`Can't generate a id for the given track reference: ${e}`)}var CL=[U.ConnectionStateChanged,U.RoomMetadataChanged,U.ActiveSpeakersChanged,U.ConnectionQualityChanged,U.ParticipantConnected,U.ParticipantDisconnected,U.ParticipantPermissionsChanged,U.ParticipantMetadataChanged,U.ParticipantNameChanged,U.ParticipantAttributesChanged,U.TrackMuted,U.TrackUnmuted,U.TrackPublished,U.TrackUnpublished,U.TrackStreamStateChanged,U.TrackSubscriptionFailed,U.TrackSubscriptionPermissionChanged,U.TrackSubscriptionStatusChanged],TL=[...CL,U.LocalTrackPublished,U.LocalTrackUnpublished];Y.TrackPublished,Y.TrackUnpublished,Y.TrackMuted,Y.TrackUnmuted,Y.TrackStreamStateChanged,Y.TrackSubscribed,Y.TrackUnsubscribed,Y.TrackSubscriptionPermissionChanged,Y.TrackSubscriptionFailed,Y.LocalTrackPublished,Y.LocalTrackUnpublished;var AL=[Y.ConnectionQualityChanged,Y.IsSpeakingChanged,Y.ParticipantMetadataChanged,Y.ParticipantPermissionsChanged,Y.TrackMuted,Y.TrackUnmuted,Y.TrackPublished,Y.TrackUnpublished,Y.TrackStreamStateChanged,Y.TrackSubscriptionFailed,Y.TrackSubscriptionPermissionChanged,Y.TrackSubscriptionStatusChanged];[...AL,Y.LocalTrackPublished,Y.LocalTrackUnpublished];var kr=D2.getLogger("lk-components-js");kr.setDefaultLevel("WARN");var kw=(e=>(e.AgentState="lk.agent.state",e.PublishOnBehalf="lk.publish_on_behalf",e.TranscriptionFinal="lk.transcription_final",e.TranscriptionSegmentId="lk.segment_id",e.TranscribedTrackId="lk.transcribed_track_id",e))(kw||{});function Ew(e){return typeof e=="object"}function ww(e){return Array.isArray(e)&&e.filter(Ew).length>0}function Cw(e){return`${xL}-${e}`}function RL(e){const t=rf(e),n=NL(e.participant).pipe(Ta(()=>rf(e)),Yl(t));return{className:Cw(e.source===z.Source.Camera||e.source===z.Source.ScreenShare?"participant-media-video":"participant-media-audio"),trackObserver:n}}function rf(e){if(Yp(e))return e.publication;{const{source:t,name:n,participant:i}=e;if(t&&n)return i.getTrackPublications().find(r=>r.source===t&&r.trackName===n);if(n)return i.getTrackPublicationByName(n);if(t)return i.getTrackPublication(t);throw new Error("At least one of source and name needs to be defined")}}function Tw(e,...t){return new Fn(n=>{const i=()=>{n.next(e)};return t.forEach(r=>{e.on(r,i)}),()=>{t.forEach(r=>{e.off(r,i)})}}).pipe(Yl(e))}function _L(e){return Tw(e,U.AudioPlaybackStatusChanged).pipe(Ta(t=>({canPlayAudio:t.canPlaybackAudio})))}function IL(e,...t){return new Fn(n=>{const i=()=>{n.next(e)};return t.forEach(r=>{e.on(r,i)}),()=>{t.forEach(r=>{e.off(r,i)})}}).pipe(Yl(e))}function NL(e){return IL(e,Y.TrackMuted,Y.TrackUnmuted,Y.ParticipantPermissionsChanged,Y.TrackPublished,Y.TrackUnpublished,Y.LocalTrackPublished,Y.LocalTrackUnpublished,Y.MediaDevicesError,Y.TrackSubscriptionStatusChanged).pipe(Ta(t=>{const{isMicrophoneEnabled:n,isCameraEnabled:i,isScreenShareEnabled:r}=t,s=t.getTrackPublication(z.Source.Microphone),o=t.getTrackPublication(z.Source.Camera);return{isCameraEnabled:i,isMicrophoneEnabled:n,isScreenShareEnabled:r,cameraTrack:o,microphoneTrack:s,participant:t}}))}function ML(){const e=t=>vL(this,null,function*(){kr.info("Start Audio for room: ",t),yield t.startAudio()});return{className:Cw("start-audio-button"),roomAudioPlaybackAllowedObservable:_L,handleStartAudioPlayback:e}}function By(e,t,n=!0){const i=[e.localParticipant,...Array.from(e.remoteParticipants.values())],r=[];return i.forEach(s=>{t.forEach(o=>{const a=Array.from(s.trackPublications.values()).filter(c=>c.source===o&&(!n||c.track)).map(c=>({participant:s,publication:c,source:c.source}));r.push(...a)})}),{trackReferences:r,participants:i}}function PL(e,t,n){var i,r;const s=(i=n.additionalRoomEvents)!=null?i:TL,o=(r=n.onlySubscribed)!=null?r:!0,a=Array.from(new Set([U.ParticipantConnected,U.ParticipantDisconnected,U.ConnectionStateChanged,U.LocalTrackPublished,U.LocalTrackUnpublished,U.TrackPublished,U.TrackUnpublished,U.TrackSubscriptionStatusChanged,...s]).values());return Tw(e,...a).pipe(Ta(c=>{const l=By(c,t,o);return kr.debug(`TrackReference[] was updated. (length ${l.trackReferences.length})`,l),l}),Yl(By(e,t,o)))}D.createContext(void 0);const OL=D.createContext(void 0);function Aw(){return D.useContext(OL)}function Rw(e){const t=Aw(),n=e??t;if(!n)throw new Error("No TrackRef, make sure you are inside a TrackRefContext or pass the TrackRef explicitly");return n}D.createContext(void 0);const Jp=D.createContext(void 0);function DL(){const e=D.useContext(Jp);if(!e)throw Error("tried to access room context outside of livekit room component");return e}function LL(){return D.useContext(Jp)}function Xp(e){const t=LL(),n=e??t;if(!n)throw new Error("No room provided, make sure you are inside a Room context or pass the room explicitly");return n}D.createContext(void 0);D.createContext(void 0);function _w(e){var t,n,i="";if(typeof e=="string"||typeof e=="number")i+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(t=0;t<r;t++)e[t]&&(n=_w(e[t]))&&(i&&(i+=" "),i+=n)}else for(n in e)e[n]&&(i&&(i+=" "),i+=n);return i}function Iw(){for(var e,t,n=0,i="",r=arguments.length;n<r;n++)(e=arguments[n])&&(t=_w(e))&&(i&&(i+=" "),i+=t);return i}function BL(...e){return(...t)=>{for(const n of e)if(typeof n=="function")try{n(...t)}catch(i){console.error(i)}}}function Nw(...e){const t={...e[0]};for(let n=1;n<e.length;n++){const i=e[n];for(const r in i){const s=t[r],o=i[r];typeof s=="function"&&typeof o=="function"&&r[0]==="o"&&r[1]==="n"&&r.charCodeAt(2)>=65&&r.charCodeAt(2)<=90?t[r]=BL(s,o):(r==="className"||r==="UNSAFE_className")&&typeof s=="string"&&typeof o=="string"?t[r]=Iw(s,o):t[r]=o!==void 0?o:s}}return t}function FL(e){return e!==void 0}function Mw(...e){return Nw(...e.filter(FL))}function UL(e,t,n){return D.Children.map(e,i=>D.isValidElement(i)&&D.Children.only(e)?(i.props.className&&(t??(t={}),t.className=Iw(i.props.className,t.className),t.style={...i.props.style,...t.style}),D.cloneElement(i,{...t,key:n})):i)}function jL(e,t,n=!0){const[i,r]=D.useState(t);return D.useEffect(()=>{if(n&&r(t),typeof window>"u"||!e)return;const s=e.subscribe(r);return()=>s.unsubscribe()},[e,n]),i}function VL({room:e,props:t}){const n=Xp(e),{className:i,roomAudioPlaybackAllowedObservable:r,handleStartAudioPlayback:s}=D.useMemo(()=>ML(),[]),o=D.useMemo(()=>r(n),[n,r]),{canPlayAudio:a}=jL(o,{canPlayAudio:n.canPlaybackAudio});return{mergedProps:D.useMemo(()=>Nw(t,{className:i,onClick:()=>{s(n)},style:{display:a?"none":"block"}}),[t,i,a,s,n]),canPlayAudio:a}}function Pw(e=[z.Source.Camera,z.Source.Microphone,z.Source.ScreenShare,z.Source.ScreenShareAudio,z.Source.Unknown],t={}){const n=Xp(t.room),[i,r]=D.useState([]),[s,o]=D.useState([]),a=D.useMemo(()=>e.map(c=>Ew(c)?c.source:c),[JSON.stringify(e)]);return D.useEffect(()=>{const c=PL(n,a,{additionalRoomEvents:t.updateOnlyOn,onlySubscribed:t.onlySubscribed}).subscribe(({trackReferences:l,participants:u})=>{kr.debug("setting track bundles",l,u),r(l),o(u)});return()=>c.unsubscribe()},[n,JSON.stringify(t.onlySubscribed),JSON.stringify(t.updateOnlyOn),JSON.stringify(e)]),D.useMemo(()=>{if(ww(e)){const c=GL(e,s),l=Array.from(i);return s.forEach(u=>{c.has(u.identity)&&(c.get(u.identity)??[]).forEach(d=>{if(i.find(({participant:f,publication:g})=>u.identity===f.identity&&g.source===d))return;kr.debug(`Add ${d} placeholder for participant ${u.identity}.`);const h={participant:u,source:d};l.push(h)})}),l}else return i},[i,s,e])}function zL(e,t){const n=new Set(e);for(const i of t)n.delete(i);return n}function GL(e,t){const n=new Map;if(ww(e)){const i=e.filter(r=>r.withPlaceholder).map(r=>r.source);t.forEach(r=>{const s=r.getTrackPublications().map(a=>{var c;return(c=a.track)==null?void 0:c.source}).filter(a=>a!==void 0),o=Array.from(zL(new Set(i),new Set(s)));o.length>0&&n.set(r.identity,o)})}return n}const HL=e=>{const t=n=>{let i=1-Math.max(-100,Math.min(-10,n))*-1/100;return i=Math.sqrt(i),i};return e.map(n=>n===-1/0?0:t(n))},KL={bands:5,loPass:100,hiPass:600,updateInterval:32,analyserOptions:{fftSize:2048}};function WL(e,t={}){var n;const i=e instanceof z?e:(n=e==null?void 0:e.publication)==null?void 0:n.track,r={...KL,...t},[s,o]=D.useState(new Array(r.bands).fill(0));return D.useEffect(()=>{if(!i||!(i!=null&&i.mediaStream)){o(h=>h.slice().fill(0));return}const{analyser:a,cleanup:c}=t1(i,r.analyserOptions),l=a.frequencyBinCount,u=new Float32Array(l),d=setInterval(()=>{a.getFloatFrequencyData(u);let h=new Float32Array(u.length);for(let x=0;x<u.length;x++)h[x]=u[x];h=h.slice(r.loPass,r.hiPass);const f=HL(h),g=f.length,p=[];for(let x=0;x<r.bands;x++){const y=Math.floor(x*g/r.bands),E=Math.floor((x+1)*g/r.bands),w=f.slice(y,E),S=w.length;if(S===0)p.push(0);else{const v=w.reduce((k,_)=>k+=_,0);p.push(v/S)}}o(p)},r.updateInterval);return()=>{c(),clearInterval(d)}},[i,i==null?void 0:i.mediaStream,JSON.stringify(t)]),s}kw.AgentState;var tc={exports:{}},Fy;function qL(){if(Fy)return tc.exports;Fy=1;var e=typeof Reflect=="object"?Reflect:null,t=e&&typeof e.apply=="function"?e.apply:function(S,v,k){return Function.prototype.apply.call(S,v,k)},n;e&&typeof e.ownKeys=="function"?n=e.ownKeys:Object.getOwnPropertySymbols?n=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:n=function(S){return Object.getOwnPropertyNames(S)};function i(S){console&&console.warn&&console.warn(S)}var r=Number.isNaN||function(S){return S!==S};function s(){s.init.call(this)}tc.exports=s,tc.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(S){if(typeof S!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof S)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(S){if(typeof S!="number"||S<0||r(S))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+S+".");o=S}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(S){if(typeof S!="number"||S<0||r(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function c(S){return S._maxListeners===void 0?s.defaultMaxListeners:S._maxListeners}s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(S){for(var v=[],k=1;k<arguments.length;k++)v.push(arguments[k]);var _=S==="error",T=this._events;if(T!==void 0)_=_&&T.error===void 0;else if(!_)return!1;if(_){var I;if(v.length>0&&(I=v[0]),I instanceof Error)throw I;var b=new Error("Unhandled error."+(I?" ("+I.message+")":""));throw b.context=I,b}var A=T[S];if(A===void 0)return!1;if(typeof A=="function")t(A,this,v);else for(var P=A.length,B=g(A,P),k=0;k<P;++k)t(B[k],this,v);return!0};function l(S,v,k,_){var T,I,b;if(a(k),I=S._events,I===void 0?(I=S._events=Object.create(null),S._eventsCount=0):(I.newListener!==void 0&&(S.emit("newListener",v,k.listener?k.listener:k),I=S._events),b=I[v]),b===void 0)b=I[v]=k,++S._eventsCount;else if(typeof b=="function"?b=I[v]=_?[k,b]:[b,k]:_?b.unshift(k):b.push(k),T=c(S),T>0&&b.length>T&&!b.warned){b.warned=!0;var A=new Error("Possible EventEmitter memory leak detected. "+b.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");A.name="MaxListenersExceededWarning",A.emitter=S,A.type=v,A.count=b.length,i(A)}return S}s.prototype.addListener=function(S,v){return l(this,S,v,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(S,v){return l(this,S,v,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(S,v,k){var _={fired:!1,wrapFn:void 0,target:S,type:v,listener:k},T=u.bind(_);return T.listener=k,_.wrapFn=T,T}s.prototype.once=function(S,v){return a(v),this.on(S,d(this,S,v)),this},s.prototype.prependOnceListener=function(S,v){return a(v),this.prependListener(S,d(this,S,v)),this},s.prototype.removeListener=function(S,v){var k,_,T,I,b;if(a(v),_=this._events,_===void 0)return this;if(k=_[S],k===void 0)return this;if(k===v||k.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete _[S],_.removeListener&&this.emit("removeListener",S,k.listener||v));else if(typeof k!="function"){for(T=-1,I=k.length-1;I>=0;I--)if(k[I]===v||k[I].listener===v){b=k[I].listener,T=I;break}if(T<0)return this;T===0?k.shift():p(k,T),k.length===1&&(_[S]=k[0]),_.removeListener!==void 0&&this.emit("removeListener",S,b||v)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(S){var v,k,_;if(k=this._events,k===void 0)return this;if(k.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):k[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete k[S]),this;if(arguments.length===0){var T=Object.keys(k),I;for(_=0;_<T.length;++_)I=T[_],I!=="removeListener"&&this.removeAllListeners(I);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=k[S],typeof v=="function")this.removeListener(S,v);else if(v!==void 0)for(_=v.length-1;_>=0;_--)this.removeListener(S,v[_]);return this};function h(S,v,k){var _=S._events;if(_===void 0)return[];var T=_[v];return T===void 0?[]:typeof T=="function"?k?[T.listener||T]:[T]:k?x(T):g(T,T.length)}s.prototype.listeners=function(S){return h(this,S,!0)},s.prototype.rawListeners=function(S){return h(this,S,!1)},s.listenerCount=function(S,v){return typeof S.listenerCount=="function"?S.listenerCount(v):f.call(S,v)},s.prototype.listenerCount=f;function f(S){var v=this._events;if(v!==void 0){var k=v[S];if(typeof k=="function")return 1;if(k!==void 0)return k.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function g(S,v){for(var k=new Array(v),_=0;_<v;++_)k[_]=S[_];return k}function p(S,v){for(;v+1<S.length;v++)S[v]=S[v+1];S.pop()}function x(S){for(var v=new Array(S.length),k=0;k<v.length;++k)v[k]=S[k].listener||S[k];return v}function y(S,v){return new Promise(function(k,_){function T(b){S.removeListener(v,I),_(b)}function I(){typeof S.removeListener=="function"&&S.removeListener("error",T),k([].slice.call(arguments))}w(S,v,I,{once:!0}),v!=="error"&&E(S,T,{once:!0})})}function E(S,v,k){typeof S.on=="function"&&w(S,"error",v,k)}function w(S,v,k,_){if(typeof S.on=="function")_.once?S.once(v,k):S.on(v,k);else if(typeof S.addEventListener=="function")S.addEventListener(v,function T(I){_.once&&S.removeEventListener(v,T),k(I)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof S)}return tc.exports}qL();const QL=D.forwardRef(function({label:e="Allow Audio",...t},n){const i=Xp(t.room),{mergedProps:r}=VL({room:i,props:t});return D.createElement("button",{ref:n,...r},e)});function Ow(e,t={}){const[n,i]=D.useState(rf(e)),[r,s]=D.useState(n==null?void 0:n.isMuted),[o,a]=D.useState(n==null?void 0:n.isSubscribed),[c,l]=D.useState(n==null?void 0:n.track),[u,d]=D.useState("landscape"),h=D.useRef(),{className:f,trackObserver:g}=D.useMemo(()=>RL(e),[e.participant.sid??e.participant.identity,e.source,Yp(e)&&e.publication.trackSid]);return D.useEffect(()=>{const p=g.subscribe(x=>{kr.debug("update track",x),i(x),s(x==null?void 0:x.isMuted),a(x==null?void 0:x.isSubscribed),l(x==null?void 0:x.track)});return()=>p==null?void 0:p.unsubscribe()},[g]),D.useEffect(()=>{var p,x;return c&&(h.current&&c.detach(h.current),(p=t.element)!=null&&p.current&&!(e.participant.isLocal&&(c==null?void 0:c.kind)==="audio")&&c.attach(t.element.current)),h.current=(x=t.element)==null?void 0:x.current,()=>{h.current&&(c==null||c.detach(h.current))}},[c,t.element]),D.useEffect(()=>{var p,x;if(typeof((p=n==null?void 0:n.dimensions)==null?void 0:p.width)=="number"&&typeof((x=n==null?void 0:n.dimensions)==null?void 0:x.height)=="number"){const y=n.dimensions.width>n.dimensions.height?"landscape":"portrait";d(y)}},[n]),{publication:n,isMuted:r,isSubscribed:o,track:c,elementProps:Mw(t.props,{className:f,"data-lk-local-participant":e.participant.isLocal,"data-lk-source":n==null?void 0:n.source,...(n==null?void 0:n.kind)==="video"&&{"data-lk-orientation":u}})}}var fd,Uy;function YL(){if(Uy)return fd;Uy=1;var e="Expected a function",t=NaN,n="[object Symbol]",i=/^\s+|\s+$/g,r=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,o=/^0o[0-7]+$/i,a=parseInt,c=typeof $a=="object"&&$a&&$a.Object===Object&&$a,l=typeof self=="object"&&self&&self.Object===Object&&self,u=c||l||Function("return this")(),d=Object.prototype,h=d.toString,f=Math.max,g=Math.min,p=function(){return u.Date.now()};function x(v,k,_){var T,I,b,A,P,B,L=0,V=!1,J=!1,re=!0;if(typeof v!="function")throw new TypeError(e);k=S(k)||0,y(_)&&(V=!!_.leading,J="maxWait"in _,b=J?f(S(_.maxWait)||0,k):b,re="trailing"in _?!!_.trailing:re);function G(ee){var te=T,ue=I;return T=I=void 0,L=ee,A=v.apply(ue,te),A}function Q(ee){return L=ee,P=setTimeout(X,k),V?G(ee):A}function C(ee){var te=ee-B,ue=ee-L,me=k-te;return J?g(me,b-ue):me}function K(ee){var te=ee-B,ue=ee-L;return B===void 0||te>=k||te<0||J&&ue>=b}function X(){var ee=p();if(K(ee))return R(ee);P=setTimeout(X,C(ee))}function R(ee){return P=void 0,re&&T?G(ee):(T=I=void 0,A)}function ae(){P!==void 0&&clearTimeout(P),L=0,T=B=I=P=void 0}function he(){return P===void 0?A:R(p())}function ce(){var ee=p(),te=K(ee);if(T=arguments,I=this,B=ee,te){if(P===void 0)return Q(B);if(J)return P=setTimeout(X,k),G(B)}return P===void 0&&(P=setTimeout(X,k)),A}return ce.cancel=ae,ce.flush=he,ce}function y(v){var k=typeof v;return!!v&&(k=="object"||k=="function")}function E(v){return!!v&&typeof v=="object"}function w(v){return typeof v=="symbol"||E(v)&&h.call(v)==n}function S(v){if(typeof v=="number")return v;if(w(v))return t;if(y(v)){var k=typeof v.valueOf=="function"?v.valueOf():v;v=y(k)?k+"":k}if(typeof v!="string")return v===0?v:+v;v=v.replace(i,"");var _=s.test(v);return _||o.test(v)?a(v.slice(2),_?2:8):r.test(v)?t:+v}return fd=x,fd}var JL=YL();const jy=ew(JL);function XL(e){const t=M.useRef(e);t.current=e,M.useEffect(()=>()=>{t.current()},[])}function ZL(e,t=500,n){const i=M.useRef();XL(()=>{i.current&&i.current.cancel()});const r=M.useMemo(()=>{const s=jy(e,t,n),o=(...a)=>s(...a);return o.cancel=()=>{s.cancel()},o.isPending=()=>!!i.current,o.flush=()=>s.flush(),o},[e,t,n]);return M.useEffect(()=>{i.current=jy(e,t,n)},[e,t,n]),r}function $L(e,t,n){const i=((l,u)=>l===u),r=e instanceof Function?e():e,[s,o]=M.useState(r),a=M.useRef(r),c=ZL(o,t,n);return i(a.current,r)||(c(r),a.current=r),[s,c]}function eB({threshold:e=0,root:t=null,rootMargin:n="0%",freezeOnceVisible:i=!1,initialIsIntersecting:r=!1,onChange:s}={}){var o;const[a,c]=M.useState(null),[l,u]=M.useState(()=>({isIntersecting:r,entry:void 0})),d=M.useRef();d.current=s;const h=((o=l.entry)==null?void 0:o.isIntersecting)&&i;M.useEffect(()=>{if(!a||!("IntersectionObserver"in window)||h)return;const p=new IntersectionObserver(x=>{const y=Array.isArray(p.thresholds)?p.thresholds:[p.thresholds];x.forEach(E=>{const w=E.isIntersecting&&y.some(S=>E.intersectionRatio>=S);u({isIntersecting:w,entry:E}),d.current&&d.current(w,E)})},{threshold:e,root:t,rootMargin:n});return p.observe(a),()=>{p.disconnect()}},[a,JSON.stringify(e),t,n,h,i]);const f=M.useRef(null);M.useEffect(()=>{var p;!a&&(p=l.entry)!=null&&p.target&&!i&&!h&&f.current!==l.entry.target&&(f.current=l.entry.target,u({isIntersecting:r,entry:void 0}))},[a,l.entry,i,h,r]);const g=[c,!!l.isIntersecting,l.entry];return g.ref=g[0],g.isIntersecting=g[1],g.entry=g[2],g}const Jl=D.forwardRef(function({onTrackClick:e,onClick:t,onSubscriptionStatusChanged:n,trackRef:i,manageSubscription:r,...s},o){const a=Rw(i),c=D.useRef(null);D.useImperativeHandle(o,()=>c.current);const l=eB({root:c.current}),[u]=$L(l,3e3);D.useEffect(()=>{r&&a.publication instanceof ll&&(u==null?void 0:u.isIntersecting)===!1&&(l==null?void 0:l.isIntersecting)===!1&&a.publication.setSubscribed(!1)},[u,a,r]),D.useEffect(()=>{r&&a.publication instanceof ll&&(l==null?void 0:l.isIntersecting)===!0&&a.publication.setSubscribed(!0)},[l,a,r]);const{elementProps:d,publication:h,isSubscribed:f}=Ow(a,{element:c,props:s});D.useEffect(()=>{n==null||n(!!f)},[f,n]);const g=p=>{t==null||t(p),e==null||e({participant:a==null?void 0:a.participant,track:h})};return D.createElement("video",{ref:c,...d,muted:!0,onClick:g})}),Dw=D.forwardRef(function({trackRef:e,onSubscriptionStatusChanged:t,volume:n,...i},r){const s=Rw(e),o=D.useRef(null);D.useImperativeHandle(r,()=>o.current);const{elementProps:a,isSubscribed:c,track:l,publication:u}=Ow(s,{element:o,props:i});return D.useEffect(()=>{t==null||t(!!c)},[c,t]),D.useEffect(()=>{l===void 0||n===void 0||(l instanceof mk?l.setVolume(n):kr.warn("Volume can only be set on remote audio tracks."))},[n,l]),D.useEffect(()=>{u===void 0||i.muted===void 0||(u instanceof ll?u.setEnabled(!i.muted):kr.warn("Can only call setEnabled on remote track publications."))},[i.muted,u,l]),D.createElement("audio",{ref:o,...a})});function tB({room:e,volume:t,muted:n}){const i=Pw([z.Source.Microphone,z.Source.ScreenShareAudio,z.Source.Unknown],{updateOnlyOn:[],onlySubscribed:!0,room:e}).filter(r=>!r.participant.isLocal&&r.publication.kind===z.Kind.Audio);return D.createElement("div",{style:{display:"none"}},i.map(r=>D.createElement(Dw,{key:wL(r),trackRef:r,volume:t,muted:n})))}const nB=e=>{const t=[];for(let n=0;n<e;n++)t.push([n,e-1-n]);return t},Vy=e=>[[Math.floor(e/2)],[-1]],iB=(e,t,n)=>{const[i,r]=M.useState(0),[s,o]=M.useState([[]]);M.useEffect(()=>{if(e==="thinking")o(Vy(t));else if(e==="connecting"||e==="initializing"){const c=[...nB(t)];o(c)}else o(e==="listening"?Vy(t):e===void 0||e==="speaking"?[new Array(t).fill(0).map((c,l)=>l)]:[[]]);r(0)},[e,t]);const a=M.useRef(null);return M.useEffect(()=>{let c=performance.now();const l=u=>{u-c>=n&&(r(d=>d+1),c=u),a.current=requestAnimationFrame(l)};return a.current=requestAnimationFrame(l),()=>{a.current!==null&&cancelAnimationFrame(a.current)}},[n,t,e,s.length]),s[i%s.length]},rB=new Map([["connecting",2e3],["initializing",2e3],["listening",500],["thinking",150]]),sB=(e,t)=>{if(e===void 0)return 1e3;let n=rB.get(e);if(n)switch(e){case"connecting":n/=t;break}return n},Lw=D.forwardRef(function({state:e,options:t,barCount:n=15,trackRef:i,track:r,children:s,...o},a){const c=Mw(o,{className:"lk-audio-bar-visualizer"});let l=Aw();(i||r)&&(l=i||r);const u=WL(l,{bands:n,loPass:100,hiPass:200}),d=(t==null?void 0:t.minHeight)??20,h=(t==null?void 0:t.maxHeight)??100,f=iB(e,n,sB(e,n)??100);return D.createElement("div",{ref:a,...c,"data-lk-va-state":e},u.map((g,p)=>s?UL(s,{"data-lk-highlighted":f.includes(p),"data-lk-bar-index":p,className:"lk-audio-bar",style:{height:`${Math.min(h,Math.max(d,g*100+5))}%`}}):D.createElement("span",{key:p,"data-lk-highlighted":f.includes(p),"data-lk-bar-index":p,className:`lk-audio-bar ${f.includes(p)&&"lk-highlighted"}`,style:{height:`${Math.min(h,Math.max(d,g*100+5))}%`}})))});function oB(e){const[t,n]=M.useState(()=>e.getLocalParticipant()),[i,r]=M.useState(()=>e.getMicrophoneTrack());return M.useEffect(()=>{const s=()=>{const a=e.getLocalParticipant(),c=e.getMicrophoneTrack();console.log("🎤 useVoxketLocalParticipant: Updating state:",{hasParticipant:!!a,hasMicTrack:!!c,isMicEnabled:e.isMicrophoneEnabled,trackPublications:a?a.trackPublications.size:0}),n(a),r(c)};s(),e.on("connection.connected",s),e.on("connection.disconnected",s),e.on("track.muted",s),e.on("track.unmuted",s);const o=e.getRoom();if(o){const a=()=>{console.log("🎤 Track published, updating participant state"),s()},c=()=>{console.log("🎤 Track unpublished, updating participant state"),s()};return o.on("localTrackPublished",a),o.on("localTrackUnpublished",c),()=>{e.off("connection.connected",s),e.off("connection.disconnected",s),e.off("track.muted",s),e.off("track.unmuted",s),o.off("localTrackPublished",a),o.off("localTrackUnpublished",c)}}else return()=>{e.off("connection.connected",s),e.off("connection.disconnected",s),e.off("track.muted",s),e.off("track.unmuted",s)}},[e]),{localParticipant:t,microphoneTrack:i}}function Vc(e,t,n){const[i,r]=M.useState(!1),[s,o]=M.useState(!1);return M.useEffect(()=>{const c=()=>{let l=!1;switch(t){case"microphone":l=e.isMicrophoneEnabled;break;case"camera":l=e.isCameraEnabled;break;case"screenShare":l=e.isScreenShareEnabled;break}console.log(`🎬 useVoxketTrackToggle: ${t} enabled state updated:`,{oldEnabled:i,newEnabled:l,changed:i!==l}),r(l)};return c(),e.on("track.muted",c),e.on("track.unmuted",c),e.on("connection.connected",c),()=>{e.off("track.muted",c),e.off("track.unmuted",c),e.off("connection.connected",c)}},[e,t]),{enabled:i,pending:s,toggle:async c=>{try{o(!0);const l=c!==void 0?c:!i;switch(console.log(`🎬 useVoxketTrackToggle: ${t} toggle called`,{currentEnabled:i,targetEnabled:l,forceEnabled:c}),t){case"microphone":await e.toggleMicrophone(l);break;case"camera":await e.toggleCamera(l);break;case"screenShare":l?(console.log("🎬 useVoxketTrackToggle: Starting screen share"),await e.startScreenShare()):(console.log("🎬 useVoxketTrackToggle: Stopping screen share"),await e.stopScreenShare());break}console.log(`🎬 useVoxketTrackToggle: ${t} toggle completed`)}catch(l){console.error(`🎬 useVoxketTrackToggle: ${t} toggle failed:`,l)}finally{o(!1)}}}}function aB(e){const[t,n]=M.useState(()=>e.getRoom()),[i,r]=M.useState(()=>e.getConnectionState());return M.useEffect(()=>{const s=()=>{n(e.getRoom()),r(e.getConnectionState())};return e.on("connection.connected",s),e.on("connection.disconnected",s),e.on("connection.connecting",s),()=>{e.off("connection.connected",s),e.off("connection.disconnected",s),e.off("connection.connecting",s)}},[e]),t}function Zp(e){const[t,n]=M.useState(()=>e.getIsAgentConnected()),[i,r]=M.useState(()=>e.getCurrentSession()),[s,o]=M.useState(()=>e.getCurrentAgentInfo()),[a,c]=M.useState(()=>e.getAgentState()),[l,u]=M.useState(()=>e.getAgentAudioTrack()),[d,h]=M.useState(()=>e.getAgentVideoTrack());return M.useEffect(()=>{const f=()=>{const S=e.getIsAgentConnected(),v=e.getCurrentSession(),k=e.getCurrentAgentInfo(),_=e.getAgentState(),T=e.getAgentAudioTrack(),I=e.getAgentVideoTrack();console.log("🤖 useVoxketVoiceAssistant: Updating state:",{isAgentConnected:S,hasSession:!!v,sessionId:v==null?void 0:v.id,sessionState:v==null?void 0:v.state,hasAgentInfo:!!k,agentState:_,hasAudioTrack:!!T,hasVideoTrack:!!I}),n(S),r(v),o(k),c(_),u(T),h(I)};f();const g=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent connected event"),f()},p=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent disconnected event"),f()},x=()=>{console.log("🤖 useVoxketVoiceAssistant: Session changed event"),f()},y=()=>{console.log("🤖 useVoxketVoiceAssistant: Connection changed event"),f()},E=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent state changed event"),f()},w=()=>{console.log("🎵 useVoxketVoiceAssistant: Track subscribed event - updating audio/video tracks"),f()};return e.on("agent.connected",g),e.on("agent.speaking",g),e.on("agent.thinking",g),e.on("agent.state.changed",E),e.on("connection.disconnected",p),e.on("session.created",x),e.on("session.ended",x),e.on("session.state.changed",x),e.on("connection.connected",y),e.on("media.track.subscribed",w),e.on("media.track.unsubscribed",w),()=>{e.off("agent.connected",g),e.off("agent.speaking",g),e.off("agent.thinking",g),e.off("agent.state.changed",E),e.off("connection.disconnected",p),e.off("session.created",x),e.off("session.ended",x),e.off("session.state.changed",x),e.off("connection.connected",y),e.off("media.track.subscribed",w),e.off("media.track.unsubscribed",w)}},[e]),{agent:{isActive:t,info:s},session:i,state:a,audioTrack:l,videoTrack:d}}function cB(e){const[t,n]=M.useState(()=>e.getVideoTrackRefs()),[i,r]=M.useState(()=>e.getCameraTrackRefs()),[s,o]=M.useState(()=>e.getScreenShareTrackRefs());return M.useEffect(()=>{const a=()=>{const l=e.getVideoTrackRefs(),u=e.getCameraTrackRefs(),d=e.getScreenShareTrackRefs();console.log("📹 useVoxketVideoTracks: Updating tracks:",{videoCount:l.length,cameraCount:u.length,screenShareCount:d.length}),n(l),r(u),o(d)};a(),e.on("connection.connected",a),e.on("connection.disconnected",a),e.on("track.muted",a),e.on("track.unmuted",a),e.on("participant.joined",a),e.on("participant.left",a);const c=e.getRoom();if(c){const l=()=>{console.log("📹 Track event, updating video tracks"),a()};return c.on("localTrackPublished",l),c.on("localTrackUnpublished",l),c.on("trackPublished",l),c.on("trackUnpublished",l),c.on("trackSubscribed",l),c.on("trackUnsubscribed",l),()=>{e.off("connection.connected",a),e.off("connection.disconnected",a),e.off("track.muted",a),e.off("track.unmuted",a),e.off("participant.joined",a),e.off("participant.left",a),c.off("localTrackPublished",l),c.off("localTrackUnpublished",l),c.off("trackPublished",l),c.off("trackUnpublished",l),c.off("trackSubscribed",l),c.off("trackUnsubscribed",l)}}else return()=>{e.off("connection.connected",a),e.off("connection.disconnected",a),e.off("track.muted",a),e.off("track.unmuted",a),e.off("participant.joined",a),e.off("participant.left",a)}},[e]),{videoTrackRefs:t,cameraTrackRefs:i,screenShareTrackRefs:s}}const $p="-",lB=e=>{const t=dB(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:i}=e;return{getClassGroupId:o=>{const a=o.split($p);return a[0]===""&&a.length!==1&&a.shift(),Bw(a,t)||uB(o)},getConflictingClassGroupIds:(o,a)=>{const c=n[o]||[];return a&&i[o]?[...c,...i[o]]:c}}},Bw=(e,t)=>{var o;if(e.length===0)return t.classGroupId;const n=e[0],i=t.nextPart.get(n),r=i?Bw(e.slice(1),i):void 0;if(r)return r;if(t.validators.length===0)return;const s=e.join($p);return(o=t.validators.find(({validator:a})=>a(s)))==null?void 0:o.classGroupId},zy=/^\[(.+)\]$/,uB=e=>{if(zy.test(e)){const t=zy.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},dB=e=>{const{theme:t,classGroups:n}=e,i={nextPart:new Map,validators:[]};for(const r in n)sf(n[r],i,r,t);return i},sf=(e,t,n,i)=>{e.forEach(r=>{if(typeof r=="string"){const s=r===""?t:Gy(t,r);s.classGroupId=n;return}if(typeof r=="function"){if(hB(r)){sf(r(i),t,n,i);return}t.validators.push({validator:r,classGroupId:n});return}Object.entries(r).forEach(([s,o])=>{sf(o,Gy(t,s),n,i)})})},Gy=(e,t)=>{let n=e;return t.split($p).forEach(i=>{n.nextPart.has(i)||n.nextPart.set(i,{nextPart:new Map,validators:[]}),n=n.nextPart.get(i)}),n},hB=e=>e.isThemeGetter,fB=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,i=new Map;const r=(s,o)=>{n.set(s,o),t++,t>e&&(t=0,i=n,n=new Map)};return{get(s){let o=n.get(s);if(o!==void 0)return o;if((o=i.get(s))!==void 0)return r(s,o),o},set(s,o){n.has(s)?n.set(s,o):r(s,o)}}},of="!",af=":",pB=af.length,mB=e=>{const{prefix:t,experimentalParseClassName:n}=e;let i=r=>{const s=[];let o=0,a=0,c=0,l;for(let g=0;g<r.length;g++){let p=r[g];if(o===0&&a===0){if(p===af){s.push(r.slice(c,g)),c=g+pB;continue}if(p==="/"){l=g;continue}}p==="["?o++:p==="]"?o--:p==="("?a++:p===")"&&a--}const u=s.length===0?r:r.substring(c),d=gB(u),h=d!==u,f=l&&l>c?l-c:void 0;return{modifiers:s,hasImportantModifier:h,baseClassName:d,maybePostfixModifierPosition:f}};if(t){const r=t+af,s=i;i=o=>o.startsWith(r)?s(o.substring(r.length)):{isExternal:!0,modifiers:[],hasImportantModifier:!1,baseClassName:o,maybePostfixModifierPosition:void 0}}if(n){const r=i;i=s=>n({className:s,parseClassName:r})}return i},gB=e=>e.endsWith(of)?e.substring(0,e.length-1):e.startsWith(of)?e.substring(1):e,bB=e=>{const t=Object.fromEntries(e.orderSensitiveModifiers.map(i=>[i,!0]));return i=>{if(i.length<=1)return i;const r=[];let s=[];return i.forEach(o=>{o[0]==="["||t[o]?(r.push(...s.sort(),o),s=[]):s.push(o)}),r.push(...s.sort()),r}},yB=e=>({cache:fB(e.cacheSize),parseClassName:mB(e),sortModifiers:bB(e),...lB(e)}),vB=/\s+/,xB=(e,t)=>{const{parseClassName:n,getClassGroupId:i,getConflictingClassGroupIds:r,sortModifiers:s}=t,o=[],a=e.trim().split(vB);let c="";for(let l=a.length-1;l>=0;l-=1){const u=a[l],{isExternal:d,modifiers:h,hasImportantModifier:f,baseClassName:g,maybePostfixModifierPosition:p}=n(u);if(d){c=u+(c.length>0?" "+c:c);continue}let x=!!p,y=i(x?g.substring(0,p):g);if(!y){if(!x){c=u+(c.length>0?" "+c:c);continue}if(y=i(g),!y){c=u+(c.length>0?" "+c:c);continue}x=!1}const E=s(h).join(":"),w=f?E+of:E,S=w+y;if(o.includes(S))continue;o.push(S);const v=r(y,x);for(let k=0;k<v.length;++k){const _=v[k];o.push(w+_)}c=u+(c.length>0?" "+c:c)}return c};function SB(){let e=0,t,n,i="";for(;e<arguments.length;)(t=arguments[e++])&&(n=Fw(t))&&(i&&(i+=" "),i+=n);return i}const Fw=e=>{if(typeof e=="string")return e;let t,n="";for(let i=0;i<e.length;i++)e[i]&&(t=Fw(e[i]))&&(n&&(n+=" "),n+=t);return n};function kB(e,...t){let n,i,r,s=o;function o(c){const l=t.reduce((u,d)=>d(u),e());return n=yB(l),i=n.cache.get,r=n.cache.set,s=a,a(c)}function a(c){const l=i(c);if(l)return l;const u=xB(c,n);return r(c,u),u}return function(){return s(SB.apply(null,arguments))}}const Jt=e=>{const t=n=>n[e]||[];return t.isThemeGetter=!0,t},Uw=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,jw=/^\((?:(\w[\w-]*):)?(.+)\)$/i,EB=/^\d+\/\d+$/,wB=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,CB=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,TB=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,AB=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,RB=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,fs=e=>EB.test(e),qe=e=>!!e&&!Number.isNaN(Number(e)),or=e=>!!e&&Number.isInteger(Number(e)),pd=e=>e.endsWith("%")&&qe(e.slice(0,-1)),Pi=e=>wB.test(e),_B=()=>!0,IB=e=>CB.test(e)&&!TB.test(e),Vw=()=>!1,NB=e=>AB.test(e),MB=e=>RB.test(e),PB=e=>!Se(e)&&!ke(e),OB=e=>co(e,Hw,Vw),Se=e=>Uw.test(e),Dr=e=>co(e,Kw,IB),md=e=>co(e,UB,qe),Hy=e=>co(e,zw,Vw),DB=e=>co(e,Gw,MB),nc=e=>co(e,Ww,NB),ke=e=>jw.test(e),Ro=e=>lo(e,Kw),LB=e=>lo(e,jB),Ky=e=>lo(e,zw),BB=e=>lo(e,Hw),FB=e=>lo(e,Gw),ic=e=>lo(e,Ww,!0),co=(e,t,n)=>{const i=Uw.exec(e);return i?i[1]?t(i[1]):n(i[2]):!1},lo=(e,t,n=!1)=>{const i=jw.exec(e);return i?i[1]?t(i[1]):n:!1},zw=e=>e==="position"||e==="percentage",Gw=e=>e==="image"||e==="url",Hw=e=>e==="length"||e==="size"||e==="bg-size",Kw=e=>e==="length",UB=e=>e==="number",jB=e=>e==="family-name",Ww=e=>e==="shadow",VB=()=>{const e=Jt("color"),t=Jt("font"),n=Jt("text"),i=Jt("font-weight"),r=Jt("tracking"),s=Jt("leading"),o=Jt("breakpoint"),a=Jt("container"),c=Jt("spacing"),l=Jt("radius"),u=Jt("shadow"),d=Jt("inset-shadow"),h=Jt("text-shadow"),f=Jt("drop-shadow"),g=Jt("blur"),p=Jt("perspective"),x=Jt("aspect"),y=Jt("ease"),E=Jt("animate"),w=()=>["auto","avoid","all","avoid-page","page","left","right","column"],S=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],v=()=>[...S(),ke,Se],k=()=>["auto","hidden","clip","visible","scroll"],_=()=>["auto","contain","none"],T=()=>[ke,Se,c],I=()=>[fs,"full","auto",...T()],b=()=>[or,"none","subgrid",ke,Se],A=()=>["auto",{span:["full",or,ke,Se]},or,ke,Se],P=()=>[or,"auto",ke,Se],B=()=>["auto","min","max","fr",ke,Se],L=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],V=()=>["start","end","center","stretch","center-safe","end-safe"],J=()=>["auto",...T()],re=()=>[fs,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...T()],G=()=>[e,ke,Se],Q=()=>[...S(),Ky,Hy,{position:[ke,Se]}],C=()=>["no-repeat",{repeat:["","x","y","space","round"]}],K=()=>["auto","cover","contain",BB,OB,{size:[ke,Se]}],X=()=>[pd,Ro,Dr],R=()=>["","none","full",l,ke,Se],ae=()=>["",qe,Ro,Dr],he=()=>["solid","dashed","dotted","double"],ce=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ee=()=>[qe,pd,Ky,Hy],te=()=>["","none",g,ke,Se],ue=()=>["none",qe,ke,Se],me=()=>["none",qe,ke,Se],Me=()=>[qe,ke,Se],ne=()=>[fs,"full",...T()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Pi],breakpoint:[Pi],color:[_B],container:[Pi],"drop-shadow":[Pi],ease:["in","out","in-out"],font:[PB],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Pi],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Pi],shadow:[Pi],spacing:["px",qe],text:[Pi],"text-shadow":[Pi],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",fs,Se,ke,x]}],container:["container"],columns:[{columns:[qe,Se,ke,a]}],"break-after":[{"break-after":w()}],"break-before":[{"break-before":w()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:v()}],overflow:[{overflow:k()}],"overflow-x":[{"overflow-x":k()}],"overflow-y":[{"overflow-y":k()}],overscroll:[{overscroll:_()}],"overscroll-x":[{"overscroll-x":_()}],"overscroll-y":[{"overscroll-y":_()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:I()}],"inset-x":[{"inset-x":I()}],"inset-y":[{"inset-y":I()}],start:[{start:I()}],end:[{end:I()}],top:[{top:I()}],right:[{right:I()}],bottom:[{bottom:I()}],left:[{left:I()}],visibility:["visible","invisible","collapse"],z:[{z:[or,"auto",ke,Se]}],basis:[{basis:[fs,"full","auto",a,...T()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[qe,fs,"auto","initial","none",Se]}],grow:[{grow:["",qe,ke,Se]}],shrink:[{shrink:["",qe,ke,Se]}],order:[{order:[or,"first","last","none",ke,Se]}],"grid-cols":[{"grid-cols":b()}],"col-start-end":[{col:A()}],"col-start":[{"col-start":P()}],"col-end":[{"col-end":P()}],"grid-rows":[{"grid-rows":b()}],"row-start-end":[{row:A()}],"row-start":[{"row-start":P()}],"row-end":[{"row-end":P()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":B()}],"auto-rows":[{"auto-rows":B()}],gap:[{gap:T()}],"gap-x":[{"gap-x":T()}],"gap-y":[{"gap-y":T()}],"justify-content":[{justify:[...L(),"normal"]}],"justify-items":[{"justify-items":[...V(),"normal"]}],"justify-self":[{"justify-self":["auto",...V()]}],"align-content":[{content:["normal",...L()]}],"align-items":[{items:[...V(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...V(),{baseline:["","last"]}]}],"place-content":[{"place-content":L()}],"place-items":[{"place-items":[...V(),"baseline"]}],"place-self":[{"place-self":["auto",...V()]}],p:[{p:T()}],px:[{px:T()}],py:[{py:T()}],ps:[{ps:T()}],pe:[{pe:T()}],pt:[{pt:T()}],pr:[{pr:T()}],pb:[{pb:T()}],pl:[{pl:T()}],m:[{m:J()}],mx:[{mx:J()}],my:[{my:J()}],ms:[{ms:J()}],me:[{me:J()}],mt:[{mt:J()}],mr:[{mr:J()}],mb:[{mb:J()}],ml:[{ml:J()}],"space-x":[{"space-x":T()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":T()}],"space-y-reverse":["space-y-reverse"],size:[{size:re()}],w:[{w:[a,"screen",...re()]}],"min-w":[{"min-w":[a,"screen","none",...re()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[o]},...re()]}],h:[{h:["screen","lh",...re()]}],"min-h":[{"min-h":["screen","lh","none",...re()]}],"max-h":[{"max-h":["screen","lh",...re()]}],"font-size":[{text:["base",n,Ro,Dr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[i,ke,md]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",pd,Se]}],"font-family":[{font:[LB,Se,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,ke,Se]}],"line-clamp":[{"line-clamp":[qe,"none",ke,md]}],leading:[{leading:[s,...T()]}],"list-image":[{"list-image":["none",ke,Se]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",ke,Se]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:G()}],"text-color":[{text:G()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[qe,"from-font","auto",ke,Dr]}],"text-decoration-color":[{decoration:G()}],"underline-offset":[{"underline-offset":[qe,"auto",ke,Se]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:T()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",ke,Se]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",ke,Se]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:Q()}],"bg-repeat":[{bg:C()}],"bg-size":[{bg:K()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},or,ke,Se],radial:["",ke,Se],conic:[or,ke,Se]},FB,DB]}],"bg-color":[{bg:G()}],"gradient-from-pos":[{from:X()}],"gradient-via-pos":[{via:X()}],"gradient-to-pos":[{to:X()}],"gradient-from":[{from:G()}],"gradient-via":[{via:G()}],"gradient-to":[{to:G()}],rounded:[{rounded:R()}],"rounded-s":[{"rounded-s":R()}],"rounded-e":[{"rounded-e":R()}],"rounded-t":[{"rounded-t":R()}],"rounded-r":[{"rounded-r":R()}],"rounded-b":[{"rounded-b":R()}],"rounded-l":[{"rounded-l":R()}],"rounded-ss":[{"rounded-ss":R()}],"rounded-se":[{"rounded-se":R()}],"rounded-ee":[{"rounded-ee":R()}],"rounded-es":[{"rounded-es":R()}],"rounded-tl":[{"rounded-tl":R()}],"rounded-tr":[{"rounded-tr":R()}],"rounded-br":[{"rounded-br":R()}],"rounded-bl":[{"rounded-bl":R()}],"border-w":[{border:ae()}],"border-w-x":[{"border-x":ae()}],"border-w-y":[{"border-y":ae()}],"border-w-s":[{"border-s":ae()}],"border-w-e":[{"border-e":ae()}],"border-w-t":[{"border-t":ae()}],"border-w-r":[{"border-r":ae()}],"border-w-b":[{"border-b":ae()}],"border-w-l":[{"border-l":ae()}],"divide-x":[{"divide-x":ae()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":ae()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:G()}],"border-color-x":[{"border-x":G()}],"border-color-y":[{"border-y":G()}],"border-color-s":[{"border-s":G()}],"border-color-e":[{"border-e":G()}],"border-color-t":[{"border-t":G()}],"border-color-r":[{"border-r":G()}],"border-color-b":[{"border-b":G()}],"border-color-l":[{"border-l":G()}],"divide-color":[{divide:G()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[qe,ke,Se]}],"outline-w":[{outline:["",qe,Ro,Dr]}],"outline-color":[{outline:G()}],shadow:[{shadow:["","none",u,ic,nc]}],"shadow-color":[{shadow:G()}],"inset-shadow":[{"inset-shadow":["none",d,ic,nc]}],"inset-shadow-color":[{"inset-shadow":G()}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:G()}],"ring-offset-w":[{"ring-offset":[qe,Dr]}],"ring-offset-color":[{"ring-offset":G()}],"inset-ring-w":[{"inset-ring":ae()}],"inset-ring-color":[{"inset-ring":G()}],"text-shadow":[{"text-shadow":["none",h,ic,nc]}],"text-shadow-color":[{"text-shadow":G()}],opacity:[{opacity:[qe,ke,Se]}],"mix-blend":[{"mix-blend":[...ce(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ce()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[qe]}],"mask-image-linear-from-pos":[{"mask-linear-from":ee()}],"mask-image-linear-to-pos":[{"mask-linear-to":ee()}],"mask-image-linear-from-color":[{"mask-linear-from":G()}],"mask-image-linear-to-color":[{"mask-linear-to":G()}],"mask-image-t-from-pos":[{"mask-t-from":ee()}],"mask-image-t-to-pos":[{"mask-t-to":ee()}],"mask-image-t-from-color":[{"mask-t-from":G()}],"mask-image-t-to-color":[{"mask-t-to":G()}],"mask-image-r-from-pos":[{"mask-r-from":ee()}],"mask-image-r-to-pos":[{"mask-r-to":ee()}],"mask-image-r-from-color":[{"mask-r-from":G()}],"mask-image-r-to-color":[{"mask-r-to":G()}],"mask-image-b-from-pos":[{"mask-b-from":ee()}],"mask-image-b-to-pos":[{"mask-b-to":ee()}],"mask-image-b-from-color":[{"mask-b-from":G()}],"mask-image-b-to-color":[{"mask-b-to":G()}],"mask-image-l-from-pos":[{"mask-l-from":ee()}],"mask-image-l-to-pos":[{"mask-l-to":ee()}],"mask-image-l-from-color":[{"mask-l-from":G()}],"mask-image-l-to-color":[{"mask-l-to":G()}],"mask-image-x-from-pos":[{"mask-x-from":ee()}],"mask-image-x-to-pos":[{"mask-x-to":ee()}],"mask-image-x-from-color":[{"mask-x-from":G()}],"mask-image-x-to-color":[{"mask-x-to":G()}],"mask-image-y-from-pos":[{"mask-y-from":ee()}],"mask-image-y-to-pos":[{"mask-y-to":ee()}],"mask-image-y-from-color":[{"mask-y-from":G()}],"mask-image-y-to-color":[{"mask-y-to":G()}],"mask-image-radial":[{"mask-radial":[ke,Se]}],"mask-image-radial-from-pos":[{"mask-radial-from":ee()}],"mask-image-radial-to-pos":[{"mask-radial-to":ee()}],"mask-image-radial-from-color":[{"mask-radial-from":G()}],"mask-image-radial-to-color":[{"mask-radial-to":G()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":S()}],"mask-image-conic-pos":[{"mask-conic":[qe]}],"mask-image-conic-from-pos":[{"mask-conic-from":ee()}],"mask-image-conic-to-pos":[{"mask-conic-to":ee()}],"mask-image-conic-from-color":[{"mask-conic-from":G()}],"mask-image-conic-to-color":[{"mask-conic-to":G()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:Q()}],"mask-repeat":[{mask:C()}],"mask-size":[{mask:K()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",ke,Se]}],filter:[{filter:["","none",ke,Se]}],blur:[{blur:te()}],brightness:[{brightness:[qe,ke,Se]}],contrast:[{contrast:[qe,ke,Se]}],"drop-shadow":[{"drop-shadow":["","none",f,ic,nc]}],"drop-shadow-color":[{"drop-shadow":G()}],grayscale:[{grayscale:["",qe,ke,Se]}],"hue-rotate":[{"hue-rotate":[qe,ke,Se]}],invert:[{invert:["",qe,ke,Se]}],saturate:[{saturate:[qe,ke,Se]}],sepia:[{sepia:["",qe,ke,Se]}],"backdrop-filter":[{"backdrop-filter":["","none",ke,Se]}],"backdrop-blur":[{"backdrop-blur":te()}],"backdrop-brightness":[{"backdrop-brightness":[qe,ke,Se]}],"backdrop-contrast":[{"backdrop-contrast":[qe,ke,Se]}],"backdrop-grayscale":[{"backdrop-grayscale":["",qe,ke,Se]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[qe,ke,Se]}],"backdrop-invert":[{"backdrop-invert":["",qe,ke,Se]}],"backdrop-opacity":[{"backdrop-opacity":[qe,ke,Se]}],"backdrop-saturate":[{"backdrop-saturate":[qe,ke,Se]}],"backdrop-sepia":[{"backdrop-sepia":["",qe,ke,Se]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":T()}],"border-spacing-x":[{"border-spacing-x":T()}],"border-spacing-y":[{"border-spacing-y":T()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",ke,Se]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[qe,"initial",ke,Se]}],ease:[{ease:["linear","initial",y,ke,Se]}],delay:[{delay:[qe,ke,Se]}],animate:[{animate:["none",E,ke,Se]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,ke,Se]}],"perspective-origin":[{"perspective-origin":v()}],rotate:[{rotate:ue()}],"rotate-x":[{"rotate-x":ue()}],"rotate-y":[{"rotate-y":ue()}],"rotate-z":[{"rotate-z":ue()}],scale:[{scale:me()}],"scale-x":[{"scale-x":me()}],"scale-y":[{"scale-y":me()}],"scale-z":[{"scale-z":me()}],"scale-3d":["scale-3d"],skew:[{skew:Me()}],"skew-x":[{"skew-x":Me()}],"skew-y":[{"skew-y":Me()}],transform:[{transform:[ke,Se,"","none","gpu","cpu"]}],"transform-origin":[{origin:v()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ne()}],"translate-x":[{"translate-x":ne()}],"translate-y":[{"translate-y":ne()}],"translate-z":[{"translate-z":ne()}],"translate-none":["translate-none"],accent:[{accent:G()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:G()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",ke,Se]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":T()}],"scroll-mx":[{"scroll-mx":T()}],"scroll-my":[{"scroll-my":T()}],"scroll-ms":[{"scroll-ms":T()}],"scroll-me":[{"scroll-me":T()}],"scroll-mt":[{"scroll-mt":T()}],"scroll-mr":[{"scroll-mr":T()}],"scroll-mb":[{"scroll-mb":T()}],"scroll-ml":[{"scroll-ml":T()}],"scroll-p":[{"scroll-p":T()}],"scroll-px":[{"scroll-px":T()}],"scroll-py":[{"scroll-py":T()}],"scroll-ps":[{"scroll-ps":T()}],"scroll-pe":[{"scroll-pe":T()}],"scroll-pt":[{"scroll-pt":T()}],"scroll-pr":[{"scroll-pr":T()}],"scroll-pb":[{"scroll-pb":T()}],"scroll-pl":[{"scroll-pl":T()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",ke,Se]}],fill:[{fill:["none",...G()]}],"stroke-w":[{stroke:[qe,Ro,Dr,md]}],stroke:[{stroke:["none",...G()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},zB=kB(VB);function at(...e){return zB(jf.clsx(e))}function Xl(e){var r;if(!e)return{sessionSettings:{},capabilities:{},modality:"voice"};const t={session_timer:((r=e.session_settings)==null?void 0:r.session_timer)||null},n=e.capabilities||{},i=e.modality||"voice";return{sessionSettings:t,capabilities:n,modality:i}}function GB(e,t){return e.capabilities[t]===!0}function Zl(e){return e.sessionSettings.session_timer||null}function qw(e){const t=e.capabilities;return{userVideoEnabled:t.user_video_enabled!==!1,agentAvatarEnabled:t.agent_avatar_enabled!==!1,screenshareEnabled:t.screenshare_session_enabled!==!1}}function Qw(e){const t=e.capabilities;return{suggestedReplyEnabled:t.suggested_reply_enabled!==!1,attachmentsEnabled:t.support_in_chat_attachments!==!1}}function Yw(e){return{...e.capabilities}}function Jw(e){const t=Math.floor(e/60),n=e%60;return`${t}:${n.toString().padStart(2,"0")}`}const Xw=M.forwardRef(({state:e,audioTrack:t,className:n,theme:i="vox"},r)=>{var l,u,d,h,f;const s=M.useRef(null),[o,a]=M.useState(!1);M.useEffect(()=>{s.current&&(console.log("🔊 AgentTile: Audio element created:",{autoplay:s.current.autoplay,muted:s.current.muted,volume:s.current.volume,readyState:s.current.readyState,paused:s.current.paused}),a(!0))},[t]),M.useEffect(()=>{const g=s.current;if(!g)return;const p=()=>console.log("▶️ AgentTile: Audio started playing"),x=()=>console.log("⏸️ AgentTile: Audio paused"),y=()=>console.log("⏹️ AgentTile: Audio ended"),E=v=>console.error("❌ AgentTile: Audio error:",v),w=()=>console.log("⏳ AgentTile: Audio load started"),S=()=>console.log("✅ AgentTile: Audio can play");return g.addEventListener("play",p),g.addEventListener("pause",x),g.addEventListener("ended",y),g.addEventListener("error",E),g.addEventListener("loadstart",w),g.addEventListener("canplay",S),()=>{g.removeEventListener("play",p),g.removeEventListener("pause",x),g.removeEventListener("ended",y),g.removeEventListener("error",E),g.removeEventListener("loadstart",w),g.removeEventListener("canplay",S)}},[o]),console.log("🎤 AgentTile render:",{state:e,hasAudioTrack:!!t,trackSource:t==null?void 0:t.source,participantId:(l=t==null?void 0:t.participant)==null?void 0:l.identity,publicationMuted:(u=t==null?void 0:t.publication)==null?void 0:u.isMuted,audioElementReady:o,trackMediaStreamTrack:(f=(h=(d=t==null?void 0:t.publication)==null?void 0:d.track)==null?void 0:h.mediaStreamTrack)==null?void 0:f.readyState});const c=M.useMemo(()=>i==="light"?{base:"bg-black/90",highlighted:"bg-black",muted:"bg-black/30"}:{base:"bg-white/90",highlighted:"bg-white",muted:"bg-white/30"},[i]);return m.jsxs("div",{ref:r,className:at("",n),children:[t&&m.jsxs(m.Fragment,{children:[m.jsx(Dw,{ref:s,trackRef:t,volume:1}),m.jsx(Lw,{barCount:5,state:e,options:{minHeight:5},trackRef:t,className:at("flex aspect-video w-40 items-center justify-center gap-1.5"),children:m.jsx("span",{className:at([`${c.base} min-h-2 w-2 rounded-full`,"origin-center transition-colors duration-250 ease-linear",`data-[lk-highlighted=true]:${c.highlighted}`,`data-[lk-muted=true]:${c.muted}`])})})]}),!t&&m.jsx("div",{className:at("flex aspect-video w-40 items-center justify-center"),children:m.jsx("div",{className:"flex flex-col items-center justify-center",children:m.jsx("div",{className:"flex gap-1.5",children:Array.from({length:5}).map((g,p)=>m.jsx("span",{className:at([`${c.base} min-h-2 w-2 rounded-full`,"origin-center transition-colors duration-250 ease-linear",e==="speaking"&&`animate-pulse ${c.highlighted}`,e==="thinking"&&`animate-pulse ${c.muted}`])},p))})})})]})});Xw.displayName="AgentTile";const HB=({videoTrack:e,className:t,ref:n})=>{var i,r;return!e||!e.publication||!e.participant?m.jsx("div",{ref:n,className:at(t),children:m.jsx("div",{className:"w-full h-full bg-gray-200 rounded-md flex items-center justify-center",children:m.jsx("span",{className:"text-gray-500",children:"No video available"})})}):m.jsx("div",{ref:n,className:at(t),children:m.jsx(Jl,{trackRef:e,width:((i=e.publication.dimensions)==null?void 0:i.width)??0,height:((r=e.publication.dimensions)==null?void 0:r.height)??0,className:"rounded-md"})})},KB=D.forwardRef(function({trackRef:t,className:n,...i},r){var s,o;return m.jsx("div",{ref:r,className:at("bg-muted overflow-hidden rounded-md",n),children:m.jsx(Jl,{trackRef:t,width:((s=t==null?void 0:t.publication.dimensions)==null?void 0:s.width)??0,height:((o=t==null?void 0:t.publication.dimensions)==null?void 0:o.height)??0,className:at("h-full w-auto"),...i})})}),Wy=Ve.create(KB),WB=Ve.create(Xw),qB=Ve.create(HB),Oi={initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},exit:{opacity:0,scale:0},transition:{type:"spring",stiffness:675,damping:75,mass:1}},ps={grid:["h-full w-full","grid gap-x-2 place-content-center","grid-cols-[1fr_1fr] grid-rows-[90px_1fr_90px]"],agentChatOpenWithSecondTile:["col-start-1 row-start-1","self-center justify-self-end"],agentChatOpenWithoutSecondTile:["col-start-1 row-start-1","col-span-2","place-content-center"],agentChatClosed:["col-start-1 row-start-1","col-span-2","place-content-center"],secondTileChatOpen:["col-start-2 row-start-1","self-center justify-self-start"],secondTileChatClosed:["col-start-2 row-start-3","place-content-end"]};function QB(e,t){const{localParticipant:n}=oB(t),i=n==null?void 0:n.getTrackPublication(e);return M.useMemo(()=>i&&n?{source:e,participant:n,publication:i}:void 0,[e,i,n])}function YB({chatOpen:e,client:t,theme:n="vox"}){const{agent:{isActive:i=!1}={},session:r,state:s="idle",audioTrack:o,videoTrack:a}=t?Zp(t):{agent:{isActive:!1},session:null,state:"idle",audioTrack:null,videoTrack:null};console.log("🎨 MediaTiles render:",{chatOpen:e,isAgentActive:i,hasSession:!!r,sessionState:r==null?void 0:r.state,agentState:s,hasAudioTrack:!!o,hasVideoTrack:!!a});const[c]=Pw([z.Source.ScreenShare]),l=QB(z.Source.Camera,t),u=l&&!l.publication.isMuted,d=c&&!c.publication.isMuted,h=u||d,f=i||r&&r.state==="active",g={...Oi.transition,delay:e?0:.15},p={...Oi.animate,scale:e?1:3,transition:g},x={...Oi.animate,transition:g},y=g,E=g,w=a&&a.publication&&a.participant;return m.jsx("div",{className:"relative w-full h-full z-10 flex items-center justify-center",children:m.jsx("div",{className:"relative w-full h-full max-w-2xl px-4 md:px-0",children:m.jsxs("div",{className:at(ps.grid),children:[f&&m.jsx("div",{className:at(["grid",!e&&ps.agentChatClosed,e&&h&&ps.agentChatOpenWithSecondTile,e&&!h&&ps.agentChatOpenWithoutSecondTile]),children:m.jsxs("div",{className:"h-full flex items-center justify-center",children:[!w&&m.jsx(WB,{layoutId:"agent",...Oi,animate:p,transition:y,state:s,audioTrack:o||void 0,theme:n,className:at(e?"h-[90px]":"h-auto w-full")},"agent"),w&&a&&m.jsx(qB,{layoutId:"avatar",...Oi,animate:x,transition:E,videoTrack:a,className:at(e?"h-[90px] [&>video]:h-[90px] [&>video]:w-auto":"h-auto w-full")},"avatar")]})}),m.jsx("div",{className:at(["grid",e&&ps.secondTileChatOpen,!e&&ps.secondTileChatClosed]),children:m.jsxs("div",{className:"w-full px-10 flex items-center shadow-2xl justify-between",children:[l&&u&&m.jsx(Wy,{layout:"position",layoutId:"camera",...Oi,trackRef:l,transition:{...Oi.transition,delay:e?0:.15},className:"h-[60px] order-1"},"camera"),d&&m.jsx(Wy,{layout:"position",layoutId:"screen",...Oi,trackRef:c,transition:{...Oi.transition,delay:e?0:.15},className:"h-[70px] order-2"},"screen")]})})]})})})}const JB={card:"text-gray-100 bg-gradient-to-b from-[#0a0a0a] via-[#121212] to-[#0a0a0a] border border-gray-800/50 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-2xl",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-40 z-10 bg-gradient-to-b from-black/90 via-black/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(75,85,99,0.08),transparent_50%)] opacity-100",cardPurpleBlur:"absolute top-0 left-1/2 -translate-x-1/2 w-[600px] h-[300px] bg-gradient-to-b from-gray-500/[0.12] via-gray-600/[0.06] to-transparent blur-3xl",cardPinkBlur:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[500px] h-[250px] bg-gradient-to-t from-gray-600/[0.08] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-center justify-between max-w-md mx-auto bg-gradient-to-b from-[#0a0a0a] via-[#121212] to-[#0a0a0a] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-gray-100 font-semibold",secondary:"text-gray-200",muted:"text-gray-400",accent:"text-transparent bg-clip-text bg-gradient-to-r from-gray-300 via-gray-200 to-gray-300"},micButton:"relative w-20 h-20 bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 rounded-3xl flex items-center justify-center hover:bg-gray-900 hover:border-gray-600 hover:scale-105 hover:shadow-2xl hover:shadow-gray-600/30 transition-all duration-500 ease-out group overflow-hidden",chatButton:"relative w-20 h-20 bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 rounded-3xl flex items-center justify-center hover:bg-gray-900 hover:border-gray-600 hover:scale-105 hover:shadow-2xl hover:shadow-gray-600/30 transition-all duration-500 ease-out group overflow-hidden",videoButton:"relative w-20 h-20 bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 rounded-3xl flex items-center justify-center hover:bg-gray-900 hover:border-gray-600 hover:scale-105 hover:shadow-2xl hover:shadow-gray-600/30 transition-all duration-500 ease-out group overflow-hidden",popupTrigger:"bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 text-gray-100 font-bold hover:bg-gray-900 hover:border-gray-600 hover:scale-[1.02] hover:shadow-2xl hover:shadow-gray-600/30 focus:outline-none focus:ring-2 focus:ring-gray-600 focus:ring-offset-2 focus:ring-offset-black transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-gray-900/60 backdrop-blur-xl rounded-2xl text-center text-gray-200 text-sm font-medium transition-all duration-700 ease-in-out border border-gray-700/50 shadow-xl",statusIndicator:"w-2.5 h-2.5 bg-gray-400 rounded-full animate-pulse shadow-lg shadow-gray-400/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-gray-800/50 rounded-3xl py-4 flex flex-col justify-end h-full bg-black/90 backdrop-blur-xl shadow-2xl",chatInput:{container:"bg-black/90 backdrop-blur-xl border-gray-800/50 shadow-xl",textarea:"bg-black/80 border border-gray-800/50 rounded-xl text-gray-100 placeholder-gray-500 font-medium px-4 py-3",sendButton:"bg-gray-900/90 hover:bg-gray-900 border-2 border-gray-700/50 hover:border-gray-600 disabled:border-gray-800 disabled:opacity-40 text-gray-100 font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-gray-600/30",attachButton:"text-gray-400 hover:text-gray-200 hover:bg-gray-700/30 transition-all duration-300 rounded-xl",endButton:"bg-red-600/90 hover:bg-red-600 border-2 border-red-500/40 hover:border-red-500/60 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-red-500/40"},chatMessage:{own:"bg-gray-800/70 text-gray-100 backdrop-blur-md shadow-lg border border-gray-700/50",other:"bg-gray-900/60 text-gray-100 border border-gray-700/50 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-gray-900/80 border-gray-700/50 backdrop-blur-xl shadow-xl",backButton:"text-gray-300 hover:text-gray-100 hover:bg-gray-700/30 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-gray-400 mb-2",suggestedResponse:{container:"bg-gray-900/70 text-gray-200 border-gray-700/50 backdrop-blur-md hover:bg-gray-800/80 hover:border-gray-600 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#0a0a0a] via-[#121212] to-[#0a0a0a] text-gray-100",header:"border-gray-700/50 bg-gray-900/80 backdrop-blur-xl shadow-xl",headerButton:"bg-gray-900/90 hover:bg-gray-900 border-2 border-gray-700/50 hover:border-gray-600 text-gray-100 hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-emerald-400 animate-pulse shadow-lg shadow-emerald-400/60",controlsBackground:"bg-gradient-to-t from-gray-900 via-gray-900/90 to-gray-900/60 backdrop-blur-xl border-t border-gray-700/50 shadow-2xl",controlEnabled:"bg-gray-900/90 hover:bg-gray-900 border-2 border-gray-700/50 hover:border-gray-600 text-gray-100 hover:scale-105 hover:shadow-xl hover:shadow-gray-600/30 transition-all duration-300 font-semibold",controlDisabled:"bg-gray-900/50 hover:bg-gray-900/60 text-gray-500 border border-gray-800 transition-all duration-300",endCall:"bg-red-600/90 hover:bg-red-600 border-2 border-red-500/50 hover:border-red-500/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-2xl hover:shadow-red-500/50",tile:"bg-gray-900/70 border border-gray-700/50 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-gray-900/60 text-gray-300",avatar:"bg-gray-800/80 text-gray-300 border-2 border-gray-700/50",nameOverlay:"bg-gradient-to-t from-gray-900 via-gray-900/80 to-transparent text-white backdrop-blur-sm font-bold",mutedIndicator:"bg-red-600 text-white shadow-xl shadow-red-500/40 font-semibold"}},XB={card:"text-gray-900 bg-gradient-to-b from-[#F8F9FC] via-[#FFFFFF] to-[#F8F9FC] border-[3px] border-indigo-200/60 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-2xl shadow-indigo-200/30",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-40 z-10 bg-gradient-to-b from-[#FFFFFF]/90 via-[#FFFFFF]/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(129,140,248,0.12),transparent_50%)] opacity-100",cardPurpleBlur:"absolute top-0 right-0 w-64 h-64 bg-gradient-to-br from-indigo-300/40 via-purple-300/25 to-transparent rounded-full blur-3xl animate-pulse-slow",cardPinkBlur:"absolute bottom-0 left-0 w-56 h-56 bg-gradient-to-tr from-blue-300/35 via-purple-200/20 to-transparent rounded-full blur-3xl",cardPulse1:"absolute top-4 right-4 w-8 h-8 bg-gradient-to-br from-indigo-400/30 to-purple-400/30 rounded-full blur-md opacity-60 animate-pulse",cardPulse2:"absolute bottom-6 left-6 w-6 h-6 bg-gradient-to-br from-blue-400/25 to-purple-400/25 rounded-full blur-md opacity-50 animate-pulse",main:"w-full justify-between flex flex-col items-center bg-gradient-to-b from-[#F8F9FC] via-[#FFFFFF] to-[#F8F9FC] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-gray-900 font-semibold",secondary:"text-gray-700",muted:"text-gray-500",accent:"text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 via-purple-600 to-blue-600"},micButton:"relative w-20 h-20 backdrop-blur-xl border-2 border-indigo-400/40 rounded-3xl flex items-center justify-center hover:from-indigo-700 hover:to-purple-700 hover:border-indigo-500/60 hover:scale-105 hover:shadow-2xl hover:shadow-indigo-500/40 transition-all duration-500 ease-out group overflow-hidden text-white",chatButton:"relative w-20 h-20 bg-gradient-to-br from-blue-600 to-cyan-600 backdrop-blur-xl border-2 border-blue-400/40 rounded-3xl flex items-center justify-center hover:from-blue-700 hover:to-cyan-700 hover:border-blue-500/60 hover:scale-105 hover:shadow-2xl hover:shadow-blue-500/40 transition-all duration-500 ease-out group overflow-hidden text-white",videoButton:"relative w-20 h-20 bg-gradient-to-br from-purple-600 to-pink-600 backdrop-blur-xl border-2 border-purple-400/40 rounded-3xl flex items-center justify-center hover:from-purple-700 hover:to-pink-700 hover:border-purple-500/60 hover:scale-105 hover:shadow-2xl hover:shadow-purple-500/40 transition-all duration-500 ease-out group overflow-hidden text-white",popupTrigger:"bg-gradient-to-r from-indigo-600 to-purple-600 backdrop-blur-xl border-2 border-indigo-400/40 text-white font-bold hover:from-indigo-700 hover:to-purple-700 hover:border-indigo-500/60 hover:scale-[1.02] hover:shadow-2xl hover:shadow-indigo-500/40 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:ring-offset-white transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-white/80 backdrop-blur-xl rounded-2xl text-center text-gray-700 text-sm font-medium transition-all duration-700 ease-in-out border border-indigo-100 shadow-lg shadow-indigo-100/20",statusIndicator:"w-2.5 h-2.5 bg-emerald-500 rounded-full animate-pulse shadow-lg shadow-emerald-500/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-indigo-100 rounded-3xl py-4 flex flex-col justify-end h-full bg-white/80 backdrop-blur-xl shadow-2xl",chatInput:{container:"bg-white/80 backdrop-blur-xl border-indigo-100 shadow-xl",textarea:"bg-white/90 border border-indigo-100 rounded-xl text-gray-900 placeholder-gray-400 font-medium px-4 py-3 focus:border-indigo-300 focus:ring-2 focus:ring-indigo-200",sendButton:"bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 border-2 border-transparent disabled:from-gray-300 disabled:to-gray-300 disabled:opacity-40 text-white font-bold hover:scale-105 transition-all duration-300 shadow-lg hover:shadow-indigo-500/40",attachButton:"text-gray-500 hover:text-indigo-600 hover:bg-indigo-50 transition-all duration-300 rounded-xl",endButton:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/50 hover:border-red-400/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-red-500/40"},chatMessage:{own:"bg-indigo-100/70 text-gray-900 backdrop-blur-md shadow-lg border border-indigo-200/50",other:"bg-white/80 text-gray-900 border border-gray-200 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-white/80 border-indigo-100 backdrop-blur-xl shadow-xl",backButton:"text-gray-600 hover:text-indigo-600 hover:bg-indigo-50 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-indigo-600 mb-2",suggestedResponse:{container:"bg-white/80 text-indigo-700 border-indigo-100 backdrop-blur-md hover:bg-indigo-50 hover:border-indigo-200 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#F8F9FC] via-[#FFFFFF] to-[#F8F9FC] text-gray-900",header:"border-indigo-100 bg-white/80 backdrop-blur-xl shadow-xl",headerButton:"bg-white/90 hover:bg-indigo-50 border-2 border-indigo-100 hover:border-indigo-200 text-gray-900 hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-emerald-500 animate-pulse shadow-lg shadow-emerald-500/60",controlsBackground:"bg-gradient-to-t from-white via-white/90 to-white/60 backdrop-blur-xl border-t border-indigo-100 shadow-2xl",controlEnabled:"bg-white/90 hover:bg-indigo-50 border-2 border-indigo-100 hover:border-indigo-200 text-gray-900 hover:scale-105 hover:shadow-xl hover:shadow-indigo-200/30 transition-all duration-300 font-semibold",controlDisabled:"bg-gray-100/50 hover:bg-gray-100/60 text-gray-400 border border-gray-200 transition-all duration-300",endCall:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/50 hover:border-red-400/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-2xl hover:shadow-red-500/50",tile:"bg-white/80 border border-indigo-100 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-gray-50 text-gray-600",avatar:"bg-indigo-100/80 text-indigo-700 border-2 border-indigo-200",nameOverlay:"bg-gradient-to-t from-white via-white/80 to-transparent text-gray-900 backdrop-blur-sm font-bold",mutedIndicator:"bg-red-600 text-white shadow-xl shadow-red-500/40 font-semibold"}},ZB={card:"text-white bg-gradient-to-b from-[#0a0a0a] via-[#000000] to-[#0a0a0a] border border-gray-800/30 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-[0_8px_32px_rgba(0,0,0,0.9),0_0_0_1px_rgba(255,255,255,0.08)_inset]",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-32 z-10 bg-gradient-to-b from-black/95 via-black/30 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,_rgba(255,255,255,0.03),transparent_60%)] opacity-100",cardPurpleBlur:"absolute top-0 left-1/2 -translate-x-1/2 w-[400px] h-[200px] bg-gradient-to-b from-white/[0.03] via-white/[0.015] to-transparent blur-3xl",cardPinkBlur:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[300px] h-[150px] bg-gradient-to-t from-white/[0.02] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-between justify-center max-w-md mx-auto bg-black p-0 overflow-hidden h-full relative",text:{primary:"text-white font-semibold",secondary:"text-white/95",muted:"text-gray-400",accent:"text-transparent bg-clip-text bg-gradient-to-r from-gray-200 via-white to-gray-200"},micButton:"relative w-20 h-20 bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] rounded-2xl flex items-center justify-center hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.03] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] transition-all duration-300 ease-out group overflow-hidden",chatButton:"relative w-20 h-20 bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] rounded-2xl flex items-center justify-center hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.03] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] transition-all duration-300 ease-out group overflow-hidden",videoButton:"relative w-20 h-20 bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] rounded-2xl flex items-center justify-center hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.03] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] transition-all duration-300 ease-out group overflow-hidden",popupTrigger:"bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] text-white font-bold hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.02] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] focus:outline-none focus:ring-2 focus:ring-white/30 focus:ring-offset-2 focus:ring-offset-black transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-white/[0.06] backdrop-blur-md rounded-xl text-center text-white/90 text-sm font-medium transition-all duration-700 ease-in-out border border-white/[0.12] ",statusIndicator:"w-2 h-2 bg-emerald-400 rounded-full animate-pulse shadow-[0_0_8px_rgba(52,211,153,0.6)]",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-white/[0.12] rounded-2xl py-4 flex flex-col justify-end h-full bg-black/90 backdrop-blur-md shadow-[0_4px_24px_rgba(0,0,0,0.6)]",chatInput:{container:"bg-black/90 backdrop-blur-md border-white/[0.12] shadow-[0_4px_16px_rgba(0,0,0,0.4)]",textarea:"bg-white/[0.08] border border-white/[0.12] rounded-xl text-white placeholder-gray-500 font-medium px-4 py-3 focus:border-white/[0.2] focus:ring-1 focus:ring-white/[0.15] transition-all",sendButton:"bg-white/[0.12] hover:bg-white/[0.18] border border-white/[0.2] hover:border-white/[0.35] disabled:border-white/[0.08] disabled:opacity-40 text-white font-bold hover:scale-[1.02] transition-all duration-300 shadow-md hover:shadow-[0_4px_16px_rgba(255,255,255,0.12)]",attachButton:"text-gray-400 hover:text-white hover:bg-white/[0.08] transition-all duration-300 rounded-lg",endButton:"bg-red-500/90 hover:bg-red-500 border border-red-400/40 hover:border-red-400/60 text-white font-bold hover:scale-[1.02] transition-all duration-300 shadow-md hover:shadow-[0_4px_16px_rgba(239,68,68,0.3)]"},chatMessage:{own:"bg-white/[0.10] text-white backdrop-blur-sm shadow-md border border-white/[0.15]",other:"bg-white/[0.06] text-white border border-white/[0.10] backdrop-blur-sm shadow-md"},chatHeader:{container:"bg-black/90 border-white/[0.12] backdrop-blur-md shadow-lg",backButton:"text-gray-400 hover:text-white hover:bg-white/[0.08] transition-all duration-300 rounded-lg"},spinner:"w-10 h-10 animate-spin text-white mb-2",suggestedResponse:{container:"bg-white/[0.08] text-white border-white/[0.15] backdrop-blur-sm hover:bg-white/[0.12] hover:border-white/[0.25] transition-all duration-300 shadow-md"},video:{container:"bg-black text-white",header:"border-white/[0.12] bg-black/90 backdrop-blur-md shadow-lg",headerButton:"bg-white/[0.12] hover:bg-white/[0.18] border border-white/[0.2] hover:border-white/[0.35] text-white hover:scale-[1.02] transition-all duration-300 rounded-lg shadow-md",statusDot:"bg-emerald-400 animate-pulse shadow-[0_0_8px_rgba(52,211,153,0.6)]",controlsBackground:"bg-gradient-to-t from-black via-black/95 to-black/70 backdrop-blur-md border-t border-white/[0.12] shadow-[0_-4px_24px_rgba(0,0,0,0.6)]",controlEnabled:"bg-white/[0.12] hover:bg-white/[0.18] border border-white/[0.2] hover:border-white/[0.35] text-white hover:scale-[1.02] hover:shadow-md hover:shadow-white/10 transition-all duration-300 font-semibold",controlDisabled:"bg-white/[0.04] hover:bg-white/[0.06] text-gray-500 border border-white/[0.08] transition-all duration-300",endCall:"bg-red-500/90 hover:bg-red-500 border border-red-400/40 hover:border-red-400/60 text-white font-bold hover:scale-[1.02] transition-all duration-300 shadow-md hover:shadow-red-500/30",tile:"bg-white/[0.08] border border-white/[0.12] shadow-lg backdrop-blur-sm rounded-xl",placeholder:"bg-white/[0.06] text-gray-400",avatar:"bg-white/[0.10] text-gray-300 border border-white/[0.12]",nameOverlay:"bg-gradient-to-t from-black via-black/85 to-transparent text-white backdrop-blur-sm font-semibold",mutedIndicator:"bg-red-500 text-white shadow-md shadow-red-500/30 font-semibold"}},$B={card:"text-white bg-gradient-to-b from-[#0e1218] via-[#161a25] to-[#0e1218] border border-[#2a3142]/50 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-2xl",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-40 z-10 bg-gradient-to-b from-[#0b1220]/90 via-[#0b1220]/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(34,211,238,0.08),transparent_50%)] opacity-100",cardPurpleBlur:"absolute top-0 left-1/2 -translate-x-1/2 w-[600px] h-[300px] bg-gradient-to-b from-cyan-500/[0.12] via-sky-500/[0.06] to-transparent blur-3xl",cardPinkBlur:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[500px] h-[250px] bg-gradient-to-t from-cyan-600/[0.08] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-center justify-between max-w-md mx-auto bg-gradient-to-b from-[#0e1218] via-[#161a25] to-[#0e1218] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-white font-semibold",secondary:"text-white/95",muted:"text-white/70",accent:"text-transparent bg-clip-text bg-gradient-to-r from-cyan-300 via-sky-300 to-cyan-300"},micButton:"relative w-20 h-20 bg-[#171b26]/90 backdrop-blur-xl border-2 border-cyan-500/30 rounded-3xl flex items-center justify-center hover:bg-[#171b26] hover:border-cyan-400/50 hover:scale-105 hover:shadow-2xl hover:shadow-cyan-500/30 transition-all duration-500 ease-out group overflow-hidden",chatButton:"relative w-20 h-20 bg-[#171b26]/90 backdrop-blur-xl border-2 border-sky-500/30 rounded-3xl flex items-center justify-center hover:bg-[#171b26] hover:border-sky-400/50 hover:scale-105 hover:shadow-2xl hover:shadow-sky-500/30 transition-all duration-500 ease-out group overflow-hidden",videoButton:"relative w-20 h-20 bg-[#171b26]/90 backdrop-blur-xl border-2 border-cyan-500/30 rounded-3xl flex items-center justify-center hover:bg-[#171b26] hover:border-cyan-400/50 hover:scale-105 hover:shadow-2xl hover:shadow-cyan-500/30 transition-all duration-500 ease-out group overflow-hidden",popupTrigger:"bg-[#171b26]/90 backdrop-blur-xl border-2 border-cyan-500/30 text-white font-bold hover:bg-[#171b26] hover:border-cyan-400/50 hover:scale-[1.02] hover:shadow-2xl hover:shadow-cyan-500/30 focus:outline-none focus:ring-2 focus:ring-cyan-400/50 focus:ring-offset-2 focus:ring-offset-[#161a25] transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-[#1c2230]/60 backdrop-blur-xl rounded-2xl text-center text-white/90 text-sm font-medium transition-all duration-700 ease-in-out border border-[#2a3142]/80 shadow-xl",statusIndicator:"w-2.5 h-2.5 bg-emerald-400 rounded-full animate-pulse shadow-lg shadow-emerald-400/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-[#2a3142]/80 rounded-3xl py-4 flex flex-col justify-end h-full bg-[#161a25]/80 backdrop-blur-xl shadow-2xl",chatInput:{container:"bg-[#1c2230]/80 backdrop-blur-xl border-[#2a3142]/80 shadow-xl",textarea:"bg-[#1c2230]/60 border border-[#2a3142]/50 rounded-xl text-white placeholder-gray-400 font-medium px-4 py-3",sendButton:"bg-[#171b26]/90 hover:bg-[#171b26] border-2 border-cyan-500/30 hover:border-cyan-400/50 disabled:border-[#2a3142] disabled:opacity-40 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-cyan-500/30",attachButton:"text-gray-400 hover:text-white hover:bg-[#2a3142]/30 transition-all duration-300 rounded-xl",endButton:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/40 hover:border-red-400/60 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-red-500/40"},chatMessage:{own:"bg-[#243049]/70 text-white backdrop-blur-md shadow-lg border border-[#2a3142]/80",other:"bg-[#1c2230]/60 text-white border border-[#2a3142]/80 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-[#1c2230]/80 border-[#2a3142]/80 backdrop-blur-xl shadow-xl",backButton:"text-white/80 hover:text-white hover:bg-[#2a3142]/30 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-cyan-400 mb-2",suggestedResponse:{container:"bg-[#1c2230]/70 text-white border-[#2a3142]/80 backdrop-blur-md hover:bg-[#1c2230]/80 hover:border-cyan-400/30 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#0e1218] via-[#161a25] to-[#0e1218] text-white",header:"border-[#2a3142]/80 bg-[#1c2230]/80 backdrop-blur-xl shadow-xl",headerButton:"bg-[#171b26]/90 hover:bg-[#171b26] border-2 border-cyan-500/30 hover:border-cyan-400/50 text-white hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-emerald-400 animate-pulse shadow-lg shadow-emerald-400/60",controlsBackground:"bg-gradient-to-t from-[#161a25] via-[#161a25]/90 to-[#161a25]/60 backdrop-blur-xl border-t border-[#2a3142]/80 shadow-2xl",controlEnabled:"bg-[#171b26]/90 hover:bg-[#171b26] border-2 border-cyan-500/30 hover:border-cyan-400/50 text-white hover:scale-105 hover:shadow-xl hover:shadow-cyan-500/30 transition-all duration-300 font-semibold",controlDisabled:"bg-[#1c2230]/50 hover:bg-[#1c2230]/60 text-white/40 border border-[#2a3142] transition-all duration-300",endCall:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/50 hover:border-red-400/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-2xl hover:shadow-red-500/50",tile:"bg-[#1c2230]/70 border border-[#2a3142]/80 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-[#1c2230]/60 text-white/80",avatar:"bg-[#171b26]/80 text-white border-2 border-[#2a3142]/80",nameOverlay:"bg-gradient-to-t from-[#161a25] via-[#161a25]/80 to-transparent text-white backdrop-blur-sm font-bold",mutedIndicator:"bg-red-600 text-white shadow-xl shadow-red-500/40 font-semibold"}},eF={card:" text-white bg-gradient-to-br from-[#171727] to-[#12121F] border border-gray-800 w-full h-full flex flex-col justify-between overflow-hidden relative",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-10 z-10 bg-gradient-to-b from-[#171727]/90 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-[#3B82F6]/15 via-transparent to-transparent",cardPurpleBlur:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-[#8B5CF6]/25 to-transparent rounded-full blur-2xl",cardPinkBlur:"absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-[#EC4899]/20 to-transparent rounded-full blur-xl",cardPulse1:"absolute -top-2 -left-2 w-6 h-6 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full blur-sm opacity-50 animate-pulse",cardPulse2:"absolute -bottom-2 -right-2 w-4 h-4 bg-gradient-to-br from-[#EC4899] to-[#8B5CF6] rounded-full blur-sm opacity-40 animate-pulse",main:"w-full flex flex-col items-center justify-between max-w-md mx-auto bg-gradient-to-br from-[#171727] to-[#12121F] rounded-2xl shadow-xl p-0 overflow-hidden h-full",text:{primary:"text-white font-semibold",secondary:"text-white/95",muted:"text-white/70",accent:"bg-clip-text text-transparent bg-gradient-to-r from-[#3B82F6] via-[#8B5CF6] to-[#EC4899]"},micButton:"relative w-20 h-20 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 mic-glow shadow-2xl group",chatButton:"relative w-20 h-20 bg-gradient-to-br from-[#10B981] to-[#059669] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",videoButton:"relative w-20 h-20 bg-gradient-to-br from-[#8B5CF6] to-[#EC4899] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",popupTrigger:"bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] text-white font-medium hover:from-[#2563EB] hover:to-[#7C3AED] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-900 shadow-xl",promptSlider:"absolute w-full py-3 px-2 bg-[#1E1E2E] rounded-xl text-center text-gray-200 text-sm transition-opacity duration-700 ease-in-out border border-gray-700",statusIndicator:"w-2 h-2 bg-[#10B981] rounded-full animate-pulse",pulseRings:{ring1:"w-32 h-32 rounded-full border-2 border-[#3B82F6]/40 pulse-ring",ring2:"absolute w-28 h-28 rounded-full border-2 border-[#8B5CF6]/30 pulse-ring",ring3:"absolute w-24 h-24 rounded-full border-2 border-[#EC4899]/20 pulse-ring"},controlBar:"border border-border rounded-3xl py-4 flex flex-col justify-end h-full bg-[#1E1E2E] shadow-2xl",chatInput:{container:"bg-[#1E1E2E] border-gray-700",textarea:"bg-[#1E1E2E] border-none text-white placeholder-gray-400",sendButton:"bg-[#3B82F6] hover:bg-[#2563EB] disabled:bg-gray-600 disabled:opacity-50 text-white",attachButton:"text-gray-400 hover:text-gray-300 hover:bg-gray-700",endButton:"bg-red-900/20 hover:bg-red-800/30 text-red-400 border-red-800"},chatMessage:{own:"bg-[#1E1E2E]/80 text-white",other:"bg-[#1E1E2E] text-white border border-gray-700"},chatHeader:{container:"bg-[#1E1E2E] border-gray-700",backButton:"text-gray-400 hover:text-white hover:bg-gray-700"},spinner:"w-10 h-10 animate-spin text-blue-400 mb-2",suggestedResponse:{container:"bg-[#221f3f] text-white border-none"},video:{container:"bg-gradient-to-br from-[#171727] to-[#12121F] text-white",header:"border-gray-700 bg-[#1E1E2E]/80",headerButton:"bg-[#1E1E2E] hover:bg-gray-700 text-gray-300",statusDot:"bg-[#10B981] animate-pulse",controlsBackground:"bg-[#1E1E2E]/90 backdrop-blur-sm border-t border-gray-700",controlEnabled:"bg-[#3B82F6] hover:bg-[#2563EB] text-white",controlDisabled:"bg-gray-700 hover:bg-gray-600 text-gray-300",endCall:"bg-red-600 hover:bg-red-700 text-white",tile:"bg-[#1E1E2E] border border-gray-700 shadow-xl",placeholder:"bg-[#1E1E2E] text-gray-300",avatar:"bg-gray-700 text-gray-300",nameOverlay:"bg-black/70 text-white",mutedIndicator:"bg-red-600/80 text-white"}},qy={dark:JB,light:XB,vox:ZB,midnight:$B,levish:eF};function wn(e){return qy[e]||qy.vox}function Qy({timeout:e}){const[t,n]=M.useState(100),i=M.useRef(null),r=M.useRef(null);return M.useEffect(()=>{if(!e||e<=0)return;n(100),r.current=Date.now();const s=()=>{if(!e||r.current===null)return;const o=Date.now()-r.current,a=Math.max(0,100-o/e*100);n(a),a>0&&(i.current=requestAnimationFrame(s))};return i.current=requestAnimationFrame(s),()=>{i.current&&cancelAnimationFrame(i.current)}},[e]),!e||e<=0?null:m.jsx("div",{className:"w-full h-1 relative top-1 rounded-t-4xl bg-gray-700 overflow-hidden",children:m.jsx(Ve.div,{className:"h-1 rounded-t-4xl dark:bg-white bg-blue-200 ",initial:{width:"100%"},animate:{width:`${Math.max(t,2)}%`},transition:{duration:.1,ease:"linear"},style:{minWidth:"2%"}})})}function da({interaction:e,theme:t,onDismiss:n,client:i,addLocalMessage:r}){var a;if(!e||!e.isVisible||!e.component)return null;const[s]=D.useState(()=>Date.now()),o=()=>e.component?D.createElement(e.component,{handler:e.handler||void 0,timeout:e.timeout,loadData:async l=>{console.log("InteractiveComponent: Loading data:",l)},presentationMode:e.presentationMode,data:e.data,client:i,addLocalMessage:r}):m.jsx("div",{className:"p-4 text-red-500",children:"Component not found"});switch(e.presentationMode){case"fullscreen":return m.jsx(Ys,{children:m.jsxs(Ve.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[9999] bg-black",children:[m.jsxs("div",{className:"flex flex-col",children:[m.jsx(Qy,{timeout:e.timeout}),m.jsxs("div",{className:"flex items-center justify-between p-4 bg-black/80 text-white border-b border-gray-700",children:[m.jsx("h3",{className:"text-lg font-semibold",children:e.methodName.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase())}),m.jsx("button",{onClick:n||((a=e.handler)==null?void 0:a.dismissView),className:"p-2 rounded-full bg-white/20 hover:bg-white/30 text-white transition-colors",children:m.jsx(Ot.X,{className:"w-5 h-5"})})]})]}),m.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:o()})]})});case"embedded":default:return m.jsx(Ys,{children:m.jsx(Ve.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"w-fit rounded-lg ",children:m.jsxs("div",{children:[m.jsx(Qy,{timeout:e.timeout}),o()]})})})}}function ha({duration:e,theme:t="vox",onTimerExpired:n,className:i="",showIcon:r=!0}){const[s,o]=M.useState(e),[a,c]=M.useState(!1);M.useEffect(()=>{if(s<=0){c(!0),n==null||n();return}const u=setInterval(()=>{o(d=>{const h=d-1;return h<=0?(c(!0),n==null||n(),0):h})},1e3);return()=>clearInterval(u)},[s,n]),M.useEffect(()=>{o(e),c(!1)},[e]);const l=()=>a?"text-red-500":s<=60?"text-orange-500":s<=300?"text-yellow-500":t==="dark"?"text-gray-300":"text-gray-600";return m.jsxs("div",{className:`flex items-center gap-1 text-sm ${l()} ${i}`,children:[r&&m.jsx(Ot.Clock,{className:"w-4 h-4"}),m.jsx("span",{className:"font-mono",children:Jw(s)}),a&&m.jsx("span",{className:"text-xs ml-1 text-red-500",children:"(Expired)"})]})}function $l({modality:e,theme:t,disabled:n=!1,showMicrophone:i=!1,microphoneEnabled:r=!0,microphoneLoading:s=!1,onToggleMicrophone:o,showCamera:a=!1,cameraEnabled:c=!0,cameraLoading:l=!1,onToggleCamera:u,showScreenShare:d=!1,screenShareEnabled:h=!1,screenShareLoading:f=!1,onToggleScreenShare:g,showChatToggle:p=!1,chatOpen:x=!1,onToggleChat:y,showTextInput:E=!1,textInputPlaceholder:w="Type a message...",onSendText:S,onSendAttachments:v,supportsAttachments:k=!1,showEndCall:_=!0,onEndCall:T}){var Q;const I=wn(t),[b,A]=M.useState(""),P=M.useRef(null),B=()=>{const C=b.trim();C&&S&&(S(C),A(""))},L=C=>{C.key==="Enter"&&!C.shiftKey&&(C.preventDefault(),B())},V=C=>{const K=Array.from(C.target.files||[]);K.length>0&&v&&v(K),P.current&&(P.current.value="")},J=at("flex items-center gap-3 px-2 sm:px-3 py-2 w-full backdrop-blur-xl overflow-hidden",E?"justify-between":"justify-center",t==="light"?"bg-white/95 border-gray-200":""),re=(C,K)=>{var X,R,ae;return K==="end-call"?at("p-3 rounded-full transition-all duration-200",((X=I.video)==null?void 0:X.endCall)||"bg-red-500 text-white hover:bg-red-600",n?"opacity-50 cursor-not-allowed":"hover:scale-105"):at("p-3 rounded-full transition-all duration-200",C?((R=I.video)==null?void 0:R.controlEnabled)||"bg-green-500 text-white":((ae=I.video)==null?void 0:ae.controlDisabled)||"bg-gray-500 text-white",n?"opacity-50 cursor-not-allowed":"hover:scale-105")},G=()=>m.jsx("div",{className:"w-5 h-5 animate-spin rounded-full border-2 border-current border-t-transparent"});return m.jsxs("div",{className:J,children:[E&&m.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[k&&v&&m.jsxs(m.Fragment,{children:[m.jsx("button",{onClick:()=>{var C;return(C=P.current)==null?void 0:C.click()},disabled:n,className:at("p-2 rounded-full transition-all duration-200",t==="light"?"hover:bg-gray-100":"hover:bg-gray-800",n&&"opacity-50 cursor-not-allowed"),title:"Attach files",children:m.jsx(Ot.Paperclip,{className:"w-5 h-5"})}),m.jsx("input",{ref:P,type:"file",multiple:!0,accept:"image/*",onChange:V,className:"hidden"})]}),m.jsx("input",{type:"text",value:b,onChange:C=>A(C.target.value),onKeyDown:L,disabled:n,placeholder:w,className:at("flex-1 min-w-0 px-4 py-2 rounded-full border outline-none transition-all",t==="light"?"bg-gray-100 border-gray-300 focus:border-blue-500 text-gray-900":"bg-gray-800 border-gray-700 focus:border-blue-400 text-white",n&&"opacity-50 cursor-not-allowed")}),m.jsx("button",{onClick:B,disabled:n||!b.trim(),className:at("p-2 rounded-full transition-all duration-200",b.trim()?((Q=I.video)==null?void 0:Q.controlEnabled)||"bg-blue-500 text-white hover:bg-blue-600":t==="light"?"bg-gray-200 text-gray-400":"bg-gray-700 text-gray-500",n&&"opacity-50 cursor-not-allowed",b.trim()&&!n&&"hover:scale-105"),title:"Send message",children:m.jsx(Ot.SendHorizontal,{className:"w-5 h-5"})})]}),!E&&m.jsxs(m.Fragment,{children:[i&&o&&m.jsx("button",{onClick:o,disabled:n||s,className:re(r),title:r?"Mute microphone":"Unmute microphone",children:s?m.jsx(G,{}):r?m.jsx(Ot.Mic,{className:"w-5 h-5"}):m.jsx(Ot.MicOff,{className:"w-5 h-5"})}),a&&u&&m.jsx("button",{onClick:u,disabled:n||l,className:re(c),title:c?"Turn off camera":"Turn on camera",children:l?m.jsx(G,{}):c?m.jsx(Ot.Camera,{className:"w-5 h-5"}):m.jsx(Ot.CameraOff,{className:"w-5 h-5"})}),d&&g&&m.jsx("button",{onClick:g,disabled:n||f,className:re(h),title:h?"Stop screen share":"Share screen",children:f?m.jsx(G,{}):m.jsx(Ot.Monitor,{className:"w-5 h-5"})}),p&&y&&m.jsx("button",{onClick:y,disabled:n,className:re(x),title:e==="voice"?x?"Hide transcription":"Show transcription":x?"Hide chat":"Show chat",children:m.jsx(Ot.MessageCircle,{className:"w-5 h-5"})})]}),_&&T&&m.jsx("button",{onClick:T,disabled:n,className:re(!1,"end-call"),title:"End call",children:m.jsx(Ot.PhoneOff,{className:"w-5 h-5"})})]})}$l.displayName="UnifiedControlBar";const tF=({logLevel:e}={})=>{const t=DL();D.useEffect(()=>(dI(e??"debug"),window.__lk_room=t,()=>{window.__lk_room=void 0}),[t,e])},Zw=D.forwardRef((e,t)=>{const{alt:n,color:i="currentColor",size:r="1em",weight:s="regular",mirrored:o=!1,children:a,weights:c,...l}=e;return D.createElement("svg",{ref:t,xmlns:"http://www.w3.org/2000/svg",width:r,height:r,fill:i,viewBox:"0 0 256 256",transform:o?"scale(-1, 1)":void 0,...l},!!n&&D.createElement("title",null,n),a,c.get(s))});Zw.displayName="SSRBase";const nF=new Map([["bold",D.createElement(D.Fragment,null,D.createElement("path",{d:"M140,32V64a12,12,0,0,1-24,0V32a12,12,0,0,1,24,0Zm33.25,62.75a12,12,0,0,0,8.49-3.52L204.37,68.6a12,12,0,0,0-17-17L164.77,74.26a12,12,0,0,0,8.48,20.49ZM224,116H192a12,12,0,0,0,0,24h32a12,12,0,0,0,0-24Zm-42.26,48.77a12,12,0,1,0-17,17l22.63,22.63a12,12,0,0,0,17-17ZM128,180a12,12,0,0,0-12,12v32a12,12,0,0,0,24,0V192A12,12,0,0,0,128,180ZM74.26,164.77,51.63,187.4a12,12,0,0,0,17,17l22.63-22.63a12,12,0,1,0-17-17ZM76,128a12,12,0,0,0-12-12H32a12,12,0,0,0,0,24H64A12,12,0,0,0,76,128ZM68.6,51.63a12,12,0,1,0-17,17L74.26,91.23a12,12,0,0,0,17-17Z"}))],["duotone",D.createElement(D.Fragment,null,D.createElement("path",{d:"M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z",opacity:"0.2"}),D.createElement("path",{d:"M136,32V64a8,8,0,0,1-16,0V32a8,8,0,0,1,16,0Zm37.25,58.75a8,8,0,0,0,5.66-2.35l22.63-22.62a8,8,0,0,0-11.32-11.32L167.6,77.09a8,8,0,0,0,5.65,13.66ZM224,120H192a8,8,0,0,0,0,16h32a8,8,0,0,0,0-16Zm-45.09,47.6a8,8,0,0,0-11.31,11.31l22.62,22.63a8,8,0,0,0,11.32-11.32ZM128,184a8,8,0,0,0-8,8v32a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184ZM77.09,167.6,54.46,190.22a8,8,0,0,0,11.32,11.32L88.4,178.91A8,8,0,0,0,77.09,167.6ZM72,128a8,8,0,0,0-8-8H32a8,8,0,0,0,0,16H64A8,8,0,0,0,72,128ZM65.78,54.46A8,8,0,0,0,54.46,65.78L77.09,88.4A8,8,0,0,0,88.4,77.09Z"}))],["fill",D.createElement(D.Fragment,null,D.createElement("path",{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm33.94,58.75,17-17a8,8,0,0,1,11.32,11.32l-17,17a8,8,0,0,1-11.31-11.31ZM48,136a8,8,0,0,1,0-16H72a8,8,0,0,1,0,16Zm46.06,37.25-17,17a8,8,0,0,1-11.32-11.32l17-17a8,8,0,0,1,11.31,11.31Zm0-79.19a8,8,0,0,1-11.31,0l-17-17A8,8,0,0,1,77.09,65.77l17,17A8,8,0,0,1,94.06,94.06ZM136,208a8,8,0,0,1-16,0V184a8,8,0,0,1,16,0Zm0-136a8,8,0,0,1-16,0V48a8,8,0,0,1,16,0Zm54.23,118.23a8,8,0,0,1-11.32,0l-17-17a8,8,0,0,1,11.31-11.31l17,17A8,8,0,0,1,190.23,190.23ZM208,136H184a8,8,0,0,1,0-16h24a8,8,0,0,1,0,16Z"}))],["light",D.createElement(D.Fragment,null,D.createElement("path",{d:"M134,32V64a6,6,0,0,1-12,0V32a6,6,0,0,1,12,0Zm39.25,56.75A6,6,0,0,0,177.5,87l22.62-22.63a6,6,0,0,0-8.48-8.48L169,78.5a6,6,0,0,0,4.24,10.25ZM224,122H192a6,6,0,0,0,0,12h32a6,6,0,0,0,0-12Zm-46.5,47A6,6,0,0,0,169,177.5l22.63,22.62a6,6,0,0,0,8.48-8.48ZM128,186a6,6,0,0,0-6,6v32a6,6,0,0,0,12,0V192A6,6,0,0,0,128,186ZM78.5,169,55.88,191.64a6,6,0,1,0,8.48,8.48L87,177.5A6,6,0,1,0,78.5,169ZM70,128a6,6,0,0,0-6-6H32a6,6,0,0,0,0,12H64A6,6,0,0,0,70,128ZM64.36,55.88a6,6,0,0,0-8.48,8.48L78.5,87A6,6,0,1,0,87,78.5Z"}))],["regular",D.createElement(D.Fragment,null,D.createElement("path",{d:"M136,32V64a8,8,0,0,1-16,0V32a8,8,0,0,1,16,0Zm37.25,58.75a8,8,0,0,0,5.66-2.35l22.63-22.62a8,8,0,0,0-11.32-11.32L167.6,77.09a8,8,0,0,0,5.65,13.66ZM224,120H192a8,8,0,0,0,0,16h32a8,8,0,0,0,0-16Zm-45.09,47.6a8,8,0,0,0-11.31,11.31l22.62,22.63a8,8,0,0,0,11.32-11.32ZM128,184a8,8,0,0,0-8,8v32a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184ZM77.09,167.6,54.46,190.22a8,8,0,0,0,11.32,11.32L88.4,178.91A8,8,0,0,0,77.09,167.6ZM72,128a8,8,0,0,0-8-8H32a8,8,0,0,0,0,16H64A8,8,0,0,0,72,128ZM65.78,54.46A8,8,0,0,0,54.46,65.78L77.09,88.4A8,8,0,0,0,88.4,77.09Z"}))],["thin",D.createElement(D.Fragment,null,D.createElement("path",{d:"M132,32V64a4,4,0,0,1-8,0V32a4,4,0,0,1,8,0Zm41.25,54.75a4,4,0,0,0,2.83-1.18L198.71,63a4,4,0,0,0-5.66-5.66L170.43,79.92a4,4,0,0,0,2.82,6.83ZM224,124H192a4,4,0,0,0,0,8h32a4,4,0,0,0,0-8Zm-47.92,46.43a4,4,0,1,0-5.65,5.65l22.62,22.63a4,4,0,0,0,5.66-5.66ZM128,188a4,4,0,0,0-4,4v32a4,4,0,0,0,8,0V192A4,4,0,0,0,128,188ZM79.92,170.43,57.29,193.05A4,4,0,0,0,63,198.71l22.62-22.63a4,4,0,1,0-5.65-5.65ZM68,128a4,4,0,0,0-4-4H32a4,4,0,0,0,0,8H64A4,4,0,0,0,68,128ZM63,57.29A4,4,0,0,0,57.29,63L79.92,85.57a4,4,0,1,0,5.65-5.65Z"}))]]),kl=D.forwardRef((e,t)=>D.createElement(Zw,{ref:t,...e,weights:nF}));kl.displayName="SpinnerIcon";function iF({text:e,isComplete:t,isRealTimeStream:n=!1,speed:i=50}){const[r,s]=D.useState(""),[o,a]=D.useState(0);return D.useEffect(()=>{if(n){s(e);return}if(t){s(e);return}if(o<e.length){const c=setTimeout(()=>{s(e.slice(0,o+1)),a(o+1)},i);return()=>clearTimeout(c)}},[e,o,t,i,n]),D.useEffect(()=>{n||(a(0),s(""))},[e,n]),m.jsxs("span",{className:"relative",children:[m.jsx("span",{className:"inline-block",children:r}),!t&&m.jsx("span",{className:"inline-flex items-center ml-1",children:[0,1,2].map(c=>m.jsx(Ve.span,{className:"w-1.5 h-1.5 bg-current rounded-full mx-0.5",animate:{y:[0,-4,0],opacity:[.4,1,.4],scale:[.8,1,.8]},transition:{duration:.8,repeat:1/0,repeatType:"mirror",delay:c*.2,ease:"easeInOut"}},c))})]})}function rF(e,t){return e.startsWith("image/")?Ot.Image:e.startsWith("video/")?Ot.Video:e.startsWith("audio/")?Ot.Music:e.includes("zip")||e.includes("rar")||e.includes("archive")?Ot.Archive:Ot.FileText}function sF(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,i)).toFixed(2))+" "+n[i]}function oF({message:e,theme:t,isOwn:n}){const i=wn(t),r=e.metadata,s=(r==null?void 0:r.fileName)||"Unknown file",o=(r==null?void 0:r.fileSize)||0,a=(r==null?void 0:r.mimeType)||"application/octet-stream",c=r==null?void 0:r.downloading,l=r==null?void 0:r.uploading,u=(r==null?void 0:r.downloadProgress)||0,d=(r==null?void 0:r.uploadProgress)||0,h=r==null?void 0:r.downloadUrl,f=r==null?void 0:r.file,g=rF(a),p=c||l,x=c?u:d,y=c?"Downloading...":l?"Uploading...":"Complete",[E,w]=D.useState(null);D.useEffect(()=>{if(h)w(h);else if(f&&a.startsWith("image/")){const _=URL.createObjectURL(f);return w(_),()=>URL.revokeObjectURL(_)}else w(null)},[h,f,a]);const S=()=>{if(h){const _=document.createElement("a");_.href=h,_.download=s,_.click()}},k=a.startsWith("image/")&&E;return m.jsxs("div",{className:"flex flex-col gap-2 max-w-full sm:max-w-sm",children:[k&&m.jsxs("div",{className:"relative rounded-lg overflow-hidden",children:[m.jsx("img",{src:E,alt:s,className:"max-w-full h-auto max-h-48 object-cover rounded-lg cursor-pointer",onClick:S}),m.jsx("div",{className:"absolute inset-0 bg-black/0 hover:bg-black/10 transition-colors duration-200 cursor-pointer"})]}),m.jsxs("div",{className:`
48
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function xl(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var Ea=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,n,i,r,s;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=Js(o),c=a.next();!c.done;c=a.next()){var l=c.value;l.remove(this)}}catch(p){t={error:p}}finally{try{c&&!c.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}else o.remove(this);var u=this.initialTeardown;if($t(u))try{u()}catch(p){s=p instanceof hd?p.errors:[p]}var d=this._finalizers;if(d){this._finalizers=null;try{for(var h=Js(d),f=h.next();!f.done;f=h.next()){var g=f.value;try{Iy(g)}catch(p){s=s??[],p instanceof hd?s=vl(vl([],yl(s)),yl(p.errors)):s.push(p)}}}catch(p){i={error:p}}finally{try{f&&!f.done&&(r=h.return)&&r.call(h)}finally{if(i)throw i.error}}}if(s)throw new hd(s)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Iy(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(t)}},e.prototype._hasParent=function(t){var n=this._parentage;return n===t||Array.isArray(n)&&n.includes(t)},e.prototype._addParent=function(t){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(t),n):n?[n,t]:t},e.prototype._removeParent=function(t){var n=this._parentage;n===t?this._parentage=null:Array.isArray(n)&&xl(n,t)},e.prototype.remove=function(t){var n=this._finalizers;n&&xl(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),nw=Ea.EMPTY;function iw(e){return e instanceof Ea||e&&"closed"in e&&$t(e.remove)&&$t(e.add)&&$t(e.unsubscribe)}function Iy(e){$t(e)?e():e.unsubscribe()}var U2={Promise:void 0},j2={setTimeout:function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];return setTimeout.apply(void 0,vl([e,t],yl(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function rw(e){j2.setTimeout(function(){throw e})}function Ny(){}function jc(e){e()}var qp=(function(e){Zi(t,e);function t(n){var i=e.call(this)||this;return i.isStopped=!1,n?(i.destination=n,iw(n)&&n.add(i)):i.destination=G2,i}return t.create=function(n,i,r){return new nf(n,i,r)},t.prototype.next=function(n){this.isStopped||this._next(n)},t.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(n){this.destination.next(n)},t.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(Ea),V2=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var n=this.partialObserver;if(n.next)try{n.next(t)}catch(i){ec(i)}},e.prototype.error=function(t){var n=this.partialObserver;if(n.error)try{n.error(t)}catch(i){ec(i)}else ec(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(n){ec(n)}},e})(),nf=(function(e){Zi(t,e);function t(n,i,r){var s=e.call(this)||this,o;return $t(n)||!n?o={next:n??void 0,error:i??void 0,complete:r??void 0}:o=n,s.destination=new V2(o),s}return t})(qp);function ec(e){rw(e)}function z2(e){throw e}var G2={closed:!0,next:Ny,error:z2,complete:Ny},Qp=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function sw(e){return e}function H2(e){return e.length===0?sw:e.length===1?e[0]:function(t){return e.reduce(function(n,i){return i(n)},t)}}var Fn=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(t,n,i){var r=this,s=W2(t)?t:new nf(t,n,i);return jc(function(){var o=r,a=o.operator,c=o.source;s.add(a?a.call(s,c):c?r._subscribe(s):r._trySubscribe(s))}),s},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(n){t.error(n)}},e.prototype.forEach=function(t,n){var i=this;return n=My(n),new n(function(r,s){var o=new nf({next:function(a){try{t(a)}catch(c){s(c),o.unsubscribe()}},error:s,complete:r});i.subscribe(o)})},e.prototype._subscribe=function(t){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(t)},e.prototype[Qp]=function(){return this},e.prototype.pipe=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return H2(t)(this)},e.prototype.toPromise=function(t){var n=this;return t=My(t),new t(function(i,r){var s;n.subscribe(function(o){return s=o},function(o){return r(o)},function(){return i(s)})})},e.create=function(t){return new e(t)},e})();function My(e){var t;return(t=e??U2.Promise)!==null&&t!==void 0?t:Promise}function K2(e){return e&&$t(e.next)&&$t(e.error)&&$t(e.complete)}function W2(e){return e&&e instanceof qp||K2(e)&&iw(e)}function q2(e){return $t(e==null?void 0:e.lift)}function wa(e){return function(t){if(q2(t))return t.lift(function(n){try{return e(n,this)}catch(i){this.error(i)}});throw new TypeError("Unable to lift unknown Observable type")}}function Sl(e,t,n,i,r){return new Q2(e,t,n,i,r)}var Q2=(function(e){Zi(t,e);function t(n,i,r,s,o,a){var c=e.call(this,n)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=i?function(l){try{i(l)}catch(u){n.error(u)}}:e.prototype._next,c._error=s?function(l){try{s(l)}catch(u){n.error(u)}finally{this.unsubscribe()}}:e.prototype._error,c._complete=r?function(){try{r()}catch(l){n.error(l)}finally{this.unsubscribe()}}:e.prototype._complete,c}return t.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var i=this.closed;e.prototype.unsubscribe.call(this),!i&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},t})(qp),Y2=Wp(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),ow=(function(e){Zi(t,e);function t(){var n=e.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return t.prototype.lift=function(n){var i=new Py(this,this);return i.operator=n,i},t.prototype._throwIfClosed=function(){if(this.closed)throw new Y2},t.prototype.next=function(n){var i=this;jc(function(){var r,s;if(i._throwIfClosed(),!i.isStopped){i.currentObservers||(i.currentObservers=Array.from(i.observers));try{for(var o=Js(i.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(n)}}catch(l){r={error:l}}finally{try{a&&!a.done&&(s=o.return)&&s.call(o)}finally{if(r)throw r.error}}}})},t.prototype.error=function(n){var i=this;jc(function(){if(i._throwIfClosed(),!i.isStopped){i.hasError=i.isStopped=!0,i.thrownError=n;for(var r=i.observers;r.length;)r.shift().error(n)}})},t.prototype.complete=function(){var n=this;jc(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var i=n.observers;i.length;)i.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(n){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,n)},t.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},t.prototype._innerSubscribe=function(n){var i=this,r=this,s=r.hasError,o=r.isStopped,a=r.observers;return s||o?nw:(this.currentObservers=null,a.push(n),new Ea(function(){i.currentObservers=null,xl(a,n)}))},t.prototype._checkFinalizedStatuses=function(n){var i=this,r=i.hasError,s=i.thrownError,o=i.isStopped;r?n.error(s):o&&n.complete()},t.prototype.asObservable=function(){var n=new Fn;return n.source=this,n},t.create=function(n,i){return new Py(n,i)},t})(Fn),Py=(function(e){Zi(t,e);function t(n,i){var r=e.call(this)||this;return r.destination=n,r.source=i,r}return t.prototype.next=function(n){var i,r;(r=(i=this.destination)===null||i===void 0?void 0:i.next)===null||r===void 0||r.call(i,n)},t.prototype.error=function(n){var i,r;(r=(i=this.destination)===null||i===void 0?void 0:i.error)===null||r===void 0||r.call(i,n)},t.prototype.complete=function(){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||i===void 0||i.call(n)},t.prototype._subscribe=function(n){var i,r;return(r=(i=this.source)===null||i===void 0?void 0:i.subscribe(n))!==null&&r!==void 0?r:nw},t})(ow);(function(e){Zi(t,e);function t(n){var i=e.call(this)||this;return i._value=n,i}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(n){var i=e.prototype._subscribe.call(this,n);return!i.closed&&n.next(this._value),i},t.prototype.getValue=function(){var n=this,i=n.hasError,r=n.thrownError,s=n._value;if(i)throw r;return this._throwIfClosed(),s},t.prototype.next=function(n){e.prototype.next.call(this,this._value=n)},t})(ow);var J2={now:function(){return Date.now()}},X2=(function(e){Zi(t,e);function t(n,i){return e.call(this)||this}return t.prototype.schedule=function(n,i){return this},t})(Ea),Oy={setInterval:function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];return setInterval.apply(void 0,vl([e,t],yl(n)))},clearInterval:function(e){return clearInterval(e)},delegate:void 0},Z2=(function(e){Zi(t,e);function t(n,i){var r=e.call(this,n,i)||this;return r.scheduler=n,r.work=i,r.pending=!1,r}return t.prototype.schedule=function(n,i){var r;if(i===void 0&&(i=0),this.closed)return this;this.state=n;var s=this.id,o=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(o,s,i)),this.pending=!0,this.delay=i,this.id=(r=this.id)!==null&&r!==void 0?r:this.requestAsyncId(o,this.id,i),this},t.prototype.requestAsyncId=function(n,i,r){return r===void 0&&(r=0),Oy.setInterval(n.flush.bind(n,this),r)},t.prototype.recycleAsyncId=function(n,i,r){if(r===void 0&&(r=0),r!=null&&this.delay===r&&this.pending===!1)return i;i!=null&&Oy.clearInterval(i)},t.prototype.execute=function(n,i){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(n,i);if(r)return r;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(n,i){var r=!1,s;try{this.work(n)}catch(o){r=!0,s=o||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),s},t.prototype.unsubscribe=function(){if(!this.closed){var n=this,i=n.id,r=n.scheduler,s=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,xl(s,this),i!=null&&(this.id=this.recycleAsyncId(r,i,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t})(X2),Dy=(function(){function e(t,n){n===void 0&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(t,n,i){return n===void 0&&(n=0),new this.schedulerActionCtor(this,t).schedule(i,n)},e.now=J2.now,e})(),$2=(function(e){Zi(t,e);function t(n,i){i===void 0&&(i=Dy.now);var r=e.call(this,n,i)||this;return r.actions=[],r._active=!1,r}return t.prototype.flush=function(n){var i=this.actions;if(this._active){i.push(n);return}var r;this._active=!0;do if(r=n.execute(n.state,n.delay))break;while(n=i.shift());if(this._active=!1,r){for(;n=i.shift();)n.unsubscribe();throw r}},t})(Dy);new $2(Z2);function eL(e){return e&&$t(e.schedule)}function tL(e){return e[e.length-1]}function aw(e){return eL(tL(e))?e.pop():void 0}var cw=(function(e){return e&&typeof e.length=="number"&&typeof e!="function"});function lw(e){return $t(e==null?void 0:e.then)}function uw(e){return $t(e[Qp])}function dw(e){return Symbol.asyncIterator&&$t(e==null?void 0:e[Symbol.asyncIterator])}function hw(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function nL(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var fw=nL();function pw(e){return $t(e==null?void 0:e[fw])}function mw(e){return B2(this,arguments,function(){var t,n,i,r;return tw(this,function(s){switch(s.label){case 0:t=e.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,Gs(t.read())];case 3:return n=s.sent(),i=n.value,r=n.done,r?[4,Gs(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,Gs(i)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function gw(e){return $t(e==null?void 0:e.getReader)}function Ca(e){if(e instanceof Fn)return e;if(e!=null){if(uw(e))return iL(e);if(cw(e))return rL(e);if(lw(e))return sL(e);if(dw(e))return bw(e);if(pw(e))return oL(e);if(gw(e))return aL(e)}throw hw(e)}function iL(e){return new Fn(function(t){var n=e[Qp]();if($t(n.subscribe))return n.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function rL(e){return new Fn(function(t){for(var n=0;n<e.length&&!t.closed;n++)t.next(e[n]);t.complete()})}function sL(e){return new Fn(function(t){e.then(function(n){t.closed||(t.next(n),t.complete())},function(n){return t.error(n)}).then(null,rw)})}function oL(e){return new Fn(function(t){var n,i;try{for(var r=Js(e),s=r.next();!s.done;s=r.next()){var o=s.value;if(t.next(o),t.closed)return}}catch(a){n={error:a}}finally{try{s&&!s.done&&(i=r.return)&&i.call(r)}finally{if(n)throw n.error}}t.complete()})}function bw(e){return new Fn(function(t){cL(e,t).catch(function(n){return t.error(n)})})}function aL(e){return bw(mw(e))}function cL(e,t){var n,i,r,s;return L2(this,void 0,void 0,function(){var o,a;return tw(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=F2(e),c.label=1;case 1:return[4,n.next()];case 2:if(i=c.sent(),!!i.done)return[3,4];if(o=i.value,t.next(o),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),r={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),i&&!i.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(r)throw r.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function Kr(e,t,n,i,r){i===void 0&&(i=0),r===void 0&&(r=!1);var s=t.schedule(function(){n(),r?e.add(this.schedule(null,i)):this.unsubscribe()},i);if(e.add(s),!r)return s}function yw(e,t){return t===void 0&&(t=0),wa(function(n,i){n.subscribe(Sl(i,function(r){return Kr(i,e,function(){return i.next(r)},t)},function(){return Kr(i,e,function(){return i.complete()},t)},function(r){return Kr(i,e,function(){return i.error(r)},t)}))})}function vw(e,t){return t===void 0&&(t=0),wa(function(n,i){i.add(e.schedule(function(){return n.subscribe(i)},t))})}function lL(e,t){return Ca(e).pipe(vw(t),yw(t))}function uL(e,t){return Ca(e).pipe(vw(t),yw(t))}function dL(e,t){return new Fn(function(n){var i=0;return t.schedule(function(){i===e.length?n.complete():(n.next(e[i++]),n.closed||this.schedule())})})}function hL(e,t){return new Fn(function(n){var i;return Kr(n,t,function(){i=e[fw](),Kr(n,t,function(){var r,s,o;try{r=i.next(),s=r.value,o=r.done}catch(a){n.error(a);return}o?n.complete():n.next(s)},0,!0)}),function(){return $t(i==null?void 0:i.return)&&i.return()}})}function xw(e,t){if(!e)throw new Error("Iterable cannot be null");return new Fn(function(n){Kr(n,t,function(){var i=e[Symbol.asyncIterator]();Kr(n,t,function(){i.next().then(function(r){r.done?n.complete():n.next(r.value)})},0,!0)})})}function fL(e,t){return xw(mw(e),t)}function pL(e,t){if(e!=null){if(uw(e))return lL(e,t);if(cw(e))return dL(e,t);if(lw(e))return uL(e,t);if(dw(e))return xw(e,t);if(pw(e))return hL(e,t);if(gw(e))return fL(e,t)}throw hw(e)}function mL(e,t){return t?pL(e,t):Ca(e)}Wp(function(e){return function(t){t===void 0&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Ta(e,t){return wa(function(n,i){var r=0;n.subscribe(Sl(i,function(s){i.next(e.call(t,s,r++))}))})}function gL(e,t,n,i,r,s,o,a){var c=[],l=0,u=0,d=!1,h=function(){d&&!c.length&&!l&&t.complete()},f=function(p){return l<i?g(p):c.push(p)},g=function(p){l++;var x=!1;Ca(n(p,u++)).subscribe(Sl(t,function(y){t.next(y)},function(){x=!0},void 0,function(){if(x)try{l--;for(var y=function(){var E=c.shift();o||g(E)};c.length&&l<i;)y();h()}catch(E){t.error(E)}}))};return e.subscribe(Sl(t,f,function(){d=!0,h()})),function(){}}function Sw(e,t,n){return n===void 0&&(n=1/0),$t(t)?Sw(function(i,r){return Ta(function(s,o){return t(i,s,r,o)})(Ca(e(i,r)))},n):(typeof t=="number"&&(n=t),wa(function(i,r){return gL(i,r,e,n)}))}function bL(e){return Sw(sw,e)}function yL(){return bL(1)}function Ly(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return yL()(mL(e,aw(e)))}function Yl(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=aw(e);return wa(function(i,r){(n?Ly(e,i,n):Ly(e,i)).subscribe(r)})}var vL=(e,t,n)=>new Promise((i,r)=>{var s=c=>{try{a(n.next(c))}catch(l){r(l)}},o=c=>{try{a(n.throw(c))}catch(l){r(l)}},a=c=>c.done?i(c.value):Promise.resolve(c.value).then(s,o);a((n=n.apply(e,t)).next())}),xL="lk";function Yp(e){return typeof e>"u"?!1:SL(e)||kL(e)}function SL(e){var t;return e?e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&e.hasOwnProperty("track")&&typeof((t=e.publication)==null?void 0:t.track)<"u":!1}function kL(e){return e?e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&e.hasOwnProperty("publication")&&typeof e.publication<"u":!1}function EL(e){return e?e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&typeof e.publication>"u":!1}function wL(e){if(typeof e=="string"||typeof e=="number")return`${e}`;if(EL(e))return`${e.participant.identity}_${e.source}_placeholder`;if(Yp(e))return`${e.participant.identity}_${e.publication.source}_${e.publication.trackSid}`;throw new Error(`Can't generate a id for the given track reference: ${e}`)}var CL=[U.ConnectionStateChanged,U.RoomMetadataChanged,U.ActiveSpeakersChanged,U.ConnectionQualityChanged,U.ParticipantConnected,U.ParticipantDisconnected,U.ParticipantPermissionsChanged,U.ParticipantMetadataChanged,U.ParticipantNameChanged,U.ParticipantAttributesChanged,U.TrackMuted,U.TrackUnmuted,U.TrackPublished,U.TrackUnpublished,U.TrackStreamStateChanged,U.TrackSubscriptionFailed,U.TrackSubscriptionPermissionChanged,U.TrackSubscriptionStatusChanged],TL=[...CL,U.LocalTrackPublished,U.LocalTrackUnpublished];Y.TrackPublished,Y.TrackUnpublished,Y.TrackMuted,Y.TrackUnmuted,Y.TrackStreamStateChanged,Y.TrackSubscribed,Y.TrackUnsubscribed,Y.TrackSubscriptionPermissionChanged,Y.TrackSubscriptionFailed,Y.LocalTrackPublished,Y.LocalTrackUnpublished;var AL=[Y.ConnectionQualityChanged,Y.IsSpeakingChanged,Y.ParticipantMetadataChanged,Y.ParticipantPermissionsChanged,Y.TrackMuted,Y.TrackUnmuted,Y.TrackPublished,Y.TrackUnpublished,Y.TrackStreamStateChanged,Y.TrackSubscriptionFailed,Y.TrackSubscriptionPermissionChanged,Y.TrackSubscriptionStatusChanged];[...AL,Y.LocalTrackPublished,Y.LocalTrackUnpublished];var kr=D2.getLogger("lk-components-js");kr.setDefaultLevel("WARN");var kw=(e=>(e.AgentState="lk.agent.state",e.PublishOnBehalf="lk.publish_on_behalf",e.TranscriptionFinal="lk.transcription_final",e.TranscriptionSegmentId="lk.segment_id",e.TranscribedTrackId="lk.transcribed_track_id",e))(kw||{});function Ew(e){return typeof e=="object"}function ww(e){return Array.isArray(e)&&e.filter(Ew).length>0}function Cw(e){return`${xL}-${e}`}function RL(e){const t=rf(e),n=NL(e.participant).pipe(Ta(()=>rf(e)),Yl(t));return{className:Cw(e.source===z.Source.Camera||e.source===z.Source.ScreenShare?"participant-media-video":"participant-media-audio"),trackObserver:n}}function rf(e){if(Yp(e))return e.publication;{const{source:t,name:n,participant:i}=e;if(t&&n)return i.getTrackPublications().find(r=>r.source===t&&r.trackName===n);if(n)return i.getTrackPublicationByName(n);if(t)return i.getTrackPublication(t);throw new Error("At least one of source and name needs to be defined")}}function Tw(e,...t){return new Fn(n=>{const i=()=>{n.next(e)};return t.forEach(r=>{e.on(r,i)}),()=>{t.forEach(r=>{e.off(r,i)})}}).pipe(Yl(e))}function _L(e){return Tw(e,U.AudioPlaybackStatusChanged).pipe(Ta(t=>({canPlayAudio:t.canPlaybackAudio})))}function IL(e,...t){return new Fn(n=>{const i=()=>{n.next(e)};return t.forEach(r=>{e.on(r,i)}),()=>{t.forEach(r=>{e.off(r,i)})}}).pipe(Yl(e))}function NL(e){return IL(e,Y.TrackMuted,Y.TrackUnmuted,Y.ParticipantPermissionsChanged,Y.TrackPublished,Y.TrackUnpublished,Y.LocalTrackPublished,Y.LocalTrackUnpublished,Y.MediaDevicesError,Y.TrackSubscriptionStatusChanged).pipe(Ta(t=>{const{isMicrophoneEnabled:n,isCameraEnabled:i,isScreenShareEnabled:r}=t,s=t.getTrackPublication(z.Source.Microphone),o=t.getTrackPublication(z.Source.Camera);return{isCameraEnabled:i,isMicrophoneEnabled:n,isScreenShareEnabled:r,cameraTrack:o,microphoneTrack:s,participant:t}}))}function ML(){const e=t=>vL(this,null,function*(){kr.info("Start Audio for room: ",t),yield t.startAudio()});return{className:Cw("start-audio-button"),roomAudioPlaybackAllowedObservable:_L,handleStartAudioPlayback:e}}function By(e,t,n=!0){const i=[e.localParticipant,...Array.from(e.remoteParticipants.values())],r=[];return i.forEach(s=>{t.forEach(o=>{const a=Array.from(s.trackPublications.values()).filter(c=>c.source===o&&(!n||c.track)).map(c=>({participant:s,publication:c,source:c.source}));r.push(...a)})}),{trackReferences:r,participants:i}}function PL(e,t,n){var i,r;const s=(i=n.additionalRoomEvents)!=null?i:TL,o=(r=n.onlySubscribed)!=null?r:!0,a=Array.from(new Set([U.ParticipantConnected,U.ParticipantDisconnected,U.ConnectionStateChanged,U.LocalTrackPublished,U.LocalTrackUnpublished,U.TrackPublished,U.TrackUnpublished,U.TrackSubscriptionStatusChanged,...s]).values());return Tw(e,...a).pipe(Ta(c=>{const l=By(c,t,o);return kr.debug(`TrackReference[] was updated. (length ${l.trackReferences.length})`,l),l}),Yl(By(e,t,o)))}D.createContext(void 0);const OL=D.createContext(void 0);function Aw(){return D.useContext(OL)}function Rw(e){const t=Aw(),n=e??t;if(!n)throw new Error("No TrackRef, make sure you are inside a TrackRefContext or pass the TrackRef explicitly");return n}D.createContext(void 0);const Jp=D.createContext(void 0);function DL(){const e=D.useContext(Jp);if(!e)throw Error("tried to access room context outside of livekit room component");return e}function LL(){return D.useContext(Jp)}function Xp(e){const t=LL(),n=e??t;if(!n)throw new Error("No room provided, make sure you are inside a Room context or pass the room explicitly");return n}D.createContext(void 0);D.createContext(void 0);function _w(e){var t,n,i="";if(typeof e=="string"||typeof e=="number")i+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(t=0;t<r;t++)e[t]&&(n=_w(e[t]))&&(i&&(i+=" "),i+=n)}else for(n in e)e[n]&&(i&&(i+=" "),i+=n);return i}function Iw(){for(var e,t,n=0,i="",r=arguments.length;n<r;n++)(e=arguments[n])&&(t=_w(e))&&(i&&(i+=" "),i+=t);return i}function BL(...e){return(...t)=>{for(const n of e)if(typeof n=="function")try{n(...t)}catch(i){console.error(i)}}}function Nw(...e){const t={...e[0]};for(let n=1;n<e.length;n++){const i=e[n];for(const r in i){const s=t[r],o=i[r];typeof s=="function"&&typeof o=="function"&&r[0]==="o"&&r[1]==="n"&&r.charCodeAt(2)>=65&&r.charCodeAt(2)<=90?t[r]=BL(s,o):(r==="className"||r==="UNSAFE_className")&&typeof s=="string"&&typeof o=="string"?t[r]=Iw(s,o):t[r]=o!==void 0?o:s}}return t}function FL(e){return e!==void 0}function Mw(...e){return Nw(...e.filter(FL))}function UL(e,t,n){return D.Children.map(e,i=>D.isValidElement(i)&&D.Children.only(e)?(i.props.className&&(t??(t={}),t.className=Iw(i.props.className,t.className),t.style={...i.props.style,...t.style}),D.cloneElement(i,{...t,key:n})):i)}function jL(e,t,n=!0){const[i,r]=D.useState(t);return D.useEffect(()=>{if(n&&r(t),typeof window>"u"||!e)return;const s=e.subscribe(r);return()=>s.unsubscribe()},[e,n]),i}function VL({room:e,props:t}){const n=Xp(e),{className:i,roomAudioPlaybackAllowedObservable:r,handleStartAudioPlayback:s}=D.useMemo(()=>ML(),[]),o=D.useMemo(()=>r(n),[n,r]),{canPlayAudio:a}=jL(o,{canPlayAudio:n.canPlaybackAudio});return{mergedProps:D.useMemo(()=>Nw(t,{className:i,onClick:()=>{s(n)},style:{display:a?"none":"block"}}),[t,i,a,s,n]),canPlayAudio:a}}function Pw(e=[z.Source.Camera,z.Source.Microphone,z.Source.ScreenShare,z.Source.ScreenShareAudio,z.Source.Unknown],t={}){const n=Xp(t.room),[i,r]=D.useState([]),[s,o]=D.useState([]),a=D.useMemo(()=>e.map(c=>Ew(c)?c.source:c),[JSON.stringify(e)]);return D.useEffect(()=>{const c=PL(n,a,{additionalRoomEvents:t.updateOnlyOn,onlySubscribed:t.onlySubscribed}).subscribe(({trackReferences:l,participants:u})=>{kr.debug("setting track bundles",l,u),r(l),o(u)});return()=>c.unsubscribe()},[n,JSON.stringify(t.onlySubscribed),JSON.stringify(t.updateOnlyOn),JSON.stringify(e)]),D.useMemo(()=>{if(ww(e)){const c=GL(e,s),l=Array.from(i);return s.forEach(u=>{c.has(u.identity)&&(c.get(u.identity)??[]).forEach(d=>{if(i.find(({participant:f,publication:g})=>u.identity===f.identity&&g.source===d))return;kr.debug(`Add ${d} placeholder for participant ${u.identity}.`);const h={participant:u,source:d};l.push(h)})}),l}else return i},[i,s,e])}function zL(e,t){const n=new Set(e);for(const i of t)n.delete(i);return n}function GL(e,t){const n=new Map;if(ww(e)){const i=e.filter(r=>r.withPlaceholder).map(r=>r.source);t.forEach(r=>{const s=r.getTrackPublications().map(a=>{var c;return(c=a.track)==null?void 0:c.source}).filter(a=>a!==void 0),o=Array.from(zL(new Set(i),new Set(s)));o.length>0&&n.set(r.identity,o)})}return n}const HL=e=>{const t=n=>{let i=1-Math.max(-100,Math.min(-10,n))*-1/100;return i=Math.sqrt(i),i};return e.map(n=>n===-1/0?0:t(n))},KL={bands:5,loPass:100,hiPass:600,updateInterval:32,analyserOptions:{fftSize:2048}};function WL(e,t={}){var n;const i=e instanceof z?e:(n=e==null?void 0:e.publication)==null?void 0:n.track,r={...KL,...t},[s,o]=D.useState(new Array(r.bands).fill(0));return D.useEffect(()=>{if(!i||!(i!=null&&i.mediaStream)){o(h=>h.slice().fill(0));return}const{analyser:a,cleanup:c}=t1(i,r.analyserOptions),l=a.frequencyBinCount,u=new Float32Array(l),d=setInterval(()=>{a.getFloatFrequencyData(u);let h=new Float32Array(u.length);for(let x=0;x<u.length;x++)h[x]=u[x];h=h.slice(r.loPass,r.hiPass);const f=HL(h),g=f.length,p=[];for(let x=0;x<r.bands;x++){const y=Math.floor(x*g/r.bands),E=Math.floor((x+1)*g/r.bands),w=f.slice(y,E),S=w.length;if(S===0)p.push(0);else{const v=w.reduce((k,_)=>k+=_,0);p.push(v/S)}}o(p)},r.updateInterval);return()=>{c(),clearInterval(d)}},[i,i==null?void 0:i.mediaStream,JSON.stringify(t)]),s}kw.AgentState;var tc={exports:{}},Fy;function qL(){if(Fy)return tc.exports;Fy=1;var e=typeof Reflect=="object"?Reflect:null,t=e&&typeof e.apply=="function"?e.apply:function(S,v,k){return Function.prototype.apply.call(S,v,k)},n;e&&typeof e.ownKeys=="function"?n=e.ownKeys:Object.getOwnPropertySymbols?n=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:n=function(S){return Object.getOwnPropertyNames(S)};function i(S){console&&console.warn&&console.warn(S)}var r=Number.isNaN||function(S){return S!==S};function s(){s.init.call(this)}tc.exports=s,tc.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(S){if(typeof S!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof S)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(S){if(typeof S!="number"||S<0||r(S))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+S+".");o=S}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(S){if(typeof S!="number"||S<0||r(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function c(S){return S._maxListeners===void 0?s.defaultMaxListeners:S._maxListeners}s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(S){for(var v=[],k=1;k<arguments.length;k++)v.push(arguments[k]);var _=S==="error",T=this._events;if(T!==void 0)_=_&&T.error===void 0;else if(!_)return!1;if(_){var I;if(v.length>0&&(I=v[0]),I instanceof Error)throw I;var b=new Error("Unhandled error."+(I?" ("+I.message+")":""));throw b.context=I,b}var A=T[S];if(A===void 0)return!1;if(typeof A=="function")t(A,this,v);else for(var P=A.length,B=g(A,P),k=0;k<P;++k)t(B[k],this,v);return!0};function l(S,v,k,_){var T,I,b;if(a(k),I=S._events,I===void 0?(I=S._events=Object.create(null),S._eventsCount=0):(I.newListener!==void 0&&(S.emit("newListener",v,k.listener?k.listener:k),I=S._events),b=I[v]),b===void 0)b=I[v]=k,++S._eventsCount;else if(typeof b=="function"?b=I[v]=_?[k,b]:[b,k]:_?b.unshift(k):b.push(k),T=c(S),T>0&&b.length>T&&!b.warned){b.warned=!0;var A=new Error("Possible EventEmitter memory leak detected. "+b.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");A.name="MaxListenersExceededWarning",A.emitter=S,A.type=v,A.count=b.length,i(A)}return S}s.prototype.addListener=function(S,v){return l(this,S,v,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(S,v){return l(this,S,v,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(S,v,k){var _={fired:!1,wrapFn:void 0,target:S,type:v,listener:k},T=u.bind(_);return T.listener=k,_.wrapFn=T,T}s.prototype.once=function(S,v){return a(v),this.on(S,d(this,S,v)),this},s.prototype.prependOnceListener=function(S,v){return a(v),this.prependListener(S,d(this,S,v)),this},s.prototype.removeListener=function(S,v){var k,_,T,I,b;if(a(v),_=this._events,_===void 0)return this;if(k=_[S],k===void 0)return this;if(k===v||k.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete _[S],_.removeListener&&this.emit("removeListener",S,k.listener||v));else if(typeof k!="function"){for(T=-1,I=k.length-1;I>=0;I--)if(k[I]===v||k[I].listener===v){b=k[I].listener,T=I;break}if(T<0)return this;T===0?k.shift():p(k,T),k.length===1&&(_[S]=k[0]),_.removeListener!==void 0&&this.emit("removeListener",S,b||v)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(S){var v,k,_;if(k=this._events,k===void 0)return this;if(k.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):k[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete k[S]),this;if(arguments.length===0){var T=Object.keys(k),I;for(_=0;_<T.length;++_)I=T[_],I!=="removeListener"&&this.removeAllListeners(I);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=k[S],typeof v=="function")this.removeListener(S,v);else if(v!==void 0)for(_=v.length-1;_>=0;_--)this.removeListener(S,v[_]);return this};function h(S,v,k){var _=S._events;if(_===void 0)return[];var T=_[v];return T===void 0?[]:typeof T=="function"?k?[T.listener||T]:[T]:k?x(T):g(T,T.length)}s.prototype.listeners=function(S){return h(this,S,!0)},s.prototype.rawListeners=function(S){return h(this,S,!1)},s.listenerCount=function(S,v){return typeof S.listenerCount=="function"?S.listenerCount(v):f.call(S,v)},s.prototype.listenerCount=f;function f(S){var v=this._events;if(v!==void 0){var k=v[S];if(typeof k=="function")return 1;if(k!==void 0)return k.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function g(S,v){for(var k=new Array(v),_=0;_<v;++_)k[_]=S[_];return k}function p(S,v){for(;v+1<S.length;v++)S[v]=S[v+1];S.pop()}function x(S){for(var v=new Array(S.length),k=0;k<v.length;++k)v[k]=S[k].listener||S[k];return v}function y(S,v){return new Promise(function(k,_){function T(b){S.removeListener(v,I),_(b)}function I(){typeof S.removeListener=="function"&&S.removeListener("error",T),k([].slice.call(arguments))}w(S,v,I,{once:!0}),v!=="error"&&E(S,T,{once:!0})})}function E(S,v,k){typeof S.on=="function"&&w(S,"error",v,k)}function w(S,v,k,_){if(typeof S.on=="function")_.once?S.once(v,k):S.on(v,k);else if(typeof S.addEventListener=="function")S.addEventListener(v,function T(I){_.once&&S.removeEventListener(v,T),k(I)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof S)}return tc.exports}qL();const QL=D.forwardRef(function({label:e="Allow Audio",...t},n){const i=Xp(t.room),{mergedProps:r}=VL({room:i,props:t});return D.createElement("button",{ref:n,...r},e)});function Ow(e,t={}){const[n,i]=D.useState(rf(e)),[r,s]=D.useState(n==null?void 0:n.isMuted),[o,a]=D.useState(n==null?void 0:n.isSubscribed),[c,l]=D.useState(n==null?void 0:n.track),[u,d]=D.useState("landscape"),h=D.useRef(),{className:f,trackObserver:g}=D.useMemo(()=>RL(e),[e.participant.sid??e.participant.identity,e.source,Yp(e)&&e.publication.trackSid]);return D.useEffect(()=>{const p=g.subscribe(x=>{kr.debug("update track",x),i(x),s(x==null?void 0:x.isMuted),a(x==null?void 0:x.isSubscribed),l(x==null?void 0:x.track)});return()=>p==null?void 0:p.unsubscribe()},[g]),D.useEffect(()=>{var p,x;return c&&(h.current&&c.detach(h.current),(p=t.element)!=null&&p.current&&!(e.participant.isLocal&&(c==null?void 0:c.kind)==="audio")&&c.attach(t.element.current)),h.current=(x=t.element)==null?void 0:x.current,()=>{h.current&&(c==null||c.detach(h.current))}},[c,t.element]),D.useEffect(()=>{var p,x;if(typeof((p=n==null?void 0:n.dimensions)==null?void 0:p.width)=="number"&&typeof((x=n==null?void 0:n.dimensions)==null?void 0:x.height)=="number"){const y=n.dimensions.width>n.dimensions.height?"landscape":"portrait";d(y)}},[n]),{publication:n,isMuted:r,isSubscribed:o,track:c,elementProps:Mw(t.props,{className:f,"data-lk-local-participant":e.participant.isLocal,"data-lk-source":n==null?void 0:n.source,...(n==null?void 0:n.kind)==="video"&&{"data-lk-orientation":u}})}}var fd,Uy;function YL(){if(Uy)return fd;Uy=1;var e="Expected a function",t=NaN,n="[object Symbol]",i=/^\s+|\s+$/g,r=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,o=/^0o[0-7]+$/i,a=parseInt,c=typeof $a=="object"&&$a&&$a.Object===Object&&$a,l=typeof self=="object"&&self&&self.Object===Object&&self,u=c||l||Function("return this")(),d=Object.prototype,h=d.toString,f=Math.max,g=Math.min,p=function(){return u.Date.now()};function x(v,k,_){var T,I,b,A,P,B,L=0,V=!1,J=!1,re=!0;if(typeof v!="function")throw new TypeError(e);k=S(k)||0,y(_)&&(V=!!_.leading,J="maxWait"in _,b=J?f(S(_.maxWait)||0,k):b,re="trailing"in _?!!_.trailing:re);function G(ee){var te=T,ue=I;return T=I=void 0,L=ee,A=v.apply(ue,te),A}function Q(ee){return L=ee,P=setTimeout(X,k),V?G(ee):A}function C(ee){var te=ee-B,ue=ee-L,me=k-te;return J?g(me,b-ue):me}function K(ee){var te=ee-B,ue=ee-L;return B===void 0||te>=k||te<0||J&&ue>=b}function X(){var ee=p();if(K(ee))return R(ee);P=setTimeout(X,C(ee))}function R(ee){return P=void 0,re&&T?G(ee):(T=I=void 0,A)}function ae(){P!==void 0&&clearTimeout(P),L=0,T=B=I=P=void 0}function he(){return P===void 0?A:R(p())}function ce(){var ee=p(),te=K(ee);if(T=arguments,I=this,B=ee,te){if(P===void 0)return Q(B);if(J)return P=setTimeout(X,k),G(B)}return P===void 0&&(P=setTimeout(X,k)),A}return ce.cancel=ae,ce.flush=he,ce}function y(v){var k=typeof v;return!!v&&(k=="object"||k=="function")}function E(v){return!!v&&typeof v=="object"}function w(v){return typeof v=="symbol"||E(v)&&h.call(v)==n}function S(v){if(typeof v=="number")return v;if(w(v))return t;if(y(v)){var k=typeof v.valueOf=="function"?v.valueOf():v;v=y(k)?k+"":k}if(typeof v!="string")return v===0?v:+v;v=v.replace(i,"");var _=s.test(v);return _||o.test(v)?a(v.slice(2),_?2:8):r.test(v)?t:+v}return fd=x,fd}var JL=YL();const jy=ew(JL);function XL(e){const t=M.useRef(e);t.current=e,M.useEffect(()=>()=>{t.current()},[])}function ZL(e,t=500,n){const i=M.useRef();XL(()=>{i.current&&i.current.cancel()});const r=M.useMemo(()=>{const s=jy(e,t,n),o=(...a)=>s(...a);return o.cancel=()=>{s.cancel()},o.isPending=()=>!!i.current,o.flush=()=>s.flush(),o},[e,t,n]);return M.useEffect(()=>{i.current=jy(e,t,n)},[e,t,n]),r}function $L(e,t,n){const i=((l,u)=>l===u),r=e instanceof Function?e():e,[s,o]=M.useState(r),a=M.useRef(r),c=ZL(o,t,n);return i(a.current,r)||(c(r),a.current=r),[s,c]}function eB({threshold:e=0,root:t=null,rootMargin:n="0%",freezeOnceVisible:i=!1,initialIsIntersecting:r=!1,onChange:s}={}){var o;const[a,c]=M.useState(null),[l,u]=M.useState(()=>({isIntersecting:r,entry:void 0})),d=M.useRef();d.current=s;const h=((o=l.entry)==null?void 0:o.isIntersecting)&&i;M.useEffect(()=>{if(!a||!("IntersectionObserver"in window)||h)return;const p=new IntersectionObserver(x=>{const y=Array.isArray(p.thresholds)?p.thresholds:[p.thresholds];x.forEach(E=>{const w=E.isIntersecting&&y.some(S=>E.intersectionRatio>=S);u({isIntersecting:w,entry:E}),d.current&&d.current(w,E)})},{threshold:e,root:t,rootMargin:n});return p.observe(a),()=>{p.disconnect()}},[a,JSON.stringify(e),t,n,h,i]);const f=M.useRef(null);M.useEffect(()=>{var p;!a&&(p=l.entry)!=null&&p.target&&!i&&!h&&f.current!==l.entry.target&&(f.current=l.entry.target,u({isIntersecting:r,entry:void 0}))},[a,l.entry,i,h,r]);const g=[c,!!l.isIntersecting,l.entry];return g.ref=g[0],g.isIntersecting=g[1],g.entry=g[2],g}const Jl=D.forwardRef(function({onTrackClick:e,onClick:t,onSubscriptionStatusChanged:n,trackRef:i,manageSubscription:r,...s},o){const a=Rw(i),c=D.useRef(null);D.useImperativeHandle(o,()=>c.current);const l=eB({root:c.current}),[u]=$L(l,3e3);D.useEffect(()=>{r&&a.publication instanceof ll&&(u==null?void 0:u.isIntersecting)===!1&&(l==null?void 0:l.isIntersecting)===!1&&a.publication.setSubscribed(!1)},[u,a,r]),D.useEffect(()=>{r&&a.publication instanceof ll&&(l==null?void 0:l.isIntersecting)===!0&&a.publication.setSubscribed(!0)},[l,a,r]);const{elementProps:d,publication:h,isSubscribed:f}=Ow(a,{element:c,props:s});D.useEffect(()=>{n==null||n(!!f)},[f,n]);const g=p=>{t==null||t(p),e==null||e({participant:a==null?void 0:a.participant,track:h})};return D.createElement("video",{ref:c,...d,muted:!0,onClick:g})}),Dw=D.forwardRef(function({trackRef:e,onSubscriptionStatusChanged:t,volume:n,...i},r){const s=Rw(e),o=D.useRef(null);D.useImperativeHandle(r,()=>o.current);const{elementProps:a,isSubscribed:c,track:l,publication:u}=Ow(s,{element:o,props:i});return D.useEffect(()=>{t==null||t(!!c)},[c,t]),D.useEffect(()=>{l===void 0||n===void 0||(l instanceof mk?l.setVolume(n):kr.warn("Volume can only be set on remote audio tracks."))},[n,l]),D.useEffect(()=>{u===void 0||i.muted===void 0||(u instanceof ll?u.setEnabled(!i.muted):kr.warn("Can only call setEnabled on remote track publications."))},[i.muted,u,l]),D.createElement("audio",{ref:o,...a})});function tB({room:e,volume:t,muted:n}){const i=Pw([z.Source.Microphone,z.Source.ScreenShareAudio,z.Source.Unknown],{updateOnlyOn:[],onlySubscribed:!0,room:e}).filter(r=>!r.participant.isLocal&&r.publication.kind===z.Kind.Audio);return D.createElement("div",{style:{display:"none"}},i.map(r=>D.createElement(Dw,{key:wL(r),trackRef:r,volume:t,muted:n})))}const nB=e=>{const t=[];for(let n=0;n<e;n++)t.push([n,e-1-n]);return t},Vy=e=>[[Math.floor(e/2)],[-1]],iB=(e,t,n)=>{const[i,r]=M.useState(0),[s,o]=M.useState([[]]);M.useEffect(()=>{if(e==="thinking")o(Vy(t));else if(e==="connecting"||e==="initializing"){const c=[...nB(t)];o(c)}else o(e==="listening"?Vy(t):e===void 0||e==="speaking"?[new Array(t).fill(0).map((c,l)=>l)]:[[]]);r(0)},[e,t]);const a=M.useRef(null);return M.useEffect(()=>{let c=performance.now();const l=u=>{u-c>=n&&(r(d=>d+1),c=u),a.current=requestAnimationFrame(l)};return a.current=requestAnimationFrame(l),()=>{a.current!==null&&cancelAnimationFrame(a.current)}},[n,t,e,s.length]),s[i%s.length]},rB=new Map([["connecting",2e3],["initializing",2e3],["listening",500],["thinking",150]]),sB=(e,t)=>{if(e===void 0)return 1e3;let n=rB.get(e);if(n)switch(e){case"connecting":n/=t;break}return n},Lw=D.forwardRef(function({state:e,options:t,barCount:n=15,trackRef:i,track:r,children:s,...o},a){const c=Mw(o,{className:"lk-audio-bar-visualizer"});let l=Aw();(i||r)&&(l=i||r);const u=WL(l,{bands:n,loPass:100,hiPass:200}),d=(t==null?void 0:t.minHeight)??20,h=(t==null?void 0:t.maxHeight)??100,f=iB(e,n,sB(e,n)??100);return D.createElement("div",{ref:a,...c,"data-lk-va-state":e},u.map((g,p)=>s?UL(s,{"data-lk-highlighted":f.includes(p),"data-lk-bar-index":p,className:"lk-audio-bar",style:{height:`${Math.min(h,Math.max(d,g*100+5))}%`}}):D.createElement("span",{key:p,"data-lk-highlighted":f.includes(p),"data-lk-bar-index":p,className:`lk-audio-bar ${f.includes(p)&&"lk-highlighted"}`,style:{height:`${Math.min(h,Math.max(d,g*100+5))}%`}})))});function oB(e){const[t,n]=M.useState(()=>e.getLocalParticipant()),[i,r]=M.useState(()=>e.getMicrophoneTrack());return M.useEffect(()=>{const s=()=>{const a=e.getLocalParticipant(),c=e.getMicrophoneTrack();n(a),r(c)};s(),e.on("connection.connected",s),e.on("connection.disconnected",s),e.on("track.muted",s),e.on("track.unmuted",s);const o=e.getRoom();if(o){const a=()=>{s()},c=()=>{s()};return o.on("localTrackPublished",a),o.on("localTrackUnpublished",c),()=>{e.off("connection.connected",s),e.off("connection.disconnected",s),e.off("track.muted",s),e.off("track.unmuted",s),o.off("localTrackPublished",a),o.off("localTrackUnpublished",c)}}else return()=>{e.off("connection.connected",s),e.off("connection.disconnected",s),e.off("track.muted",s),e.off("track.unmuted",s)}},[e]),{localParticipant:t,microphoneTrack:i}}function Vc(e,t,n){const[i,r]=M.useState(!1),[s,o]=M.useState(!1);return M.useEffect(()=>{const c=()=>{let l=!1;switch(t){case"microphone":l=e.isMicrophoneEnabled;break;case"camera":l=e.isCameraEnabled;break;case"screenShare":l=e.isScreenShareEnabled;break}r(l)};return c(),e.on("track.muted",c),e.on("track.unmuted",c),e.on("connection.connected",c),()=>{e.off("track.muted",c),e.off("track.unmuted",c),e.off("connection.connected",c)}},[e,t]),{enabled:i,pending:s,toggle:async c=>{try{o(!0);const l=c!==void 0?c:!i;switch(t){case"microphone":await e.toggleMicrophone(l);break;case"camera":await e.toggleCamera(l);break;case"screenShare":l?await e.startScreenShare():await e.stopScreenShare();break}}catch{}finally{o(!1)}}}}function aB(e){const[t,n]=M.useState(()=>e.getRoom()),[i,r]=M.useState(()=>e.getConnectionState());return M.useEffect(()=>{const s=()=>{n(e.getRoom()),r(e.getConnectionState())};return e.on("connection.connected",s),e.on("connection.disconnected",s),e.on("connection.connecting",s),()=>{e.off("connection.connected",s),e.off("connection.disconnected",s),e.off("connection.connecting",s)}},[e]),t}function Zp(e){const[t,n]=M.useState(()=>e.getIsAgentConnected()),[i,r]=M.useState(()=>e.getCurrentSession()),[s,o]=M.useState(()=>e.getCurrentAgentInfo()),[a,c]=M.useState(()=>e.getAgentState()),[l,u]=M.useState(()=>e.getAgentAudioTrack()),[d,h]=M.useState(()=>e.getAgentVideoTrack());return M.useEffect(()=>{const f=()=>{const S=e.getIsAgentConnected(),v=e.getCurrentSession(),k=e.getCurrentAgentInfo(),_=e.getAgentState(),T=e.getAgentAudioTrack(),I=e.getAgentVideoTrack();n(S),r(v),o(k),c(_),u(T),h(I)};f();const g=()=>{f()},p=()=>{f()},x=()=>{f()},y=()=>{f()},E=()=>{f()},w=()=>{f()};return e.on("agent.connected",g),e.on("agent.speaking",g),e.on("agent.thinking",g),e.on("agent.state.changed",E),e.on("connection.disconnected",p),e.on("session.created",x),e.on("session.ended",x),e.on("session.state.changed",x),e.on("connection.connected",y),e.on("media.track.subscribed",w),e.on("media.track.unsubscribed",w),()=>{e.off("agent.connected",g),e.off("agent.speaking",g),e.off("agent.thinking",g),e.off("agent.state.changed",E),e.off("connection.disconnected",p),e.off("session.created",x),e.off("session.ended",x),e.off("session.state.changed",x),e.off("connection.connected",y),e.off("media.track.subscribed",w),e.off("media.track.unsubscribed",w)}},[e]),{agent:{isActive:t,info:s},session:i,state:a,audioTrack:l,videoTrack:d}}function cB(e){const[t,n]=M.useState(()=>e.getVideoTrackRefs()),[i,r]=M.useState(()=>e.getCameraTrackRefs()),[s,o]=M.useState(()=>e.getScreenShareTrackRefs());return M.useEffect(()=>{const a=()=>{const l=e.getVideoTrackRefs(),u=e.getCameraTrackRefs(),d=e.getScreenShareTrackRefs();n(l),r(u),o(d)};a(),e.on("connection.connected",a),e.on("connection.disconnected",a),e.on("track.muted",a),e.on("track.unmuted",a),e.on("participant.joined",a),e.on("participant.left",a);const c=e.getRoom();if(c){const l=()=>{a()};return c.on("localTrackPublished",l),c.on("localTrackUnpublished",l),c.on("trackPublished",l),c.on("trackUnpublished",l),c.on("trackSubscribed",l),c.on("trackUnsubscribed",l),()=>{e.off("connection.connected",a),e.off("connection.disconnected",a),e.off("track.muted",a),e.off("track.unmuted",a),e.off("participant.joined",a),e.off("participant.left",a),c.off("localTrackPublished",l),c.off("localTrackUnpublished",l),c.off("trackPublished",l),c.off("trackUnpublished",l),c.off("trackSubscribed",l),c.off("trackUnsubscribed",l)}}else return()=>{e.off("connection.connected",a),e.off("connection.disconnected",a),e.off("track.muted",a),e.off("track.unmuted",a),e.off("participant.joined",a),e.off("participant.left",a)}},[e]),{videoTrackRefs:t,cameraTrackRefs:i,screenShareTrackRefs:s}}const $p="-",lB=e=>{const t=dB(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:i}=e;return{getClassGroupId:o=>{const a=o.split($p);return a[0]===""&&a.length!==1&&a.shift(),Bw(a,t)||uB(o)},getConflictingClassGroupIds:(o,a)=>{const c=n[o]||[];return a&&i[o]?[...c,...i[o]]:c}}},Bw=(e,t)=>{var o;if(e.length===0)return t.classGroupId;const n=e[0],i=t.nextPart.get(n),r=i?Bw(e.slice(1),i):void 0;if(r)return r;if(t.validators.length===0)return;const s=e.join($p);return(o=t.validators.find(({validator:a})=>a(s)))==null?void 0:o.classGroupId},zy=/^\[(.+)\]$/,uB=e=>{if(zy.test(e)){const t=zy.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},dB=e=>{const{theme:t,classGroups:n}=e,i={nextPart:new Map,validators:[]};for(const r in n)sf(n[r],i,r,t);return i},sf=(e,t,n,i)=>{e.forEach(r=>{if(typeof r=="string"){const s=r===""?t:Gy(t,r);s.classGroupId=n;return}if(typeof r=="function"){if(hB(r)){sf(r(i),t,n,i);return}t.validators.push({validator:r,classGroupId:n});return}Object.entries(r).forEach(([s,o])=>{sf(o,Gy(t,s),n,i)})})},Gy=(e,t)=>{let n=e;return t.split($p).forEach(i=>{n.nextPart.has(i)||n.nextPart.set(i,{nextPart:new Map,validators:[]}),n=n.nextPart.get(i)}),n},hB=e=>e.isThemeGetter,fB=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,i=new Map;const r=(s,o)=>{n.set(s,o),t++,t>e&&(t=0,i=n,n=new Map)};return{get(s){let o=n.get(s);if(o!==void 0)return o;if((o=i.get(s))!==void 0)return r(s,o),o},set(s,o){n.has(s)?n.set(s,o):r(s,o)}}},of="!",af=":",pB=af.length,mB=e=>{const{prefix:t,experimentalParseClassName:n}=e;let i=r=>{const s=[];let o=0,a=0,c=0,l;for(let g=0;g<r.length;g++){let p=r[g];if(o===0&&a===0){if(p===af){s.push(r.slice(c,g)),c=g+pB;continue}if(p==="/"){l=g;continue}}p==="["?o++:p==="]"?o--:p==="("?a++:p===")"&&a--}const u=s.length===0?r:r.substring(c),d=gB(u),h=d!==u,f=l&&l>c?l-c:void 0;return{modifiers:s,hasImportantModifier:h,baseClassName:d,maybePostfixModifierPosition:f}};if(t){const r=t+af,s=i;i=o=>o.startsWith(r)?s(o.substring(r.length)):{isExternal:!0,modifiers:[],hasImportantModifier:!1,baseClassName:o,maybePostfixModifierPosition:void 0}}if(n){const r=i;i=s=>n({className:s,parseClassName:r})}return i},gB=e=>e.endsWith(of)?e.substring(0,e.length-1):e.startsWith(of)?e.substring(1):e,bB=e=>{const t=Object.fromEntries(e.orderSensitiveModifiers.map(i=>[i,!0]));return i=>{if(i.length<=1)return i;const r=[];let s=[];return i.forEach(o=>{o[0]==="["||t[o]?(r.push(...s.sort(),o),s=[]):s.push(o)}),r.push(...s.sort()),r}},yB=e=>({cache:fB(e.cacheSize),parseClassName:mB(e),sortModifiers:bB(e),...lB(e)}),vB=/\s+/,xB=(e,t)=>{const{parseClassName:n,getClassGroupId:i,getConflictingClassGroupIds:r,sortModifiers:s}=t,o=[],a=e.trim().split(vB);let c="";for(let l=a.length-1;l>=0;l-=1){const u=a[l],{isExternal:d,modifiers:h,hasImportantModifier:f,baseClassName:g,maybePostfixModifierPosition:p}=n(u);if(d){c=u+(c.length>0?" "+c:c);continue}let x=!!p,y=i(x?g.substring(0,p):g);if(!y){if(!x){c=u+(c.length>0?" "+c:c);continue}if(y=i(g),!y){c=u+(c.length>0?" "+c:c);continue}x=!1}const E=s(h).join(":"),w=f?E+of:E,S=w+y;if(o.includes(S))continue;o.push(S);const v=r(y,x);for(let k=0;k<v.length;++k){const _=v[k];o.push(w+_)}c=u+(c.length>0?" "+c:c)}return c};function SB(){let e=0,t,n,i="";for(;e<arguments.length;)(t=arguments[e++])&&(n=Fw(t))&&(i&&(i+=" "),i+=n);return i}const Fw=e=>{if(typeof e=="string")return e;let t,n="";for(let i=0;i<e.length;i++)e[i]&&(t=Fw(e[i]))&&(n&&(n+=" "),n+=t);return n};function kB(e,...t){let n,i,r,s=o;function o(c){const l=t.reduce((u,d)=>d(u),e());return n=yB(l),i=n.cache.get,r=n.cache.set,s=a,a(c)}function a(c){const l=i(c);if(l)return l;const u=xB(c,n);return r(c,u),u}return function(){return s(SB.apply(null,arguments))}}const Jt=e=>{const t=n=>n[e]||[];return t.isThemeGetter=!0,t},Uw=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,jw=/^\((?:(\w[\w-]*):)?(.+)\)$/i,EB=/^\d+\/\d+$/,wB=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,CB=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,TB=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,AB=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,RB=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,fs=e=>EB.test(e),qe=e=>!!e&&!Number.isNaN(Number(e)),or=e=>!!e&&Number.isInteger(Number(e)),pd=e=>e.endsWith("%")&&qe(e.slice(0,-1)),Pi=e=>wB.test(e),_B=()=>!0,IB=e=>CB.test(e)&&!TB.test(e),Vw=()=>!1,NB=e=>AB.test(e),MB=e=>RB.test(e),PB=e=>!Se(e)&&!ke(e),OB=e=>co(e,Hw,Vw),Se=e=>Uw.test(e),Dr=e=>co(e,Kw,IB),md=e=>co(e,UB,qe),Hy=e=>co(e,zw,Vw),DB=e=>co(e,Gw,MB),nc=e=>co(e,Ww,NB),ke=e=>jw.test(e),Ro=e=>lo(e,Kw),LB=e=>lo(e,jB),Ky=e=>lo(e,zw),BB=e=>lo(e,Hw),FB=e=>lo(e,Gw),ic=e=>lo(e,Ww,!0),co=(e,t,n)=>{const i=Uw.exec(e);return i?i[1]?t(i[1]):n(i[2]):!1},lo=(e,t,n=!1)=>{const i=jw.exec(e);return i?i[1]?t(i[1]):n:!1},zw=e=>e==="position"||e==="percentage",Gw=e=>e==="image"||e==="url",Hw=e=>e==="length"||e==="size"||e==="bg-size",Kw=e=>e==="length",UB=e=>e==="number",jB=e=>e==="family-name",Ww=e=>e==="shadow",VB=()=>{const e=Jt("color"),t=Jt("font"),n=Jt("text"),i=Jt("font-weight"),r=Jt("tracking"),s=Jt("leading"),o=Jt("breakpoint"),a=Jt("container"),c=Jt("spacing"),l=Jt("radius"),u=Jt("shadow"),d=Jt("inset-shadow"),h=Jt("text-shadow"),f=Jt("drop-shadow"),g=Jt("blur"),p=Jt("perspective"),x=Jt("aspect"),y=Jt("ease"),E=Jt("animate"),w=()=>["auto","avoid","all","avoid-page","page","left","right","column"],S=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],v=()=>[...S(),ke,Se],k=()=>["auto","hidden","clip","visible","scroll"],_=()=>["auto","contain","none"],T=()=>[ke,Se,c],I=()=>[fs,"full","auto",...T()],b=()=>[or,"none","subgrid",ke,Se],A=()=>["auto",{span:["full",or,ke,Se]},or,ke,Se],P=()=>[or,"auto",ke,Se],B=()=>["auto","min","max","fr",ke,Se],L=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],V=()=>["start","end","center","stretch","center-safe","end-safe"],J=()=>["auto",...T()],re=()=>[fs,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...T()],G=()=>[e,ke,Se],Q=()=>[...S(),Ky,Hy,{position:[ke,Se]}],C=()=>["no-repeat",{repeat:["","x","y","space","round"]}],K=()=>["auto","cover","contain",BB,OB,{size:[ke,Se]}],X=()=>[pd,Ro,Dr],R=()=>["","none","full",l,ke,Se],ae=()=>["",qe,Ro,Dr],he=()=>["solid","dashed","dotted","double"],ce=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ee=()=>[qe,pd,Ky,Hy],te=()=>["","none",g,ke,Se],ue=()=>["none",qe,ke,Se],me=()=>["none",qe,ke,Se],Me=()=>[qe,ke,Se],ne=()=>[fs,"full",...T()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Pi],breakpoint:[Pi],color:[_B],container:[Pi],"drop-shadow":[Pi],ease:["in","out","in-out"],font:[PB],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Pi],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Pi],shadow:[Pi],spacing:["px",qe],text:[Pi],"text-shadow":[Pi],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",fs,Se,ke,x]}],container:["container"],columns:[{columns:[qe,Se,ke,a]}],"break-after":[{"break-after":w()}],"break-before":[{"break-before":w()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:v()}],overflow:[{overflow:k()}],"overflow-x":[{"overflow-x":k()}],"overflow-y":[{"overflow-y":k()}],overscroll:[{overscroll:_()}],"overscroll-x":[{"overscroll-x":_()}],"overscroll-y":[{"overscroll-y":_()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:I()}],"inset-x":[{"inset-x":I()}],"inset-y":[{"inset-y":I()}],start:[{start:I()}],end:[{end:I()}],top:[{top:I()}],right:[{right:I()}],bottom:[{bottom:I()}],left:[{left:I()}],visibility:["visible","invisible","collapse"],z:[{z:[or,"auto",ke,Se]}],basis:[{basis:[fs,"full","auto",a,...T()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[qe,fs,"auto","initial","none",Se]}],grow:[{grow:["",qe,ke,Se]}],shrink:[{shrink:["",qe,ke,Se]}],order:[{order:[or,"first","last","none",ke,Se]}],"grid-cols":[{"grid-cols":b()}],"col-start-end":[{col:A()}],"col-start":[{"col-start":P()}],"col-end":[{"col-end":P()}],"grid-rows":[{"grid-rows":b()}],"row-start-end":[{row:A()}],"row-start":[{"row-start":P()}],"row-end":[{"row-end":P()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":B()}],"auto-rows":[{"auto-rows":B()}],gap:[{gap:T()}],"gap-x":[{"gap-x":T()}],"gap-y":[{"gap-y":T()}],"justify-content":[{justify:[...L(),"normal"]}],"justify-items":[{"justify-items":[...V(),"normal"]}],"justify-self":[{"justify-self":["auto",...V()]}],"align-content":[{content:["normal",...L()]}],"align-items":[{items:[...V(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...V(),{baseline:["","last"]}]}],"place-content":[{"place-content":L()}],"place-items":[{"place-items":[...V(),"baseline"]}],"place-self":[{"place-self":["auto",...V()]}],p:[{p:T()}],px:[{px:T()}],py:[{py:T()}],ps:[{ps:T()}],pe:[{pe:T()}],pt:[{pt:T()}],pr:[{pr:T()}],pb:[{pb:T()}],pl:[{pl:T()}],m:[{m:J()}],mx:[{mx:J()}],my:[{my:J()}],ms:[{ms:J()}],me:[{me:J()}],mt:[{mt:J()}],mr:[{mr:J()}],mb:[{mb:J()}],ml:[{ml:J()}],"space-x":[{"space-x":T()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":T()}],"space-y-reverse":["space-y-reverse"],size:[{size:re()}],w:[{w:[a,"screen",...re()]}],"min-w":[{"min-w":[a,"screen","none",...re()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[o]},...re()]}],h:[{h:["screen","lh",...re()]}],"min-h":[{"min-h":["screen","lh","none",...re()]}],"max-h":[{"max-h":["screen","lh",...re()]}],"font-size":[{text:["base",n,Ro,Dr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[i,ke,md]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",pd,Se]}],"font-family":[{font:[LB,Se,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,ke,Se]}],"line-clamp":[{"line-clamp":[qe,"none",ke,md]}],leading:[{leading:[s,...T()]}],"list-image":[{"list-image":["none",ke,Se]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",ke,Se]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:G()}],"text-color":[{text:G()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[qe,"from-font","auto",ke,Dr]}],"text-decoration-color":[{decoration:G()}],"underline-offset":[{"underline-offset":[qe,"auto",ke,Se]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:T()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",ke,Se]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",ke,Se]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:Q()}],"bg-repeat":[{bg:C()}],"bg-size":[{bg:K()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},or,ke,Se],radial:["",ke,Se],conic:[or,ke,Se]},FB,DB]}],"bg-color":[{bg:G()}],"gradient-from-pos":[{from:X()}],"gradient-via-pos":[{via:X()}],"gradient-to-pos":[{to:X()}],"gradient-from":[{from:G()}],"gradient-via":[{via:G()}],"gradient-to":[{to:G()}],rounded:[{rounded:R()}],"rounded-s":[{"rounded-s":R()}],"rounded-e":[{"rounded-e":R()}],"rounded-t":[{"rounded-t":R()}],"rounded-r":[{"rounded-r":R()}],"rounded-b":[{"rounded-b":R()}],"rounded-l":[{"rounded-l":R()}],"rounded-ss":[{"rounded-ss":R()}],"rounded-se":[{"rounded-se":R()}],"rounded-ee":[{"rounded-ee":R()}],"rounded-es":[{"rounded-es":R()}],"rounded-tl":[{"rounded-tl":R()}],"rounded-tr":[{"rounded-tr":R()}],"rounded-br":[{"rounded-br":R()}],"rounded-bl":[{"rounded-bl":R()}],"border-w":[{border:ae()}],"border-w-x":[{"border-x":ae()}],"border-w-y":[{"border-y":ae()}],"border-w-s":[{"border-s":ae()}],"border-w-e":[{"border-e":ae()}],"border-w-t":[{"border-t":ae()}],"border-w-r":[{"border-r":ae()}],"border-w-b":[{"border-b":ae()}],"border-w-l":[{"border-l":ae()}],"divide-x":[{"divide-x":ae()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":ae()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:G()}],"border-color-x":[{"border-x":G()}],"border-color-y":[{"border-y":G()}],"border-color-s":[{"border-s":G()}],"border-color-e":[{"border-e":G()}],"border-color-t":[{"border-t":G()}],"border-color-r":[{"border-r":G()}],"border-color-b":[{"border-b":G()}],"border-color-l":[{"border-l":G()}],"divide-color":[{divide:G()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[qe,ke,Se]}],"outline-w":[{outline:["",qe,Ro,Dr]}],"outline-color":[{outline:G()}],shadow:[{shadow:["","none",u,ic,nc]}],"shadow-color":[{shadow:G()}],"inset-shadow":[{"inset-shadow":["none",d,ic,nc]}],"inset-shadow-color":[{"inset-shadow":G()}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:G()}],"ring-offset-w":[{"ring-offset":[qe,Dr]}],"ring-offset-color":[{"ring-offset":G()}],"inset-ring-w":[{"inset-ring":ae()}],"inset-ring-color":[{"inset-ring":G()}],"text-shadow":[{"text-shadow":["none",h,ic,nc]}],"text-shadow-color":[{"text-shadow":G()}],opacity:[{opacity:[qe,ke,Se]}],"mix-blend":[{"mix-blend":[...ce(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ce()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[qe]}],"mask-image-linear-from-pos":[{"mask-linear-from":ee()}],"mask-image-linear-to-pos":[{"mask-linear-to":ee()}],"mask-image-linear-from-color":[{"mask-linear-from":G()}],"mask-image-linear-to-color":[{"mask-linear-to":G()}],"mask-image-t-from-pos":[{"mask-t-from":ee()}],"mask-image-t-to-pos":[{"mask-t-to":ee()}],"mask-image-t-from-color":[{"mask-t-from":G()}],"mask-image-t-to-color":[{"mask-t-to":G()}],"mask-image-r-from-pos":[{"mask-r-from":ee()}],"mask-image-r-to-pos":[{"mask-r-to":ee()}],"mask-image-r-from-color":[{"mask-r-from":G()}],"mask-image-r-to-color":[{"mask-r-to":G()}],"mask-image-b-from-pos":[{"mask-b-from":ee()}],"mask-image-b-to-pos":[{"mask-b-to":ee()}],"mask-image-b-from-color":[{"mask-b-from":G()}],"mask-image-b-to-color":[{"mask-b-to":G()}],"mask-image-l-from-pos":[{"mask-l-from":ee()}],"mask-image-l-to-pos":[{"mask-l-to":ee()}],"mask-image-l-from-color":[{"mask-l-from":G()}],"mask-image-l-to-color":[{"mask-l-to":G()}],"mask-image-x-from-pos":[{"mask-x-from":ee()}],"mask-image-x-to-pos":[{"mask-x-to":ee()}],"mask-image-x-from-color":[{"mask-x-from":G()}],"mask-image-x-to-color":[{"mask-x-to":G()}],"mask-image-y-from-pos":[{"mask-y-from":ee()}],"mask-image-y-to-pos":[{"mask-y-to":ee()}],"mask-image-y-from-color":[{"mask-y-from":G()}],"mask-image-y-to-color":[{"mask-y-to":G()}],"mask-image-radial":[{"mask-radial":[ke,Se]}],"mask-image-radial-from-pos":[{"mask-radial-from":ee()}],"mask-image-radial-to-pos":[{"mask-radial-to":ee()}],"mask-image-radial-from-color":[{"mask-radial-from":G()}],"mask-image-radial-to-color":[{"mask-radial-to":G()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":S()}],"mask-image-conic-pos":[{"mask-conic":[qe]}],"mask-image-conic-from-pos":[{"mask-conic-from":ee()}],"mask-image-conic-to-pos":[{"mask-conic-to":ee()}],"mask-image-conic-from-color":[{"mask-conic-from":G()}],"mask-image-conic-to-color":[{"mask-conic-to":G()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:Q()}],"mask-repeat":[{mask:C()}],"mask-size":[{mask:K()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",ke,Se]}],filter:[{filter:["","none",ke,Se]}],blur:[{blur:te()}],brightness:[{brightness:[qe,ke,Se]}],contrast:[{contrast:[qe,ke,Se]}],"drop-shadow":[{"drop-shadow":["","none",f,ic,nc]}],"drop-shadow-color":[{"drop-shadow":G()}],grayscale:[{grayscale:["",qe,ke,Se]}],"hue-rotate":[{"hue-rotate":[qe,ke,Se]}],invert:[{invert:["",qe,ke,Se]}],saturate:[{saturate:[qe,ke,Se]}],sepia:[{sepia:["",qe,ke,Se]}],"backdrop-filter":[{"backdrop-filter":["","none",ke,Se]}],"backdrop-blur":[{"backdrop-blur":te()}],"backdrop-brightness":[{"backdrop-brightness":[qe,ke,Se]}],"backdrop-contrast":[{"backdrop-contrast":[qe,ke,Se]}],"backdrop-grayscale":[{"backdrop-grayscale":["",qe,ke,Se]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[qe,ke,Se]}],"backdrop-invert":[{"backdrop-invert":["",qe,ke,Se]}],"backdrop-opacity":[{"backdrop-opacity":[qe,ke,Se]}],"backdrop-saturate":[{"backdrop-saturate":[qe,ke,Se]}],"backdrop-sepia":[{"backdrop-sepia":["",qe,ke,Se]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":T()}],"border-spacing-x":[{"border-spacing-x":T()}],"border-spacing-y":[{"border-spacing-y":T()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",ke,Se]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[qe,"initial",ke,Se]}],ease:[{ease:["linear","initial",y,ke,Se]}],delay:[{delay:[qe,ke,Se]}],animate:[{animate:["none",E,ke,Se]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,ke,Se]}],"perspective-origin":[{"perspective-origin":v()}],rotate:[{rotate:ue()}],"rotate-x":[{"rotate-x":ue()}],"rotate-y":[{"rotate-y":ue()}],"rotate-z":[{"rotate-z":ue()}],scale:[{scale:me()}],"scale-x":[{"scale-x":me()}],"scale-y":[{"scale-y":me()}],"scale-z":[{"scale-z":me()}],"scale-3d":["scale-3d"],skew:[{skew:Me()}],"skew-x":[{"skew-x":Me()}],"skew-y":[{"skew-y":Me()}],transform:[{transform:[ke,Se,"","none","gpu","cpu"]}],"transform-origin":[{origin:v()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ne()}],"translate-x":[{"translate-x":ne()}],"translate-y":[{"translate-y":ne()}],"translate-z":[{"translate-z":ne()}],"translate-none":["translate-none"],accent:[{accent:G()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:G()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",ke,Se]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":T()}],"scroll-mx":[{"scroll-mx":T()}],"scroll-my":[{"scroll-my":T()}],"scroll-ms":[{"scroll-ms":T()}],"scroll-me":[{"scroll-me":T()}],"scroll-mt":[{"scroll-mt":T()}],"scroll-mr":[{"scroll-mr":T()}],"scroll-mb":[{"scroll-mb":T()}],"scroll-ml":[{"scroll-ml":T()}],"scroll-p":[{"scroll-p":T()}],"scroll-px":[{"scroll-px":T()}],"scroll-py":[{"scroll-py":T()}],"scroll-ps":[{"scroll-ps":T()}],"scroll-pe":[{"scroll-pe":T()}],"scroll-pt":[{"scroll-pt":T()}],"scroll-pr":[{"scroll-pr":T()}],"scroll-pb":[{"scroll-pb":T()}],"scroll-pl":[{"scroll-pl":T()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",ke,Se]}],fill:[{fill:["none",...G()]}],"stroke-w":[{stroke:[qe,Ro,Dr,md]}],stroke:[{stroke:["none",...G()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},zB=kB(VB);function at(...e){return zB(jf.clsx(e))}function Xl(e){var r;if(!e)return{sessionSettings:{},capabilities:{},modality:"voice"};const t={session_timer:((r=e.session_settings)==null?void 0:r.session_timer)||null},n=e.capabilities||{},i=e.modality||"voice";return{sessionSettings:t,capabilities:n,modality:i}}function GB(e,t){return e.capabilities[t]===!0}function Zl(e){return e.sessionSettings.session_timer||null}function qw(e){const t=e.capabilities;return{userVideoEnabled:t.user_video_enabled!==!1,agentAvatarEnabled:t.agent_avatar_enabled!==!1,screenshareEnabled:t.screenshare_session_enabled!==!1}}function Qw(e){const t=e.capabilities;return{suggestedReplyEnabled:t.suggested_reply_enabled!==!1,attachmentsEnabled:t.support_in_chat_attachments!==!1}}function Yw(e){return{...e.capabilities}}function Jw(e){const t=Math.floor(e/60),n=e%60;return`${t}:${n.toString().padStart(2,"0")}`}const Xw=M.forwardRef(({state:e,audioTrack:t,className:n,theme:i="vox"},r)=>{const s=M.useRef(null),[o,a]=M.useState(!1);M.useEffect(()=>{s.current&&(console.log("🔊 AgentTile: Audio element created:",{autoplay:s.current.autoplay,muted:s.current.muted,volume:s.current.volume,readyState:s.current.readyState,paused:s.current.paused}),a(!0))},[t]),M.useEffect(()=>{const l=s.current;if(!l)return;const u=()=>console.log("▶️ AgentTile: Audio started playing"),d=()=>console.log("⏸️ AgentTile: Audio paused"),h=()=>console.log("⏹️ AgentTile: Audio ended"),f=x=>console.error("❌ AgentTile: Audio error:",x),g=()=>console.log("⏳ AgentTile: Audio load started"),p=()=>console.log("✅ AgentTile: Audio can play");return l.addEventListener("play",u),l.addEventListener("pause",d),l.addEventListener("ended",h),l.addEventListener("error",f),l.addEventListener("loadstart",g),l.addEventListener("canplay",p),()=>{l.removeEventListener("play",u),l.removeEventListener("pause",d),l.removeEventListener("ended",h),l.removeEventListener("error",f),l.removeEventListener("loadstart",g),l.removeEventListener("canplay",p)}},[o]);const c=M.useMemo(()=>i==="light"?{base:"bg-black/90",highlighted:"bg-black",muted:"bg-black/30"}:{base:"bg-white/90",highlighted:"bg-white",muted:"bg-white/30"},[i]);return m.jsxs("div",{ref:r,className:at("",n),children:[t&&m.jsxs(m.Fragment,{children:[m.jsx(Dw,{ref:s,trackRef:t,volume:1}),m.jsx(Lw,{barCount:5,state:e,options:{minHeight:5},trackRef:t,className:at("flex aspect-video w-40 items-center justify-center gap-1.5"),children:m.jsx("span",{className:at([`${c.base} min-h-2 w-2 rounded-full`,"origin-center transition-colors duration-250 ease-linear",`data-[lk-highlighted=true]:${c.highlighted}`,`data-[lk-muted=true]:${c.muted}`])})})]}),!t&&m.jsx("div",{className:at("flex aspect-video w-40 items-center justify-center"),children:m.jsx("div",{className:"flex flex-col items-center justify-center",children:m.jsx("div",{className:"flex gap-1.5",children:Array.from({length:5}).map((l,u)=>m.jsx("span",{className:at([`${c.base} min-h-2 w-2 rounded-full`,"origin-center transition-colors duration-250 ease-linear",e==="speaking"&&`animate-pulse ${c.highlighted}`,e==="thinking"&&`animate-pulse ${c.muted}`])},u))})})})]})});Xw.displayName="AgentTile";const HB=({videoTrack:e,className:t,ref:n})=>{var i,r;return!e||!e.publication||!e.participant?m.jsx("div",{ref:n,className:at(t),children:m.jsx("div",{className:"w-full h-full bg-gray-200 rounded-md flex items-center justify-center",children:m.jsx("span",{className:"text-gray-500",children:"No video available"})})}):m.jsx("div",{ref:n,className:at(t),children:m.jsx(Jl,{trackRef:e,width:((i=e.publication.dimensions)==null?void 0:i.width)??0,height:((r=e.publication.dimensions)==null?void 0:r.height)??0,className:"rounded-md"})})},KB=D.forwardRef(function({trackRef:t,className:n,...i},r){var s,o;return m.jsx("div",{ref:r,className:at("bg-muted overflow-hidden rounded-md",n),children:m.jsx(Jl,{trackRef:t,width:((s=t==null?void 0:t.publication.dimensions)==null?void 0:s.width)??0,height:((o=t==null?void 0:t.publication.dimensions)==null?void 0:o.height)??0,className:at("h-full w-auto"),...i})})}),Wy=Ve.create(KB),WB=Ve.create(Xw),qB=Ve.create(HB),Oi={initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},exit:{opacity:0,scale:0},transition:{type:"spring",stiffness:675,damping:75,mass:1}},ps={grid:["h-full w-full","grid gap-x-2 place-content-center","grid-cols-[1fr_1fr] grid-rows-[90px_1fr_90px]"],agentChatOpenWithSecondTile:["col-start-1 row-start-1","self-center justify-self-end"],agentChatOpenWithoutSecondTile:["col-start-1 row-start-1","col-span-2","place-content-center"],agentChatClosed:["col-start-1 row-start-1","col-span-2","place-content-center"],secondTileChatOpen:["col-start-2 row-start-1","self-center justify-self-start"],secondTileChatClosed:["col-start-2 row-start-3","place-content-end"]};function QB(e,t){const{localParticipant:n}=oB(t),i=n==null?void 0:n.getTrackPublication(e);return M.useMemo(()=>i&&n?{source:e,participant:n,publication:i}:void 0,[e,i,n])}function YB({chatOpen:e,client:t,theme:n="vox"}){const{agent:{isActive:i=!1}={},session:r,state:s="idle",audioTrack:o,videoTrack:a}=t?Zp(t):{agent:{isActive:!1},session:null,state:"idle",audioTrack:null,videoTrack:null},[c]=Pw([z.Source.ScreenShare]),l=QB(z.Source.Camera,t),u=l&&!l.publication.isMuted,d=c&&!c.publication.isMuted,h=u||d,f=i||r&&r.state==="active",g={...Oi.transition,delay:e?0:.15},p={...Oi.animate,scale:e?1:3,transition:g},x={...Oi.animate,transition:g},y=g,E=g,w=a&&a.publication&&a.participant;return m.jsx("div",{className:"relative w-full h-full z-10 flex items-center justify-center",children:m.jsx("div",{className:"relative w-full h-full max-w-2xl px-4 md:px-0",children:m.jsxs("div",{className:at(ps.grid),children:[f&&m.jsx("div",{className:at(["grid",!e&&ps.agentChatClosed,e&&h&&ps.agentChatOpenWithSecondTile,e&&!h&&ps.agentChatOpenWithoutSecondTile]),children:m.jsxs("div",{className:"h-full flex items-center justify-center",children:[!w&&m.jsx(WB,{layoutId:"agent",...Oi,animate:p,transition:y,state:s,audioTrack:o||void 0,theme:n,className:at(e?"h-[90px]":"h-auto w-full")},"agent"),w&&a&&m.jsx(qB,{layoutId:"avatar",...Oi,animate:x,transition:E,videoTrack:a,className:at(e?"h-[90px] [&>video]:h-[90px] [&>video]:w-auto":"h-auto w-full")},"avatar")]})}),m.jsx("div",{className:at(["grid",e&&ps.secondTileChatOpen,!e&&ps.secondTileChatClosed]),children:m.jsxs("div",{className:"w-full px-10 flex items-center shadow-2xl justify-between",children:[l&&u&&m.jsx(Wy,{layout:"position",layoutId:"camera",...Oi,trackRef:l,transition:{...Oi.transition,delay:e?0:.15},className:"h-[60px] order-1"},"camera"),d&&m.jsx(Wy,{layout:"position",layoutId:"screen",...Oi,trackRef:c,transition:{...Oi.transition,delay:e?0:.15},className:"h-[70px] order-2"},"screen")]})})]})})})}const JB={card:"text-gray-100 bg-gradient-to-b from-[#0a0a0a] via-[#121212] to-[#0a0a0a] border border-gray-800/50 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-2xl",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-40 z-10 bg-gradient-to-b from-black/90 via-black/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(75,85,99,0.08),transparent_50%)] opacity-100",cardPurpleBlur:"absolute top-0 left-1/2 -translate-x-1/2 w-[600px] h-[300px] bg-gradient-to-b from-gray-500/[0.12] via-gray-600/[0.06] to-transparent blur-3xl",cardPinkBlur:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[500px] h-[250px] bg-gradient-to-t from-gray-600/[0.08] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-center justify-between max-w-md mx-auto bg-gradient-to-b from-[#0a0a0a] via-[#121212] to-[#0a0a0a] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-gray-100 font-semibold",secondary:"text-gray-200",muted:"text-gray-400",accent:"text-transparent bg-clip-text bg-gradient-to-r from-gray-300 via-gray-200 to-gray-300"},micButton:"relative w-20 h-20 bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 rounded-3xl flex items-center justify-center hover:bg-gray-900 hover:border-gray-600 hover:scale-105 hover:shadow-2xl hover:shadow-gray-600/30 transition-all duration-500 ease-out group overflow-hidden",chatButton:"relative w-20 h-20 bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 rounded-3xl flex items-center justify-center hover:bg-gray-900 hover:border-gray-600 hover:scale-105 hover:shadow-2xl hover:shadow-gray-600/30 transition-all duration-500 ease-out group overflow-hidden",videoButton:"relative w-20 h-20 bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 rounded-3xl flex items-center justify-center hover:bg-gray-900 hover:border-gray-600 hover:scale-105 hover:shadow-2xl hover:shadow-gray-600/30 transition-all duration-500 ease-out group overflow-hidden",popupTrigger:"bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 text-gray-100 font-bold hover:bg-gray-900 hover:border-gray-600 hover:scale-[1.02] hover:shadow-2xl hover:shadow-gray-600/30 focus:outline-none focus:ring-2 focus:ring-gray-600 focus:ring-offset-2 focus:ring-offset-black transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-gray-900/60 backdrop-blur-xl rounded-2xl text-center text-gray-200 text-sm font-medium transition-all duration-700 ease-in-out border border-gray-700/50 shadow-xl",statusIndicator:"w-2.5 h-2.5 bg-gray-400 rounded-full animate-pulse shadow-lg shadow-gray-400/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-gray-800/50 rounded-3xl py-4 flex flex-col justify-end h-full bg-black/90 backdrop-blur-xl shadow-2xl",chatInput:{container:"bg-black/90 backdrop-blur-xl border-gray-800/50 shadow-xl",textarea:"bg-black/80 border border-gray-800/50 rounded-xl text-gray-100 placeholder-gray-500 font-medium px-4 py-3",sendButton:"bg-gray-900/90 hover:bg-gray-900 border-2 border-gray-700/50 hover:border-gray-600 disabled:border-gray-800 disabled:opacity-40 text-gray-100 font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-gray-600/30",attachButton:"text-gray-400 hover:text-gray-200 hover:bg-gray-700/30 transition-all duration-300 rounded-xl",endButton:"bg-red-600/90 hover:bg-red-600 border-2 border-red-500/40 hover:border-red-500/60 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-red-500/40"},chatMessage:{own:"bg-gray-800/70 text-gray-100 backdrop-blur-md shadow-lg border border-gray-700/50",other:"bg-gray-900/60 text-gray-100 border border-gray-700/50 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-gray-900/80 border-gray-700/50 backdrop-blur-xl shadow-xl",backButton:"text-gray-300 hover:text-gray-100 hover:bg-gray-700/30 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-gray-400 mb-2",suggestedResponse:{container:"bg-gray-900/70 text-gray-200 border-gray-700/50 backdrop-blur-md hover:bg-gray-800/80 hover:border-gray-600 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#0a0a0a] via-[#121212] to-[#0a0a0a] text-gray-100",header:"border-gray-700/50 bg-gray-900/80 backdrop-blur-xl shadow-xl",headerButton:"bg-gray-900/90 hover:bg-gray-900 border-2 border-gray-700/50 hover:border-gray-600 text-gray-100 hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-emerald-400 animate-pulse shadow-lg shadow-emerald-400/60",controlsBackground:"bg-gradient-to-t from-gray-900 via-gray-900/90 to-gray-900/60 backdrop-blur-xl border-t border-gray-700/50 shadow-2xl",controlEnabled:"bg-gray-900/90 hover:bg-gray-900 border-2 border-gray-700/50 hover:border-gray-600 text-gray-100 hover:scale-105 hover:shadow-xl hover:shadow-gray-600/30 transition-all duration-300 font-semibold",controlDisabled:"bg-gray-900/50 hover:bg-gray-900/60 text-gray-500 border border-gray-800 transition-all duration-300",endCall:"bg-red-600/90 hover:bg-red-600 border-2 border-red-500/50 hover:border-red-500/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-2xl hover:shadow-red-500/50",tile:"bg-gray-900/70 border border-gray-700/50 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-gray-900/60 text-gray-300",avatar:"bg-gray-800/80 text-gray-300 border-2 border-gray-700/50",nameOverlay:"bg-gradient-to-t from-gray-900 via-gray-900/80 to-transparent text-white backdrop-blur-sm font-bold",mutedIndicator:"bg-red-600 text-white shadow-xl shadow-red-500/40 font-semibold"}},XB={card:"text-gray-900 bg-gradient-to-b from-[#F8F9FC] via-[#FFFFFF] to-[#F8F9FC] border-[3px] border-indigo-200/60 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-2xl shadow-indigo-200/30",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-40 z-10 bg-gradient-to-b from-[#FFFFFF]/90 via-[#FFFFFF]/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(129,140,248,0.12),transparent_50%)] opacity-100",cardPurpleBlur:"absolute top-0 right-0 w-64 h-64 bg-gradient-to-br from-indigo-300/40 via-purple-300/25 to-transparent rounded-full blur-3xl animate-pulse-slow",cardPinkBlur:"absolute bottom-0 left-0 w-56 h-56 bg-gradient-to-tr from-blue-300/35 via-purple-200/20 to-transparent rounded-full blur-3xl",cardPulse1:"absolute top-4 right-4 w-8 h-8 bg-gradient-to-br from-indigo-400/30 to-purple-400/30 rounded-full blur-md opacity-60 animate-pulse",cardPulse2:"absolute bottom-6 left-6 w-6 h-6 bg-gradient-to-br from-blue-400/25 to-purple-400/25 rounded-full blur-md opacity-50 animate-pulse",main:"w-full justify-between flex flex-col items-center bg-gradient-to-b from-[#F8F9FC] via-[#FFFFFF] to-[#F8F9FC] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-gray-900 font-semibold",secondary:"text-gray-700",muted:"text-gray-500",accent:"text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 via-purple-600 to-blue-600"},micButton:"relative w-20 h-20 backdrop-blur-xl border-2 border-indigo-400/40 rounded-3xl flex items-center justify-center hover:from-indigo-700 hover:to-purple-700 hover:border-indigo-500/60 hover:scale-105 hover:shadow-2xl hover:shadow-indigo-500/40 transition-all duration-500 ease-out group overflow-hidden text-white",chatButton:"relative w-20 h-20 bg-gradient-to-br from-blue-600 to-cyan-600 backdrop-blur-xl border-2 border-blue-400/40 rounded-3xl flex items-center justify-center hover:from-blue-700 hover:to-cyan-700 hover:border-blue-500/60 hover:scale-105 hover:shadow-2xl hover:shadow-blue-500/40 transition-all duration-500 ease-out group overflow-hidden text-white",videoButton:"relative w-20 h-20 bg-gradient-to-br from-purple-600 to-pink-600 backdrop-blur-xl border-2 border-purple-400/40 rounded-3xl flex items-center justify-center hover:from-purple-700 hover:to-pink-700 hover:border-purple-500/60 hover:scale-105 hover:shadow-2xl hover:shadow-purple-500/40 transition-all duration-500 ease-out group overflow-hidden text-white",popupTrigger:"bg-gradient-to-r from-indigo-600 to-purple-600 backdrop-blur-xl border-2 border-indigo-400/40 text-white font-bold hover:from-indigo-700 hover:to-purple-700 hover:border-indigo-500/60 hover:scale-[1.02] hover:shadow-2xl hover:shadow-indigo-500/40 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:ring-offset-white transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-white/80 backdrop-blur-xl rounded-2xl text-center text-gray-700 text-sm font-medium transition-all duration-700 ease-in-out border border-indigo-100 shadow-lg shadow-indigo-100/20",statusIndicator:"w-2.5 h-2.5 bg-emerald-500 rounded-full animate-pulse shadow-lg shadow-emerald-500/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-indigo-100 rounded-3xl py-4 flex flex-col justify-end h-full bg-white/80 backdrop-blur-xl shadow-2xl",chatInput:{container:"bg-white/80 backdrop-blur-xl border-indigo-100 shadow-xl",textarea:"bg-white/90 border border-indigo-100 rounded-xl text-gray-900 placeholder-gray-400 font-medium px-4 py-3 focus:border-indigo-300 focus:ring-2 focus:ring-indigo-200",sendButton:"bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 border-2 border-transparent disabled:from-gray-300 disabled:to-gray-300 disabled:opacity-40 text-white font-bold hover:scale-105 transition-all duration-300 shadow-lg hover:shadow-indigo-500/40",attachButton:"text-gray-500 hover:text-indigo-600 hover:bg-indigo-50 transition-all duration-300 rounded-xl",endButton:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/50 hover:border-red-400/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-red-500/40"},chatMessage:{own:"bg-indigo-100/70 text-gray-900 backdrop-blur-md shadow-lg border border-indigo-200/50",other:"bg-white/80 text-gray-900 border border-gray-200 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-white/80 border-indigo-100 backdrop-blur-xl shadow-xl",backButton:"text-gray-600 hover:text-indigo-600 hover:bg-indigo-50 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-indigo-600 mb-2",suggestedResponse:{container:"bg-white/80 text-indigo-700 border-indigo-100 backdrop-blur-md hover:bg-indigo-50 hover:border-indigo-200 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#F8F9FC] via-[#FFFFFF] to-[#F8F9FC] text-gray-900",header:"border-indigo-100 bg-white/80 backdrop-blur-xl shadow-xl",headerButton:"bg-white/90 hover:bg-indigo-50 border-2 border-indigo-100 hover:border-indigo-200 text-gray-900 hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-emerald-500 animate-pulse shadow-lg shadow-emerald-500/60",controlsBackground:"bg-gradient-to-t from-white via-white/90 to-white/60 backdrop-blur-xl border-t border-indigo-100 shadow-2xl",controlEnabled:"bg-white/90 hover:bg-indigo-50 border-2 border-indigo-100 hover:border-indigo-200 text-gray-900 hover:scale-105 hover:shadow-xl hover:shadow-indigo-200/30 transition-all duration-300 font-semibold",controlDisabled:"bg-gray-100/50 hover:bg-gray-100/60 text-gray-400 border border-gray-200 transition-all duration-300",endCall:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/50 hover:border-red-400/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-2xl hover:shadow-red-500/50",tile:"bg-white/80 border border-indigo-100 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-gray-50 text-gray-600",avatar:"bg-indigo-100/80 text-indigo-700 border-2 border-indigo-200",nameOverlay:"bg-gradient-to-t from-white via-white/80 to-transparent text-gray-900 backdrop-blur-sm font-bold",mutedIndicator:"bg-red-600 text-white shadow-xl shadow-red-500/40 font-semibold"}},ZB={card:"text-white bg-gradient-to-b from-[#0a0a0a] via-[#000000] to-[#0a0a0a] border border-gray-800/30 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-[0_8px_32px_rgba(0,0,0,0.9),0_0_0_1px_rgba(255,255,255,0.08)_inset]",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-32 z-10 bg-gradient-to-b from-black/95 via-black/30 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,_rgba(255,255,255,0.03),transparent_60%)] opacity-100",cardPurpleBlur:"absolute top-0 left-1/2 -translate-x-1/2 w-[400px] h-[200px] bg-gradient-to-b from-white/[0.03] via-white/[0.015] to-transparent blur-3xl",cardPinkBlur:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[300px] h-[150px] bg-gradient-to-t from-white/[0.02] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-between justify-center max-w-md mx-auto bg-black p-0 overflow-hidden h-full relative",text:{primary:"text-white font-semibold",secondary:"text-white/95",muted:"text-gray-400",accent:"text-transparent bg-clip-text bg-gradient-to-r from-gray-200 via-white to-gray-200"},micButton:"relative w-20 h-20 bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] rounded-2xl flex items-center justify-center hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.03] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] transition-all duration-300 ease-out group overflow-hidden",chatButton:"relative w-20 h-20 bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] rounded-2xl flex items-center justify-center hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.03] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] transition-all duration-300 ease-out group overflow-hidden",videoButton:"relative w-20 h-20 bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] rounded-2xl flex items-center justify-center hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.03] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] transition-all duration-300 ease-out group overflow-hidden",popupTrigger:"bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] text-white font-bold hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.02] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] focus:outline-none focus:ring-2 focus:ring-white/30 focus:ring-offset-2 focus:ring-offset-black transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-white/[0.06] backdrop-blur-md rounded-xl text-center text-white/90 text-sm font-medium transition-all duration-700 ease-in-out border border-white/[0.12] ",statusIndicator:"w-2 h-2 bg-emerald-400 rounded-full animate-pulse shadow-[0_0_8px_rgba(52,211,153,0.6)]",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-white/[0.12] rounded-2xl py-4 flex flex-col justify-end h-full bg-black/90 backdrop-blur-md shadow-[0_4px_24px_rgba(0,0,0,0.6)]",chatInput:{container:"bg-black/90 backdrop-blur-md border-white/[0.12] shadow-[0_4px_16px_rgba(0,0,0,0.4)]",textarea:"bg-white/[0.08] border border-white/[0.12] rounded-xl text-white placeholder-gray-500 font-medium px-4 py-3 focus:border-white/[0.2] focus:ring-1 focus:ring-white/[0.15] transition-all",sendButton:"bg-white/[0.12] hover:bg-white/[0.18] border border-white/[0.2] hover:border-white/[0.35] disabled:border-white/[0.08] disabled:opacity-40 text-white font-bold hover:scale-[1.02] transition-all duration-300 shadow-md hover:shadow-[0_4px_16px_rgba(255,255,255,0.12)]",attachButton:"text-gray-400 hover:text-white hover:bg-white/[0.08] transition-all duration-300 rounded-lg",endButton:"bg-red-500/90 hover:bg-red-500 border border-red-400/40 hover:border-red-400/60 text-white font-bold hover:scale-[1.02] transition-all duration-300 shadow-md hover:shadow-[0_4px_16px_rgba(239,68,68,0.3)]"},chatMessage:{own:"bg-white/[0.10] text-white backdrop-blur-sm shadow-md border border-white/[0.15]",other:"bg-white/[0.06] text-white border border-white/[0.10] backdrop-blur-sm shadow-md"},chatHeader:{container:"bg-black/90 border-white/[0.12] backdrop-blur-md shadow-lg",backButton:"text-gray-400 hover:text-white hover:bg-white/[0.08] transition-all duration-300 rounded-lg"},spinner:"w-10 h-10 animate-spin text-white mb-2",suggestedResponse:{container:"bg-white/[0.08] text-white border-white/[0.15] backdrop-blur-sm hover:bg-white/[0.12] hover:border-white/[0.25] transition-all duration-300 shadow-md"},video:{container:"bg-black text-white",header:"border-white/[0.12] bg-black/90 backdrop-blur-md shadow-lg",headerButton:"bg-white/[0.12] hover:bg-white/[0.18] border border-white/[0.2] hover:border-white/[0.35] text-white hover:scale-[1.02] transition-all duration-300 rounded-lg shadow-md",statusDot:"bg-emerald-400 animate-pulse shadow-[0_0_8px_rgba(52,211,153,0.6)]",controlsBackground:"bg-gradient-to-t from-black via-black/95 to-black/70 backdrop-blur-md border-t border-white/[0.12] shadow-[0_-4px_24px_rgba(0,0,0,0.6)]",controlEnabled:"bg-white/[0.12] hover:bg-white/[0.18] border border-white/[0.2] hover:border-white/[0.35] text-white hover:scale-[1.02] hover:shadow-md hover:shadow-white/10 transition-all duration-300 font-semibold",controlDisabled:"bg-white/[0.04] hover:bg-white/[0.06] text-gray-500 border border-white/[0.08] transition-all duration-300",endCall:"bg-red-500/90 hover:bg-red-500 border border-red-400/40 hover:border-red-400/60 text-white font-bold hover:scale-[1.02] transition-all duration-300 shadow-md hover:shadow-red-500/30",tile:"bg-white/[0.08] border border-white/[0.12] shadow-lg backdrop-blur-sm rounded-xl",placeholder:"bg-white/[0.06] text-gray-400",avatar:"bg-white/[0.10] text-gray-300 border border-white/[0.12]",nameOverlay:"bg-gradient-to-t from-black via-black/85 to-transparent text-white backdrop-blur-sm font-semibold",mutedIndicator:"bg-red-500 text-white shadow-md shadow-red-500/30 font-semibold"}},$B={card:"text-white bg-gradient-to-b from-[#0e1218] via-[#161a25] to-[#0e1218] border border-[#2a3142]/50 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-2xl",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-40 z-10 bg-gradient-to-b from-[#0b1220]/90 via-[#0b1220]/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(34,211,238,0.08),transparent_50%)] opacity-100",cardPurpleBlur:"absolute top-0 left-1/2 -translate-x-1/2 w-[600px] h-[300px] bg-gradient-to-b from-cyan-500/[0.12] via-sky-500/[0.06] to-transparent blur-3xl",cardPinkBlur:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[500px] h-[250px] bg-gradient-to-t from-cyan-600/[0.08] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-center justify-between max-w-md mx-auto bg-gradient-to-b from-[#0e1218] via-[#161a25] to-[#0e1218] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-white font-semibold",secondary:"text-white/95",muted:"text-white/70",accent:"text-transparent bg-clip-text bg-gradient-to-r from-cyan-300 via-sky-300 to-cyan-300"},micButton:"relative w-20 h-20 bg-[#171b26]/90 backdrop-blur-xl border-2 border-cyan-500/30 rounded-3xl flex items-center justify-center hover:bg-[#171b26] hover:border-cyan-400/50 hover:scale-105 hover:shadow-2xl hover:shadow-cyan-500/30 transition-all duration-500 ease-out group overflow-hidden",chatButton:"relative w-20 h-20 bg-[#171b26]/90 backdrop-blur-xl border-2 border-sky-500/30 rounded-3xl flex items-center justify-center hover:bg-[#171b26] hover:border-sky-400/50 hover:scale-105 hover:shadow-2xl hover:shadow-sky-500/30 transition-all duration-500 ease-out group overflow-hidden",videoButton:"relative w-20 h-20 bg-[#171b26]/90 backdrop-blur-xl border-2 border-cyan-500/30 rounded-3xl flex items-center justify-center hover:bg-[#171b26] hover:border-cyan-400/50 hover:scale-105 hover:shadow-2xl hover:shadow-cyan-500/30 transition-all duration-500 ease-out group overflow-hidden",popupTrigger:"bg-[#171b26]/90 backdrop-blur-xl border-2 border-cyan-500/30 text-white font-bold hover:bg-[#171b26] hover:border-cyan-400/50 hover:scale-[1.02] hover:shadow-2xl hover:shadow-cyan-500/30 focus:outline-none focus:ring-2 focus:ring-cyan-400/50 focus:ring-offset-2 focus:ring-offset-[#161a25] transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-[#1c2230]/60 backdrop-blur-xl rounded-2xl text-center text-white/90 text-sm font-medium transition-all duration-700 ease-in-out border border-[#2a3142]/80 shadow-xl",statusIndicator:"w-2.5 h-2.5 bg-emerald-400 rounded-full animate-pulse shadow-lg shadow-emerald-400/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-[#2a3142]/80 rounded-3xl py-4 flex flex-col justify-end h-full bg-[#161a25]/80 backdrop-blur-xl shadow-2xl",chatInput:{container:"bg-[#1c2230]/80 backdrop-blur-xl border-[#2a3142]/80 shadow-xl",textarea:"bg-[#1c2230]/60 border border-[#2a3142]/50 rounded-xl text-white placeholder-gray-400 font-medium px-4 py-3",sendButton:"bg-[#171b26]/90 hover:bg-[#171b26] border-2 border-cyan-500/30 hover:border-cyan-400/50 disabled:border-[#2a3142] disabled:opacity-40 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-cyan-500/30",attachButton:"text-gray-400 hover:text-white hover:bg-[#2a3142]/30 transition-all duration-300 rounded-xl",endButton:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/40 hover:border-red-400/60 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-red-500/40"},chatMessage:{own:"bg-[#243049]/70 text-white backdrop-blur-md shadow-lg border border-[#2a3142]/80",other:"bg-[#1c2230]/60 text-white border border-[#2a3142]/80 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-[#1c2230]/80 border-[#2a3142]/80 backdrop-blur-xl shadow-xl",backButton:"text-white/80 hover:text-white hover:bg-[#2a3142]/30 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-cyan-400 mb-2",suggestedResponse:{container:"bg-[#1c2230]/70 text-white border-[#2a3142]/80 backdrop-blur-md hover:bg-[#1c2230]/80 hover:border-cyan-400/30 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#0e1218] via-[#161a25] to-[#0e1218] text-white",header:"border-[#2a3142]/80 bg-[#1c2230]/80 backdrop-blur-xl shadow-xl",headerButton:"bg-[#171b26]/90 hover:bg-[#171b26] border-2 border-cyan-500/30 hover:border-cyan-400/50 text-white hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-emerald-400 animate-pulse shadow-lg shadow-emerald-400/60",controlsBackground:"bg-gradient-to-t from-[#161a25] via-[#161a25]/90 to-[#161a25]/60 backdrop-blur-xl border-t border-[#2a3142]/80 shadow-2xl",controlEnabled:"bg-[#171b26]/90 hover:bg-[#171b26] border-2 border-cyan-500/30 hover:border-cyan-400/50 text-white hover:scale-105 hover:shadow-xl hover:shadow-cyan-500/30 transition-all duration-300 font-semibold",controlDisabled:"bg-[#1c2230]/50 hover:bg-[#1c2230]/60 text-white/40 border border-[#2a3142] transition-all duration-300",endCall:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/50 hover:border-red-400/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-2xl hover:shadow-red-500/50",tile:"bg-[#1c2230]/70 border border-[#2a3142]/80 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-[#1c2230]/60 text-white/80",avatar:"bg-[#171b26]/80 text-white border-2 border-[#2a3142]/80",nameOverlay:"bg-gradient-to-t from-[#161a25] via-[#161a25]/80 to-transparent text-white backdrop-blur-sm font-bold",mutedIndicator:"bg-red-600 text-white shadow-xl shadow-red-500/40 font-semibold"}},eF={card:" text-white bg-gradient-to-br from-[#171727] to-[#12121F] border border-gray-800 w-full h-full flex flex-col justify-between overflow-hidden relative",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-10 z-10 bg-gradient-to-b from-[#171727]/90 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-[#3B82F6]/15 via-transparent to-transparent",cardPurpleBlur:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-[#8B5CF6]/25 to-transparent rounded-full blur-2xl",cardPinkBlur:"absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-[#EC4899]/20 to-transparent rounded-full blur-xl",cardPulse1:"absolute -top-2 -left-2 w-6 h-6 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full blur-sm opacity-50 animate-pulse",cardPulse2:"absolute -bottom-2 -right-2 w-4 h-4 bg-gradient-to-br from-[#EC4899] to-[#8B5CF6] rounded-full blur-sm opacity-40 animate-pulse",main:"w-full flex flex-col items-center justify-between max-w-md mx-auto bg-gradient-to-br from-[#171727] to-[#12121F] rounded-2xl shadow-xl p-0 overflow-hidden h-full",text:{primary:"text-white font-semibold",secondary:"text-white/95",muted:"text-white/70",accent:"bg-clip-text text-transparent bg-gradient-to-r from-[#3B82F6] via-[#8B5CF6] to-[#EC4899]"},micButton:"relative w-20 h-20 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 mic-glow shadow-2xl group",chatButton:"relative w-20 h-20 bg-gradient-to-br from-[#10B981] to-[#059669] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",videoButton:"relative w-20 h-20 bg-gradient-to-br from-[#8B5CF6] to-[#EC4899] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",popupTrigger:"bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] text-white font-medium hover:from-[#2563EB] hover:to-[#7C3AED] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-900 shadow-xl",promptSlider:"absolute w-full py-3 px-2 bg-[#1E1E2E] rounded-xl text-center text-gray-200 text-sm transition-opacity duration-700 ease-in-out border border-gray-700",statusIndicator:"w-2 h-2 bg-[#10B981] rounded-full animate-pulse",pulseRings:{ring1:"w-32 h-32 rounded-full border-2 border-[#3B82F6]/40 pulse-ring",ring2:"absolute w-28 h-28 rounded-full border-2 border-[#8B5CF6]/30 pulse-ring",ring3:"absolute w-24 h-24 rounded-full border-2 border-[#EC4899]/20 pulse-ring"},controlBar:"border border-border rounded-3xl py-4 flex flex-col justify-end h-full bg-[#1E1E2E] shadow-2xl",chatInput:{container:"bg-[#1E1E2E] border-gray-700",textarea:"bg-[#1E1E2E] border-none text-white placeholder-gray-400",sendButton:"bg-[#3B82F6] hover:bg-[#2563EB] disabled:bg-gray-600 disabled:opacity-50 text-white",attachButton:"text-gray-400 hover:text-gray-300 hover:bg-gray-700",endButton:"bg-red-900/20 hover:bg-red-800/30 text-red-400 border-red-800"},chatMessage:{own:"bg-[#1E1E2E]/80 text-white",other:"bg-[#1E1E2E] text-white border border-gray-700"},chatHeader:{container:"bg-[#1E1E2E] border-gray-700",backButton:"text-gray-400 hover:text-white hover:bg-gray-700"},spinner:"w-10 h-10 animate-spin text-blue-400 mb-2",suggestedResponse:{container:"bg-[#221f3f] text-white border-none"},video:{container:"bg-gradient-to-br from-[#171727] to-[#12121F] text-white",header:"border-gray-700 bg-[#1E1E2E]/80",headerButton:"bg-[#1E1E2E] hover:bg-gray-700 text-gray-300",statusDot:"bg-[#10B981] animate-pulse",controlsBackground:"bg-[#1E1E2E]/90 backdrop-blur-sm border-t border-gray-700",controlEnabled:"bg-[#3B82F6] hover:bg-[#2563EB] text-white",controlDisabled:"bg-gray-700 hover:bg-gray-600 text-gray-300",endCall:"bg-red-600 hover:bg-red-700 text-white",tile:"bg-[#1E1E2E] border border-gray-700 shadow-xl",placeholder:"bg-[#1E1E2E] text-gray-300",avatar:"bg-gray-700 text-gray-300",nameOverlay:"bg-black/70 text-white",mutedIndicator:"bg-red-600/80 text-white"}},qy={dark:JB,light:XB,vox:ZB,midnight:$B,levish:eF};function wn(e){return qy[e]||qy.vox}function Qy({timeout:e}){const[t,n]=M.useState(100),i=M.useRef(null),r=M.useRef(null);return M.useEffect(()=>{if(!e||e<=0)return;n(100),r.current=Date.now();const s=()=>{if(!e||r.current===null)return;const o=Date.now()-r.current,a=Math.max(0,100-o/e*100);n(a),a>0&&(i.current=requestAnimationFrame(s))};return i.current=requestAnimationFrame(s),()=>{i.current&&cancelAnimationFrame(i.current)}},[e]),!e||e<=0?null:m.jsx("div",{className:"w-full h-1 relative top-1 rounded-t-4xl bg-gray-700 overflow-hidden",children:m.jsx(Ve.div,{className:"h-1 rounded-t-4xl dark:bg-white bg-blue-200 ",initial:{width:"100%"},animate:{width:`${Math.max(t,2)}%`},transition:{duration:.1,ease:"linear"},style:{minWidth:"2%"}})})}function da({interaction:e,theme:t,onDismiss:n,client:i,addLocalMessage:r}){var a;if(!e||!e.isVisible||!e.component)return null;const[s]=D.useState(()=>Date.now()),o=()=>e.component?D.createElement(e.component,{handler:e.handler||void 0,timeout:e.timeout,loadData:async l=>{console.log("InteractiveComponent: Loading data:",l)},presentationMode:e.presentationMode,data:e.data,client:i,addLocalMessage:r}):m.jsx("div",{className:"p-4 text-red-500",children:"Component not found"});switch(e.presentationMode){case"fullscreen":return m.jsx(Ys,{children:m.jsxs(Ve.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[9999] bg-black",children:[m.jsxs("div",{className:"flex flex-col",children:[m.jsx(Qy,{timeout:e.timeout}),m.jsxs("div",{className:"flex items-center justify-between p-4 bg-black/80 text-white border-b border-gray-700",children:[m.jsx("h3",{className:"text-lg font-semibold",children:e.methodName.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase())}),m.jsx("button",{onClick:n||((a=e.handler)==null?void 0:a.dismissView),className:"p-2 rounded-full bg-white/20 hover:bg-white/30 text-white transition-colors",children:m.jsx(Ot.X,{className:"w-5 h-5"})})]})]}),m.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:o()})]})});case"embedded":default:return m.jsx(Ys,{children:m.jsx(Ve.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"w-fit rounded-lg ",children:m.jsxs("div",{children:[m.jsx(Qy,{timeout:e.timeout}),o()]})})})}}function ha({duration:e,theme:t="vox",onTimerExpired:n,className:i="",showIcon:r=!0}){const[s,o]=M.useState(e),[a,c]=M.useState(!1);M.useEffect(()=>{if(s<=0){c(!0),n==null||n();return}const u=setInterval(()=>{o(d=>{const h=d-1;return h<=0?(c(!0),n==null||n(),0):h})},1e3);return()=>clearInterval(u)},[s,n]),M.useEffect(()=>{o(e),c(!1)},[e]);const l=()=>a?"text-red-500":s<=60?"text-orange-500":s<=300?"text-yellow-500":t==="dark"?"text-gray-300":"text-gray-600";return m.jsxs("div",{className:`flex items-center gap-1 text-sm ${l()} ${i}`,children:[r&&m.jsx(Ot.Clock,{className:"w-4 h-4"}),m.jsx("span",{className:"font-mono",children:Jw(s)}),a&&m.jsx("span",{className:"text-xs ml-1 text-red-500",children:"(Expired)"})]})}function $l({modality:e,theme:t,disabled:n=!1,showMicrophone:i=!1,microphoneEnabled:r=!0,microphoneLoading:s=!1,onToggleMicrophone:o,showCamera:a=!1,cameraEnabled:c=!0,cameraLoading:l=!1,onToggleCamera:u,showScreenShare:d=!1,screenShareEnabled:h=!1,screenShareLoading:f=!1,onToggleScreenShare:g,showChatToggle:p=!1,chatOpen:x=!1,onToggleChat:y,showTextInput:E=!1,textInputPlaceholder:w="Type a message...",onSendText:S,onSendAttachments:v,supportsAttachments:k=!1,showEndCall:_=!0,onEndCall:T}){var Q;const I=wn(t),[b,A]=M.useState(""),P=M.useRef(null),B=()=>{const C=b.trim();C&&S&&(S(C),A(""))},L=C=>{C.key==="Enter"&&!C.shiftKey&&(C.preventDefault(),B())},V=C=>{const K=Array.from(C.target.files||[]);K.length>0&&v&&v(K),P.current&&(P.current.value="")},J=at("flex items-center gap-3 px-2 sm:px-3 py-2 w-full backdrop-blur-xl overflow-hidden",E?"justify-between":"justify-center",t==="light"?"bg-white/95 border-gray-200":""),re=(C,K)=>{var X,R,ae;return K==="end-call"?at("p-3 rounded-full transition-all duration-200",((X=I.video)==null?void 0:X.endCall)||"bg-red-500 text-white hover:bg-red-600",n?"opacity-50 cursor-not-allowed":"hover:scale-105"):at("p-3 rounded-full transition-all duration-200",C?((R=I.video)==null?void 0:R.controlEnabled)||"bg-green-500 text-white":((ae=I.video)==null?void 0:ae.controlDisabled)||"bg-gray-500 text-white",n?"opacity-50 cursor-not-allowed":"hover:scale-105")},G=()=>m.jsx("div",{className:"w-5 h-5 animate-spin rounded-full border-2 border-current border-t-transparent"});return m.jsxs("div",{className:J,children:[E&&m.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[k&&v&&m.jsxs(m.Fragment,{children:[m.jsx("button",{onClick:()=>{var C;return(C=P.current)==null?void 0:C.click()},disabled:n,className:at("p-2 rounded-full transition-all duration-200",t==="light"?"hover:bg-gray-100":"hover:bg-gray-800",n&&"opacity-50 cursor-not-allowed"),title:"Attach files",children:m.jsx(Ot.Paperclip,{className:"w-5 h-5"})}),m.jsx("input",{ref:P,type:"file",multiple:!0,accept:"image/*",onChange:V,className:"hidden"})]}),m.jsx("input",{type:"text",value:b,onChange:C=>A(C.target.value),onKeyDown:L,disabled:n,placeholder:w,className:at("flex-1 min-w-0 px-4 py-2 rounded-full border outline-none transition-all",t==="light"?"bg-gray-100 border-gray-300 focus:border-blue-500 text-gray-900":"bg-gray-800 border-gray-700 focus:border-blue-400 text-white",n&&"opacity-50 cursor-not-allowed")}),m.jsx("button",{onClick:B,disabled:n||!b.trim(),className:at("p-2 rounded-full transition-all duration-200",b.trim()?((Q=I.video)==null?void 0:Q.controlEnabled)||"bg-blue-500 text-white hover:bg-blue-600":t==="light"?"bg-gray-200 text-gray-400":"bg-gray-700 text-gray-500",n&&"opacity-50 cursor-not-allowed",b.trim()&&!n&&"hover:scale-105"),title:"Send message",children:m.jsx(Ot.SendHorizontal,{className:"w-5 h-5"})})]}),!E&&m.jsxs(m.Fragment,{children:[i&&o&&m.jsx("button",{onClick:o,disabled:n||s,className:re(r),title:r?"Mute microphone":"Unmute microphone",children:s?m.jsx(G,{}):r?m.jsx(Ot.Mic,{className:"w-5 h-5"}):m.jsx(Ot.MicOff,{className:"w-5 h-5"})}),a&&u&&m.jsx("button",{onClick:u,disabled:n||l,className:re(c),title:c?"Turn off camera":"Turn on camera",children:l?m.jsx(G,{}):c?m.jsx(Ot.Camera,{className:"w-5 h-5"}):m.jsx(Ot.CameraOff,{className:"w-5 h-5"})}),d&&g&&m.jsx("button",{onClick:g,disabled:n||f,className:re(h),title:h?"Stop screen share":"Share screen",children:f?m.jsx(G,{}):m.jsx(Ot.Monitor,{className:"w-5 h-5"})}),p&&y&&m.jsx("button",{onClick:y,disabled:n,className:re(x),title:e==="voice"?x?"Hide transcription":"Show transcription":x?"Hide chat":"Show chat",children:m.jsx(Ot.MessageCircle,{className:"w-5 h-5"})})]}),_&&T&&m.jsx("button",{onClick:T,disabled:n,className:re(!1,"end-call"),title:"End call",children:m.jsx(Ot.PhoneOff,{className:"w-5 h-5"})})]})}$l.displayName="UnifiedControlBar";const tF=({logLevel:e}={})=>{const t=DL();D.useEffect(()=>(dI(e??"debug"),window.__lk_room=t,()=>{window.__lk_room=void 0}),[t,e])},Zw=D.forwardRef((e,t)=>{const{alt:n,color:i="currentColor",size:r="1em",weight:s="regular",mirrored:o=!1,children:a,weights:c,...l}=e;return D.createElement("svg",{ref:t,xmlns:"http://www.w3.org/2000/svg",width:r,height:r,fill:i,viewBox:"0 0 256 256",transform:o?"scale(-1, 1)":void 0,...l},!!n&&D.createElement("title",null,n),a,c.get(s))});Zw.displayName="SSRBase";const nF=new Map([["bold",D.createElement(D.Fragment,null,D.createElement("path",{d:"M140,32V64a12,12,0,0,1-24,0V32a12,12,0,0,1,24,0Zm33.25,62.75a12,12,0,0,0,8.49-3.52L204.37,68.6a12,12,0,0,0-17-17L164.77,74.26a12,12,0,0,0,8.48,20.49ZM224,116H192a12,12,0,0,0,0,24h32a12,12,0,0,0,0-24Zm-42.26,48.77a12,12,0,1,0-17,17l22.63,22.63a12,12,0,0,0,17-17ZM128,180a12,12,0,0,0-12,12v32a12,12,0,0,0,24,0V192A12,12,0,0,0,128,180ZM74.26,164.77,51.63,187.4a12,12,0,0,0,17,17l22.63-22.63a12,12,0,1,0-17-17ZM76,128a12,12,0,0,0-12-12H32a12,12,0,0,0,0,24H64A12,12,0,0,0,76,128ZM68.6,51.63a12,12,0,1,0-17,17L74.26,91.23a12,12,0,0,0,17-17Z"}))],["duotone",D.createElement(D.Fragment,null,D.createElement("path",{d:"M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z",opacity:"0.2"}),D.createElement("path",{d:"M136,32V64a8,8,0,0,1-16,0V32a8,8,0,0,1,16,0Zm37.25,58.75a8,8,0,0,0,5.66-2.35l22.63-22.62a8,8,0,0,0-11.32-11.32L167.6,77.09a8,8,0,0,0,5.65,13.66ZM224,120H192a8,8,0,0,0,0,16h32a8,8,0,0,0,0-16Zm-45.09,47.6a8,8,0,0,0-11.31,11.31l22.62,22.63a8,8,0,0,0,11.32-11.32ZM128,184a8,8,0,0,0-8,8v32a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184ZM77.09,167.6,54.46,190.22a8,8,0,0,0,11.32,11.32L88.4,178.91A8,8,0,0,0,77.09,167.6ZM72,128a8,8,0,0,0-8-8H32a8,8,0,0,0,0,16H64A8,8,0,0,0,72,128ZM65.78,54.46A8,8,0,0,0,54.46,65.78L77.09,88.4A8,8,0,0,0,88.4,77.09Z"}))],["fill",D.createElement(D.Fragment,null,D.createElement("path",{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm33.94,58.75,17-17a8,8,0,0,1,11.32,11.32l-17,17a8,8,0,0,1-11.31-11.31ZM48,136a8,8,0,0,1,0-16H72a8,8,0,0,1,0,16Zm46.06,37.25-17,17a8,8,0,0,1-11.32-11.32l17-17a8,8,0,0,1,11.31,11.31Zm0-79.19a8,8,0,0,1-11.31,0l-17-17A8,8,0,0,1,77.09,65.77l17,17A8,8,0,0,1,94.06,94.06ZM136,208a8,8,0,0,1-16,0V184a8,8,0,0,1,16,0Zm0-136a8,8,0,0,1-16,0V48a8,8,0,0,1,16,0Zm54.23,118.23a8,8,0,0,1-11.32,0l-17-17a8,8,0,0,1,11.31-11.31l17,17A8,8,0,0,1,190.23,190.23ZM208,136H184a8,8,0,0,1,0-16h24a8,8,0,0,1,0,16Z"}))],["light",D.createElement(D.Fragment,null,D.createElement("path",{d:"M134,32V64a6,6,0,0,1-12,0V32a6,6,0,0,1,12,0Zm39.25,56.75A6,6,0,0,0,177.5,87l22.62-22.63a6,6,0,0,0-8.48-8.48L169,78.5a6,6,0,0,0,4.24,10.25ZM224,122H192a6,6,0,0,0,0,12h32a6,6,0,0,0,0-12Zm-46.5,47A6,6,0,0,0,169,177.5l22.63,22.62a6,6,0,0,0,8.48-8.48ZM128,186a6,6,0,0,0-6,6v32a6,6,0,0,0,12,0V192A6,6,0,0,0,128,186ZM78.5,169,55.88,191.64a6,6,0,1,0,8.48,8.48L87,177.5A6,6,0,1,0,78.5,169ZM70,128a6,6,0,0,0-6-6H32a6,6,0,0,0,0,12H64A6,6,0,0,0,70,128ZM64.36,55.88a6,6,0,0,0-8.48,8.48L78.5,87A6,6,0,1,0,87,78.5Z"}))],["regular",D.createElement(D.Fragment,null,D.createElement("path",{d:"M136,32V64a8,8,0,0,1-16,0V32a8,8,0,0,1,16,0Zm37.25,58.75a8,8,0,0,0,5.66-2.35l22.63-22.62a8,8,0,0,0-11.32-11.32L167.6,77.09a8,8,0,0,0,5.65,13.66ZM224,120H192a8,8,0,0,0,0,16h32a8,8,0,0,0,0-16Zm-45.09,47.6a8,8,0,0,0-11.31,11.31l22.62,22.63a8,8,0,0,0,11.32-11.32ZM128,184a8,8,0,0,0-8,8v32a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184ZM77.09,167.6,54.46,190.22a8,8,0,0,0,11.32,11.32L88.4,178.91A8,8,0,0,0,77.09,167.6ZM72,128a8,8,0,0,0-8-8H32a8,8,0,0,0,0,16H64A8,8,0,0,0,72,128ZM65.78,54.46A8,8,0,0,0,54.46,65.78L77.09,88.4A8,8,0,0,0,88.4,77.09Z"}))],["thin",D.createElement(D.Fragment,null,D.createElement("path",{d:"M132,32V64a4,4,0,0,1-8,0V32a4,4,0,0,1,8,0Zm41.25,54.75a4,4,0,0,0,2.83-1.18L198.71,63a4,4,0,0,0-5.66-5.66L170.43,79.92a4,4,0,0,0,2.82,6.83ZM224,124H192a4,4,0,0,0,0,8h32a4,4,0,0,0,0-8Zm-47.92,46.43a4,4,0,1,0-5.65,5.65l22.62,22.63a4,4,0,0,0,5.66-5.66ZM128,188a4,4,0,0,0-4,4v32a4,4,0,0,0,8,0V192A4,4,0,0,0,128,188ZM79.92,170.43,57.29,193.05A4,4,0,0,0,63,198.71l22.62-22.63a4,4,0,1,0-5.65-5.65ZM68,128a4,4,0,0,0-4-4H32a4,4,0,0,0,0,8H64A4,4,0,0,0,68,128ZM63,57.29A4,4,0,0,0,57.29,63L79.92,85.57a4,4,0,1,0,5.65-5.65Z"}))]]),kl=D.forwardRef((e,t)=>D.createElement(Zw,{ref:t,...e,weights:nF}));kl.displayName="SpinnerIcon";function iF({text:e,isComplete:t,isRealTimeStream:n=!1,speed:i=50}){const[r,s]=D.useState(""),[o,a]=D.useState(0);return D.useEffect(()=>{if(n){s(e);return}if(t){s(e);return}if(o<e.length){const c=setTimeout(()=>{s(e.slice(0,o+1)),a(o+1)},i);return()=>clearTimeout(c)}},[e,o,t,i,n]),D.useEffect(()=>{n||(a(0),s(""))},[e,n]),m.jsxs("span",{className:"relative",children:[m.jsx("span",{className:"inline-block",children:r}),!t&&m.jsx("span",{className:"inline-flex items-center ml-1",children:[0,1,2].map(c=>m.jsx(Ve.span,{className:"w-1.5 h-1.5 bg-current rounded-full mx-0.5",animate:{y:[0,-4,0],opacity:[.4,1,.4],scale:[.8,1,.8]},transition:{duration:.8,repeat:1/0,repeatType:"mirror",delay:c*.2,ease:"easeInOut"}},c))})]})}function rF(e,t){return e.startsWith("image/")?Ot.Image:e.startsWith("video/")?Ot.Video:e.startsWith("audio/")?Ot.Music:e.includes("zip")||e.includes("rar")||e.includes("archive")?Ot.Archive:Ot.FileText}function sF(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,i)).toFixed(2))+" "+n[i]}function oF({message:e,theme:t,isOwn:n}){const i=wn(t),r=e.metadata,s=(r==null?void 0:r.fileName)||"Unknown file",o=(r==null?void 0:r.fileSize)||0,a=(r==null?void 0:r.mimeType)||"application/octet-stream",c=r==null?void 0:r.downloading,l=r==null?void 0:r.uploading,u=(r==null?void 0:r.downloadProgress)||0,d=(r==null?void 0:r.uploadProgress)||0,h=r==null?void 0:r.downloadUrl,f=r==null?void 0:r.file,g=rF(a),p=c||l,x=c?u:d,y=c?"Downloading...":l?"Uploading...":"Complete",[E,w]=D.useState(null);D.useEffect(()=>{if(h)w(h);else if(f&&a.startsWith("image/")){const _=URL.createObjectURL(f);return w(_),()=>URL.revokeObjectURL(_)}else w(null)},[h,f,a]);const S=()=>{if(h){const _=document.createElement("a");_.href=h,_.download=s,_.click()}},k=a.startsWith("image/")&&E;return m.jsxs("div",{className:"flex flex-col gap-2 max-w-full sm:max-w-sm",children:[k&&m.jsxs("div",{className:"relative rounded-lg overflow-hidden",children:[m.jsx("img",{src:E,alt:s,className:"max-w-full h-auto max-h-48 object-cover rounded-lg cursor-pointer",onClick:S}),m.jsx("div",{className:"absolute inset-0 bg-black/0 hover:bg-black/10 transition-colors duration-200 cursor-pointer"})]}),m.jsxs("div",{className:`
49
49
  flex items-center gap-3 p-3 rounded-lg border transition-all duration-200
50
50
  ${t==="light"?"bg-gray-50 border-gray-200 hover:bg-gray-100":"bg-gray-800/50 border-gray-700 hover:bg-gray-700/50"}
51
51
  `,children:[m.jsx("div",{className:`
@@ -193,15 +193,7 @@ Event: ${jr(e)}`),!0;if(u7(e,t.denyUrls))return ze&&Oe.warn(`Event dropped due t
193
193
  Event: ${jr(e)}.
194
194
  Url: ${Dl(e)}`),!0;if(!d7(e,t.allowUrls))return ze&&Oe.warn(`Event dropped due to not being matched by \`allowUrls\` option.
195
195
  Event: ${jr(e)}.
196
- Url: ${Dl(e)}`),!0}return!1}function c7(e,t){return t!=null&&t.length?CA(e).some(n=>wu(n,t)):!1}function l7(e,t){if(!(t!=null&&t.length))return!1;const n=e.transaction;return n?wu(n,t):!1}function u7(e,t){if(!(t!=null&&t.length))return!1;const n=Dl(e);return n?wu(n,t):!1}function d7(e,t){if(!(t!=null&&t.length))return!0;const n=Dl(e);return n?wu(n,t):!0}function h7(e=[]){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n&&n.filename!=="<anonymous>"&&n.filename!=="[native code]")return n.filename||null}return null}function Dl(e){var t,n;try{const i=[...((t=e.exception)==null?void 0:t.values)??[]].reverse().find(s=>{var o,a,c;return((o=s.mechanism)==null?void 0:o.parent_id)===void 0&&((c=(a=s.stacktrace)==null?void 0:a.frames)==null?void 0:c.length)}),r=(n=i==null?void 0:i.stacktrace)==null?void 0:n.frames;return r?h7(r):null}catch{return ze&&Oe.error(`Cannot extract url for event ${jr(e)}`),null}}function f7(e){var t,n;return(n=(t=e.exception)==null?void 0:t.values)!=null&&n.length?!e.message&&!e.exception.values.some(i=>i.stacktrace||i.type&&i.type!=="Error"||i.value):!1}function p7(e,t,n,i,r,s){var a;if(!((a=r.exception)!=null&&a.values)||!s||!Tr(s.originalException,Error))return;const o=r.exception.values.length>0?r.exception.values[r.exception.values.length-1]:void 0;o&&(r.exception.values=Nf(e,t,i,s.originalException,n,r.exception.values,o,0))}function Nf(e,t,n,i,r,s,o,a){if(s.length>=n+1)return s;let c=[...s];if(Tr(i[r],Error)){yx(o,a);const l=e(t,i[r]),u=c.length;vx(l,r,u,a),c=Nf(e,t,n,i[r],r,[l,...c],l,u)}return Array.isArray(i.errors)&&i.errors.forEach((l,u)=>{if(Tr(l,Error)){yx(o,a);const d=e(t,l),h=c.length;vx(d,`errors[${u}]`,h,a),c=Nf(e,t,n,l,r,[d,...c],d,h)}}),c}function yx(e,t){e.mechanism={handled:!0,type:"auto.core.linked_errors",...e.mechanism,...e.type==="AggregateError"&&{is_exception_group:!0},exception_id:t}}function vx(e,t,n,i){e.mechanism={handled:!0,...e.mechanism,type:"chained",source:t,exception_id:n,parent_id:i}}function m7(e){const t="console";ss(t,e),os(t,g7)}function g7(){"console"in ht&&yG.forEach(function(e){e in ht.console&&Dn(ht.console,e,function(t){return Pl[e]=t,function(...n){ai("console",{args:n,level:e});const r=Pl[e];r==null||r.apply(ht.console,n)}})})}function b7(e){return e==="warn"?"warning":["fatal","error","warning","log","info","debug"].includes(e)?e:"log"}const y7="Dedupe",v7=(()=>{let e;return{name:y7,processEvent(t){if(t.type)return t;try{if(S7(t,e))return ze&&Oe.warn("Event dropped due to being a duplicate of previously captured event."),null}catch{}return e=t}}}),x7=v7;function S7(e,t){return t?!!(k7(e,t)||E7(e,t)):!1}function k7(e,t){const n=e.message,i=t.message;return!(!n&&!i||n&&!i||!n&&i||n!==i||!MA(e,t)||!NA(e,t))}function E7(e,t){const n=xx(t),i=xx(e);return!(!n||!i||n.type!==i.type||n.value!==i.value||!MA(e,t)||!NA(e,t))}function NA(e,t){let n=Nv(e),i=Nv(t);if(!n&&!i)return!0;if(n&&!i||!n&&i||(n=n,i=i,i.length!==n.length))return!1;for(let r=0;r<i.length;r++){const s=i[r],o=n[r];if(s.filename!==o.filename||s.lineno!==o.lineno||s.colno!==o.colno||s.function!==o.function)return!1}return!0}function MA(e,t){let n=e.fingerprint,i=t.fingerprint;if(!n&&!i)return!0;if(n&&!i||!n&&i)return!1;n=n,i=i;try{return n.join("")===i.join("")}catch{return!1}}function xx(e){var t,n;return(n=(t=e.exception)==null?void 0:t.values)==null?void 0:n[0]}function PA(e){if(e!==void 0)return e>=400&&e<500?"warning":e>=500?"error":void 0}const ya=ht;function w7(){return"history"in ya&&!!ya.history}function C7(){if(!("fetch"in ya))return!1;try{return new Headers,new Request("data:,"),new Response,!0}catch{return!1}}function Mf(e){return e&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(e.toString())}function T7(){var n;if(typeof EdgeRuntime=="string")return!0;if(!C7())return!1;if(Mf(ya.fetch))return!0;let e=!1;const t=ya.document;if(t&&typeof t.createElement=="function")try{const i=t.createElement("iframe");i.hidden=!0,t.head.appendChild(i),(n=i.contentWindow)!=null&&n.fetch&&(e=Mf(i.contentWindow.fetch)),t.head.removeChild(i)}catch(i){ze&&Oe.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",i)}return e}function A7(e,t){const n="fetch";ss(n,e),os(n,()=>R7(void 0,t))}function R7(e,t=!1){t&&!T7()||Dn(ht,"fetch",function(n){return function(...i){const r=new Error,{method:s,url:o}=_7(i),a={args:i,fetchData:{method:s,url:o},startTimestamp:qi()*1e3,virtualError:r,headers:I7(i)};return ai("fetch",{...a}),n.apply(ht,i).then(async c=>(ai("fetch",{...a,endTimestamp:qi()*1e3,response:c}),c),c=>{ai("fetch",{...a,endTimestamp:qi()*1e3,error:c}),Pa(c)&&c.stack===void 0&&(c.stack=r.stack,Ar(c,"framesToPop",1));const l=rn(),u=(l==null?void 0:l.getOptions().enhanceFetchErrorMessages)??"always";if(u!==!1&&c instanceof TypeError&&(c.message==="Failed to fetch"||c.message==="Load failed"||c.message==="NetworkError when attempting to fetch resource."))try{const f=new URL(a.fetchData.url).host;u==="always"?c.message=`${c.message} (${f})`:Ar(c,"__sentry_fetch_url_host__",f)}catch{}throw c})}})}function qc(e,t){return!!e&&typeof e=="object"&&!!e[t]}function Sx(e){return typeof e=="string"?e:e?qc(e,"url")?e.url:e.toString?e.toString():"":""}function _7(e){if(e.length===0)return{method:"GET",url:""};if(e.length===2){const[n,i]=e;return{url:Sx(n),method:qc(i,"method")?String(i.method).toUpperCase():ZT(n)&&qc(n,"method")?String(n.method).toUpperCase():"GET"}}const t=e[0];return{url:Sx(t),method:qc(t,"method")?String(t.method).toUpperCase():"GET"}}function I7(e){const[t,n]=e;try{if(typeof n=="object"&&n!==null&&"headers"in n&&n.headers)return new Headers(n.headers);if(ZT(t))return new Headers(t.headers)}catch{}}function N7(){return"npm"}const _t=ht;let Pf=0;function OA(){return Pf>0}function M7(){Pf++,setTimeout(()=>{Pf--})}function no(e,t={}){function n(r){return typeof r=="function"}if(!n(e))return e;try{const r=e.__sentry_wrapped__;if(r)return typeof r=="function"?r:e;if(Dm(e))return e}catch{return e}const i=function(...r){try{const s=r.map(o=>no(o,t));return e.apply(this,s)}catch(s){throw M7(),Bm(o=>{o.addEventProcessor(a=>(t.mechanism&&(wf(a,void 0),$s(a,t.mechanism)),a.extra={...a.extra,arguments:r},a)),Vm(s)}),s}};try{for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r])}catch{}eA(i,e),Ar(e,"__sentry_wrapped__",i);try{Object.getOwnPropertyDescriptor(i,"name").configurable&&Object.defineProperty(i,"name",{get(){return e.name}})}catch{}return i}function P7(){const e=Om(),{referrer:t}=_t.document||{},{userAgent:n}=_t.navigator||{},i={...t&&{Referer:t},...n&&{"User-Agent":n}};return{url:e,headers:i}}function Hm(e,t){const n=Km(e,t),i={type:F7(t),value:U7(t)};return n.length&&(i.stacktrace={frames:n}),i.type===void 0&&i.value===""&&(i.value="Unrecoverable error caught"),i}function O7(e,t,n,i){const r=rn(),s=r==null?void 0:r.getOptions().normalizeDepth,o=H7(t),a={__serialized__:fA(t,s)};if(o)return{exception:{values:[Hm(e,o)]},extra:a};const c={exception:{values:[{type:Su(t)?t.constructor.name:i?"UnhandledRejection":"Error",value:z7(t,{isUnhandledRejection:i})}]},extra:a};if(n){const l=Km(e,n);l.length&&(c.exception.values[0].stacktrace={frames:l})}return c}function th(e,t){return{exception:{values:[Hm(e,t)]}}}function Km(e,t){const n=t.stacktrace||t.stack||"",i=L7(t),r=B7(t);try{return e(n,i,r)}catch{}return[]}const D7=/Minified React error #\d+;/i;function L7(e){return e&&D7.test(e.message)?1:0}function B7(e){return typeof e.framesToPop=="number"?e.framesToPop:0}function DA(e){return typeof WebAssembly<"u"&&typeof WebAssembly.Exception<"u"?e instanceof WebAssembly.Exception:!1}function F7(e){const t=e==null?void 0:e.name;return!t&&DA(e)?e.message&&Array.isArray(e.message)&&e.message.length==2?e.message[0]:"WebAssembly.Exception":t}function U7(e){const t=e==null?void 0:e.message;return DA(e)?Array.isArray(e.message)&&e.message.length==2?e.message[1]:"wasm exception":t?t.error&&typeof t.error.message=="string"?px(t.error):px(e):"No error message"}function j7(e,t,n,i){const r=(n==null?void 0:n.syntheticException)||void 0,s=Wm(e,t,r,i);return $s(s),s.level="error",n!=null&&n.event_id&&(s.event_id=n.event_id),Cu(s)}function V7(e,t,n="info",i,r){const s=(i==null?void 0:i.syntheticException)||void 0,o=Of(e,t,s,r);return o.level=n,i!=null&&i.event_id&&(o.event_id=i.event_id),Cu(o)}function Wm(e,t,n,i,r){let s;if(JT(t)&&t.error)return th(e,t.error);if(Pv(t)||NG(t)){const o=t;if("stack"in t)s=th(e,t);else{const a=o.name||(Pv(o)?"DOMError":"DOMException"),c=o.message?`${a}: ${o.message}`:a;s=Of(e,c,n,i),wf(s,c)}return"code"in o&&(s.tags={...s.tags,"DOMException.code":`${o.code}`}),s}return Pa(t)?th(e,t):ga(t)||Su(t)?(s=O7(e,t,n,r),$s(s,{synthetic:!0}),s):(s=Of(e,t,n,i),wf(s,`${t}`),$s(s,{synthetic:!0}),s)}function Of(e,t,n,i){const r={};if(i&&n){const s=Km(e,n);s.length&&(r.exception={values:[{value:t,stacktrace:{frames:s}}]}),$s(r,{synthetic:!0})}if(Mm(t)){const{__sentry_template_string__:s,__sentry_template_values__:o}=t;return r.logentry={message:s,params:o},r}return r.message=t,r}function z7(e,{isUnhandledRejection:t}){const n=FG(e),i=t?"promise rejection":"exception";return JT(e)?`Event \`ErrorEvent\` captured as ${i} with message \`${e.message}\``:Su(e)?`Event \`${G7(e)}\` (type=${e.type}) captured as ${i}`:`Object captured as ${i} with keys: ${n}`}function G7(e){try{const t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function H7(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const n=e[t];if(n instanceof Error)return n}}class K7 extends GK{constructor(t){var u;const n=W7(t),i=_t.SENTRY_SDK_SOURCE||N7();IA(n,"browser",["browser"],i),(u=n._metadata)!=null&&u.sdk&&(n._metadata.sdk.settings={infer_ip:n.sendDefaultPii?"auto":"never",...n._metadata.sdk.settings}),super(n);const{sendDefaultPii:r,sendClientReports:s,enableLogs:o,_experiments:a,enableMetrics:c}=this._options,l=c??(a==null?void 0:a.enableMetrics)??!0;_t.document&&(s||o||l)&&_t.document.addEventListener("visibilitychange",()=>{_t.document.visibilityState==="hidden"&&(s&&this._flushOutcomes(),o&&xA(this),l&&kA(this))}),r&&this.on("beforeSendSession",ZK)}eventFromException(t,n){return j7(this._options.stackParser,t,n,this._options.attachStacktrace)}eventFromMessage(t,n="info",i){return V7(this._options.stackParser,t,n,i,this._options.attachStacktrace)}_prepareEvent(t,n,i,r){return t.platform=t.platform||"javascript",super._prepareEvent(t,n,i,r)}}function W7(e){var t;return{release:typeof __SENTRY_RELEASE__=="string"?__SENTRY_RELEASE__:(t=_t.SENTRY_RELEASE)==null?void 0:t.id,sendClientReports:!0,parentSpanIsAlwaysRootSpan:!0,...e}}const q7=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,Sn=ht,Q7=1e3;let kx,Df,Lf;function Y7(e){ss("dom",e),os("dom",J7)}function J7(){if(!Sn.document)return;const e=ai.bind(null,"dom"),t=Ex(e,!0);Sn.document.addEventListener("click",t,!1),Sn.document.addEventListener("keypress",t,!1),["EventTarget","Node"].forEach(n=>{var s,o;const r=(s=Sn[n])==null?void 0:s.prototype;(o=r==null?void 0:r.hasOwnProperty)!=null&&o.call(r,"addEventListener")&&(Dn(r,"addEventListener",function(a){return function(c,l,u){if(c==="click"||c=="keypress")try{const d=this.__sentry_instrumentation_handlers__=this.__sentry_instrumentation_handlers__||{},h=d[c]=d[c]||{refCount:0};if(!h.handler){const f=Ex(e);h.handler=f,a.call(this,c,f,u)}h.refCount++}catch{}return a.call(this,c,l,u)}}),Dn(r,"removeEventListener",function(a){return function(c,l,u){if(c==="click"||c=="keypress")try{const d=this.__sentry_instrumentation_handlers__||{},h=d[c];h&&(h.refCount--,h.refCount<=0&&(a.call(this,c,h.handler,u),h.handler=void 0,delete d[c]),Object.keys(d).length===0&&delete this.__sentry_instrumentation_handlers__)}catch{}return a.call(this,c,l,u)}}))})}function X7(e){if(e.type!==Df)return!1;try{if(!e.target||e.target._sentryId!==Lf)return!1}catch{}return!0}function Z7(e,t){return e!=="keypress"?!1:t!=null&&t.tagName?!(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable):!0}function Ex(e,t=!1){return n=>{if(!n||n._sentryCaptured)return;const i=$7(n);if(Z7(n.type,i))return;Ar(n,"_sentryCaptured",!0),i&&!i._sentryId&&Ar(i,"_sentryId",Qn());const r=n.type==="keypress"?"input":n.type;X7(n)||(e({event:n,name:r,global:t}),Df=n.type,Lf=i?i._sentryId:void 0),clearTimeout(kx),kx=Sn.setTimeout(()=>{Lf=void 0,Df=void 0},Q7)}}function $7(e){try{return e.target}catch{return null}}let xc;function LA(e){const t="history";ss(t,e),os(t,eW)}function eW(){if(Sn.addEventListener("popstate",()=>{const t=Sn.location.href,n=xc;if(xc=t,n===t)return;ai("history",{from:n,to:t})}),!w7())return;function e(t){return function(...n){const i=n.length>2?n[2]:void 0;if(i){const r=xc,s=tW(String(i));if(xc=s,r===s)return t.apply(this,n);ai("history",{from:r,to:s})}return t.apply(this,n)}}Dn(Sn.history,"pushState",e),Dn(Sn.history,"replaceState",e)}function tW(e){try{return new URL(e,Sn.location.origin).toString()}catch{return e}}const Qc={};function nW(e){const t=Qc[e];if(t)return t;let n=Sn[e];if(Mf(n))return Qc[e]=n.bind(Sn);const i=Sn.document;if(i&&typeof i.createElement=="function")try{const r=i.createElement("iframe");r.hidden=!0,i.head.appendChild(r);const s=r.contentWindow;s!=null&&s[e]&&(n=s[e]),i.head.removeChild(r)}catch(r){q7&&Oe.warn(`Could not create sandbox iframe for ${e} check, bailing to window.${e}: `,r)}return n&&(Qc[e]=n.bind(Sn))}function iW(e){Qc[e]=void 0}const zo="__sentry_xhr_v3__";function rW(e){ss("xhr",e),os("xhr",sW)}function sW(){if(!Sn.XMLHttpRequest)return;const e=XMLHttpRequest.prototype;e.open=new Proxy(e.open,{apply(t,n,i){const r=new Error,s=qi()*1e3,o=Wi(i[0])?i[0].toUpperCase():void 0,a=oW(i[1]);if(!o||!a)return t.apply(n,i);n[zo]={method:o,url:a,request_headers:{}},o==="POST"&&a.match(/sentry_key/)&&(n.__sentry_own_request__=!0);const c=()=>{const l=n[zo];if(l&&n.readyState===4){try{l.status_code=n.status}catch{}const u={endTimestamp:qi()*1e3,startTimestamp:s,xhr:n,virtualError:r};ai("xhr",u)}};return"onreadystatechange"in n&&typeof n.onreadystatechange=="function"?n.onreadystatechange=new Proxy(n.onreadystatechange,{apply(l,u,d){return c(),l.apply(u,d)}}):n.addEventListener("readystatechange",c),n.setRequestHeader=new Proxy(n.setRequestHeader,{apply(l,u,d){const[h,f]=d,g=u[zo];return g&&Wi(h)&&Wi(f)&&(g.request_headers[h.toLowerCase()]=f),l.apply(u,d)}}),t.apply(n,i)}}),e.send=new Proxy(e.send,{apply(t,n,i){const r=n[zo];if(!r)return t.apply(n,i);i[0]!==void 0&&(r.body=i[0]);const s={startTimestamp:qi()*1e3,xhr:n};return ai("xhr",s),t.apply(n,i)}})}function oW(e){if(Wi(e))return e;try{return e.toString()}catch{}}const aW=40;function cW(e,t=nW("fetch")){let n=0,i=0;async function r(s){const o=s.body.length;n+=o,i++;const a={body:s.body,method:"POST",referrerPolicy:"strict-origin",headers:e.headers,keepalive:n<=6e4&&i<15,...e.fetchOptions};try{const c=await t(e.url,a);return{statusCode:c.status,headers:{"x-sentry-rate-limits":c.headers.get("X-Sentry-Rate-Limits"),"retry-after":c.headers.get("Retry-After")}}}catch(c){throw iW("fetch"),c}finally{n-=o,i--}}return FK(e,r,Gm(e.bufferSize||aW))}const io=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,lW=30,uW=50;function Bf(e,t,n,i){const r={filename:e,function:t==="<anonymous>"?es:t,in_app:!0};return n!==void 0&&(r.lineno=n),i!==void 0&&(r.colno=i),r}const dW=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,hW=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,fW=/\((\S*)(?::(\d+))(?::(\d+))\)/,pW=/at (.+?) ?\(data:(.+?),/,mW=e=>{const t=e.match(pW);if(t)return{filename:`<data:${t[2]}>`,function:t[1]};const n=dW.exec(e);if(n){const[,r,s,o]=n;return Bf(r,es,+s,+o)}const i=hW.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){const a=fW.exec(i[2]);a&&(i[2]=a[1],i[3]=a[2],i[4]=a[3])}const[s,o]=BA(i[1]||es,i[2]);return Bf(o,s,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},gW=[lW,mW],bW=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,yW=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vW=e=>{const t=bW.exec(e);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){const s=yW.exec(t[3]);s&&(t[1]=t[1]||"eval",t[3]=s[1],t[4]=s[2],t[5]="")}let i=t[3],r=t[1]||es;return[r,i]=BA(r,i),Bf(i,r,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}},xW=[uW,vW],SW=[gW,xW],kW=qT(...SW),BA=(e,t)=>{const n=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return n||i?[e.indexOf("@")!==-1?e.split("@")[0]:es,n?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},Sc=1024,EW="Breadcrumbs",wW=((e={})=>{const t={console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0,...e};return{name:EW,setup(n){t.console&&m7(RW(n)),t.dom&&Y7(AW(n,t.dom)),t.xhr&&rW(_W(n)),t.fetch&&A7(IW(n)),t.history&&LA(NW(n)),t.sentry&&n.on("beforeSendEvent",TW(n))}}}),CW=wW;function TW(e){return function(n){rn()===e&&ts({category:`sentry.${n.type==="transaction"?"transaction":"event"}`,event_id:n.event_id,level:n.level,message:jr(n)},{event:n})}}function AW(e,t){return function(i){if(rn()!==e)return;let r,s,o=typeof t=="object"?t.serializeAttribute:void 0,a=typeof t=="object"&&typeof t.maxStringLength=="number"?t.maxStringLength:void 0;a&&a>Sc&&(io&&Oe.warn(`\`dom.maxStringLength\` cannot exceed ${Sc}, but a value of ${a} was configured. Sentry will use ${Sc} instead.`),a=Sc),typeof o=="string"&&(o=[o]);try{const l=i.event,u=MW(l)?l.target:l;r=$T(u,{keyAttrs:o,maxStringLength:a}),s=BG(u)}catch{r="<unknown>"}if(r.length===0)return;const c={category:`ui.${i.name}`,message:r};s&&(c.data={"ui.component_name":s}),ts(c,{event:i.event,name:i.name,global:i.global})}}function RW(e){return function(n){if(rn()!==e)return;const i={category:"console",data:{arguments:n.args,logger:"console"},level:b7(n.level),message:Lv(n.args," ")};if(n.level==="assert")if(n.args[0]===!1)i.message=`Assertion failed: ${Lv(n.args.slice(1)," ")||"console.assert"}`,i.data.arguments=n.args.slice(1);else return;ts(i,{input:n.args,level:n.level})}}function _W(e){return function(n){if(rn()!==e)return;const{startTimestamp:i,endTimestamp:r}=n,s=n.xhr[zo];if(!i||!r||!s)return;const{method:o,url:a,status_code:c,body:l}=s,u={method:o,url:a,status_code:c},d={xhr:n.xhr,input:l,startTimestamp:i,endTimestamp:r},h={category:"xhr",data:u,type:"http",level:PA(c)};e.emit("beforeOutgoingRequestBreadcrumb",h,d),ts(h,d)}}function IW(e){return function(n){if(rn()!==e)return;const{startTimestamp:i,endTimestamp:r}=n;if(r&&!(n.fetchData.url.match(/sentry_key/)&&n.fetchData.method==="POST"))if(n.fetchData.method,n.fetchData.url,n.error){const s=n.fetchData,o={data:n.error,input:n.args,startTimestamp:i,endTimestamp:r},a={category:"fetch",data:s,level:"error",type:"http"};e.emit("beforeOutgoingRequestBreadcrumb",a,o),ts(a,o)}else{const s=n.response,o={...n.fetchData,status_code:s==null?void 0:s.status};n.fetchData.request_body_size,n.fetchData.response_body_size,s==null||s.status;const a={input:n.args,response:s,startTimestamp:i,endTimestamp:r},c={category:"fetch",data:o,type:"http",level:PA(o.status_code)};e.emit("beforeOutgoingRequestBreadcrumb",c,a),ts(c,a)}}}function NW(e){return function(n){if(rn()!==e)return;let i=n.from,r=n.to;const s=eh(_t.location.href);let o=i?eh(i):void 0;const a=eh(r);o!=null&&o.path||(o=s),s.protocol===a.protocol&&s.host===a.host&&(r=a.relative),s.protocol===o.protocol&&s.host===o.host&&(i=o.relative),ts({category:"navigation",data:{from:i,to:r}})}}function MW(e){return!!e&&!!e.target}const PW=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","BroadcastChannel","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","SharedWorker","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],OW="BrowserApiErrors",DW=((e={})=>{const t={XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0,unregisterOriginalCallbacks:!1,...e};return{name:OW,setupOnce(){t.setTimeout&&Dn(_t,"setTimeout",wx),t.setInterval&&Dn(_t,"setInterval",wx),t.requestAnimationFrame&&Dn(_t,"requestAnimationFrame",BW),t.XMLHttpRequest&&"XMLHttpRequest"in _t&&Dn(XMLHttpRequest.prototype,"send",FW);const n=t.eventTarget;n&&(Array.isArray(n)?n:PW).forEach(r=>UW(r,t))}}}),LW=DW;function wx(e){return function(...t){const n=t[0];return t[0]=no(n,{mechanism:{handled:!1,type:`auto.browser.browserapierrors.${Cr(e)}`}}),e.apply(this,t)}}function BW(e){return function(t){return e.apply(this,[no(t,{mechanism:{data:{handler:Cr(e)},handled:!1,type:"auto.browser.browserapierrors.requestAnimationFrame"}})])}}function FW(e){return function(...t){const n=this;return["onload","onerror","onprogress","onreadystatechange"].forEach(r=>{r in n&&typeof n[r]=="function"&&Dn(n,r,function(s){const o={mechanism:{data:{handler:Cr(s)},handled:!1,type:`auto.browser.browserapierrors.xhr.${r}`}},a=Dm(s);return a&&(o.mechanism.data.handler=Cr(a)),no(s,o)})}),e.apply(this,t)}}function UW(e,t){var r,s;const i=(r=_t[e])==null?void 0:r.prototype;(s=i==null?void 0:i.hasOwnProperty)!=null&&s.call(i,"addEventListener")&&(Dn(i,"addEventListener",function(o){return function(a,c,l){try{jW(c)&&(c.handleEvent=no(c.handleEvent,{mechanism:{data:{handler:Cr(c),target:e},handled:!1,type:"auto.browser.browserapierrors.handleEvent"}}))}catch{}return t.unregisterOriginalCallbacks&&VW(this,a,c),o.apply(this,[a,no(c,{mechanism:{data:{handler:Cr(c),target:e},handled:!1,type:"auto.browser.browserapierrors.addEventListener"}}),l])}}),Dn(i,"removeEventListener",function(o){return function(a,c,l){try{const u=c.__sentry_wrapped__;u&&o.call(this,a,u,l)}catch{}return o.call(this,a,c,l)}}))}function jW(e){return typeof e.handleEvent=="function"}function VW(e,t,n){e&&typeof e=="object"&&"removeEventListener"in e&&typeof e.removeEventListener=="function"&&e.removeEventListener(t,n)}const zW=()=>({name:"BrowserSession",setupOnce(){if(typeof _t.document>"u"){io&&Oe.warn("Using the `browserSessionIntegration` in non-browser environments is not supported.");return}ix({ignoreDuration:!0}),rx(),LA(({from:e,to:t})=>{e!==void 0&&e!==t&&(ix({ignoreDuration:!0}),rx())})}}),GW="GlobalHandlers",HW=((e={})=>{const t={onerror:!0,onunhandledrejection:!0,...e};return{name:GW,setupOnce(){Error.stackTraceLimit=50},setup(n){t.onerror&&(WW(n),Cx("onerror")),t.onunhandledrejection&&(qW(n),Cx("onunhandledrejection"))}}}),KW=HW;function WW(e){AG(t=>{const{stackParser:n,attachStacktrace:i}=FA();if(rn()!==e||OA())return;const{msg:r,url:s,line:o,column:a,error:c}=t,l=JW(Wm(n,c||r,void 0,i,!1),s,o,a);l.level="error",mA(l,{originalException:c,mechanism:{handled:!1,type:"auto.browser.global_handlers.onerror"}})})}function qW(e){_G(t=>{const{stackParser:n,attachStacktrace:i}=FA();if(rn()!==e||OA())return;const r=QW(t),s=xu(r)?YW(r):Wm(n,r,void 0,i,!0);s.level="error",mA(s,{originalException:r,mechanism:{handled:!1,type:"auto.browser.global_handlers.onunhandledrejection"}})})}function QW(e){if(xu(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch{}return e}function YW(e){return{exception:{values:[{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(e)}`}]}}}function JW(e,t,n,i){const r=e.exception=e.exception||{},s=r.values=r.values||[],o=s[0]=s[0]||{},a=o.stacktrace=o.stacktrace||{},c=a.frames=a.frames||[],l=i,u=n,d=XW(t)??Om();return c.length===0&&c.push({colno:l,filename:d,function:es,in_app:!0,lineno:u}),e}function Cx(e){io&&Oe.log(`Global Handler attached: ${e}`)}function FA(){const e=rn();return(e==null?void 0:e.getOptions())||{stackParser:()=>[],attachStacktrace:!1}}function XW(e){if(!(!Wi(e)||e.length===0))return e.startsWith("data:")?`<${XK(e,!1)}>`:e}const ZW=()=>({name:"HttpContext",preprocessEvent(e){var i;if(!_t.navigator&&!_t.location&&!_t.document)return;const t=P7(),n={...t.headers,...(i=e.request)==null?void 0:i.headers};e.request={...t,...e.request,headers:n}}}),$W="cause",eq=5,tq="LinkedErrors",nq=((e={})=>{const t=e.limit||eq,n=e.key||$W;return{name:tq,preprocessEvent(i,r,s){const o=s.getOptions();p7(Hm,o.stackParser,n,t,i,r)}}}),iq=nq;function rq(){return sq()?(io&&po(()=>{console.error("[Sentry] You cannot use Sentry.init() in a browser extension, see: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/")}),!0):!1}function sq(){var s;if(typeof _t.window>"u")return!1;const e=_t;if(e.nw)return!1;const t=e.chrome||e.browser;if(!((s=t==null?void 0:t.runtime)!=null&&s.id))return!1;const n=Om(),i=["chrome-extension","moz-extension","ms-browser-extension","safari-web-extension"];return!(_t===_t.top&&i.some(o=>n.startsWith(`${o}://`)))}function oq(e){return[o7(),n7(),LW(),CW(),KW(),iq(),x7(),ZW(),zW()]}function aq(e={}){const t=!e.skipBrowserExtensionCheck&&rq();let n=e.defaultIntegrations==null?oq():e.defaultIntegrations;const i={...e,enabled:t?!1:e.enabled,stackParser:CG(e.stackParser||kW),integrations:CK({integrations:e.integrations,defaultIntegrations:n}),transport:e.transport||cW};return YK(K7,i)}function Tx(e={}){const t=_t.document,n=(t==null?void 0:t.head)||(t==null?void 0:t.body);if(!n){io&&Oe.error("[showReportDialog] Global document not defined");return}const i=_i(),r=rn(),s=r==null?void 0:r.getDsn();if(!s){io&&Oe.error("[showReportDialog] DSN not configured");return}const o={...e,user:{...i.getUser(),...e.user},eventId:e.eventId||yK()},a=_t.document.createElement("script");a.async=!0,a.crossOrigin="anonymous",a.src=EK(s,o);const{onLoad:c,onClose:l}=o;if(c&&(a.onload=c),l){const u=d=>{if(d.data==="__sentry_reportdialog_closed__")try{l()}finally{_t.removeEventListener("message",u)}};_t.addEventListener("message",u)}n.appendChild(a)}function cq(e){const t={...e};return IA(t,"react"),bK("react",{version:M.version}),aq(t)}function lq(e){const t=e.match(/^([^.]+)/);return t!==null&&parseInt(t[0])>=17}function uq(e,t){const n=new WeakSet;function i(r,s){if(!n.has(r)){if(r.cause)return n.add(r),i(r.cause,s);r.cause=s}}i(e,t)}function dq(e,{componentStack:t},n){if(lq(M.version)&&Pa(e)&&t){const i=new Error(e.message);i.name=`React ErrorBoundary ${e.name}`,i.stack=t,uq(e,i)}return Bm(i=>(i.setContext("react",{componentStack:t}),Vm(e,n)))}const hq=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,nh={componentStack:null,error:null,eventId:null};class fq extends D.Component{constructor(t){super(t),this.state=nh,this._openFallbackReportDialog=!0;const n=rn();n&&t.showDialog&&(this._openFallbackReportDialog=!1,this._cleanupHook=n.on("afterSendEvent",i=>{!i.type&&this._lastEventId&&i.event_id===this._lastEventId&&Tx({...t.dialogOptions,eventId:this._lastEventId})}))}componentDidCatch(t,n){const{componentStack:i}=n,{beforeCapture:r,onError:s,showDialog:o,dialogOptions:a}=this.props;Bm(c=>{r&&r(c,t,i);const l=this.props.handled!=null?this.props.handled:!!this.props.fallback,u=dq(t,n,{mechanism:{handled:l,type:"auto.function.react.error_boundary"}});s&&s(t,i,u),o&&(this._lastEventId=u,this._openFallbackReportDialog&&Tx({...a,eventId:u})),this.setState({error:t,componentStack:i,eventId:u})})}componentDidMount(){const{onMount:t}=this.props;t&&t()}componentWillUnmount(){const{error:t,componentStack:n,eventId:i}=this.state,{onUnmount:r}=this.props;r&&(this.state===nh?r(null,null,null):r(t,n,i)),this._cleanupHook&&(this._cleanupHook(),this._cleanupHook=void 0)}resetErrorBoundary(){const{onReset:t}=this.props,{error:n,componentStack:i,eventId:r}=this.state;t&&t(n,i,r),this.setState(nh)}render(){const{fallback:t,children:n}=this.props,i=this.state;if(i.componentStack===null)return typeof n=="function"?n():n;const r=typeof t=="function"?D.createElement(t,{error:i.error,componentStack:i.componentStack,resetError:()=>this.resetErrorBoundary(),eventId:i.eventId}):t;return D.isValidElement(r)?r:(t&&hq&&Oe.warn("fallback did not produce a valid ReactElement"),null)}}function pq(){cq({dsn:"https://e4ccc87e3f5dc1378aedf8d8af13b74d@o4509436774645760.ingest.us.sentry.io/4510775191732225",sendDefaultPii:!0})}const oe={info(e,t){nx(e,{level:"info",extra:t})},warn(e,t){nx(e,{level:"warning",extra:t})},error(e,t){Vm(e,{extra:t})}};class qm{constructor(){Be(this,"listeners",{})}on(t,n){return this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(n),()=>this.off(t,n)}once(t,n){const i=((...r)=>{this.off(t,i),n(...r)});return this.on(t,i)}off(t,n){const i=this.listeners[t];if(!i)return;const r=i.indexOf(n);r>-1&&i.splice(r,1)}removeAllListeners(t){t?delete this.listeners[t]:this.listeners={}}emit(t,...n){const i=this.listeners[t];if(!i)return;const r=[...i];for(const s of r)try{s(...n)}catch(o){oe.error(o)}}listenerCount(t){var n;return((n=this.listeners[t])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class UA{constructor(t){Be(this,"plugins",new Map);Be(this,"installedPlugins",new Set);Be(this,"context");this.context={client:t,emit:t.emit.bind(t),on:t.on.bind(t),config:{}}}register(t){if(this.plugins.has(t.name))throw new Error(`Plugin '${t.name}' is already registered`);if(t.dependencies){for(const n of t.dependencies)if(!this.plugins.has(n))throw new Error(`Plugin '${t.name}' depends on '${n}' which is not registered`)}this.plugins.set(t.name,t)}async install(t,n){const i=this.plugins.get(t);if(!i)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t))throw new Error(`Plugin '${t}' is already installed`);if(i.dependencies)for(const s of i.dependencies)this.installedPlugins.has(s)||await this.install(s);const r={...this.context,config:{...i.config,...n}};i.install&&await i.install(r),this.installedPlugins.add(t),this.setupPluginEvents(i,r)}async uninstall(t){var i;const n=this.plugins.get(t);if(!n)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t)){for(const[r,s]of this.plugins)if(this.installedPlugins.has(r)&&((i=s.dependencies)!=null&&i.includes(t)))throw new Error(`Cannot uninstall '${t}' because '${r}' depends on it`);n.uninstall&&await n.uninstall(this.context),this.installedPlugins.delete(t)}}isInstalled(t){return this.installedPlugins.has(t)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(t){return this.plugins.get(t)}setupPluginEvents(t,n){t.onSessionStart&&n.on("session.started",i=>{t.onSessionStart(n,i.id)}),t.onSessionEnd&&n.on("session.ended",i=>{t.onSessionEnd(n,i.id)}),t.onAgentResponse&&n.on("agent.response",i=>{t.onAgentResponse(n,i)})}}function mq(e){return e}function Qm(e,t,n){return{name:e,version:"1.0.0",description:`${t} modality plugin`,install:async i=>{n.onActivate&&await n.onActivate(i)},uninstall:async i=>{n.onDeactivate&&await n.onDeactivate(i)},onAgentResponse:n.onMessage}}const gq={name:"analytics",version:"1.0.0",description:"Built-in analytics tracking",install:async e=>{console.log("Analytics plugin installed"),e.on("session.started",t=>{console.log("Analytics: Session started",t.id)}),e.on("session.ended",(t,n)=>{console.log("Analytics: Session ended",t.id,n)}),e.on("chat.message.sent",t=>{console.log("Analytics: User message sent",t.content.length)})}},bq={name:"debug",version:"1.0.0",description:"Debug logging and development tools",install:async e=>{console.log("Debug plugin installed");const t=e.emit;e.emit=(n,...i)=>(console.log(`[Debug] Event: ${String(n)}`,i),t(n,...i))}},yq={name:"metrics",version:"1.0.0",description:"Advanced metrics collection",install:async e=>{console.log("Metrics plugin installed");const t=new Map;e.on("session.started",n=>{t.set(n.id,{startTime:Date.now(),events:[]})}),e.on("agent.response",n=>{console.log("Metrics: Agent response analyzed",{type:n.type,length:n.content.length,timestamp:n.timestamp})})}};class se extends Error{constructor(t,n,i){super(t),this.code=n,this.details=i,this.name="VoxketError"}}class jA extends qm{constructor(n,i){super();Be(this,"room",null);Be(this,"registeredMethods",new Map);Be(this,"activeInteractions",new Map);Be(this,"eventEmitter");Be(this,"currentInteraction",null);this.eventEmitter=n,i&&this.setRoom(i)}setRoom(n){this.room=n}async registerFrontendRPC(n,i,r="embedded"){if(!this.room){const o=new se("Room not initialized","UNKNOWN_ERROR");throw this.eventEmitter.emit("connection.error",o),oe.error(o),o}if(!this.room.localParticipant){const o=new se("Local participant not available for RPC registration","UNKNOWN_ERROR");throw this.eventEmitter.emit("connection.error",o),oe.error(o),o}const s={methodName:n,component:i,presentationMode:r};this.registeredMethods.set(n,s);try{this.room.registerRpcMethod(n,async o=>{this.emit("rpc.method.called",{methodName:n,data:o});let a,c=o.responseTimeout||30;try{a=JSON.parse(o.payload)}catch{a=o.payload}try{const l=await this.awaitUserInteraction(n,i,r,a,c);return JSON.stringify(l)}catch(l){throw new se(`RpcManager: Error in RPC method '${n}':`,"UNKNOWN_ERROR",l)}}),this.emit("rpc.method.registered",{methodName:n})}catch(o){if(o instanceof se)throw this.eventEmitter.emit("connection.error",o),oe.error(o),o;const a=new se(`RpcManager: Failed to register RPC method '${n}'`,"UNKNOWN_ERROR",o);throw this.eventEmitter.emit("connection.error",a),oe.error(a),o}}async awaitUserInteraction(n,i,r,s,o){return new Promise((a,c)=>{const l=`${n}_${Date.now()}`,u={didSuccess:(h,f)=>{this.clearInteraction(l),this.currentInteraction=null;const g={success:!0,message:"User interaction completed successfully",data:h,timestamp:new Date,...f?{successView:f}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:g}),a(g)},didFail:h=>{oe.warn(`RpcManager: User interaction failed for method: ${n}`),this.clearInteraction(l);const f={success:!1,message:"User interaction failed",error:h,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:f}),a(f)},dismissView:()=>{var f;oe.warn(`RpcManager: User dismissed interaction for method: ${n}`,{currentInteraction:(f=this.currentInteraction)==null?void 0:f.methodName}),this.clearInteraction(l),this.currentInteraction=null;const h={success:!0,data:{dismissed:!0,reason:"User dismissed the interaction"},message:"User interaction dismissed",timestamp:new Date};this.emit("rpc.interaction.dismissed",{methodName:n,response:h}),this.emit("rpc.interaction.completed",{methodName:n,response:h}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(this.currentInteraction=null)},0),a(h)},didTimeout:h=>{oe.warn(`RpcManager: User interaction timeout for method: ${n}`),this.clearInteraction(l),this.currentInteraction=null;const f={success:!0,message:`User interaction timed out after ${o} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...h?{timeoutView:h}:{}};this.emit("rpc.interaction.timeout",{methodName:n,response:f}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(oe.warn(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(f)}},d=setTimeout(()=>{u.didTimeout&&u.didTimeout()},o);this.activeInteractions.set(l,{resolve:h=>a(JSON.parse(h)),reject:c,timeoutId:d}),this.currentInteraction={isVisible:!0,methodName:n,component:i,presentationMode:r,timeout:o,data:s,handler:u},this.emit("rpc.interaction.started",{methodName:n,presentationMode:r}),setTimeout(async()=>{var h;if((h=this.currentInteraction)!=null&&h.handler)try{oe.info(`RpcManager: Component created for method: ${n} with data`,s)}catch(f){u.didFail({error:"Failed to load data into component"});const g=new se("Failed to load data into component","UNKNOWN_ERROR",f);this.eventEmitter.emit("connection.error",g),oe.error(g)}},100)})}clearInteraction(n){const i=this.activeInteractions.get(n);i&&(clearTimeout(i.timeoutId),this.activeInteractions.delete(n))}getCurrentInteraction(){return this.currentInteraction}dismissCurrentInteraction(){var n;this.currentInteraction&&((n=this.currentInteraction.handler)==null||n.dismissView(),setTimeout(()=>{this.currentInteraction&&(this.currentInteraction=null)},0))}getRegisteredMethods(){return Array.from(this.registeredMethods.keys())}unregisterMethod(n){this.registeredMethods.delete(n)}clear(){for(const[n,i]of this.activeInteractions)clearTimeout(i.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null}}class VA{constructor(t,n="User"){Be(this,"chatMessages",[]);Be(this,"activeTranscriptions",new Map);Be(this,"room",null);Be(this,"eventEmitter");Be(this,"participantName");this.eventEmitter=t,this.participantName=n}setRoom(t){this.room=t}setParticipantName(t){this.participantName=t}getChatMessages(){return[...this.chatMessages]}addChatMessage(t){this.chatMessages.some(i=>i.id===t.id)||this.chatMessages.push(t)}updateChatMessage(t){const n=this.chatMessages.findIndex(i=>i.id===t.id);n!==-1&&(this.chatMessages[n]=t)}clearChatMessages(){this.chatMessages=[],this.activeTranscriptions.clear()}trackTranscription(t,n){this.activeTranscriptions.set(t,{messageId:n,timestamp:Date.now()})}getActiveTranscription(t){const n=Date.now(),i=this.activeTranscriptions.get(t);return i&&n-i.timestamp<1e3?i:null}async sendMessage(t,n){if(!this.room){const i=new se("No room connection","CONNECTION_FAILED");throw oe.error(i),this.eventEmitter.emit("connection.error",i),i}if(!this.room.localParticipant){const i=new se("No local participant","CONNECTION_FAILED");throw oe.error(i),this.eventEmitter.emit("connection.error",i),i}try{const i={id:`msg_${Date.now()}`,content:t,sender:{id:"user",name:this.participantName,type:"participant"},timestamp:new Date,metadata:n||{}};await this.room.localParticipant.sendText(t,{topic:"lk.chat",destinationIdentities:[]}),this.eventEmitter.emit("chat.message.sent",i)}catch(i){const r=new se("Failed to send message","NETWORK_ERROR",i);throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}}async sendAttachments(t,n){if(!this.room){const r=new se("No room connection","CONNECTION_FAILED");throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}if(!this.room.localParticipant){const r=new se("No local participant","CONNECTION_FAILED");throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}if(!t||t.length===0){const r=new se("No files provided","INVALID_PARAMETER");throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}const i=t.filter(r=>r.type.startsWith("image/"));if(i.length===0){const r=new se("Only image files are allowed","INVALID_PARAMETER");throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}i.length!==t.length&&(this.eventEmitter.emit("connection.error",new se("Some non-image files were filtered out","WARN")),oe.warn("ChatManager: Some non-image files were filtered out"));try{const r=i.map(async(s,o)=>{const c={id:`att_${Date.now()}_${o}`,content:`📎 ${s.name}`,sender:{id:"user",name:this.participantName,type:"participant"},timestamp:new Date,metadata:{...n,type:"attachment",fileName:s.name,fileSize:s.size,mimeType:s.type,uploading:!0}};this.eventEmitter.emit("chat.message.sent",c);const l=await this.room.localParticipant.sendFile(s,{mimeType:s.type,topic:"images",onProgress:d=>{const h={...c,metadata:{...c.metadata,uploadProgress:d}};this.eventEmitter.emit("chat.message.updated",h)}});try{const d=new FileReader,h=new Promise((p,x)=>{d.onload=()=>{typeof d.result=="string"?p(d.result):x(new Error("Failed to convert to base64"))},d.onerror=x});d.readAsDataURL(s);const g={type:"image",data:await h,filename:s.name,mimeType:s.type,size:s.size};await this.room.localParticipant.sendText(JSON.stringify(g),{topic:"images",destinationIdentities:[]})}catch(d){oe.warn(`Send attachments error ${d}`);try{const h=`I've shared an image: ${s.name}`;await this.room.localParticipant.sendText(h,{topic:"lk.chat",destinationIdentities:[]})}catch(h){const f=new se("ChatManager: Failed to send image notification to agent","UNKNOWN_ERROR",h);this.eventEmitter.emit("connection.error",new se("Failed to send image notification to agent","WARN",h)),oe.error(f)}}const u={...c,metadata:{...c.metadata,uploading:!1,uploadProgress:1,streamId:l.id}};return this.eventEmitter.emit("chat.message.updated",u),l});await Promise.all(r)}catch(r){const s=new se("Failed to send attachments","NETWORK_ERROR",r);throw oe.error(s),this.eventEmitter.emit("connection.error",s),s}}async sendAttachment(t,n){return this.sendAttachments([t],n)}convertMarkdownToText(t){if(!t)return"";let n=t;return n=n.replace(/\*\*(.*?)\*\*/g,"$1"),n=n.replace(/__(.*?)__/g,"$1"),n=n.replace(/\*(.*?)\*/g,"$1"),n=n.replace(/_(.*?)_/g,"$1"),n=n.replace(/~~(.*?)~~/g,"$1"),n=n.replace(/`([^`]+)`/g,"$1"),n=n.replace(/```[\s\S]*?```/g,""),n=n.replace(/^#{1,6}\s+/gm,""),n=n.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),n.trim()}}class zA{constructor(t){Be(this,"room",null);Be(this,"eventEmitter");Be(this,"silencePreventionNode",null);Be(this,"silencePreventionOscillator",null);Be(this,"audioContext",null);this.eventEmitter=t,this.initializeAudioContext()}initializeAudioContext(){try{if(this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioContext.state==="suspended"){const t=async()=>{this.audioContext&&this.audioContext.state==="suspended"&&await this.audioContext.resume(),document.removeEventListener("click",t),document.removeEventListener("touchstart",t),document.removeEventListener("keydown",t)};document.addEventListener("click",t,{once:!0}),document.addEventListener("touchstart",t,{once:!0}),document.addEventListener("keydown",t,{once:!0})}}catch(t){const n=new se("MediaManager: Failed to initialize AudioContext:","UNKNOWN_ERROR",t);this.eventEmitter.emit("connection.error",new se("Audiocontext initialize failed","WARN",t)),oe.error(n)}}async ensureAudioContextRunning(){if(this.audioContext||this.initializeAudioContext(),this.audioContext&&this.audioContext.state==="suspended")try{await this.audioContext.resume()}catch(t){const n=new se("Failed to resume AudioContext","WARN",t);oe.error(n),this.eventEmitter.emit("connection.error",n)}}setRoom(t){this.room=t}getLocalParticipant(){var t;return((t=this.room)==null?void 0:t.localParticipant)??null}getRemoteParticipants(){var t;return Array.from(((t=this.room)==null?void 0:t.remoteParticipants.values())??[])}async toggleMicrophone(t){return this.setMicrophoneEnabled(t!==!1)}async setMicrophoneEnabled(t){var n,i;try{if(!this.room||this.room.state!=="connected"){const o=new se("Cannot enable microphone: room not connected","CONNECTION_FAILED");throw this.eventEmitter.emit("connection.error",o),oe.error(o),o}await this.ensureAudioContextRunning();const r=(n=this.room)==null?void 0:n.localParticipant.isMicrophoneEnabled,s=t??!r;s&&this.startSilencePrevention(),await((i=this.room)==null?void 0:i.localParticipant.setMicrophoneEnabled(s,{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0})),s?this.eventEmitter.emit("track.unmuted",{source:"microphone",enabled:!0}):(this.eventEmitter.emit("track.muted",{source:"microphone",enabled:!1}),this.stopSilencePrevention())}catch(r){this.stopSilencePrevention();const s=new se("Failed to toggle microphone","PERMISSION_DENIED",r);throw this.eventEmitter.emit("connection.error",s),oe.error(s),s}}startSilencePrevention(){try{if(this.audioContext||(this.audioContext=new AudioContext),this.silencePreventionOscillator)return;this.silencePreventionOscillator=this.audioContext.createOscillator(),this.silencePreventionNode=this.audioContext.createGain(),this.silencePreventionOscillator.frequency.value=20,this.silencePreventionNode.gain.value=.001,this.silencePreventionOscillator.connect(this.silencePreventionNode),this.silencePreventionNode.connect(this.audioContext.destination),this.silencePreventionOscillator.start()}catch(t){const n=new se("MediaManager: Failed to start silence prevention","UNKNOWN_ERROR",t);oe.error(n),this.eventEmitter.emit("connection.error",new se("Failed to start silence prevention","WARN",t))}}stopSilencePrevention(){try{this.silencePreventionOscillator&&(this.silencePreventionOscillator.stop(),this.silencePreventionOscillator.disconnect(),this.silencePreventionOscillator=null),this.silencePreventionNode&&(this.silencePreventionNode.disconnect(),this.silencePreventionNode=null)}catch(t){const n=new se("MediaManager: Failed to stop silence prevention","UNKNOWN_ERROR",t);oe.error(n),this.eventEmitter.emit("connection.error",new se("Failed to stop silence prevention","WARN",t))}}async toggleCamera(t){return this.setCameraEnabled(t!==!1)}async setCameraEnabled(t){var n,i;try{const r=(n=this.room)==null?void 0:n.localParticipant.isCameraEnabled,s=t??!r;await((i=this.room)==null?void 0:i.localParticipant.setCameraEnabled(s)),s?this.eventEmitter.emit("track.unmuted",{source:"camera",enabled:!0}):this.eventEmitter.emit("track.muted",{source:"camera",enabled:!1})}catch(r){const s=new se("Failed to toggle camera","PERMISSION_DENIED",r);throw oe.error(s),this.eventEmitter.emit("connection.error",s),s}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var t;try{await((t=this.room)==null?void 0:t.localParticipant.setScreenShareEnabled(!0)),this.eventEmitter.emit("track.unmuted",{source:"screenShare",enabled:!0})}catch(n){const i=new se("Failed to start screen share","PERMISSION_DENIED",n);throw oe.error(i),this.eventEmitter.emit("connection.error",i),i}}async stopScreenShare(){var t;try{await((t=this.room)==null?void 0:t.localParticipant.setScreenShareEnabled(!1)),this.eventEmitter.emit("track.muted",{source:"screenShare",enabled:!1})}catch(n){const i=new se("Failed to stop screen share","PERMISSION_DENIED",n);throw oe.error(i),this.eventEmitter.emit("connection.error",i),i}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="audioinput")}catch(t){const n=new se("Failed to get audio input devices","DEVICE_ERROR",t);throw oe.error(n),this.eventEmitter.emit("connection.error",n),n}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="videoinput")}catch(t){const n=new se("Failed to get video input devices","DEVICE_ERROR",t);throw oe.error(n),this.eventEmitter.emit("connection.error",n),n}}async setAudioInputDevice(t){var n;try{if(!((n=this.room)!=null&&n.localParticipant))throw new Error("Not connected to room")}catch(i){const r=new se("Failed to set audio input device","DEVICE_ERROR",i);throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}}async setVideoInputDevice(t){var n;try{if(!((n=this.room)!=null&&n.localParticipant))throw new Error("Not connected to room")}catch(i){const r=new se("Failed to set video input device","DEVICE_ERROR",i);throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}}getMicrophoneTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===z.Source.Microphone)return n.track;return null}getCameraTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===z.Source.Camera)return n.track;return null}getScreenShareTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===z.Source.ScreenShare)return n.track;return null}get isMicrophoneEnabled(){const t=this.getMicrophoneTrack();return t?!t.isMuted:!1}get isCameraEnabled(){const t=this.getCameraTrack();return t?!t.isMuted:!1}get isScreenShareEnabled(){const t=this.getScreenShareTrack();return t?!t.isMuted:!1}getAgentAudioTrack(){const t=this.getRemoteParticipants();for(const n of t){const i=n.getTrackPublication(z.Source.Microphone);if(i!=null&&i.track)return{source:z.Source.Microphone,participant:n,publication:i}}return null}getAgentVideoTrack(){const t=this.getRemoteParticipants();for(const n of t){const i=n.getTrackPublication(z.Source.Camera);if(i!=null&&i.track)return{source:z.Source.Camera,participant:n,publication:i}}return null}getVideoTrackRefs(){const t=[],n=this.getLocalParticipant();if(n){const r=n.getTrackPublication(z.Source.Camera);r!=null&&r.track&&t.push({source:z.Source.Camera,participant:n,publication:r});const s=n.getTrackPublication(z.Source.ScreenShare);s!=null&&s.track&&t.push({source:z.Source.ScreenShare,participant:n,publication:s})}const i=this.getRemoteParticipants();for(const r of i){const s=r.getTrackPublication(z.Source.Camera);s!=null&&s.track&&t.push({source:z.Source.Camera,participant:r,publication:s});const o=r.getTrackPublication(z.Source.ScreenShare);o!=null&&o.track&&t.push({source:z.Source.ScreenShare,participant:r,publication:o})}return t}getCameraTrackRefs(){return this.getVideoTrackRefs().filter(t=>t.source===z.Source.Camera)}getScreenShareTrackRefs(){return this.getVideoTrackRefs().filter(t=>t.source===z.Source.ScreenShare)}getPublishPermissions(){const t=this.getLocalParticipant();if(!t)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const n=t.permissions;if(!n)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const i=r=>!!n.canPublish&&(n.canPublishSources.length===0||n.canPublishSources.includes(r));return{camera:i(1),microphone:i(2),screenShare:i(3),data:n.canPublishData??!1}}canPublishSource(t){return this.getPublishPermissions()[t]}}class GA{constructor(t,n){Be(this,"room",null);Be(this,"config");Be(this,"eventEmitter");Be(this,"connectionState",Je.Disconnected);Be(this,"isConnected",!1);Be(this,"currentAgentInfo",null);this.config=t,this.eventEmitter=n,this.initializeRoom()}initializeRoom(){this.room=new Ki({adaptiveStream:!1,stopLocalTrackOnUnpublish:!1,audioCaptureDefaults:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},publishDefaults:{stopMicTrackOnMute:!1,preConnectBuffer:!0}}),this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(U.Connected,()=>{this.connectionState=Je.Connected,this.isConnected=!0,this.eventEmitter.emit("connection.connected")}),this.room.on(U.Disconnected,t=>{this.connectionState=Je.Disconnected,this.isConnected=!1,this.eventEmitter.emit("connection.disconnected",t==null?void 0:t.toString())}),this.room.on(U.ConnectionStateChanged,t=>{this.connectionState=t,t===Je.Connecting&&this.eventEmitter.emit("connection.connecting")}),this.room.on(U.ParticipantConnected,t=>{const n={id:t.identity,name:t.name||t.identity,isLocal:!1};this.eventEmitter.emit("participant.joined",n)}),this.room.on(U.ParticipantDisconnected,t=>{const n={id:t.identity,name:t.name||t.identity,isLocal:!1};this.eventEmitter.emit("participant.left",n)}),this.room.on(U.LocalTrackPublished,t=>{t.source===z.Source.ScreenShare&&this.eventEmitter.emit("track.unmuted",{source:"screenShare",enabled:!0})}),this.room.on(U.LocalTrackUnpublished,t=>{t.source===z.Source.ScreenShare&&this.eventEmitter.emit("track.muted",{source:"screenShare",enabled:!1})}),this.room.on(U.LocalAudioSilenceDetected,()=>{var t;(t=this.room)==null||t.remoteParticipants.forEach(n=>{this.eventEmitter.emit("connection.error",new se("Audio disabled detected!","WARN",{identity:n.identity,audioTracks:n.audioTrackPublications.size,hasAudio:Array.from(n.audioTrackPublications.values()).some(i=>i.track)}))})}),this.room.on(U.TrackSubscribed,(t,n,i)=>{var r;this.eventEmitter.emit("media.track.subscribed",{id:t.sid||n.trackSid,kind:t.kind,source:((r=t.source)==null?void 0:r.toString())||"unknown",participantId:i.identity,isEnabled:!t.isMuted,isMuted:t.isMuted})}),this.room.on(U.TrackUnsubscribed,(t,n,i)=>{var r;this.eventEmitter.emit("media.track.unsubscribed",{id:t.sid||n.trackSid,kind:t.kind,source:((r=t.source)==null?void 0:r.toString())||"unknown",participantId:i.identity,isEnabled:!1,isMuted:!0})}))}async fetchConnectionDetails(t,n,i,r){var s;try{const o={agent_id:t,participant_name:n,participant_metadata:r||{user_id:""},modality:i[0],modalities:i},a={accept:"application/json","Content-Type":"application/json"};if(this.config.authToken)a.Authorization=`Bearer ${this.config.authToken}`;else if(this.config.appId&&this.config.appSecret)a["X-APP-ID"]=this.config.appId,a["X-APP-SECRET"]=this.config.appSecret;else{const d=new se("Either authToken or both appId and appSecret must be provided","UNKNOWN_ERROR");throw oe.error(d),this.eventEmitter.emit("connection.error",d),d}const c=await fetch(`${this.config.baseUrl}/api/live/agent/session`,{method:"POST",headers:a,body:JSON.stringify(o)});if(!c.ok){let d=`HTTP ${c.status}: Failed to fetch connection details`;try{const h=await c.json();h&&(h.error?d=`API Error: ${h.error}`:h.detail?d=`API Error: ${h.detail}`:h.message&&(d=`API Error: ${h.message}`))}catch{try{const f=await c.text();f&&(d=`API Error: ${f}`)}catch{}}throw new Error(d)}const l=await c.json();let u;return l.agent_info&&(u={id:l.agent_info.agent_info.id,name:l.agent_info.agent_info.name,capabilities:l.agent_info.capabilities,modality_supported:l.agent_info.modality_supported,session_settings:l.agent_info.session_settings||{}},this.currentAgentInfo=u),{serverUrl:l.wss_url,participantToken:l.token,voxketSessionId:l.session_id,agentInfo:u}}catch(o){const a=new se(`Failed to fetch connection details: ${o instanceof Error?o.message:"Unknown error"}`,"CONNECTION_FAILED",o);throw this.eventEmitter.emit("connection.error",new se(((s=o.message)==null?void 0:s.split("API Error: ")[1])||"Failed to connect","CONNECTION_FAILED",o)),a}}async connect(t,n,i,r){var s;try{this.eventEmitter.emit("connection.connecting");const o=await this.fetchConnectionDetails(t,n,i,r);return await((s=this.room)==null?void 0:s.connect(o.serverUrl,o.participantToken)),this.isConnected=!0,o}catch(o){throw new se(`Failed to connect to Voxket services: ${o instanceof Error?o.message:"Unknown error"}`,"CONNECTION_FAILED",o)}}async disconnect(){try{this.room&&await this.room.disconnect(),this.isConnected=!1,this.currentAgentInfo=null,this.initializeRoom(),this.eventEmitter.emit("connection.disconnected")}catch(t){const n=new se("Failed to disconnect properly","NETWORK_ERROR",t);throw this.eventEmitter.emit("connection.error",n),n}}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===Je.Connected}getCurrentAgentInfo(){return this.currentAgentInfo}getParticipants(){if(!this.room)return[];const t=[];return this.room.localParticipant&&t.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(n=>{t.push({id:n.identity,name:n.name||n.identity,isLocal:!1})}),t}updateConfig(t){this.config={...this.config,...t}}}class HA{constructor(t,n,i){Be(this,"room",null);Be(this,"eventEmitter");Be(this,"chatManager");Be(this,"agentManager");Be(this,"textStreamHandlersRegistered",!1);Be(this,"_eventEmitters",new Map);this.eventEmitter=t,this.chatManager=n,this.agentManager=i}setRoom(t){this.room=t,t&&!this.textStreamHandlersRegistered&&this.setupTextStreamHandlers()}areHandlersRegistered(){return this.textStreamHandlersRegistered}resetHandlersFlag(){this.textStreamHandlersRegistered=!1}setupTextStreamHandlers(){this.room&&(this.registerChatHandler(),this.registerTranscriptionHandler(),this.registerSuggestedResponseHandler(),this.registerAgentStateHandler(),this.registerFunctionToolsHandler(),this.registerImageTextStreamHandler(),this.registerImageByteStreamHandler(),this.registerCommonTopicHandlers(),this.registerWildcardHandler(),this.textStreamHandlersRegistered=!0)}registerChatHandler(){try{this.room.registerTextStreamHandler("lk.chat",async(t,n)=>{try{const i=await t.readAll(),r={id:`msg_${Date.now()}_${n.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:i,timestamp:new Date,sender:{id:n.identity||"user",name:n.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.eventEmitter.emit("chat.message.received",r)}catch(i){const r=new se("StreamHandlerManager: Failed to process lk.chat message","UNKNOWN_ERROR",i);this.eventEmitter.emit("connection.error",new se("Failed to process lk.chat message","WARN",i)),oe.error(r)}})}catch(t){const n=new se("StreamHandlerManager: lk.chat handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerTranscriptionHandler(){try{this.room.registerTextStreamHandler("lk.transcription",async(t,n)=>{var i,r;try{const s=n.identity===((r=(i=this.room)==null?void 0:i.localParticipant)==null?void 0:r.identity),o=n.identity,a=this.chatManager.getActiveTranscription(o);let c,l=!0;a?(c=a.messageId,l=!1):(c=`msg_${s?"user":"agent"}_${n.identity}_${Date.now()}`,this.chatManager.trackTranscription(o,c));let u="";const d=this.agentManager.getCurrentAgentInfo(),h=(d==null?void 0:d.name)||n.identity||"AI Assistant",f=s?"participant":"agent",g=s?"User":h,p={id:c,content:"",timestamp:new Date,sender:{id:n.identity||"unknown",name:g,type:f},metadata:{topic:"lk.transcription",streaming:!0}};l&&this.eventEmitter.emit("chat.message.received",p);for await(const w of t){u+=w;const S=this.chatManager.convertMarkdownToText(u),v={...p,content:S,metadata:{...p.metadata,streaming:!0}};this.eventEmitter.emit("chat.message.updated",v)}const x=this.chatManager.convertMarkdownToText(u),y={...p,content:x,metadata:{...p.metadata,streaming:!1}};this.eventEmitter.emit("chat.message.updated",y);const E={id:c,text:x,isFinal:!0,startTime:p.timestamp.getTime(),participantId:n.identity||"agent"};this.eventEmitter.emit("transcription.received",E)}catch(s){const o=new se("StreamHandlerManager: Failed to process lk.transcription message","UNKNOWN_ERROR",s);oe.error(o);try{const a=await t.readAll(),c=this.agentManager.getCurrentAgentInfo(),l=(c==null?void 0:c.name)||n.identity||"AI Assistant",u={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:a,timestamp:new Date,sender:{id:n.identity||"agent",name:l,type:"agent"},metadata:{topic:"lk.transcription"}};this.eventEmitter.emit("chat.message.received",u);const d={id:u.id,text:u.content,isFinal:!0,startTime:u.timestamp.getTime(),participantId:n.identity||"agent"};this.eventEmitter.emit("transcription.received",d)}catch(a){const c=new se("StreamHandlerManager: Fallback failed for lk.transcription","UNKNOWN_ERROR",a);oe.error(c)}}})}catch(t){const n=new se("StreamHandlerManager: lk.transcription handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerSuggestedResponseHandler(){try{this.room.registerTextStreamHandler("suggested_response",async t=>{const n=await t.readAll();let i=[];try{i=["tes","hello how are you","algebra make me learn that","what is the meaning of life"]}catch(r){const s=new se("StreamHandlerManager: Failed to parse suggested_response","UNKNOWN_ERROR",r);oe.error(s)}this.eventEmitter.emit("suggested.response",i)})}catch(t){const n=new se("StreamHandlerManager: suggested_response handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerAgentStateHandler(){try{this.room.registerTextStreamHandler("agent_state_changed",async(t,n)=>{const i=await t.readAll();let r={};try{r=typeof i=="string"?JSON.parse(i.replace(/'/g,'"')):i}catch(s){const o=new se("StreamHandlerManager: Failed to parse agent_state_changed","UNKNOWN_ERROR",s);oe.error(o)}this.agentManager.handleAgentStateChanged(r)})}catch(t){const n=new se("StreamHandlerManager: agent_state_changed handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerFunctionToolsHandler(){try{this.room.registerTextStreamHandler("function_tools_executed",async(t,n)=>{const i=await t.readAll();let r={};try{if(typeof i=="string")try{r=JSON.parse(i)}catch{let o=i;try{o=o.replace(/\bTrue\b/g,"true"),o=o.replace(/\bFalse\b/g,"false"),o=o.replace(/\bNone\b/g,"null");const a=o.replace(/\\"/g,"___ESCAPED_QUOTE___");let c="",l=!1;for(let u=0;u<a.length;u++){const d=a[u],h=u>0?a[u-1]:"";d==='"'&&h!=="\\"?(l=!l,c+=d):d==="'"&&h!=="\\"&&!l?c+='"':c+=d}o=c.replace(/___ESCAPED_QUOTE___/g,'\\"'),r=JSON.parse(o)}catch(a){const c=new se("StreamHandlerManager: Enhanced parsing also failed","UNKNOWN_ERROR",a);oe.error(c);try{let l=i.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null");r=new Function("return "+l)()}catch(l){const u=new se("StreamHandlerManager: All parsing methods failed","UNKNOWN_ERROR",l);throw oe.error(u),u}}}else r=i}catch(s){const o=new se("StreamHandlerManager: Failed to parse function_tool_executed","UNKNOWN_ERROR",s);oe.error(o);let a=null;if(typeof i=="string"&&i.includes("visualization_data"))try{const c=i.match(/"arguments":\s*"({.*?})"/);if(c){const l=c[1].replace(/\\"/g,'"');a=JSON.parse(l)}}catch(c){const l=new se("StreamHandlerManager: Failed to extract visualization data","UNKNOWN_ERROR",c);oe.error(l)}r={type:"function_tools_executed",function_calls:[],function_call_outputs:[],created_at:Date.now()/1e3,parseError:!0,rawData:i,extractedVisualizationData:a}}this.eventEmitter.emit("tool.executed",r)})}catch(t){const n=new se("StreamHandlerManager: function_tool_executed handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerImageTextStreamHandler(){try{this.room.registerTextStreamHandler("images",async(t,n)=>{try{const i=await t.readAll()}catch(i){const r=new se("StreamHandlerManager: Error processing images stream","UNKNOWN_ERROR",i);oe.error(r)}})}catch(t){const n=new se("StreamHandlerManager: images text handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerImageByteStreamHandler(){try{this.room.registerByteStreamHandler("images",async(t,n)=>{var i,r;try{const s=t.info,o={id:`img_${Date.now()}_${n.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`🖼️ ${s.name||"Image"}`,sender:{id:n.identity||"agent",name:n.identity||"Agent",type:n.identity===((r=(i=this.room)==null?void 0:i.localParticipant)==null?void 0:r.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:s.name,fileSize:s.size,mimeType:s.mimeType,streamId:s.id,downloading:!0}};this.eventEmitter.emit("chat.message.received",o),t.onProgress&&(t.onProgress=d=>{const h={...o,metadata:{...o.metadata,downloadProgress:d||0}};this.eventEmitter.emit("chat.message.updated",h)});const a=[];for await(const d of t)a.push(d);const c=new Blob(a,{type:s.mimeType||"application/octet-stream"}),l=URL.createObjectURL(c),u={...o,metadata:{...o.metadata,downloading:!1,downloadProgress:1,downloadUrl:l,blob:c}};this.eventEmitter.emit("chat.message.updated",u)}catch(s){const o=new se("StreamHandlerManager: Error processing image attachment","UNKNOWN_ERROR",s);oe.error(o)}})}catch(t){const n=new se("StreamHandlerManager: image byte handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerCommonTopicHandlers(){["error","warning","status","system","debug","info"].forEach(n=>{try{this.room.registerTextStreamHandler(n,async(i,r)=>{try{const s=await i.readAll();if(n==="error"){let o={};try{o=typeof s=="string"?JSON.parse(s):s}catch{o={message:s}}this.eventEmitter.emit("agent.error",o)}else this.eventEmitter.emit("text.stream.received",{topic:n,data:s,participantInfo:r})}catch(s){const o=new se(`StreamHandlerManager: Failed to process '${n}' stream`,"UNKNOWN_ERROR",s);oe.error(o)}})}catch(i){const r=new se(`StreamHandlerManager: Handler for '${n}' already registered, skipping`,"UNKNOWN_ERROR",i);oe.error(r)}})}registerWildcardHandler(){try{this.room.registerTextStreamHandler("*",async(t,n)=>{var i;try{const r=await t.readAll(),s=((i=t.info)==null?void 0:i.topic)||"unknown";if(this._eventEmitters.has(s)){const o=this._eventEmitters.get(s);try{o(r)}catch(a){const c=new se(`StreamHandlerManager: Error in custom handler for topic '${s}'`,"UNKNOWN_ERROR",a);oe.error(c)}}else this.eventEmitter.emit("text.stream.unhandled",{topic:s,data:r,participantInfo:n})}catch(r){const s=new se("StreamHandlerManager: Failed to process unhandled text stream","UNKNOWN_ERROR",r);oe.error(s)}})}catch(t){const n=new se("StreamHandlerManager: Generic text stream handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerEventEmitter(t,n){if(!this.room)throw new Error("Room not available");this._eventEmitters.set(t,n);try{this.room.registerTextStreamHandler(t,async i=>{try{const r=await i.readAll();n(r)}catch(r){const s=new se(`Error processing event for topic '${t}'`,"UNKNOWN_ERROR",r);oe.error(s)}})}catch(i){const r=new se(`StreamHandlerManager: Direct handler registration failed for topic '${t}'`,"UNKNOWN_ERROR",i);oe.error(r)}}getRegisteredEventEmitters(){return Array.from(this._eventEmitters.keys())}hasEventEmitter(t){return this._eventEmitters.has(t)}}const KA=M.createContext(null);function Yc({config:e,children:t,autoConnect:n=!1,client:i}){const[r,s]=M.useState(null),[o,a]=M.useState(!1),[c,l]=M.useState(!1),[u,d]=M.useState(null),[h,f]=M.useState(null),[g,p]=M.useState("idle"),[x,y]=M.useState(null),[E,w]=M.useState([]),[S,v]=M.useState([]),[k,_]=M.useState([]);M.useEffect(()=>{const Q=i||new Ba(e);s(Q);const C=T(Q);return n&&!i&&I(Q),()=>{C(),i||Q.disconnect().catch(console.error)}},[e,n,i]);const T=Q=>{const C=()=>{l(!0),d(null)},K=()=>{a(!0),l(!1),d(null)},X=()=>{a(!1),l(!1),f(null),p("idle"),w([]),v([]),_([])},R=Z=>{d(Z),l(!1)},ae=Z=>{f(Z),p(Z.state)},he=Z=>{p(Z),h&&f({...h,state:Z})},ce=(Z,Re)=>{f(null),p("idle"),y(Re),w([]),v([]),_([])},ee=Z=>{w(Re=>[...Re,Z])},te=Z=>{w(Re=>Re.filter(tt=>tt.id!==Z.id))},ue=Z=>{v(Re=>[...Re,Z])},me=Z=>{v(Re=>[...Re,Z])},Me=Z=>{console.log("📝 VoxketProvider: Received transcription:",Z),_(Re=>Re.find(ge=>ge.id===Z.id)?(console.log("📝 VoxketProvider: Duplicate transcription detected, skipping:",Z.id),Re):(console.log("📝 VoxketProvider: Adding new transcription:",Z.id),[...Re,Z]))},ne=()=>{console.log("🧹 VoxketProvider: Clearing chat messages and transcriptions"),v([]),_([])};return Q.on("connection.connecting",C),Q.on("connection.connected",K),Q.on("connection.disconnected",X),Q.on("connection.error",R),Q.on("session.created",ae),Q.on("session.state.changed",he),Q.on("session.ended",ce),Q.on("participant.joined",ee),Q.on("participant.left",te),Q.on("chat.message.received",ue),Q.on("chat.message.sent",me),Q.on("transcription.received",Me),Q.on("chat.history.cleared",ne),()=>{console.log("📝 VoxketProvider: Cleaning up event listeners"),Q.off("connection.connecting",C),Q.off("connection.connected",K),Q.off("connection.disconnected",X),Q.off("connection.error",R),Q.off("session.created",ae),Q.off("session.state.changed",he),Q.off("session.ended",ce),Q.off("participant.joined",ee),Q.off("participant.left",te),Q.off("chat.message.received",ue),Q.off("chat.message.sent",me),Q.off("chat.history.cleared",ne),Q.off("transcription.received",Me)}},I=async Q=>{const C=Q||r;if(C)try{await C.connect()}catch(K){console.error("Failed to connect:",K)}},G={client:r,isConnected:o,isConnecting:c,connectionError:u,currentSession:h,sessionState:g,sessionMetrics:x,participants:E,chatMessages:S,transcriptions:k,connect:()=>I(),disconnect:async()=>{if(r)try{await r.disconnect()}catch(Q){console.error("Failed to disconnect:",Q)}},createSession:async(Q,C={})=>{if(!r)throw new Error("Client not initialized");const K={agentId:Q,participantName:C.participantName||"User",metadata:C.metadata,modalities:C.modalities||["voice"]};return await r.createSession(K)},endSession:async()=>r?await r.endSession():null,sendChatMessage:async Q=>{if(!r)throw new Error("Client not initialized");await r.sendChatMessage(Q)},setMicrophoneEnabled:async Q=>{if(!r)throw new Error("Client not initialized");await r.setMicrophoneEnabled(Q)},setCameraEnabled:async Q=>{if(!r)throw new Error("Client not initialized");await r.setCameraEnabled(Q)},startScreenShare:async()=>{if(!r)throw new Error("Client not initialized");await r.startScreenShare()},stopScreenShare:async()=>{if(!r)throw new Error("Client not initialized");await r.stopScreenShare()}};return m.jsx(KA.Provider,{value:G,children:t})}function Ii(){const e=M.useContext(KA);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}const pi=new WeakSet,ih=new WeakSet,kc=new WeakSet;class WA{constructor(t,n){Be(this,"renderedComponents",new Map);Be(this,"config");Be(this,"voxketClient");this.config=t,this.voxketClient=n}renderUI(t={}){const n=this.resolveTarget(t.target||"body"),i=this.getTargetKey(n);if(ih.has(n))return;if(kc.has(n)){setTimeout(()=>this.renderUI(t),100);return}if(pi.has(n)){const s=this.renderedComponents.get(i);if(s&&s.root){const o=this.buildWidgetProps(t);try{s.root.render(M.createElement(Yc,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:M.createElement(Jc,o)}));return}catch(a){const c=new se("Error re-rendering existing widget","UNKNOWN_ERROR",a);throw this.voxketClient.emit("connection.error",c),oe.error(c),c}}else pi.delete(n)}let r=this.renderedComponents.get(i);if(r&&r.target===n&&pi.has(n)){const s=r.root,o=this.buildWidgetProps(t);try{s.render(M.createElement(Yc,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:M.createElement(Jc,o)}))}catch(a){const c=new se("Error rendering Voxket widget","UNKNOWN_ERROR",a);throw this.voxketClient.emit("connection.error",c),oe.error(c),c}return}ih.add(n);try{if(r)try{r.root.unmount(),this.renderedComponents.delete(i),pi.delete(r.target),n.innerHTML=""}catch(a){const c=new se("Failed to cleanup existing root","UNKNOWN_ERROR",a);this.voxketClient.emit("connection.error",c),oe.error(c)}if(pi.has(n))return;const s=AR.createRoot(n);this.renderedComponents.set(i,{root:s,target:n}),pi.add(n);const o=this.buildWidgetProps(t);if(!s||typeof s.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{s.render(M.createElement(Yc,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:M.createElement(Jc,o)}))}catch(a){const c=new se("Error rendering Voxket widget","UNKNOWN_ERROR",a);throw this.voxketClient.emit("connection.error",c),oe.error(c),c}}finally{ih.delete(n)}}removeUI(t){const n=t?this.resolveTarget(t):null;if(n){const i=this.getTargetKey(n),r=this.renderedComponents.get(i);if(r){kc.add(n),this.renderedComponents.delete(i),pi.delete(n);const s=r.root,o=r.target;setTimeout(()=>{(l=>{typeof requestIdleCallback<"u"?requestIdleCallback(l,{timeout:100}):setTimeout(l,50)})(()=>{try{if(o&&o.isConnected&&!pi.has(o)&&s&&typeof s.unmount=="function")try{s.unmount()}catch{}}catch{}requestAnimationFrame(()=>{try{n&&n.isConnected&&n.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(u=>{try{u.parentNode&&u.parentNode.contains(u)&&u.remove()}catch{}})}catch{}finally{kc.delete(n)}})})},0)}else pi.delete(n),kc.delete(n);n===document.body&&n.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(o=>{if(o.classList.contains("bg-black")&&(o.classList.contains("backdrop-blur-sm")||o.classList.contains("bg-opacity-30")))try{o.remove()}catch(a){const c=new se("Failed to remove fixed element","UNKNOWN_ERROR",a);this.voxketClient.emit("connection.error",c),oe.error(c)}})}}removeAllUI(){const t=Array.from(this.renderedComponents.entries());this.renderedComponents.clear(),setTimeout(()=>{for(const[n,i]of t)try{i.target&&i.target.isConnected&&!pi.has(i.target)&&i.root.unmount()}catch{}this.forceCleanupFullscreenOverlays()},0)}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(n=>{if(n.classList.contains("bg-black")&&(n.classList.contains("backdrop-blur-sm")||n.classList.contains("bg-opacity-30")))try{n.remove()}catch(i){const r=new se("Failed to remove overlay","UNKNOWN_ERROR",i);this.voxketClient.emit("connection.error",r),oe.error(r)}})}resolveTarget(t){if(typeof t=="string"){const n=document.querySelector(t);if(!n)throw new Error(`Target element not found: ${t}`);return n}return t}getTargetKey(t){return t.id?t.id:t.className?t.tagName+"_"+t.className.replace(/\s+/g,"_"):t.tagName+"_"+t.outerHTML.length%1e3}buildWidgetProps(t){var i,r,s;const n=this.config;return{agentId:t.agentId||n.agentId||"default-agent",participantName:t.participantName||n.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:t.className,theme:typeof t.theme=="string"?t.theme:void 0,modalities:t.modality||n.modalities||["voice"],suportsChatInput:((i=t.modality)==null?void 0:i.includes("chat"))!==!1,suportsVideoInput:((r=t.modality)==null?void 0:r.includes("video"))===!0,suportsScreenShare:((s=t.modality)==null?void 0:s.includes("screen_share"))===!0,autoStart:t.autoStart,displayType:t.displayType||"widget",popupPosition:t.popupPosition||"bottom-right",popupTriggerText:t.popupTriggerText||"Open Chat",popupModalityMode:t.popupModalityMode||"all",width:t.width,height:t.height,onDisplayTypeChange:t.onDisplayTypeChange,prompts:t.prompts,statusMessage:t.statusMessage,welcomeTitle:t.welcomeTitle,welcomeSubTitle:t.welcomeSubTitle,loadingText:t.loadingText,voxketClient:this.voxketClient,participantMetadata:t.participantMetadata}}updateConfig(t){this.config=t}}class qA{constructor(t){Be(this,"agentState","idle");Be(this,"isAgentConnected",!1);Be(this,"currentAgentInfo",null);Be(this,"eventEmitter");this.eventEmitter=t}getAgentState(){return this.agentState}setAgentState(t){this.agentState!==t&&(this.agentState=t,this.eventEmitter.emit("agent.state.changed",{state:t}))}getIsAgentConnected(){return this.isAgentConnected}setAgentConnected(t){this.isAgentConnected=t}getCurrentAgentInfo(){return this.currentAgentInfo}setCurrentAgentInfo(t){this.currentAgentInfo=t}reset(){this.agentState="idle",this.isAgentConnected=!1,this.currentAgentInfo=null}handleAgentStateChanged(t){this.isAgentConnected||(this.setAgentConnected(!0),this.eventEmitter.emit("agent.connected",t)),t.new_state==="speaking"?(this.setAgentState("speaking"),this.eventEmitter.emit("agent.speaking",t)):t.new_state==="thinking"?(this.setAgentState("thinking"),this.eventEmitter.emit("agent.thinking",t)):(t.new_state==="idle"||t.new_state==="listening")&&this.setAgentState("idle")}}class Ba extends qm{constructor(n){super();Be(this,"config");Be(this,"pluginManager");Be(this,"rpcManager");Be(this,"chatManager");Be(this,"mediaManager");Be(this,"connectionManager");Be(this,"streamHandlerManager");Be(this,"uiRenderer");Be(this,"agentManager");Be(this,"currentSession",null);if(!n.authToken&&(!n.appId||!n.appSecret))throw new Error("Either authToken or both appId and appSecret must be provided");this.config=n,this.chatManager=new VA(this,n.participantName||"User"),this.mediaManager=new zA(this),this.agentManager=new qA(this),this.connectionManager=new GA({baseUrl:n.baseUrl,appId:n.appId,appSecret:n.appSecret,authToken:n.authToken},this),this.streamHandlerManager=new HA(this,this.chatManager,this.agentManager),this.uiRenderer=new WA(n,this),this.pluginManager=new UA(this),this.rpcManager=new jA(this),this.setupEventListeners(),this.setupRpcEventForwarding()}setupEventListeners(){this.on("connection.connected",()=>{var i,r,s,o,a;if((r=(i=this.config).onConnected)==null||r.call(i),this.currentSession&&this.currentSession.state==="connecting"){const c=this.currentSession.state;this.currentSession.state="connected",this.emit("session.state.changed","connected",c)}else oe.warn("⚠️ VoxketClient: Cannot update session state",{hasSession:!!this.currentSession,currentState:(s=this.currentSession)==null?void 0:s.state});const n=this.connectionManager.getRoom();if(n){this.rpcManager.setRoom(n);const c=Array.from(n.remoteParticipants.values()).find(l=>{var u;return(u=l.identity)==null?void 0:u.startsWith("agent-")});c&&(this.agentManager.getIsAgentConnected()||(this.agentManager.setAgentConnected(!0),this.emit("agent.connected",{identity:c.identity})))}(a=(o=this.currentSession)==null?void 0:o.activeModalities)!=null&&a.includes("voice")&&setTimeout(async()=>{try{this.mediaManager.getLocalParticipant()&&(this.mediaManager.isMicrophoneEnabled||(await this.mediaManager.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0})))}catch(c){const l=new se("VoxketClient: Failed to enable microphone after room connection:","UNKNOWN_ERROR",c);oe.error(l)}},100)}),this.on("connection.disconnected",n=>{var i,r,s;(r=(i=this.config).onDisconnected)==null||r.call(i,n),this.streamHandlerManager.resetHandlersFlag(),this.agentManager.reset(),this.chatManager.clearChatMessages(),n&&oe.warn("🔍 VoxketClient: Disconnect reason details:",{reason:n.toString(),currentSession:(s=this.currentSession)==null?void 0:s.id})}),this.on("connection.error",n=>{var i,r;(r=(i=this.config).onError)==null||r.call(i,n)}),this.on("chat.message.received",n=>{var i,r;this.chatManager.addChatMessage(n),(r=(i=this.config).onMessageReceived)==null||r.call(i,n)}),this.on("chat.message.updated",n=>{this.chatManager.updateChatMessage(n)}),this.on("chat.message.sent",n=>{this.chatManager.addChatMessage(n)}),this.on("transcription.received",n=>{var i,r;(r=(i=this.config).onTranscriptionReceived)==null||r.call(i,n)}),this.on("session.state.changed",n=>{var i,r;(r=(i=this.config).onSessionStateChanged)==null||r.call(i,n)}),this.on("session.created",n=>{var i,r;(r=(i=this.config).onSessionStart)==null||r.call(i,n.id)}),this.on("session.ended",(n,i)=>{var r,s;(s=(r=this.config).onSessionEnd)==null||s.call(r,i)}),this.on("participant.joined",n=>{var i,r;(r=(i=this.config).onUserJoined)==null||r.call(i,n.id)}),this.on("participant.left",n=>{var i,r;(r=(i=this.config).onUserLeft)==null||r.call(i,n.id)})}setupRpcEventForwarding(){if(!this.rpcManager){oe.warn("RpcManager not initialized, skipping event forwarding setup");return}this.rpcManager.on("rpc.method.registered",n=>this.emit("rpc.method.registered",n)),this.rpcManager.on("rpc.method.called",n=>this.emit("rpc.method.called",n)),this.rpcManager.on("rpc.interaction.started",n=>this.emit("rpc.interaction.started",n)),this.rpcManager.on("rpc.interaction.completed",n=>this.emit("rpc.interaction.completed",n)),this.rpcManager.on("rpc.interaction.timeout",n=>this.emit("rpc.interaction.timeout",n)),this.rpcManager.on("rpc.interaction.dismissed",n=>this.emit("rpc.interaction.dismissed",n))}async connect(n,i,r,s){const o=n||this.config.agentId||"default-agent",a=i||this.config.participantName||"User",c=r||this.config.modalities||["voice"],l=s||this.config.participantMetadata,u=await this.connectionManager.connect(o,a,c,l),d=this.connectionManager.getRoom();return this.chatManager.setRoom(d),this.mediaManager.setRoom(d),this.streamHandlerManager.setRoom(d),u.agentInfo&&this.agentManager.setCurrentAgentInfo(u.agentInfo),u}async disconnect(){await this.connectionManager.disconnect(),this.currentSession=null;const n=this.connectionManager.getRoom();this.chatManager.setRoom(n),this.mediaManager.setRoom(n),this.streamHandlerManager.setRoom(n)}async createSession(n){var i,r;try{const s=await this.connect(n.agentId,n.participantName,n.modalities,n.participantMetadata),o={id:s.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:s.agentInfo||this.agentManager.getCurrentAgentInfo()};this.currentSession=o,this.emit("session.created",o);const a=this.connectionManager.getRoom();if(a&&(a.state!=="connected"&&await new Promise((l,u)=>{const d=setTimeout(()=>{u(new Error("Room connection timeout"))},1e4),h=()=>{clearTimeout(d),a.off("connected",h),a.off("disconnected",f),l()},f=()=>{clearTimeout(d),a.off("connected",h),a.off("disconnected",f),u(new Error("Room disconnected while waiting for connection"))};a.once("connected",h),a.once("disconnected",f)}),this.currentSession.state="connected",this.emit("session.state.changed","connected","connecting"),await new Promise(l=>{const u=setTimeout(()=>{l(!1)},3e4),d=()=>{clearTimeout(u),this.off("agent.connected",d),this.off("participant.joined",h),l(!0)},h=f=>{var g,p;((g=f.id)!=null&&g.startsWith("agent-")||(p=f.name)!=null&&p.toLowerCase().includes("agent"))&&(clearTimeout(u),this.off("agent.connected",d),this.off("participant.joined",h),l(!0))};this.once("agent.connected",d),this.on("participant.joined",h),this.agentManager.getIsAgentConnected()&&(clearTimeout(u),this.off("agent.connected",d),this.off("participant.joined",h),l(!0))})&&(this.currentSession.state="active",this.emit("session.state.changed","active","connected"))),(i=n.modalities)!=null&&i.includes("voice"))try{await this.mediaManager.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0})}catch(c){const l=new se("Failed to enable microphone","WARN",c);oe.error(l)}if((r=n.modalities)!=null&&r.includes("video"))try{await new Promise(c=>setTimeout(c,200)),await this.mediaManager.enableCamera()}catch(c){oe.warn("Failed to enable camera",c)}return o}catch(s){if(s instanceof se)throw oe.error(s),s;if(s instanceof TypeError&&s.message.includes("fetch")){const a=new se("Network connection failed","CONNECTION_FAILED",s);throw oe.error(a),a}if(s instanceof Error&&s.message.includes("Failed to fetch connection details")){const a=new se(`API connection failed: ${s.message}`,"CONNECTION_FAILED",s);throw oe.error(a),a}const o=new se(`Failed to create session: ${s instanceof Error?s.message:"Unknown error"}`,"SESSION_NOT_FOUND",s);throw oe.error(o),o}}async startSession(n,i){const r={agentId:n||this.config.agentId||"default-agent",participantName:(i==null?void 0:i.participantName)||this.config.participantName||"User",modalities:(i==null?void 0:i.modalities)||this.config.modalities||["voice","chat"],metadata:i==null?void 0:i.metadata,participantMetadata:i==null?void 0:i.participantMetadata};return this.createSession(r)}async endSession(){var n,i;if(!this.currentSession)return null;try{const r={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((i=this.connectionManager.getRoom())==null?void 0:i.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]};return this.currentSession.endedAt=new Date,this.currentSession.state="disconnected",this.emit("session.ended",this.currentSession,r),await this.disconnect(),r}catch(r){throw r instanceof se?(oe.error(r),r):new se("Failed to end session","SESSION_NOT_FOUND",r)}}getCurrentSession(){return this.currentSession}getSessionMetrics(){var n,i;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((i=this.connectionManager.getRoom())==null?void 0:i.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]}:null}async sendMessage(n,i){if(!this.currentSession){const r=new se("No active session","SESSION_NOT_FOUND");throw oe.error(r),r}return this.dismissCurrentInteraction(),this.chatManager.sendMessage(n,i)}async sendChatMessage(n,i){return this.sendMessage(n,i)}async sendAttachments(n,i){if(!this.currentSession){const r=new se("No active session","SESSION_NOT_FOUND");throw oe.error(r),r}return this.dismissCurrentInteraction(),this.chatManager.sendAttachments(n,i)}async sendAttachment(n,i){return this.chatManager.sendAttachment(n,i)}getChatMessages(){return this.chatManager.getChatMessages()}addChatMessage(n){this.chatManager.addChatMessage(n)}updateChatMessage(n){this.chatManager.updateChatMessage(n)}clearChatMessages(){this.chatManager.clearChatMessages(),this.dismissCurrentInteraction(),this.uiRenderer.removeAllUI()}toggleMicrophone(n){return this.mediaManager.toggleMicrophone(n)}async setMicrophoneEnabled(n){return this.mediaManager.setMicrophoneEnabled(n)}toggleCamera(n){return this.mediaManager.toggleCamera(n)}async setCameraEnabled(n){return this.mediaManager.setCameraEnabled(n)}async enableCamera(){return this.mediaManager.enableCamera()}async disableCamera(){return this.mediaManager.disableCamera()}async startScreenShare(){return this.mediaManager.startScreenShare()}async stopScreenShare(){return this.mediaManager.stopScreenShare()}async getAudioInputDevices(){return this.mediaManager.getAudioInputDevices()}async getVideoInputDevices(){return this.mediaManager.getVideoInputDevices()}async setAudioInputDevice(n){return this.mediaManager.setAudioInputDevice(n)}async setVideoInputDevice(n){return this.mediaManager.setVideoInputDevice(n)}get isMicrophoneEnabled(){return this.mediaManager.isMicrophoneEnabled}get isCameraEnabled(){return this.mediaManager.isCameraEnabled}get isScreenShareEnabled(){return this.mediaManager.isScreenShareEnabled}getMicrophoneTrack(){return this.mediaManager.getMicrophoneTrack()}getCameraTrack(){return this.mediaManager.getCameraTrack()}getScreenShareTrack(){return this.mediaManager.getScreenShareTrack()}getAgentAudioTrack(){return this.mediaManager.getAgentAudioTrack()}getAgentVideoTrack(){return this.mediaManager.getAgentVideoTrack()}getVideoTrackRefs(){return this.mediaManager.getVideoTrackRefs()}getCameraTrackRefs(){return this.mediaManager.getCameraTrackRefs()}getScreenShareTrackRefs(){return this.mediaManager.getScreenShareTrackRefs()}getPublishPermissions(){return this.mediaManager.getPublishPermissions()}canPublishSource(n){return this.mediaManager.canPublishSource(n)}getLocalParticipant(){return this.mediaManager.getLocalParticipant()}getRemoteParticipants(){return this.mediaManager.getRemoteParticipants()}getParticipants(){return this.connectionManager.getParticipants()}getRoom(){return this.connectionManager.getRoom()}getConnectionState(){return this.connectionManager.getConnectionState()}get connected(){return this.connectionManager.connected}getCurrentAgentInfo(){return this.agentManager.getCurrentAgentInfo()}getIsAgentConnected(){return this.agentManager.getIsAgentConnected()}getAgentState(){return this.agentManager.getAgentState()}renderUI(n={}){this.uiRenderer.renderUI(n)}removeUI(n){this.uiRenderer.removeUI(n)}removeAllUI(){this.uiRenderer.removeAllUI()}async registerFrontendRPC(n,i,r="embedded"){return this.rpcManager.registerFrontendRPC(n,i,r)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}registerPlugin(n){this.pluginManager.register(n)}getPluginManager(){return this.pluginManager}registerEventListener(n,i){return this.on(n,i)}registerEventEmitter(n,i){return this.streamHandlerManager.registerEventEmitter(n,i)}getRegisteredEventEmitters(){return this.streamHandlerManager.getRegisteredEventEmitters()}hasEventEmitter(n){return this.streamHandlerManager.hasEventEmitter(n)}updateConfig(n){this.config={...this.config,...n},this.uiRenderer.updateConfig(this.config),this.connectionManager.updateConfig({baseUrl:this.config.baseUrl,appId:this.config.appId,appSecret:this.config.appSecret}),this.chatManager.setParticipantName(this.config.participantName||"User")}setParticipantMetadata(n){this.config.participantMetadata=n}getParticipantMetadata(){return this.config.participantMetadata}async startRecording(){var n;try{this.emit("recording.started",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(i){const r=new se("Failed to start recording","RECORDING_ERROR",i);throw oe.error(r),r}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(i){const r=new se("Failed to stop recording","RECORDING_ERROR",i);throw oe.error(r),r}}}let Ax=!1;function QA(){if(Ax||typeof document>"u")return;if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",QA);return}const e=document.createElement("div");e.className="flex",e.style.cssText="position:absolute;visibility:hidden;pointer-events:none;",document.body.appendChild(e);const n=window.getComputedStyle(e).display==="flex";document.body.removeChild(e),n||(Ax=!0,console.warn(`%c⚠️ Voxket SDK: CSS styles not loaded!
197
-
198
- %cThe widget will not display correctly.
199
- Please add this import to your app:
200
-
201
- %cimport '@voxket-ai/voxket-live/style.css';
202
-
203
- %cOr in your HTML:
204
- %c<link rel="stylesheet" href="node_modules/@voxket-ai/voxket-live/dist/index.css">`,"color: #f59e0b; font-size: 14px; font-weight: bold;","color: #fbbf24; font-size: 12px;","color: #22c55e; font-size: 12px; font-family: monospace; background: #1e293b; padding: 4px 8px; border-radius: 4px;","color: #fbbf24; font-size: 12px;","color: #22c55e; font-size: 11px; font-family: monospace; background: #1e293b; padding: 4px 8px; border-radius: 4px;"))}Ve.create(vm);Ve.create(ou);Ve.create(wT);Ve.create(_m);function YA({theme:e,mode:t,loadingText:n,sessionState:i}){const r=wn(e),s=()=>{if(i==="connected")return"Connecting to agent...";if(n)return n;switch(t){case"voice":return"Connecting to voice agent...";case"chat":return"Starting chat session...";default:return"Connecting..."}};return m.jsxs("div",{className:"flex flex-col items-center justify-center h-full w-full p-8",children:[m.jsxs("div",{className:"text-center",children:[m.jsx("h3",{className:`text-lg font-semibold mb-2 ${r.text.accent}`,children:s()}),m.jsx("p",{className:`text-sm ${r.text.muted}`,children:"Please wait a moment..."})]}),m.jsxs("div",{className:"flex space-x-1 mt-4",children:[m.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"0ms"}}),m.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"150ms"}}),m.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"300ms"}})]})]})}Ve.create(YA);function rh({theme:e}){const t=e==="light";return m.jsxs("div",{className:`font-bold left-0 right-0 flex-shrink-0 text-center py-1 px-2 text-[10px] mt-auto ${t?"text-gray-400 bg-white/80":"text-white/40 bg-black/40"}`,style:{lineHeight:"1.2",backdropFilter:"blur(4px)"},children:[m.jsx("span",{children:"Powered by "}),m.jsx("a",{href:"https://voxket.ai",target:"_blank",rel:"noopener noreferrer",className:`hover:underline font-bold ${t?"text-gray-500":"text-white/50"}`,children:"voxket.ai"}),m.jsx("span",{className:"mx-1",children:"·"}),m.jsx("span",{children:"AI can make mistakes"})]})}function Rx({children:e,theme:t,displayType:n="widget",onClose:i,popupPosition:r="bottom-right",onExpand:s,width:o,height:a}){const c=wn(t),l=o||"350px",u=a||"500px";if(n==="fullscreen")return m.jsx("div",{className:"fixed inset-0 z-[9999] bg-black/40 bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",onClick:d=>{d.target===d.currentTarget&&i&&i()},children:m.jsxs("div",{className:"w-full h-full max-w-7xl max-h-[95vh] rounded-2xl relative bg-transparent flex flex-col",onClick:d=>{d.stopPropagation()},children:[i&&m.jsx("button",{onClick:d=>{d.preventDefault(),d.stopPropagation(),i()},className:`absolute top-4 cursor-pointer right-4 z-[10000] w-12 h-12 rounded-full flex items-center justify-center transition-all duration-200 shadow-lg border backdrop-blur-sm ${t==="light"?"bg-white bg-opacity-90 text-gray-900 hover:bg-gray-100 border-gray-300":"bg-gray-900 bg-opacity-90 text-white hover:bg-gray-800 border-gray-700"}`,title:"Exit Fullscreen",type:"button",children:m.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:m.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),m.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${c.card} w-full h-full flex flex-col rounded-xl shadow-2xl relative overflow-hidden`,"data-theme":t,style:{minHeight:"600px",height:"100%",contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0},children:[m.jsx("div",{className:c.cardTopGradient}),m.jsx("div",{className:c.cardPurpleBlur}),m.jsx("div",{className:c.cardPinkBlur}),m.jsxs("div",{className:"relative z-10 flex flex-col h-full",style:{flex:"1 1 auto"},children:[e,m.jsx(rh,{theme:t})]}),m.jsx("div",{className:c.cardPulse1}),m.jsx("div",{className:c.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(n==="popup"){const d={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"};return m.jsx("div",{className:"fixed rounded-2xl inset-0 z-[9999] pointer-events-none",children:m.jsxs("div",{className:`fixed rounded-2xl ${d[r]} pointer-events-auto`,children:[i&&m.jsx("button",{onClick:i,className:`absolute -top-2 -right-2 z-10 w-8 h-8 rounded-full flex items-center justify-center transition-all duration-200 text-sm shadow-lg border ${t==="light"?"bg-white bg-opacity-90 text-gray-900 hover:bg-gray-100 border-gray-300":"bg-gray-900 bg-opacity-90 text-white hover:bg-gray-800 border-gray-700"}`,children:"×"}),m.jsxs("div",{id:"voice-card",className:`voxket-widget-root voxket-popup-mode theme-${t} ${c.card} rounded-2xl flex flex-col relative overflow-hidden`,"data-theme":t,"data-display-type":"popup",style:{width:l,height:u,minWidth:l,maxWidth:l,minHeight:u,maxHeight:u,contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0,display:"flex",flexDirection:"column"},children:[m.jsx("div",{className:c.cardTopGradient}),m.jsx("div",{className:c.cardPurpleBlur}),m.jsx("div",{className:c.cardPinkBlur}),m.jsxs("div",{className:"relative z-10 flex flex-col w-full min-h-0 overflow-hidden voxket-popup-content",style:{display:"flex",flexDirection:"column",flex:"1 1 auto"},children:[e,m.jsx(rh,{theme:t})]}),m.jsx("div",{className:c.cardPulse1}),m.jsx("div",{className:c.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return m.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${c.card} relative overflow-hidden w-full h-full`,"data-theme":t,style:{height:"100%",maxHeight:"100%",contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0},children:[m.jsx("div",{className:c.cardTopGradient}),m.jsx("div",{className:c.cardPurpleBlur}),m.jsx("div",{className:c.cardPinkBlur}),m.jsxs("div",{className:"relative z-10 flex flex-col h-full w-full",style:{flex:"1 1 auto"},children:[e,m.jsx(rh,{theme:t})]}),m.jsx("div",{className:c.cardPulse1}),m.jsx("div",{className:c.cardPulse2,style:{animationDelay:"1s"}})]})}function vq(e){if(typeof window>"u")return null;D.useEffect(()=>{QA()},[]);const{agentId:t,participantName:n,baseUrl:i,appSecret:r,appId:s,authToken:o,prompts:a,statusMessage:c,welcomeTitle:l,welcomeSubTitle:u,className:d,width:h,height:f,loadingText:g,suportsChatInput:p=!0,suportsVideoInput:x=!0,suportsScreenShare:y=!0,theme:E="vox",onError:w,onSessionStart:S,onSessionEnd:v,enableSessionLogging:k=!0,onSessionLogsUpdate:_,onSessionMetricsUpdate:T,modalities:I=["voice"],displayType:b="widget",popupPosition:A="bottom-right",popupTriggerText:P="Open Chat",onPopupToggle:B,voxketClient:L,onDisplayTypeChange:V,participantMetadata:J,popupModalityMode:re="all",popupTriggerLogoUrl:G}=e,[Q,C]=D.useState(null),K=D.useRef({x:0,y:0,isSwiping:!1}),X=Q||A,R=D.useRef(X);R.current=X;const ae=D.useCallback(j=>{window.removeEventListener("mouseup",ae),window.removeEventListener("touchend",ae);const ie=j.changedTouches?j.changedTouches[0].clientX:j.clientX,_e=j.changedTouches?j.changedTouches[0].clientY:j.clientY,st=ie-K.current.x,un=_e-K.current.y,ui=50;if(Math.abs(st)>ui||Math.abs(un)>ui){K.current.isSwiping=!0;let[tr,us]=R.current.split("-");Math.abs(st)>ui&&(us=st>0?"right":"left"),Math.abs(un)>ui&&(tr=un>0?"bottom":"top"),C(`${tr}-${us}`)}},[]),he=(j,ie)=>{K.current={x:j,y:ie,isSwiping:!1},window.addEventListener("mouseup",ae),window.addEventListener("touchend",ae)},[ce,ee]=D.useState(!1),[te,ue]=D.useState(null),[me,Me]=D.useState(()=>{try{if(L)return!!L.getCurrentSession()}catch(j){const ie=new se("Error checking existing session","UNKNOWN_ERROR",j);oe.error(ie)}return!1}),[ne,Z]=D.useState(!1),[Re,tt]=D.useState(t||""),[ge,Le]=D.useState(n||"User"),[ve,Pe]=D.useState(()=>{try{if(L)return L.getCurrentSession()}catch(j){const ie=new se("Error getting current session","UNKNOWN_ERROR",j);oe.error(ie)}return null}),[Te,rt]=D.useState(()=>{var j,ie;try{if(L){const _e=L.getCurrentSession();if((j=_e==null?void 0:_e.activeModalities)!=null&&j.includes("chat"))return"chat";if((ie=_e==null?void 0:_e.activeModalities)!=null&&ie.includes("voice"))return"voice"}}catch(_e){const st=new se("Error determining current mode","UNKNOWN_ERROR",_e);oe.error(st)}return"welcome"}),[Ht,ct]=D.useState(!1),[Mt,Qt]=D.useState(!1),[H,le]=D.useState(()=>I.length===1?I[0]:null),[Ue,Ke]=D.useState(!1);D.useEffect(()=>{},[b]);const $e=D.useRef(null);if(!$e.current)try{if(L)$e.current=L;else if(!o&&(!s||!r)){const j="Missing required props: Either provide 'authToken' or both 'appId' and 'appSecret'",ie=new se(j,"UNKNOWN_ERROR");oe.error(ie),ue(new Error(j)),ee(!0)}else if(i){const j={...o?{authToken:o}:{appId:s,appSecret:r},baseUrl:i,agentId:Re,onError:w,participantName:ge||"User",modalities:I,participantMetadata:J};$e.current=new Ba(j)}else{const j="Missing required prop: baseUrl",ie=new se(j,"UNKNOWN_ERROR");oe.error(ie),ue(new Error(j)),ee(!0)}}catch(j){const ie=new se("Failed to create VoxketClient","UNKNOWN_ERROR",j);oe.error(ie),ue(j),ee(!0)}const Ce=$e.current;D.useEffect(()=>{const j=$e.current;return()=>{j&&!L&&j.disconnect().catch(ie=>{const _e=new se("Error during widget cleanup disconnect","UNKNOWN_ERROR",ie);oe.error(_e)})}},[L]);const Jn=D.useMemo(()=>b==="popup"&&H?[H]:I,[b,H,I]),bt=D.useMemo(()=>{try{return Ce?Ce.getRoom()||new Ki:new Ki}catch(j){const ie=new se("Error getting room from client","UNKNOWN_ERROR",j);return oe.error(ie),new Ki}},[Ce,me,Te]);D.useEffect(()=>{if(bt){const j=()=>{},ie=(_e,st,un)=>{};return bt.on(U.Connected,j),bt.on(U.Disconnected,j),bt.on(U.TrackSubscribed,ie),()=>{bt.off(U.Connected,j),bt.off(U.Disconnected,j),bt.off(U.TrackSubscribed,ie)}}},[bt,ve==null?void 0:ve.id]),D.useEffect(()=>{(Te==="voice"||Te==="chat")&&!ve&&!me&&!ne&&Ce&&!Ce.connected&&(rt("welcome"),Z(!1))},[Te,ve,me,ne,Ce]);const{sessionMetrics:Un,sessionLogs:li,logEvent:en}=HT({room:bt,onSessionStart:S,onSessionEnd:v,enableConsoleLogging:k,enableLocalStorage:k,voxketSessionId:ve==null?void 0:ve.id});D.useEffect(()=>{_&&_(li)},[li,_]),D.useEffect(()=>{T&&Un&&T(Un)},[Un,T]),D.useEffect(()=>{if(!Ce)return;const j=(ie,_e)=>{(ie==="connecting"||ie==="connected")&&(ne||Z(!0)),ie==="active"&&(Z(!1),Me(!0)),(ie==="disconnected"||ie==="error")&&(Z(!1),Me(!1),Pe(null),rt("welcome"))};return Ce.on("session.state.changed",j),()=>{Ce.off("session.state.changed",j)}},[Ce,ne]),D.useEffect(()=>{if(!Ce)return;const j=()=>{const ie=Ce.connected,_e=Ce.getCurrentSession();!ie&&me&&!ne&&(Z(!1),Me(!1),Pe(null),rt("welcome")),ie&&_e&&ne&&(Z(!1),Me(!0),Pe(_e))};return Ce.on("connectionStateChanged",j),Ce.on("sessionEnded",()=>{Z(!1),Me(!1),Pe(null),rt("welcome")}),()=>{Ce.off("connectionStateChanged",j),Ce.off("sessionEnded",()=>{})}},[Ce,Te,ne,me]);const ln=!!(!!(Ce!=null&&Ce.connected)&&me&&ve);D.useEffect(()=>{const j=_e=>{Z(!1),Me(!1),Pe(null),rt("welcome")},ie=_e=>{const st=new se("Media devices error","UNKNOWN_ERROR",_e);oe.error(st)};return bt.on(U.MediaDevicesError,ie),bt.on(U.Disconnected,j),()=>{bt.off(U.Disconnected,j),bt.off(U.MediaDevicesError,ie)}},[bt,Te,me,ve==null?void 0:ve.id,ne]);const Ua=async()=>{try{if(!Ce){const ie=new se("VoxketClient not initialized","UNKNOWN_ERROR");oe.error(ie),ue(new Error("VoxketClient not initialized")),ee(!0);return}Z(!0),rt("voice"),en("USER_STARTED_VOICE_SESSION",{agentId:Re,participantName:ge});const j=await Ce.startSession(Re,{participantName:ge||"User",modalities:["voice"],participantMetadata:Ce.getParticipantMetadata()||J});Pe(j),Me(!0),Z(!1),S&&S(j.id)}catch(j){const ie=new se("Failed to start voice session","UNKNOWN_ERROR",j);oe.error(ie),Z(!1),Me(!1),rt("welcome")}},ja=async()=>{try{if(!Ce){const ie=new se("VoxketClient not initialized","UNKNOWN_ERROR");oe.error(ie),ue(new Error("VoxketClient not initialized")),ee(!0);return}Z(!0),rt("chat"),en("USER_STARTED_CHAT_SESSION",{agentId:Re,participantName:ge});const j=await Ce.startSession(Re,{participantName:ge||"User",modalities:["chat"],participantMetadata:Ce.getParticipantMetadata()||J});Pe(j),Me(!0),Z(!1),S&&S(j.id)}catch(j){const ie=new se("Failed to start chat session","UNKNOWN_ERROR",j);oe.error(ie),Z(!1),Me(!1),rt("welcome")}},yo=()=>{rt("welcome"),Z(!1),V&&V(e.displayType||"widget"),ve&&me?(Me(!1),Pe(null),Ce&&Ce.disconnect().catch(j=>{const ie=new se("Widget: Error during disconnect","UNKNOWN_ERROR",j);oe.error(ie)})):Ce&&Ce.connected&&Ce.disconnect().catch(j=>{const ie=new se("Widget: Error during force disconnect","UNKNOWN_ERROR",j);oe.error(ie)}),b==="popup"&&!Ht&&ct(!0)},ls=()=>{const j=!Ht;ct(j),B&&B(j),!j&&!(ve&&me)&&(rt("welcome"),Me(!1),Pe(null))},er=()=>{e.onDisplayTypeChange&&e.onDisplayTypeChange("widget")},O=()=>{if(e.onDisplayTypeChange)e.onDisplayTypeChange("fullscreen");else{const j=document.getElementById("voice-card")||document.querySelector(".voxket-widget-container");j&&j.requestFullscreen&&j.requestFullscreen().catch(ie=>{})}};D.useEffect(()=>{var j,ie;if(L&&Ce){const _e=Ce.getCurrentSession();Ce.connected,_e&&(Pe(_e),Me(!0),Z(!1),(j=_e.activeModalities)!=null&&j.includes("chat")?rt("chat"):(ie=_e.activeModalities)!=null&&ie.includes("voice")&&rt("voice"))}},[L,Ce]),D.useEffect(()=>()=>{!L&&Ce&&Ce.disconnect()},[Ce,L]);let q="w-96",ye="h-[25rem]",Fe={};if(h&&(h.startsWith("w-")?q=h:(Fe.width=h,q="")),f&&(f.startsWith("h-")?ye=f:(Fe.height=f,ye="")),b==="popup"&&!Ht)return m.jsxs("div",{onMouseDown:j=>he(j.clientX,j.clientY),onTouchStart:j=>he(j.touches[0].clientX,j.touches[0].clientY),style:{display:"contents"},children:[m.jsx(GT,{onClick:j=>{if(K.current.isSwiping){j.preventDefault(),j.stopPropagation(),K.current.isSwiping=!1;return}if(ln){!H&&(ve!=null&&ve.activeModalities)&&(ve.activeModalities.includes("chat")?le("chat"):ve.activeModalities.includes("voice")&&le("voice")),Qt(!1),ct(!0),B&&B(!0);return}if(re!=="all"){le(re),Qt(!1),ct(!0),B&&B(!0);return}if(I.length===1){le(I[0]),Qt(!1),ct(!0),B&&B(!0);return}Qt(ie=>!ie),le(null),Ke(!1)},position:X,ariaLabel:P,size:64,isRunning:ln,logoUrl:G,theme:E}),Mt&&re==="all"&&(()=>{const _e={};X==="bottom-right"?(_e.bottom=88,_e.right=16):X==="bottom-left"?(_e.bottom=88,_e.left=16):X==="top-right"?(_e.top=88,_e.right=16):(_e.top=88,_e.left=16);const st="absolute w-0 h-0 border-8",un=E==="light",ui=un?"border-t-white":"border-t-black",tr=un?"border-b-white":"border-b-black",us=X.startsWith("bottom")?m.jsx("div",{className:`${st} border-transparent ${ui}`,style:{bottom:-16,right:X.endsWith("right")?16:void 0,left:X.endsWith("left")?16:void 0}}):m.jsx("div",{className:`${st} border-transparent ${tr}`,style:{top:-16,right:X.endsWith("right")?16:void 0,left:X.endsWith("left")?16:void 0}}),vo=un?"bg-white text-gray-900 border-[2px] border-indigo-200/60 shadow-2xl shadow-indigo-200/30":"bg-black text-white shadow-2xl",Va=un?"bg-indigo-50 hover:bg-indigo-100 text-indigo-700 border border-indigo-200/50":"bg-white/10 hover:bg-white/20 text-white",Au=un?"text-gray-500":"text-white/70";return m.jsx("div",{className:`fixed z-[51] rounded-2xl ${vo}`,style:{..._e,padding:"10px"},onMouseDown:xo=>xo.stopPropagation(),onTouchStart:xo=>xo.stopPropagation(),children:m.jsxs("div",{className:"relative ",children:[us,m.jsx("div",{className:`text-xs uppercase tracking-wide mb-2 ${Au}`,children:"Choose modality"}),m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("button",{type:"button",onClick:()=>{le("voice"),Qt(!1),ct(!0),B&&B(!0)},className:`px-3 py-2 rounded-md text-sm transition-colors ${Va}`,title:"Voice",children:"Voice"}),m.jsx("button",{type:"button",onClick:()=>{le("chat"),Qt(!1),ct(!0),B&&B(!0)},className:`px-3 py-2 rounded-md text-sm transition-colors ${Va}`,title:"Chat",children:"Chat"})]})]})})})()]});if(ce||!Ce){const j=(te==null?void 0:te.message)||"VoxketWidget encountered an error. Please check your configuration.";return m.jsx("div",{className:`voxket-widget-root theme-${E} flex items-center justify-center p-8 ${d||""}`,style:{width:h||"400px",height:f||"500px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"},children:m.jsxs("div",{className:"text-center",children:[m.jsx("div",{className:"text-4xl mb-4",children:"⚠️"}),m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Widget Error"}),m.jsx("p",{className:"text-sm mb-4",children:j}),m.jsx("button",{onClick:()=>{ee(!1),ue(null),window.location.reload()},className:"px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"Retry"})]})})}let At=`voxket-widget-root theme-${E}`,Et={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};b==="widget"?(At+=` flex min-h-fit ${q} ${ye} ${d}`,Et={...Et,...Fe}):(At=`${d||""}`,Et={});const we=m.jsx("div",{className:"h-full w-full flex flex-col overflow-hidden z-10",children:m.jsxs(Ys,{mode:"wait",children:[Te==="welcome"&&!ne&&m.jsx(Ve.div,{initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"},className:"h-screen w-full",style:{height:"100%"},children:m.jsx(_m,{agentId:Re,participantName:ge||"",onAgentIdChange:tt,onParticipantNameChange:Le,onStartCall:Ua,onStartChat:ja,disabled:me||ne,prompts:a,statusMessage:c,title:l,subTitle:u,theme:E,modalities:Jn})},"welcome"),ne&&(Te==="voice"||Te==="chat")&&m.jsx(Ve.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.3,ease:"easeInOut"},className:"h-screen w-full",style:{height:"100%"},children:m.jsx(YA,{theme:E,mode:Te,loadingText:g,sessionState:ve==null?void 0:ve.state})},`loading-${Te}`),Te==="voice"&&!ne&&me&&Ce&&m.jsxs(Jp.Provider,{value:bt,children:[m.jsx(tB,{},`audio-${(ve==null?void 0:ve.id)||"no-session"}`),m.jsx(QL,{label:"Start Audio"},`start-audio-${(ve==null?void 0:ve.id)||"no-session"}`),m.jsx(Ve.div,{initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"},className:"h-screen w-full",style:{height:"100%"},children:m.jsx(vm,{loadingText:g,participantName:ge||"User",sessionStarted:me,disabled:!1,theme:E,client:Ce,displayType:b,onBack:b==="popup"?ls:yo})},"voice-session")]}),Te==="chat"&&!ne&&me&&Ce&&m.jsx(Ve.div,{initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"},className:"h-screen w-full",style:{height:"100%"},children:m.jsx(ou,{client:Ce,theme:E,displayType:b,onBack:b==="popup"?ls:yo,onEndChat:yo,disabled:!1})},"chat-view")]})});return b==="fullscreen"||b==="popup"?m.jsx(Rx,{theme:E,displayType:b,popupPosition:X,onClose:b==="fullscreen"?er:ls,width:h,height:f,children:we}):m.jsx("div",{className:At,style:Et,children:m.jsx(Rx,{theme:E,displayType:b,popupPosition:X,onExpand:O,children:we})})}function Jc(e){return m.jsx(fq,{fallback:m.jsx(gG,{}),children:m.jsx(vq,{...e})})}function xq({logs:e,onClear:t,onExport:n}){const[i,r]=M.useState(!1),[s,o]=M.useState(""),a=e.filter(c=>!s||c.event.toLowerCase().includes(s.toLowerCase()));return i?m.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:m.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[m.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[m.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("input",{type:"text",placeholder:"Filter events...",value:s,onChange:c=>o(c.target.value),className:"px-3 py-1 border rounded text-sm"}),m.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),m.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),m.jsx("button",{onClick:()=>r(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),m.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?m.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):m.jsx("div",{className:"space-y-2",children:a.map((c,l)=>m.jsxs("div",{className:"border rounded p-3 text-sm",children:[m.jsxs("div",{className:"flex items-center justify-between mb-1",children:[m.jsx("span",{className:"font-semibold text-blue-600",children:c.event}),m.jsx("span",{className:"text-gray-500 text-xs",children:new Date(c.timestamp).toLocaleTimeString()})]}),c.sessionId&&m.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",c.sessionId]}),c.data&&m.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:m.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(c.data,null,2)})})]},l))})})]})}):m.jsxs("button",{onClick:()=>r(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",e.length,")"]})}function Sq({metrics:e}){return e?m.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[m.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),m.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Session ID:"}),m.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Start Time:"}),m.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Messages:"}),m.jsx("div",{children:e.totalMessages})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Participants:"}),m.jsx("div",{children:e.participantCount})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),m.jsx("div",{children:e.connectionIssues})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Duration:"}),m.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function cs(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:i,endSession:r}=Ii(),s=M.useCallback(async(a,c)=>await i(a,c),[i]),o=M.useCallback(async()=>await r(),[r]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:s,stop:o}}function JA(){const{sessionMetrics:e,currentSession:t}=Ii();return{metrics:e,sessionId:t==null?void 0:t.id,duration:e==null?void 0:e.duration,participantCount:e==null?void 0:e.participantCount,messageCount:e==null?void 0:e.messageCount,audioQuality:e==null?void 0:e.audioQuality,networkStats:e==null?void 0:e.networkStats}}function XA(){const{setMicrophoneEnabled:e,client:t}=Ii(),[n,i]=M.useState(!1),[r,s]=M.useState(!1),o=M.useCallback(async()=>{if(!r){s(!0);try{const l=!n;await e(l),i(l)}catch(l){console.error("Failed to toggle microphone:",l)}finally{s(!1)}}},[n,r,e]),a=M.useCallback(async()=>{if(!(n||r)){s(!0);try{await e(!0),i(!0)}catch(l){console.error("Failed to enable microphone:",l)}finally{s(!1)}}},[n,r,e]),c=M.useCallback(async()=>{if(!(!n||r)){s(!0);try{await e(!1),i(!1)}catch(l){console.error("Failed to disable microphone:",l)}finally{s(!1)}}},[n,r,e]);return{isEnabled:n,isLoading:r,toggle:o,enable:a,disable:c}}function ZA(){const{setCameraEnabled:e}=Ii(),[t,n]=M.useState(!1),[i,r]=M.useState(!1),s=M.useCallback(async()=>{if(!i){r(!0);try{const c=!t;await e(c),n(c)}catch(c){console.error("Failed to toggle camera:",c)}finally{r(!1)}}},[t,i,e]),o=M.useCallback(async()=>{if(!(t||i)){r(!0);try{await e(!0),n(!0)}catch(c){console.error("Failed to enable camera:",c)}finally{r(!1)}}},[t,i,e]),a=M.useCallback(async()=>{if(!(!t||i)){r(!0);try{await e(!1),n(!1)}catch(c){console.error("Failed to disable camera:",c)}finally{r(!1)}}},[t,i,e]);return{isEnabled:t,isLoading:i,toggle:s,enable:o,disable:a}}function $A(){const{startScreenShare:e,stopScreenShare:t}=Ii(),[n,i]=M.useState(!1),[r,s]=M.useState(!1),o=M.useCallback(async()=>{if(!(n||r)){s(!0);try{await e(),i(!0)}catch(l){console.error("Failed to start screen share:",l)}finally{s(!1)}}},[n,r,e]),a=M.useCallback(async()=>{if(!(!n||r)){s(!0);try{await t(),i(!1)}catch(l){console.error("Failed to stop screen share:",l)}finally{s(!1)}}},[n,r,t]),c=M.useCallback(async()=>{n?await a():await o()},[n,o,a]);return{isSharing:n,isLoading:r,start:o,stop:a,toggle:c}}function kq(){const{client:e}=Ii(),[t,n]=M.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),i=M.useMemo(()=>t.tracks.find(p=>p.isLocal),[t.tracks]),r=M.useMemo(()=>t.tracks.filter(p=>!p.isLocal),[t.tracks]),s=M.useCallback(async()=>{try{i!=null&&i.isEnabled?await(e==null?void 0:e.disableCamera()):await(e==null?void 0:e.enableCamera())}catch(p){throw console.error("Failed to toggle camera:",p),p}},[e,i]),o=M.useCallback(async()=>{try{t.tracks.find(x=>x.isScreenShare)?await(e==null?void 0:e.stopScreenShare()):await(e==null?void 0:e.startScreenShare())}catch(p){throw console.error("Failed to toggle screen share:",p),p}},[e,t.tracks]),a=M.useCallback(p=>{n(x=>({...x,layout:p}))},[]),c=M.useCallback(p=>{n(x=>({...x,pinnedTrack:p}))},[]),l=M.useCallback(()=>{n(p=>({...p,pinnedTrack:void 0}))},[]),u=M.useCallback(async()=>{try{await(e==null?void 0:e.startRecording()),n(p=>({...p,isRecording:!0}))}catch(p){throw console.error("Failed to start recording:",p),p}},[e]),d=M.useCallback(async()=>{try{await(e==null?void 0:e.stopRecording()),n(p=>({...p,isRecording:!1}))}catch(p){throw console.error("Failed to stop recording:",p),p}},[e]),h=M.useCallback(p=>t.tracks.find(x=>x.id===p),[t.tracks]),f=M.useCallback(p=>t.tracks.filter(x=>x.participantId===p),[t.tracks]),g=M.useCallback(p=>p.isEnabled&&t.tracks.includes(p),[t.tracks]);return M.useEffect(()=>{if(!e)return;const p=E=>{n(w=>({...w,tracks:[...w.tracks.filter(S=>S.id!==E.id),E]}))},x=E=>{n(w=>{var S;return{...w,tracks:w.tracks.filter(v=>v.id!==E),pinnedTrack:((S=w.pinnedTrack)==null?void 0:S.id)===E?void 0:w.pinnedTrack}})},y=E=>{n(w=>({...w,tracks:w.tracks.map(S=>S.id===E.id?E:S)}))};return e.on("videoTrackAdded",p),e.on("videoTrackRemoved",x),e.on("videoTrackUpdated",y),()=>{e.off("videoTrackAdded",p),e.off("videoTrackRemoved",x),e.off("videoTrackUpdated",y)}},[e]),{tracks:t.tracks,localTrack:i,remoteTraracks:r,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:s,toggleScreenShare:o,setLayout:a,pinTrack:c,unpinTrack:l,startRecording:u,stopRecording:d,getTrackById:h,getTracksByParticipant:f,isTrackActive:g}}function Tu(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=Ii(),[i,r]=M.useState(!1),s=M.useCallback(async l=>{if(!(!l.trim()||i||!n)){r(!0);try{await t(l.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{r(!1)}}},[t,i,n]),{userMessages:o,agentMessages:a,allMessages:c}=M.useMemo(()=>{const l=e.filter(d=>d.sender.type==="participant"),u=e.filter(d=>d.sender.type==="agent");return{userMessages:l,agentMessages:u,allMessages:e}},[e]);return{messages:c,userMessages:o,agentMessages:a,messageCount:c.length,isSending:i,canSend:!!n&&!i,send:s}}function Eq(){const{send:e,isSending:t,canSend:n}=Tu(),[i,r]=M.useState(""),s=M.useCallback(async()=>{if(!(!i.trim()||!n))try{await e(i),r("")}catch(a){throw a}},[i,e,n]),o=M.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),s())},[s]);return{value:i,setValue:r,send:s,handleKeyPress:o,isSending:t,canSend:n&&i.trim().length>0}}function Ym(){const{isConnected:e,isConnecting:t,connectionError:n,connect:i,disconnect:r}=Ii(),s=M.useCallback(async()=>{if(!(e||t))try{await i()}catch(a){throw console.error("Failed to connect:",a),a}},[i,e,t]),o=M.useCallback(async()=>{if(e)try{await r()}catch(a){throw console.error("Failed to disconnect:",a),a}},[r,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:s,disconnect:o}}function eR(){const{participants:e}=Ii();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const tR=M.createContext({}),Fa=()=>M.useContext(tR);function nR({children:e,...t}){return m.jsx(tR.Provider,{value:t,children:e})}function Xc({name:e,children:t,fallback:n,className:i}){return m.jsx("div",{className:`voxket-slot voxket-slot--${e} ${i||""}`,children:t||n})}function iR(e,t={}){return Object.assign(e,t)}function rR({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:i=!0,customControls:r,className:s=""}){const o=cs(),a=XA(),c=ZA(),l=$A(),u=Fa(),d=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,o.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",s].filter(Boolean).join(" ");return!o.isActive&&!i?m.jsx("div",{className:d,children:m.jsx("div",{className:"voxket-controls-inactive",children:m.jsx("p",{children:"Controls available during active session"})})}):m.jsxs("div",{className:d,children:[i&&m.jsx("div",{className:"voxket-session-actions",children:o.isActive?m.jsx("button",{onClick:o.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):m.jsx(wq,{})}),o.isActive&&m.jsxs("div",{className:"voxket-media-controls",children:[e&&m.jsxs("button",{onClick:a.toggle,disabled:a.isLoading,className:`voxket-button voxket-button--media ${a.isEnabled?"voxket-button--active":""}`,title:a.isEnabled?"Mute microphone":"Unmute microphone",children:[m.jsx("span",{className:"voxket-icon",children:"🎤"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&m.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isEnabled?"voxket-button--active":""}`,title:c.isEnabled?"Stop camera":"Start camera",children:[m.jsx("span",{className:"voxket-icon",children:"📹"}),c.isLoading?"Loading...":c.isEnabled?"Stop Video":"Start Video"]}),n&&m.jsxs("button",{onClick:l.toggle,disabled:l.isLoading,className:`voxket-button voxket-button--media ${l.isSharing?"voxket-button--active":""}`,title:l.isSharing?"Stop screen share":"Start screen share",children:[m.jsx("span",{className:"voxket-icon",children:"🖥️"}),l.isLoading?"Loading...":l.isSharing?"Stop Share":"Share Screen"]})]}),r&&m.jsx("div",{className:"voxket-custom-controls",children:r})]})}function wq(){cs();const[e,t]=M.useState(!1),n=async()=>{t(!0);try{console.log("Start session - agentId needed")}catch(i){console.error("Failed to start session:",i)}finally{t(!1)}};return m.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function Jm({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:i=""}){const r=cs(),s=Ym(),o=Fa(),a=["voxket-session-header",`voxket-session-header--${o.variant||"default"}`,`voxket-session-header--${o.size||"md"}`,i].filter(Boolean).join(" ");return m.jsxs("div",{className:a,children:[e&&m.jsxs("div",{className:"voxket-connection-status",children:[m.jsx("div",{className:`voxket-status-indicator ${s.isConnected?"connected":"disconnected"}`}),m.jsx("span",{className:"voxket-status-text",children:s.isConnecting?"Connecting...":s.isConnected?"Connected":"Disconnected"})]}),t&&r.session&&m.jsxs("div",{className:"voxket-session-info",children:[m.jsxs("div",{className:"voxket-session-id",children:["Session: ",r.session.id.slice(-8)]}),m.jsxs("div",{className:"voxket-session-state",children:["State: ",r.state]})]}),n&&r.session&&m.jsxs("div",{className:"voxket-agent-info",children:[m.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",r.session.agentId]}),m.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",r.session.activeModalities.join(", ")]})]}),s.error&&m.jsxs("div",{className:"voxket-error-message",children:["Error: ",s.error.message]})]})}function Xm({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:i=""}){const r=cs(),s=Tu(),o=Fa(),a=["voxket-session-content",`voxket-session-content--${o.variant||"default"}`,`voxket-session-content--${o.size||"md"}`,i].filter(Boolean).join(" ");return r.isActive?m.jsx("div",{className:a,children:n||m.jsxs(m.Fragment,{children:[e&&m.jsxs("div",{className:"voxket-chat-container",children:[m.jsxs("div",{className:"voxket-chat-messages",children:[s.messages.map(c=>m.jsxs("div",{className:`voxket-message voxket-message--${c.sender.type}`,children:[m.jsxs("div",{className:"voxket-message-header",children:[m.jsx("span",{className:"voxket-message-sender",children:c.sender.name}),m.jsx("span",{className:"voxket-message-time",children:c.timestamp.toLocaleTimeString()})]}),m.jsx("div",{className:"voxket-message-content",children:c.content})]},c.id)),s.messages.length===0&&m.jsx("div",{className:"voxket-empty-messages",children:m.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),m.jsx(Cq,{})]}),t&&m.jsx("div",{className:"voxket-transcriptions",children:m.jsx("div",{className:"voxket-transcription-placeholder",children:m.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):m.jsx("div",{className:a,children:m.jsx("div",{className:"voxket-inactive-state",children:m.jsxs("div",{className:"voxket-inactive-message",children:[m.jsx("h3",{children:"Start a conversation"}),m.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function Cq(){const e=Tu(),[t,n]=M.useState(""),i=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(s){console.error("Failed to send message:",s)}},r=s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),i())};return m.jsxs("div",{className:"voxket-chat-input",children:[m.jsx("input",{type:"text",value:t,onChange:s=>n(s.target.value),onKeyPress:r,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),m.jsx("button",{onClick:i,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function Zm({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:i,className:r=""}){const s=cs(),o=JA(),a=eR(),c=Fa(),l=["voxket-session-footer",`voxket-session-footer--${c.variant||"default"}`,`voxket-session-footer--${c.size||"md"}`,r].filter(Boolean).join(" ");return s.isActive?m.jsx("div",{className:l,children:i||m.jsxs(m.Fragment,{children:[n&&m.jsxs("div",{className:"voxket-session-status",children:[m.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),m.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&o.metrics&&m.jsxs("div",{className:"voxket-session-metrics",children:[m.jsxs("div",{className:"voxket-metric",children:[m.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),m.jsx("span",{className:"voxket-metric-value",children:Tq(o.duration||0)})]}),m.jsxs("div",{className:"voxket-metric",children:[m.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),m.jsx("span",{className:"voxket-metric-value",children:o.metrics.messageCount})]})]}),t&&m.jsxs("div",{className:"voxket-participants-info",children:[m.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&m.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>m.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):m.jsx("div",{className:l,children:m.jsx("div",{className:"voxket-footer-inactive",children:m.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function Tq(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),i=Math.floor(n/60);return i>0?`${i}:${(n%60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}`:`${n}:${(t%60).toString().padStart(2,"0")}`}function Aq({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:i,onSessionEnd:r,variant:s="default",size:o="md",theme:a,className:c="",children:l}){var f;const u=cs(),d=Ym();M.useEffect(()=>{n&&e&&d.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,d.isConnected,u.isActive]),M.useEffect(()=>{var g;(g=u.session)!=null&&g.id&&i&&i(u.session.id)},[(f=u.session)==null?void 0:f.id,i]),M.useEffect(()=>()=>{u.isActive&&r&&u.stop().then(r).catch(console.error)},[]);const h=["voxket-session",`voxket-session--${s}`,`voxket-session--${o}`,u.isActive?"voxket-session--active":"voxket-session--inactive",c].filter(Boolean).join(" ");return m.jsx(nR,{variant:s,size:o,theme:a,className:c,children:m.jsx("div",{className:h,children:l||m.jsxs(m.Fragment,{children:[m.jsx(Xc,{name:"header",fallback:m.jsx(Jm,{})}),m.jsx(Xc,{name:"content",fallback:m.jsx(Xm,{})}),m.jsx(Xc,{name:"footer",fallback:m.jsx(Zm,{})})]})})})}const sR=iR(Aq,{Header:Jm,Content:Xm,Footer:Zm,Controls:rR}),Qr={name:"default",colors:{primary:"#3B82F6",secondary:"#6B7280",accent:"#8B5CF6",background:"#FFFFFF",surface:"#F9FAFB",text:{primary:"#111827",secondary:"#6B7280",muted:"#9CA3AF",inverse:"#FFFFFF"},status:{success:"#10B981",warning:"#F59E0B",error:"#EF4444",info:"#3B82F6"},border:"#E5E7EB",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},typography:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:{xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700},lineHeight:{tight:1.25,normal:1.5,relaxed:1.75}},spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{none:"0",sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},shadows:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",md:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1)"}},Ff={...Qr,name:"dark",colors:{primary:"#60A5FA",secondary:"#9CA3AF",accent:"#A78BFA",background:"#111827",surface:"#1F2937",text:{primary:"#F9FAFB",secondary:"#D1D5DB",muted:"#9CA3AF",inverse:"#111827"},status:{success:"#34D399",warning:"#FBBF24",error:"#F87171",info:"#60A5FA"},border:"#374151",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.3)"}},Uf={...Qr,name:"enterprise",colors:{primary:"#1E40AF",secondary:"#64748B",accent:"#7C3AED",background:"#FFFFFF",surface:"#F8FAFC",text:{primary:"#0F172A",secondary:"#475569",muted:"#94A3B8",inverse:"#FFFFFF"},status:{success:"#059669",warning:"#D97706",error:"#DC2626",info:"#1E40AF"},border:"#CBD5E1",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},borderRadius:{none:"0",sm:"0.125rem",md:"0.25rem",lg:"0.375rem",full:"9999px"}},oR=M.createContext(null),aR=()=>{const e=M.useContext(oR);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function Rq({theme:e="default",themes:t={},children:n,cssVariables:i=!0,className:r=""}){const[s,o]=M.useState(()=>{const h={default:Qr,dark:Ff,enterprise:Uf,...t};return typeof e=="string"?h[e]||Qr:e}),[a,c]=M.useState(()=>({default:Qr,dark:Ff,enterprise:Uf,...t})),l=h=>{if(typeof h=="string"){const f=a[h];f&&o(f)}else o(h)},u=h=>{c(f=>({...f,[h.name]:h}))};M.useEffect(()=>{if(i&&typeof document<"u"){const h=document.documentElement;Object.entries(cR(s)).forEach(([f,g])=>{h.style.setProperty(`--voxket-${f}`,g)})}},[s,i]);const d={theme:s,setTheme:l,themes:a,registerTheme:u};return m.jsx(oR.Provider,{value:d,children:m.jsx("div",{className:`voxket-theme voxket-theme--${s.name} ${r}`,children:n})})}function cR(e){const t={},n=(i,r="")=>{for(const[s,o]of Object.entries(i)){const a=r?`${r}-${s}`:s;typeof o=="object"&&o!==null&&!Array.isArray(o)?n(o,a):t[a]=String(o)}};return n(e),t}function _q(e=Qr,t){return{...e,...t,colors:{...e.colors,...t.colors},typography:{...e.typography,...t.typography},spacing:{...e.spacing,...t.spacing},borderRadius:{...e.borderRadius,...t.borderRadius},shadows:{...e.shadows,...t.shadows}}}function Iq(e){var n;const{theme:t}=aR();return((n=t.components)==null?void 0:n[e])||{}}const Nq=Qm("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&Mq(e),t.enableVoiceActivation&&Pq(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&Oq(e,t)}});function Mq(e,t){e.on("participant.speaking.started",n=>{console.log("Transcription: Started for",n.name)}),e.on("participant.speaking.stopped",n=>{console.log("Transcription: Stopped for",n.name)})}function Pq(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function Oq(e,t){console.log("Playing audio response:",t.content)}const Dq=Qm("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&Lq(),t.enableFileUpload&&Bq(e),t.enableCustomComponents&&Fq(),console.log("Chat modality activated",t)},onDeactivate:async e=>{console.log("Chat modality deactivated")},onMessage:async(e,t)=>{const n=e.config;t.type==="ui_component"?Uq(e,t):t.type==="text"&&n.enableRichText&&jq(e,t)}});function Lq(e){console.log("Rich text support enabled")}function Bq(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function Fq(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",Vq),t.set("form",zq),t.set("card",Gq),t.set("chart",Hq)}function Uq(e,t){const{componentType:n,props:i}=t.metadata;console.log("Rendering custom component:",n,i),e.emit("chat.component.render",{type:n,props:i,timestamp:new Date})}function jq(e,t){console.log("Processing rich text message:",t.content)}function Vq(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function zq(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function Gq(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function Hq(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function Zc({track:e,participantName:t,showControls:n=!0,showName:i=!0,showMuteIndicator:r=!0,isPinned:s=!1,className:o="",onClick:a,onPin:c,onUnpin:l}){const u=M.useRef(null),[d,h]=M.useState(!1);M.useEffect(()=>{if(!u.current||!e.isEnabled)return;const x=u.current;return x.srcObject=null,()=>{x.srcObject&&(x.srcObject=null)}},[e]);const f=()=>{a==null||a(e)},g=x=>{x.stopPropagation(),s?l==null||l(e):c==null||c(e)},p=["voxket-video-tile",e.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",e.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",s?"voxket-video-tile--pinned":"",e.isEnabled?"":"voxket-video-tile--disabled",d?"voxket-video-tile--hovered":"",o].filter(Boolean).join(" ");return m.jsxs("div",{className:p,onClick:f,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[m.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&m.jsxs("div",{className:"voxket-video-placeholder",children:[m.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"🖥️":"📹"}),m.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),m.jsxs("div",{className:"voxket-video-overlay",children:[i&&t&&m.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),r&&!e.isEnabled&&m.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),n&&(d||s)&&m.jsxs("div",{className:"voxket-video-controls",children:[m.jsx("button",{className:`voxket-video-control-btn ${s?"voxket-video-control-btn--active":""}`,onClick:g,title:s?"Unpin video":"Pin video",children:"📌"}),e.isScreenShare&&m.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),e.source&&m.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&m.jsx("div",{className:"voxket-video-loading",children:m.jsx("div",{className:"voxket-spinner"})})]})}function Kq({tracks:e,layout:t,className:n="",onLayoutChange:i,onTrackClick:r,maxVisibleTracks:s=9,showPagination:o=!0}){const[a,c]=M.useState(0),[l,u]=M.useState(null),d=M.useMemo(()=>{let E=[...e];t.type==="speaker"&&l&&(E=[l,...e.filter(v=>v.id!==l.id)]);const w=a*s,S=w+s;return E.slice(w,S)},[e,t,l,a,s]),h=Math.ceil(e.length/s),f=M.useMemo(()=>{const E=d.length;switch(t.type){case"grid":const w=Math.ceil(Math.sqrt(E)),S=Math.ceil(E/w);return{display:"grid",gridTemplateColumns:`repeat(${w}, 1fr)`,gridTemplateRows:`repeat(${S}, 1fr)`,gap:"8px"};case"speaker":return{display:"flex",flexDirection:"column",gap:"8px"};case"sidebar":return{display:"flex",gap:"8px"};case"gallery":return{display:"flex",flexWrap:"wrap",gap:"8px",justifyContent:"center"};default:return{}}},[t.type,d.length]),g=E=>{u(E)},p=()=>{u(null)},x=E=>{i==null||i({...t,type:E})},y=["voxket-video-grid",`voxket-video-grid--${t.type}`,`voxket-video-grid--${d.length}-tracks`,n].filter(Boolean).join(" ");return e.length===0?m.jsx("div",{className:"voxket-video-grid-empty",children:m.jsxs("div",{className:"voxket-video-grid-empty-content",children:[m.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),m.jsx("p",{children:"No video tracks available"})]})}):m.jsxs("div",{className:y,children:[m.jsxs("div",{className:"voxket-video-grid-controls",children:[m.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(E=>m.jsx("button",{className:`voxket-layout-btn ${t.type===E?"voxket-layout-btn--active":""}`,onClick:()=>x(E),title:`Switch to ${E} layout`,children:Wq(E)},E))}),m.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),m.jsx("div",{className:"voxket-video-grid-content",style:f,children:t.type==="speaker"&&l?m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"voxket-video-speaker-main",children:m.jsx(Zc,{track:l,participantName:`Participant ${l.participantId}`,isPinned:!0,onClick:r,onUnpin:p})}),m.jsx("div",{className:"voxket-video-speaker-sidebar",children:d.filter(E=>E.id!==l.id).map(E=>m.jsx(Zc,{track:E,participantName:`Participant ${E.participantId}`,showControls:!1,onClick:r,onPin:g},E.id))})]}):d.map(E=>m.jsx(Zc,{track:E,participantName:`Participant ${E.participantId}`,isPinned:(l==null?void 0:l.id)===E.id,onClick:r,onPin:g,onUnpin:p},E.id))}),o&&h>1&&m.jsxs("div",{className:"voxket-video-pagination",children:[m.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.max(0,a-1)),disabled:a===0,children:"←"}),m.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",h]}),m.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.min(h-1,a+1)),disabled:a===h-1,children:"→"})]})]})}function Wq(e){switch(e){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function qq({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:i,showLayoutControls:r=!0,showCameraControls:s=!0,showScreenShareControls:o=!0,className:a=""}){const c=["voxket-video-controls",a].filter(Boolean).join(" "),l=u=>{i==null||i({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return m.jsxs("div",{className:c,children:[s&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),m.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isEnabled?"voxket-control-btn--active":""}`,onClick:t,title:e!=null&&e.isEnabled?"Turn off camera":"Turn on camera",children:[m.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"📹":"📷"}),m.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&m.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," × ",e.dimensions.height]})]}),o&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),m.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isScreenShare?"voxket-control-btn--active":""}`,onClick:n,title:e!=null&&e.isScreenShare?"Stop screen sharing":"Start screen sharing",children:[m.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"🛑":"🖥️"}),m.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),r&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),m.jsx("div",{className:"voxket-layout-buttons",children:[{type:"grid",icon:"⊞",label:"Grid"},{type:"speaker",icon:"🎤",label:"Speaker"},{type:"sidebar",icon:"⫸",label:"Sidebar"},{type:"gallery",icon:"⊡",label:"Gallery"}].map(({type:u,icon:d,label:h})=>m.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>l(u),title:`Switch to ${h} layout`,children:[m.jsx("span",{className:"voxket-control-icon",children:d}),m.jsx("span",{className:"voxket-control-label",children:h})]},u))})]}),m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),m.jsxs("div",{className:"voxket-video-settings",children:[m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Quality"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"high",children:"High (720p)"}),m.jsx("option",{value:"medium",children:"Medium (480p)"}),m.jsx("option",{value:"low",children:"Low (240p)"})]})]}),m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"30",children:"30 fps"}),m.jsx("option",{value:"15",children:"15 fps"}),m.jsx("option",{value:"10",children:"10 fps"})]})]}),m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"unlimited",children:"Unlimited"}),m.jsx("option",{value:"1000",children:"1 Mbps"}),m.jsx("option",{value:"500",children:"500 Kbps"}),m.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),m.jsxs("div",{className:"voxket-video-stats",children:[m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),m.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}×${e.dimensions.height}`:"N/A"})]}),m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Source:"}),m.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Status:"}),m.jsx("span",{className:`voxket-stat-value ${e!=null&&e.isEnabled?"voxket-stat-value--active":"voxket-stat-value--inactive"}`,children:e!=null&&e.isEnabled?"Active":"Inactive"})]})]})]})]})}const lR=({handler:e,loadData:t,data:n,client:i,addLocalMessage:r})=>{const[s,o]=D.useState(null),[a,c]=D.useState(!0),[l,u]=D.useState(!1),[d]=D.useState(Date.now()),[h,f]=D.useState("pending");D.useEffect(()=>{(async()=>{try{if(c(!0),n&&typeof n=="object"){const E={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};o(E),console.log("📋 AssignmentView: Assignment loaded from RPC data:",E)}}catch(E){console.error("📋 AssignmentView: Error loading assignment:",E),o({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{c(!1)}})()},[n,t]);const g=({message:y,assignment:E})=>{const w=y.toLowerCase().includes("declined"),S=w?"bg-red-50 border-red-200":"bg-green-50 border-green-200",v=w?"text-red-700":"text-green-700",k=w?"❌":"🎉";return m.jsxs("div",{className:`max-w-sm mx-auto ${S} border rounded-lg shadow p-3 flex flex-col items-center`,children:[m.jsx("div",{className:"text-2xl mb-2",children:k}),m.jsx("div",{className:`${v} font-semibold text-sm mb-1`,children:y}),m.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:E.title}),m.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},p=async()=>{if(!(!s||!e)){u(!0);try{const y={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",y),e.didSuccess(y),f("accepted")}catch(y){console.error("📋 AssignmentView: Error accepting assignment:",y),e.didFail({error:"Failed to accept assignment"}),f("error")}finally{u(!1)}}},x=async()=>{if(!(!s||!e)){u(!0);try{const y={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",y),e.didSuccess(y),f("declined")}catch(y){console.error("📋 AssignmentView: Error declining assignment:",y),e.didFail({error:"Failed to decline assignment"}),f("error")}finally{u(!1)}}};return a?m.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:m.jsxs("div",{className:"flex items-center justify-center py-4",children:[m.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),m.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):s?h==="accepted"||h==="declined"||h==="error"?m.jsx(g,{message:h==="accepted"?"Assignment accepted!":h==="declined"?"Assignment declined":"Assignment error occurred",assignment:s}):m.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[m.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:m.jsx("div",{className:"flex items-center justify-between",children:m.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:s.title})})}),m.jsxs("div",{className:"p-3 text-black",children:[m.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:m.jsx("p",{className:"text-xs text-black leading-snug",children:s.description})}),m.jsx("div",{className:"mb-3 text-black",children:m.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[m.jsx("span",{className:"text-xs mr-1",children:"📅"}),m.jsxs("span",{children:["Est: ",s.estimated_time_of_completion]})]})}),m.jsxs("div",{className:"flex gap-2",children:[m.jsx("button",{onClick:p,disabled:l,className:"flex-1 bg-green-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:l?m.jsxs("span",{className:"flex items-center justify-center",children:[m.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),m.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),m.jsx("button",{onClick:x,disabled:l,className:"flex-1 bg-red-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Decline"})]})]})]}):m.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:m.jsxs("div",{className:"text-center py-4",children:[m.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),m.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function Qq(){const[e,t]=D.useState(null),[n,i]=D.useState([]);D.useEffect(()=>{const a=new Ba({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return t(a),a.on("rpc.method.called",c=>{console.log("RPC Method Called:",c)}),a.on("rpc.interaction.completed",c=>{console.log("RPC Interaction Completed:",c)}),()=>{a.disconnect()}},[]);const r=async()=>{if(e)try{await e.registerFrontendRPC("give_assignment",lR,"embedded");const a=e.getRegisteredRpcMethods();i(a),console.log("✅ Assignment RPC registered successfully")}catch(a){console.error("❌ Failed to register assignment RPC:",a)}},s=async()=>{if(!e)return;const a=({handler:c,timeout:l})=>{const[u,d]=D.useState(""),h=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],f=p=>{d(p)},g=()=>{const p=h.find(x=>x.id===u);c==null||c.didSuccess({selectedProduct:u,productName:p==null?void 0:p.name,price:p==null?void 0:p.price,timestamp:new Date().toISOString()})};return m.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[m.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),m.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),m.jsx("div",{className:"space-y-3 mb-6",children:h.map(p=>m.jsx("div",{onClick:()=>f(p.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${u===p.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:m.jsxs("div",{className:"flex justify-between items-center",children:[m.jsxs("div",{children:[m.jsx("h4",{className:"font-medium",children:p.name}),m.jsx("p",{className:"text-gray-600 text-sm",children:p.price})]}),m.jsx("div",{className:`w-4 h-4 rounded-full ${u===p.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},p.id))}),m.jsxs("div",{className:"flex justify-end space-x-3",children:[m.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),m.jsx("button",{onClick:g,disabled:!u,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),l&&m.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",l," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const c=e.getRegisteredRpcMethods();i(c),console.log("✅ Product Recommendation RPC registered successfully")}catch(c){console.error("❌ Failed to register product recommendation RPC:",c)}},o=async()=>{if(!e)return;const a=({handler:c})=>{const[l,u]=D.useState(0),[d,h]=D.useState(""),f=()=>{c==null||c.didSuccess({rating:l,comment:d,timestamp:new Date().toISOString()})};return m.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),m.jsxs("div",{className:"mb-4",children:[m.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),m.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(g=>m.jsx("button",{onClick:()=>u(g),className:`text-2xl ${g<=l?"text-yellow-400":"text-gray-300"}`,children:"⭐"},g))})]}),m.jsxs("div",{className:"mb-4",children:[m.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),m.jsx("textarea",{value:d,onChange:g=>h(g.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),m.jsxs("div",{className:"flex justify-end space-x-2",children:[m.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),m.jsx("button",{onClick:f,disabled:l===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await e.registerFrontendRPC("collect_feedback",a,"embedded");const c=e.getRegisteredRpcMethods();i(c),console.log("✅ Feedback RPC registered successfully")}catch(c){console.error("❌ Failed to register feedback RPC:",c)}};return m.jsxs("div",{className:"p-6",children:[m.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),m.jsxs("div",{className:"space-y-4 mb-6",children:[m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),m.jsxs("div",{className:"space-x-2",children:[m.jsx("button",{onClick:r,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),m.jsx("button",{onClick:s,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),m.jsx("button",{onClick:o,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?m.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>m.jsx("li",{className:"text-gray-700",children:m.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):m.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),m.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),m.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[m.jsxs("li",{children:["Register RPC methods with React components using ",m.jsx("code",{children:"client.registerFrontendRPC()"})]}),m.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),m.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),m.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),m.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),m.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),m.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),m.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
196
+ Url: ${Dl(e)}`),!0}return!1}function c7(e,t){return t!=null&&t.length?CA(e).some(n=>wu(n,t)):!1}function l7(e,t){if(!(t!=null&&t.length))return!1;const n=e.transaction;return n?wu(n,t):!1}function u7(e,t){if(!(t!=null&&t.length))return!1;const n=Dl(e);return n?wu(n,t):!1}function d7(e,t){if(!(t!=null&&t.length))return!0;const n=Dl(e);return n?wu(n,t):!0}function h7(e=[]){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n&&n.filename!=="<anonymous>"&&n.filename!=="[native code]")return n.filename||null}return null}function Dl(e){var t,n;try{const i=[...((t=e.exception)==null?void 0:t.values)??[]].reverse().find(s=>{var o,a,c;return((o=s.mechanism)==null?void 0:o.parent_id)===void 0&&((c=(a=s.stacktrace)==null?void 0:a.frames)==null?void 0:c.length)}),r=(n=i==null?void 0:i.stacktrace)==null?void 0:n.frames;return r?h7(r):null}catch{return ze&&Oe.error(`Cannot extract url for event ${jr(e)}`),null}}function f7(e){var t,n;return(n=(t=e.exception)==null?void 0:t.values)!=null&&n.length?!e.message&&!e.exception.values.some(i=>i.stacktrace||i.type&&i.type!=="Error"||i.value):!1}function p7(e,t,n,i,r,s){var a;if(!((a=r.exception)!=null&&a.values)||!s||!Tr(s.originalException,Error))return;const o=r.exception.values.length>0?r.exception.values[r.exception.values.length-1]:void 0;o&&(r.exception.values=Nf(e,t,i,s.originalException,n,r.exception.values,o,0))}function Nf(e,t,n,i,r,s,o,a){if(s.length>=n+1)return s;let c=[...s];if(Tr(i[r],Error)){yx(o,a);const l=e(t,i[r]),u=c.length;vx(l,r,u,a),c=Nf(e,t,n,i[r],r,[l,...c],l,u)}return Array.isArray(i.errors)&&i.errors.forEach((l,u)=>{if(Tr(l,Error)){yx(o,a);const d=e(t,l),h=c.length;vx(d,`errors[${u}]`,h,a),c=Nf(e,t,n,l,r,[d,...c],d,h)}}),c}function yx(e,t){e.mechanism={handled:!0,type:"auto.core.linked_errors",...e.mechanism,...e.type==="AggregateError"&&{is_exception_group:!0},exception_id:t}}function vx(e,t,n,i){e.mechanism={handled:!0,...e.mechanism,type:"chained",source:t,exception_id:n,parent_id:i}}function m7(e){const t="console";ss(t,e),os(t,g7)}function g7(){"console"in ht&&yG.forEach(function(e){e in ht.console&&Dn(ht.console,e,function(t){return Pl[e]=t,function(...n){ai("console",{args:n,level:e});const r=Pl[e];r==null||r.apply(ht.console,n)}})})}function b7(e){return e==="warn"?"warning":["fatal","error","warning","log","info","debug"].includes(e)?e:"log"}const y7="Dedupe",v7=(()=>{let e;return{name:y7,processEvent(t){if(t.type)return t;try{if(S7(t,e))return ze&&Oe.warn("Event dropped due to being a duplicate of previously captured event."),null}catch{}return e=t}}}),x7=v7;function S7(e,t){return t?!!(k7(e,t)||E7(e,t)):!1}function k7(e,t){const n=e.message,i=t.message;return!(!n&&!i||n&&!i||!n&&i||n!==i||!MA(e,t)||!NA(e,t))}function E7(e,t){const n=xx(t),i=xx(e);return!(!n||!i||n.type!==i.type||n.value!==i.value||!MA(e,t)||!NA(e,t))}function NA(e,t){let n=Nv(e),i=Nv(t);if(!n&&!i)return!0;if(n&&!i||!n&&i||(n=n,i=i,i.length!==n.length))return!1;for(let r=0;r<i.length;r++){const s=i[r],o=n[r];if(s.filename!==o.filename||s.lineno!==o.lineno||s.colno!==o.colno||s.function!==o.function)return!1}return!0}function MA(e,t){let n=e.fingerprint,i=t.fingerprint;if(!n&&!i)return!0;if(n&&!i||!n&&i)return!1;n=n,i=i;try{return n.join("")===i.join("")}catch{return!1}}function xx(e){var t,n;return(n=(t=e.exception)==null?void 0:t.values)==null?void 0:n[0]}function PA(e){if(e!==void 0)return e>=400&&e<500?"warning":e>=500?"error":void 0}const ya=ht;function w7(){return"history"in ya&&!!ya.history}function C7(){if(!("fetch"in ya))return!1;try{return new Headers,new Request("data:,"),new Response,!0}catch{return!1}}function Mf(e){return e&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(e.toString())}function T7(){var n;if(typeof EdgeRuntime=="string")return!0;if(!C7())return!1;if(Mf(ya.fetch))return!0;let e=!1;const t=ya.document;if(t&&typeof t.createElement=="function")try{const i=t.createElement("iframe");i.hidden=!0,t.head.appendChild(i),(n=i.contentWindow)!=null&&n.fetch&&(e=Mf(i.contentWindow.fetch)),t.head.removeChild(i)}catch(i){ze&&Oe.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",i)}return e}function A7(e,t){const n="fetch";ss(n,e),os(n,()=>R7(void 0,t))}function R7(e,t=!1){t&&!T7()||Dn(ht,"fetch",function(n){return function(...i){const r=new Error,{method:s,url:o}=_7(i),a={args:i,fetchData:{method:s,url:o},startTimestamp:qi()*1e3,virtualError:r,headers:I7(i)};return ai("fetch",{...a}),n.apply(ht,i).then(async c=>(ai("fetch",{...a,endTimestamp:qi()*1e3,response:c}),c),c=>{ai("fetch",{...a,endTimestamp:qi()*1e3,error:c}),Pa(c)&&c.stack===void 0&&(c.stack=r.stack,Ar(c,"framesToPop",1));const l=rn(),u=(l==null?void 0:l.getOptions().enhanceFetchErrorMessages)??"always";if(u!==!1&&c instanceof TypeError&&(c.message==="Failed to fetch"||c.message==="Load failed"||c.message==="NetworkError when attempting to fetch resource."))try{const f=new URL(a.fetchData.url).host;u==="always"?c.message=`${c.message} (${f})`:Ar(c,"__sentry_fetch_url_host__",f)}catch{}throw c})}})}function qc(e,t){return!!e&&typeof e=="object"&&!!e[t]}function Sx(e){return typeof e=="string"?e:e?qc(e,"url")?e.url:e.toString?e.toString():"":""}function _7(e){if(e.length===0)return{method:"GET",url:""};if(e.length===2){const[n,i]=e;return{url:Sx(n),method:qc(i,"method")?String(i.method).toUpperCase():ZT(n)&&qc(n,"method")?String(n.method).toUpperCase():"GET"}}const t=e[0];return{url:Sx(t),method:qc(t,"method")?String(t.method).toUpperCase():"GET"}}function I7(e){const[t,n]=e;try{if(typeof n=="object"&&n!==null&&"headers"in n&&n.headers)return new Headers(n.headers);if(ZT(t))return new Headers(t.headers)}catch{}}function N7(){return"npm"}const _t=ht;let Pf=0;function OA(){return Pf>0}function M7(){Pf++,setTimeout(()=>{Pf--})}function no(e,t={}){function n(r){return typeof r=="function"}if(!n(e))return e;try{const r=e.__sentry_wrapped__;if(r)return typeof r=="function"?r:e;if(Dm(e))return e}catch{return e}const i=function(...r){try{const s=r.map(o=>no(o,t));return e.apply(this,s)}catch(s){throw M7(),Bm(o=>{o.addEventProcessor(a=>(t.mechanism&&(wf(a,void 0),$s(a,t.mechanism)),a.extra={...a.extra,arguments:r},a)),Vm(s)}),s}};try{for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r])}catch{}eA(i,e),Ar(e,"__sentry_wrapped__",i);try{Object.getOwnPropertyDescriptor(i,"name").configurable&&Object.defineProperty(i,"name",{get(){return e.name}})}catch{}return i}function P7(){const e=Om(),{referrer:t}=_t.document||{},{userAgent:n}=_t.navigator||{},i={...t&&{Referer:t},...n&&{"User-Agent":n}};return{url:e,headers:i}}function Hm(e,t){const n=Km(e,t),i={type:F7(t),value:U7(t)};return n.length&&(i.stacktrace={frames:n}),i.type===void 0&&i.value===""&&(i.value="Unrecoverable error caught"),i}function O7(e,t,n,i){const r=rn(),s=r==null?void 0:r.getOptions().normalizeDepth,o=H7(t),a={__serialized__:fA(t,s)};if(o)return{exception:{values:[Hm(e,o)]},extra:a};const c={exception:{values:[{type:Su(t)?t.constructor.name:i?"UnhandledRejection":"Error",value:z7(t,{isUnhandledRejection:i})}]},extra:a};if(n){const l=Km(e,n);l.length&&(c.exception.values[0].stacktrace={frames:l})}return c}function th(e,t){return{exception:{values:[Hm(e,t)]}}}function Km(e,t){const n=t.stacktrace||t.stack||"",i=L7(t),r=B7(t);try{return e(n,i,r)}catch{}return[]}const D7=/Minified React error #\d+;/i;function L7(e){return e&&D7.test(e.message)?1:0}function B7(e){return typeof e.framesToPop=="number"?e.framesToPop:0}function DA(e){return typeof WebAssembly<"u"&&typeof WebAssembly.Exception<"u"?e instanceof WebAssembly.Exception:!1}function F7(e){const t=e==null?void 0:e.name;return!t&&DA(e)?e.message&&Array.isArray(e.message)&&e.message.length==2?e.message[0]:"WebAssembly.Exception":t}function U7(e){const t=e==null?void 0:e.message;return DA(e)?Array.isArray(e.message)&&e.message.length==2?e.message[1]:"wasm exception":t?t.error&&typeof t.error.message=="string"?px(t.error):px(e):"No error message"}function j7(e,t,n,i){const r=(n==null?void 0:n.syntheticException)||void 0,s=Wm(e,t,r,i);return $s(s),s.level="error",n!=null&&n.event_id&&(s.event_id=n.event_id),Cu(s)}function V7(e,t,n="info",i,r){const s=(i==null?void 0:i.syntheticException)||void 0,o=Of(e,t,s,r);return o.level=n,i!=null&&i.event_id&&(o.event_id=i.event_id),Cu(o)}function Wm(e,t,n,i,r){let s;if(JT(t)&&t.error)return th(e,t.error);if(Pv(t)||NG(t)){const o=t;if("stack"in t)s=th(e,t);else{const a=o.name||(Pv(o)?"DOMError":"DOMException"),c=o.message?`${a}: ${o.message}`:a;s=Of(e,c,n,i),wf(s,c)}return"code"in o&&(s.tags={...s.tags,"DOMException.code":`${o.code}`}),s}return Pa(t)?th(e,t):ga(t)||Su(t)?(s=O7(e,t,n,r),$s(s,{synthetic:!0}),s):(s=Of(e,t,n,i),wf(s,`${t}`),$s(s,{synthetic:!0}),s)}function Of(e,t,n,i){const r={};if(i&&n){const s=Km(e,n);s.length&&(r.exception={values:[{value:t,stacktrace:{frames:s}}]}),$s(r,{synthetic:!0})}if(Mm(t)){const{__sentry_template_string__:s,__sentry_template_values__:o}=t;return r.logentry={message:s,params:o},r}return r.message=t,r}function z7(e,{isUnhandledRejection:t}){const n=FG(e),i=t?"promise rejection":"exception";return JT(e)?`Event \`ErrorEvent\` captured as ${i} with message \`${e.message}\``:Su(e)?`Event \`${G7(e)}\` (type=${e.type}) captured as ${i}`:`Object captured as ${i} with keys: ${n}`}function G7(e){try{const t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function H7(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const n=e[t];if(n instanceof Error)return n}}class K7 extends GK{constructor(t){var u;const n=W7(t),i=_t.SENTRY_SDK_SOURCE||N7();IA(n,"browser",["browser"],i),(u=n._metadata)!=null&&u.sdk&&(n._metadata.sdk.settings={infer_ip:n.sendDefaultPii?"auto":"never",...n._metadata.sdk.settings}),super(n);const{sendDefaultPii:r,sendClientReports:s,enableLogs:o,_experiments:a,enableMetrics:c}=this._options,l=c??(a==null?void 0:a.enableMetrics)??!0;_t.document&&(s||o||l)&&_t.document.addEventListener("visibilitychange",()=>{_t.document.visibilityState==="hidden"&&(s&&this._flushOutcomes(),o&&xA(this),l&&kA(this))}),r&&this.on("beforeSendSession",ZK)}eventFromException(t,n){return j7(this._options.stackParser,t,n,this._options.attachStacktrace)}eventFromMessage(t,n="info",i){return V7(this._options.stackParser,t,n,i,this._options.attachStacktrace)}_prepareEvent(t,n,i,r){return t.platform=t.platform||"javascript",super._prepareEvent(t,n,i,r)}}function W7(e){var t;return{release:typeof __SENTRY_RELEASE__=="string"?__SENTRY_RELEASE__:(t=_t.SENTRY_RELEASE)==null?void 0:t.id,sendClientReports:!0,parentSpanIsAlwaysRootSpan:!0,...e}}const q7=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,Sn=ht,Q7=1e3;let kx,Df,Lf;function Y7(e){ss("dom",e),os("dom",J7)}function J7(){if(!Sn.document)return;const e=ai.bind(null,"dom"),t=Ex(e,!0);Sn.document.addEventListener("click",t,!1),Sn.document.addEventListener("keypress",t,!1),["EventTarget","Node"].forEach(n=>{var s,o;const r=(s=Sn[n])==null?void 0:s.prototype;(o=r==null?void 0:r.hasOwnProperty)!=null&&o.call(r,"addEventListener")&&(Dn(r,"addEventListener",function(a){return function(c,l,u){if(c==="click"||c=="keypress")try{const d=this.__sentry_instrumentation_handlers__=this.__sentry_instrumentation_handlers__||{},h=d[c]=d[c]||{refCount:0};if(!h.handler){const f=Ex(e);h.handler=f,a.call(this,c,f,u)}h.refCount++}catch{}return a.call(this,c,l,u)}}),Dn(r,"removeEventListener",function(a){return function(c,l,u){if(c==="click"||c=="keypress")try{const d=this.__sentry_instrumentation_handlers__||{},h=d[c];h&&(h.refCount--,h.refCount<=0&&(a.call(this,c,h.handler,u),h.handler=void 0,delete d[c]),Object.keys(d).length===0&&delete this.__sentry_instrumentation_handlers__)}catch{}return a.call(this,c,l,u)}}))})}function X7(e){if(e.type!==Df)return!1;try{if(!e.target||e.target._sentryId!==Lf)return!1}catch{}return!0}function Z7(e,t){return e!=="keypress"?!1:t!=null&&t.tagName?!(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable):!0}function Ex(e,t=!1){return n=>{if(!n||n._sentryCaptured)return;const i=$7(n);if(Z7(n.type,i))return;Ar(n,"_sentryCaptured",!0),i&&!i._sentryId&&Ar(i,"_sentryId",Qn());const r=n.type==="keypress"?"input":n.type;X7(n)||(e({event:n,name:r,global:t}),Df=n.type,Lf=i?i._sentryId:void 0),clearTimeout(kx),kx=Sn.setTimeout(()=>{Lf=void 0,Df=void 0},Q7)}}function $7(e){try{return e.target}catch{return null}}let xc;function LA(e){const t="history";ss(t,e),os(t,eW)}function eW(){if(Sn.addEventListener("popstate",()=>{const t=Sn.location.href,n=xc;if(xc=t,n===t)return;ai("history",{from:n,to:t})}),!w7())return;function e(t){return function(...n){const i=n.length>2?n[2]:void 0;if(i){const r=xc,s=tW(String(i));if(xc=s,r===s)return t.apply(this,n);ai("history",{from:r,to:s})}return t.apply(this,n)}}Dn(Sn.history,"pushState",e),Dn(Sn.history,"replaceState",e)}function tW(e){try{return new URL(e,Sn.location.origin).toString()}catch{return e}}const Qc={};function nW(e){const t=Qc[e];if(t)return t;let n=Sn[e];if(Mf(n))return Qc[e]=n.bind(Sn);const i=Sn.document;if(i&&typeof i.createElement=="function")try{const r=i.createElement("iframe");r.hidden=!0,i.head.appendChild(r);const s=r.contentWindow;s!=null&&s[e]&&(n=s[e]),i.head.removeChild(r)}catch(r){q7&&Oe.warn(`Could not create sandbox iframe for ${e} check, bailing to window.${e}: `,r)}return n&&(Qc[e]=n.bind(Sn))}function iW(e){Qc[e]=void 0}const zo="__sentry_xhr_v3__";function rW(e){ss("xhr",e),os("xhr",sW)}function sW(){if(!Sn.XMLHttpRequest)return;const e=XMLHttpRequest.prototype;e.open=new Proxy(e.open,{apply(t,n,i){const r=new Error,s=qi()*1e3,o=Wi(i[0])?i[0].toUpperCase():void 0,a=oW(i[1]);if(!o||!a)return t.apply(n,i);n[zo]={method:o,url:a,request_headers:{}},o==="POST"&&a.match(/sentry_key/)&&(n.__sentry_own_request__=!0);const c=()=>{const l=n[zo];if(l&&n.readyState===4){try{l.status_code=n.status}catch{}const u={endTimestamp:qi()*1e3,startTimestamp:s,xhr:n,virtualError:r};ai("xhr",u)}};return"onreadystatechange"in n&&typeof n.onreadystatechange=="function"?n.onreadystatechange=new Proxy(n.onreadystatechange,{apply(l,u,d){return c(),l.apply(u,d)}}):n.addEventListener("readystatechange",c),n.setRequestHeader=new Proxy(n.setRequestHeader,{apply(l,u,d){const[h,f]=d,g=u[zo];return g&&Wi(h)&&Wi(f)&&(g.request_headers[h.toLowerCase()]=f),l.apply(u,d)}}),t.apply(n,i)}}),e.send=new Proxy(e.send,{apply(t,n,i){const r=n[zo];if(!r)return t.apply(n,i);i[0]!==void 0&&(r.body=i[0]);const s={startTimestamp:qi()*1e3,xhr:n};return ai("xhr",s),t.apply(n,i)}})}function oW(e){if(Wi(e))return e;try{return e.toString()}catch{}}const aW=40;function cW(e,t=nW("fetch")){let n=0,i=0;async function r(s){const o=s.body.length;n+=o,i++;const a={body:s.body,method:"POST",referrerPolicy:"strict-origin",headers:e.headers,keepalive:n<=6e4&&i<15,...e.fetchOptions};try{const c=await t(e.url,a);return{statusCode:c.status,headers:{"x-sentry-rate-limits":c.headers.get("X-Sentry-Rate-Limits"),"retry-after":c.headers.get("Retry-After")}}}catch(c){throw iW("fetch"),c}finally{n-=o,i--}}return FK(e,r,Gm(e.bufferSize||aW))}const io=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,lW=30,uW=50;function Bf(e,t,n,i){const r={filename:e,function:t==="<anonymous>"?es:t,in_app:!0};return n!==void 0&&(r.lineno=n),i!==void 0&&(r.colno=i),r}const dW=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,hW=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,fW=/\((\S*)(?::(\d+))(?::(\d+))\)/,pW=/at (.+?) ?\(data:(.+?),/,mW=e=>{const t=e.match(pW);if(t)return{filename:`<data:${t[2]}>`,function:t[1]};const n=dW.exec(e);if(n){const[,r,s,o]=n;return Bf(r,es,+s,+o)}const i=hW.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){const a=fW.exec(i[2]);a&&(i[2]=a[1],i[3]=a[2],i[4]=a[3])}const[s,o]=BA(i[1]||es,i[2]);return Bf(o,s,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},gW=[lW,mW],bW=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,yW=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vW=e=>{const t=bW.exec(e);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){const s=yW.exec(t[3]);s&&(t[1]=t[1]||"eval",t[3]=s[1],t[4]=s[2],t[5]="")}let i=t[3],r=t[1]||es;return[r,i]=BA(r,i),Bf(i,r,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}},xW=[uW,vW],SW=[gW,xW],kW=qT(...SW),BA=(e,t)=>{const n=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return n||i?[e.indexOf("@")!==-1?e.split("@")[0]:es,n?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},Sc=1024,EW="Breadcrumbs",wW=((e={})=>{const t={console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0,...e};return{name:EW,setup(n){t.console&&m7(RW(n)),t.dom&&Y7(AW(n,t.dom)),t.xhr&&rW(_W(n)),t.fetch&&A7(IW(n)),t.history&&LA(NW(n)),t.sentry&&n.on("beforeSendEvent",TW(n))}}}),CW=wW;function TW(e){return function(n){rn()===e&&ts({category:`sentry.${n.type==="transaction"?"transaction":"event"}`,event_id:n.event_id,level:n.level,message:jr(n)},{event:n})}}function AW(e,t){return function(i){if(rn()!==e)return;let r,s,o=typeof t=="object"?t.serializeAttribute:void 0,a=typeof t=="object"&&typeof t.maxStringLength=="number"?t.maxStringLength:void 0;a&&a>Sc&&(io&&Oe.warn(`\`dom.maxStringLength\` cannot exceed ${Sc}, but a value of ${a} was configured. Sentry will use ${Sc} instead.`),a=Sc),typeof o=="string"&&(o=[o]);try{const l=i.event,u=MW(l)?l.target:l;r=$T(u,{keyAttrs:o,maxStringLength:a}),s=BG(u)}catch{r="<unknown>"}if(r.length===0)return;const c={category:`ui.${i.name}`,message:r};s&&(c.data={"ui.component_name":s}),ts(c,{event:i.event,name:i.name,global:i.global})}}function RW(e){return function(n){if(rn()!==e)return;const i={category:"console",data:{arguments:n.args,logger:"console"},level:b7(n.level),message:Lv(n.args," ")};if(n.level==="assert")if(n.args[0]===!1)i.message=`Assertion failed: ${Lv(n.args.slice(1)," ")||"console.assert"}`,i.data.arguments=n.args.slice(1);else return;ts(i,{input:n.args,level:n.level})}}function _W(e){return function(n){if(rn()!==e)return;const{startTimestamp:i,endTimestamp:r}=n,s=n.xhr[zo];if(!i||!r||!s)return;const{method:o,url:a,status_code:c,body:l}=s,u={method:o,url:a,status_code:c},d={xhr:n.xhr,input:l,startTimestamp:i,endTimestamp:r},h={category:"xhr",data:u,type:"http",level:PA(c)};e.emit("beforeOutgoingRequestBreadcrumb",h,d),ts(h,d)}}function IW(e){return function(n){if(rn()!==e)return;const{startTimestamp:i,endTimestamp:r}=n;if(r&&!(n.fetchData.url.match(/sentry_key/)&&n.fetchData.method==="POST"))if(n.fetchData.method,n.fetchData.url,n.error){const s=n.fetchData,o={data:n.error,input:n.args,startTimestamp:i,endTimestamp:r},a={category:"fetch",data:s,level:"error",type:"http"};e.emit("beforeOutgoingRequestBreadcrumb",a,o),ts(a,o)}else{const s=n.response,o={...n.fetchData,status_code:s==null?void 0:s.status};n.fetchData.request_body_size,n.fetchData.response_body_size,s==null||s.status;const a={input:n.args,response:s,startTimestamp:i,endTimestamp:r},c={category:"fetch",data:o,type:"http",level:PA(o.status_code)};e.emit("beforeOutgoingRequestBreadcrumb",c,a),ts(c,a)}}}function NW(e){return function(n){if(rn()!==e)return;let i=n.from,r=n.to;const s=eh(_t.location.href);let o=i?eh(i):void 0;const a=eh(r);o!=null&&o.path||(o=s),s.protocol===a.protocol&&s.host===a.host&&(r=a.relative),s.protocol===o.protocol&&s.host===o.host&&(i=o.relative),ts({category:"navigation",data:{from:i,to:r}})}}function MW(e){return!!e&&!!e.target}const PW=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","BroadcastChannel","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","SharedWorker","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],OW="BrowserApiErrors",DW=((e={})=>{const t={XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0,unregisterOriginalCallbacks:!1,...e};return{name:OW,setupOnce(){t.setTimeout&&Dn(_t,"setTimeout",wx),t.setInterval&&Dn(_t,"setInterval",wx),t.requestAnimationFrame&&Dn(_t,"requestAnimationFrame",BW),t.XMLHttpRequest&&"XMLHttpRequest"in _t&&Dn(XMLHttpRequest.prototype,"send",FW);const n=t.eventTarget;n&&(Array.isArray(n)?n:PW).forEach(r=>UW(r,t))}}}),LW=DW;function wx(e){return function(...t){const n=t[0];return t[0]=no(n,{mechanism:{handled:!1,type:`auto.browser.browserapierrors.${Cr(e)}`}}),e.apply(this,t)}}function BW(e){return function(t){return e.apply(this,[no(t,{mechanism:{data:{handler:Cr(e)},handled:!1,type:"auto.browser.browserapierrors.requestAnimationFrame"}})])}}function FW(e){return function(...t){const n=this;return["onload","onerror","onprogress","onreadystatechange"].forEach(r=>{r in n&&typeof n[r]=="function"&&Dn(n,r,function(s){const o={mechanism:{data:{handler:Cr(s)},handled:!1,type:`auto.browser.browserapierrors.xhr.${r}`}},a=Dm(s);return a&&(o.mechanism.data.handler=Cr(a)),no(s,o)})}),e.apply(this,t)}}function UW(e,t){var r,s;const i=(r=_t[e])==null?void 0:r.prototype;(s=i==null?void 0:i.hasOwnProperty)!=null&&s.call(i,"addEventListener")&&(Dn(i,"addEventListener",function(o){return function(a,c,l){try{jW(c)&&(c.handleEvent=no(c.handleEvent,{mechanism:{data:{handler:Cr(c),target:e},handled:!1,type:"auto.browser.browserapierrors.handleEvent"}}))}catch{}return t.unregisterOriginalCallbacks&&VW(this,a,c),o.apply(this,[a,no(c,{mechanism:{data:{handler:Cr(c),target:e},handled:!1,type:"auto.browser.browserapierrors.addEventListener"}}),l])}}),Dn(i,"removeEventListener",function(o){return function(a,c,l){try{const u=c.__sentry_wrapped__;u&&o.call(this,a,u,l)}catch{}return o.call(this,a,c,l)}}))}function jW(e){return typeof e.handleEvent=="function"}function VW(e,t,n){e&&typeof e=="object"&&"removeEventListener"in e&&typeof e.removeEventListener=="function"&&e.removeEventListener(t,n)}const zW=()=>({name:"BrowserSession",setupOnce(){if(typeof _t.document>"u"){io&&Oe.warn("Using the `browserSessionIntegration` in non-browser environments is not supported.");return}ix({ignoreDuration:!0}),rx(),LA(({from:e,to:t})=>{e!==void 0&&e!==t&&(ix({ignoreDuration:!0}),rx())})}}),GW="GlobalHandlers",HW=((e={})=>{const t={onerror:!0,onunhandledrejection:!0,...e};return{name:GW,setupOnce(){Error.stackTraceLimit=50},setup(n){t.onerror&&(WW(n),Cx("onerror")),t.onunhandledrejection&&(qW(n),Cx("onunhandledrejection"))}}}),KW=HW;function WW(e){AG(t=>{const{stackParser:n,attachStacktrace:i}=FA();if(rn()!==e||OA())return;const{msg:r,url:s,line:o,column:a,error:c}=t,l=JW(Wm(n,c||r,void 0,i,!1),s,o,a);l.level="error",mA(l,{originalException:c,mechanism:{handled:!1,type:"auto.browser.global_handlers.onerror"}})})}function qW(e){_G(t=>{const{stackParser:n,attachStacktrace:i}=FA();if(rn()!==e||OA())return;const r=QW(t),s=xu(r)?YW(r):Wm(n,r,void 0,i,!0);s.level="error",mA(s,{originalException:r,mechanism:{handled:!1,type:"auto.browser.global_handlers.onunhandledrejection"}})})}function QW(e){if(xu(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch{}return e}function YW(e){return{exception:{values:[{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(e)}`}]}}}function JW(e,t,n,i){const r=e.exception=e.exception||{},s=r.values=r.values||[],o=s[0]=s[0]||{},a=o.stacktrace=o.stacktrace||{},c=a.frames=a.frames||[],l=i,u=n,d=XW(t)??Om();return c.length===0&&c.push({colno:l,filename:d,function:es,in_app:!0,lineno:u}),e}function Cx(e){io&&Oe.log(`Global Handler attached: ${e}`)}function FA(){const e=rn();return(e==null?void 0:e.getOptions())||{stackParser:()=>[],attachStacktrace:!1}}function XW(e){if(!(!Wi(e)||e.length===0))return e.startsWith("data:")?`<${XK(e,!1)}>`:e}const ZW=()=>({name:"HttpContext",preprocessEvent(e){var i;if(!_t.navigator&&!_t.location&&!_t.document)return;const t=P7(),n={...t.headers,...(i=e.request)==null?void 0:i.headers};e.request={...t,...e.request,headers:n}}}),$W="cause",eq=5,tq="LinkedErrors",nq=((e={})=>{const t=e.limit||eq,n=e.key||$W;return{name:tq,preprocessEvent(i,r,s){const o=s.getOptions();p7(Hm,o.stackParser,n,t,i,r)}}}),iq=nq;function rq(){return sq()?(io&&po(()=>{console.error("[Sentry] You cannot use Sentry.init() in a browser extension, see: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/")}),!0):!1}function sq(){var s;if(typeof _t.window>"u")return!1;const e=_t;if(e.nw)return!1;const t=e.chrome||e.browser;if(!((s=t==null?void 0:t.runtime)!=null&&s.id))return!1;const n=Om(),i=["chrome-extension","moz-extension","ms-browser-extension","safari-web-extension"];return!(_t===_t.top&&i.some(o=>n.startsWith(`${o}://`)))}function oq(e){return[o7(),n7(),LW(),CW(),KW(),iq(),x7(),ZW(),zW()]}function aq(e={}){const t=!e.skipBrowserExtensionCheck&&rq();let n=e.defaultIntegrations==null?oq():e.defaultIntegrations;const i={...e,enabled:t?!1:e.enabled,stackParser:CG(e.stackParser||kW),integrations:CK({integrations:e.integrations,defaultIntegrations:n}),transport:e.transport||cW};return YK(K7,i)}function Tx(e={}){const t=_t.document,n=(t==null?void 0:t.head)||(t==null?void 0:t.body);if(!n){io&&Oe.error("[showReportDialog] Global document not defined");return}const i=_i(),r=rn(),s=r==null?void 0:r.getDsn();if(!s){io&&Oe.error("[showReportDialog] DSN not configured");return}const o={...e,user:{...i.getUser(),...e.user},eventId:e.eventId||yK()},a=_t.document.createElement("script");a.async=!0,a.crossOrigin="anonymous",a.src=EK(s,o);const{onLoad:c,onClose:l}=o;if(c&&(a.onload=c),l){const u=d=>{if(d.data==="__sentry_reportdialog_closed__")try{l()}finally{_t.removeEventListener("message",u)}};_t.addEventListener("message",u)}n.appendChild(a)}function cq(e){const t={...e};return IA(t,"react"),bK("react",{version:M.version}),aq(t)}function lq(e){const t=e.match(/^([^.]+)/);return t!==null&&parseInt(t[0])>=17}function uq(e,t){const n=new WeakSet;function i(r,s){if(!n.has(r)){if(r.cause)return n.add(r),i(r.cause,s);r.cause=s}}i(e,t)}function dq(e,{componentStack:t},n){if(lq(M.version)&&Pa(e)&&t){const i=new Error(e.message);i.name=`React ErrorBoundary ${e.name}`,i.stack=t,uq(e,i)}return Bm(i=>(i.setContext("react",{componentStack:t}),Vm(e,n)))}const hq=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,nh={componentStack:null,error:null,eventId:null};class fq extends D.Component{constructor(t){super(t),this.state=nh,this._openFallbackReportDialog=!0;const n=rn();n&&t.showDialog&&(this._openFallbackReportDialog=!1,this._cleanupHook=n.on("afterSendEvent",i=>{!i.type&&this._lastEventId&&i.event_id===this._lastEventId&&Tx({...t.dialogOptions,eventId:this._lastEventId})}))}componentDidCatch(t,n){const{componentStack:i}=n,{beforeCapture:r,onError:s,showDialog:o,dialogOptions:a}=this.props;Bm(c=>{r&&r(c,t,i);const l=this.props.handled!=null?this.props.handled:!!this.props.fallback,u=dq(t,n,{mechanism:{handled:l,type:"auto.function.react.error_boundary"}});s&&s(t,i,u),o&&(this._lastEventId=u,this._openFallbackReportDialog&&Tx({...a,eventId:u})),this.setState({error:t,componentStack:i,eventId:u})})}componentDidMount(){const{onMount:t}=this.props;t&&t()}componentWillUnmount(){const{error:t,componentStack:n,eventId:i}=this.state,{onUnmount:r}=this.props;r&&(this.state===nh?r(null,null,null):r(t,n,i)),this._cleanupHook&&(this._cleanupHook(),this._cleanupHook=void 0)}resetErrorBoundary(){const{onReset:t}=this.props,{error:n,componentStack:i,eventId:r}=this.state;t&&t(n,i,r),this.setState(nh)}render(){const{fallback:t,children:n}=this.props,i=this.state;if(i.componentStack===null)return typeof n=="function"?n():n;const r=typeof t=="function"?D.createElement(t,{error:i.error,componentStack:i.componentStack,resetError:()=>this.resetErrorBoundary(),eventId:i.eventId}):t;return D.isValidElement(r)?r:(t&&hq&&Oe.warn("fallback did not produce a valid ReactElement"),null)}}function pq(){cq({dsn:"https://e4ccc87e3f5dc1378aedf8d8af13b74d@o4509436774645760.ingest.us.sentry.io/4510775191732225",sendDefaultPii:!0})}const oe={info(e,t){nx(e,{level:"info",extra:t})},warn(e,t){nx(e,{level:"warning",extra:t})},error(e,t){Vm(e,{extra:t})}};class qm{constructor(){Be(this,"listeners",{})}on(t,n){return this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(n),()=>this.off(t,n)}once(t,n){const i=((...r)=>{this.off(t,i),n(...r)});return this.on(t,i)}off(t,n){const i=this.listeners[t];if(!i)return;const r=i.indexOf(n);r>-1&&i.splice(r,1)}removeAllListeners(t){t?delete this.listeners[t]:this.listeners={}}emit(t,...n){const i=this.listeners[t];if(!i)return;const r=[...i];for(const s of r)try{s(...n)}catch(o){oe.error(o)}}listenerCount(t){var n;return((n=this.listeners[t])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class UA{constructor(t){Be(this,"plugins",new Map);Be(this,"installedPlugins",new Set);Be(this,"context");this.context={client:t,emit:t.emit.bind(t),on:t.on.bind(t),config:{}}}register(t){if(this.plugins.has(t.name))throw new Error(`Plugin '${t.name}' is already registered`);if(t.dependencies){for(const n of t.dependencies)if(!this.plugins.has(n))throw new Error(`Plugin '${t.name}' depends on '${n}' which is not registered`)}this.plugins.set(t.name,t)}async install(t,n){const i=this.plugins.get(t);if(!i)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t))throw new Error(`Plugin '${t}' is already installed`);if(i.dependencies)for(const s of i.dependencies)this.installedPlugins.has(s)||await this.install(s);const r={...this.context,config:{...i.config,...n}};i.install&&await i.install(r),this.installedPlugins.add(t),this.setupPluginEvents(i,r)}async uninstall(t){var i;const n=this.plugins.get(t);if(!n)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t)){for(const[r,s]of this.plugins)if(this.installedPlugins.has(r)&&((i=s.dependencies)!=null&&i.includes(t)))throw new Error(`Cannot uninstall '${t}' because '${r}' depends on it`);n.uninstall&&await n.uninstall(this.context),this.installedPlugins.delete(t)}}isInstalled(t){return this.installedPlugins.has(t)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(t){return this.plugins.get(t)}setupPluginEvents(t,n){t.onSessionStart&&n.on("session.started",i=>{t.onSessionStart(n,i.id)}),t.onSessionEnd&&n.on("session.ended",i=>{t.onSessionEnd(n,i.id)}),t.onAgentResponse&&n.on("agent.response",i=>{t.onAgentResponse(n,i)})}}function mq(e){return e}function Qm(e,t,n){return{name:e,version:"1.0.0",description:`${t} modality plugin`,install:async i=>{n.onActivate&&await n.onActivate(i)},uninstall:async i=>{n.onDeactivate&&await n.onDeactivate(i)},onAgentResponse:n.onMessage}}const gq={name:"analytics",version:"1.0.0",description:"Built-in analytics tracking",install:async e=>{console.log("Analytics plugin installed"),e.on("session.started",t=>{console.log("Analytics: Session started",t.id)}),e.on("session.ended",(t,n)=>{console.log("Analytics: Session ended",t.id,n)}),e.on("chat.message.sent",t=>{console.log("Analytics: User message sent",t.content.length)})}},bq={name:"debug",version:"1.0.0",description:"Debug logging and development tools",install:async e=>{console.log("Debug plugin installed");const t=e.emit;e.emit=(n,...i)=>(console.log(`[Debug] Event: ${String(n)}`,i),t(n,...i))}},yq={name:"metrics",version:"1.0.0",description:"Advanced metrics collection",install:async e=>{console.log("Metrics plugin installed");const t=new Map;e.on("session.started",n=>{t.set(n.id,{startTime:Date.now(),events:[]})}),e.on("agent.response",n=>{console.log("Metrics: Agent response analyzed",{type:n.type,length:n.content.length,timestamp:n.timestamp})})}};class se extends Error{constructor(t,n,i){super(t),this.code=n,this.details=i,this.name="VoxketError"}}class jA extends qm{constructor(n,i){super();Be(this,"room",null);Be(this,"registeredMethods",new Map);Be(this,"activeInteractions",new Map);Be(this,"eventEmitter");Be(this,"currentInteraction",null);this.eventEmitter=n,i&&this.setRoom(i)}setRoom(n){this.room=n}async registerFrontendRPC(n,i,r="embedded"){if(!this.room){const o=new se("Room not initialized","UNKNOWN_ERROR");throw this.eventEmitter.emit("connection.error",o),oe.error(o),o}if(!this.room.localParticipant){const o=new se("Local participant not available for RPC registration","UNKNOWN_ERROR");throw this.eventEmitter.emit("connection.error",o),oe.error(o),o}const s={methodName:n,component:i,presentationMode:r};this.registeredMethods.set(n,s);try{this.room.registerRpcMethod(n,async o=>{this.emit("rpc.method.called",{methodName:n,data:o});let a,c=o.responseTimeout||30;try{a=JSON.parse(o.payload)}catch{a=o.payload}try{const l=await this.awaitUserInteraction(n,i,r,a,c);return JSON.stringify(l)}catch(l){throw new se(`RpcManager: Error in RPC method '${n}':`,"UNKNOWN_ERROR",l)}}),this.emit("rpc.method.registered",{methodName:n})}catch(o){if(o instanceof se)throw this.eventEmitter.emit("connection.error",o),oe.error(o),o;const a=new se(`RpcManager: Failed to register RPC method '${n}'`,"UNKNOWN_ERROR",o);throw this.eventEmitter.emit("connection.error",a),oe.error(a),o}}async awaitUserInteraction(n,i,r,s,o){return new Promise((a,c)=>{const l=`${n}_${Date.now()}`,u={didSuccess:(h,f)=>{this.clearInteraction(l),this.currentInteraction=null;const g={success:!0,message:"User interaction completed successfully",data:h,timestamp:new Date,...f?{successView:f}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:g}),a(g)},didFail:h=>{oe.warn(`RpcManager: User interaction failed for method: ${n}`),this.clearInteraction(l);const f={success:!1,message:"User interaction failed",error:h,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:f}),a(f)},dismissView:()=>{var f;oe.warn(`RpcManager: User dismissed interaction for method: ${n}`,{currentInteraction:(f=this.currentInteraction)==null?void 0:f.methodName}),this.clearInteraction(l),this.currentInteraction=null;const h={success:!0,data:{dismissed:!0,reason:"User dismissed the interaction"},message:"User interaction dismissed",timestamp:new Date};this.emit("rpc.interaction.dismissed",{methodName:n,response:h}),this.emit("rpc.interaction.completed",{methodName:n,response:h}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(this.currentInteraction=null)},0),a(h)},didTimeout:h=>{oe.warn(`RpcManager: User interaction timeout for method: ${n}`),this.clearInteraction(l),this.currentInteraction=null;const f={success:!0,message:`User interaction timed out after ${o} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...h?{timeoutView:h}:{}};this.emit("rpc.interaction.timeout",{methodName:n,response:f}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(oe.warn(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(f)}},d=setTimeout(()=>{u.didTimeout&&u.didTimeout()},o);this.activeInteractions.set(l,{resolve:h=>a(JSON.parse(h)),reject:c,timeoutId:d}),this.currentInteraction={isVisible:!0,methodName:n,component:i,presentationMode:r,timeout:o,data:s,handler:u},this.emit("rpc.interaction.started",{methodName:n,presentationMode:r}),setTimeout(async()=>{var h;if((h=this.currentInteraction)!=null&&h.handler)try{oe.info(`RpcManager: Component created for method: ${n} with data`,s)}catch(f){u.didFail({error:"Failed to load data into component"});const g=new se("Failed to load data into component","UNKNOWN_ERROR",f);this.eventEmitter.emit("connection.error",g),oe.error(g)}},100)})}clearInteraction(n){const i=this.activeInteractions.get(n);i&&(clearTimeout(i.timeoutId),this.activeInteractions.delete(n))}getCurrentInteraction(){return this.currentInteraction}dismissCurrentInteraction(){var n;this.currentInteraction&&((n=this.currentInteraction.handler)==null||n.dismissView(),setTimeout(()=>{this.currentInteraction&&(this.currentInteraction=null)},0))}getRegisteredMethods(){return Array.from(this.registeredMethods.keys())}unregisterMethod(n){this.registeredMethods.delete(n)}clear(){for(const[n,i]of this.activeInteractions)clearTimeout(i.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null}}class VA{constructor(t,n="User"){Be(this,"chatMessages",[]);Be(this,"activeTranscriptions",new Map);Be(this,"room",null);Be(this,"eventEmitter");Be(this,"participantName");this.eventEmitter=t,this.participantName=n}setRoom(t){this.room=t}setParticipantName(t){this.participantName=t}getChatMessages(){return[...this.chatMessages]}addChatMessage(t){this.chatMessages.some(i=>i.id===t.id)||this.chatMessages.push(t)}updateChatMessage(t){const n=this.chatMessages.findIndex(i=>i.id===t.id);n!==-1&&(this.chatMessages[n]=t)}clearChatMessages(){this.chatMessages=[],this.activeTranscriptions.clear()}trackTranscription(t,n){this.activeTranscriptions.set(t,{messageId:n,timestamp:Date.now()})}getActiveTranscription(t){const n=Date.now(),i=this.activeTranscriptions.get(t);return i&&n-i.timestamp<1e3?i:null}async sendMessage(t,n){if(!this.room){const i=new se("No room connection","CONNECTION_FAILED");throw oe.error(i),this.eventEmitter.emit("connection.error",i),i}if(!this.room.localParticipant){const i=new se("No local participant","CONNECTION_FAILED");throw oe.error(i),this.eventEmitter.emit("connection.error",i),i}try{const i={id:`msg_${Date.now()}`,content:t,sender:{id:"user",name:this.participantName,type:"participant"},timestamp:new Date,metadata:n||{}};await this.room.localParticipant.sendText(t,{topic:"lk.chat",destinationIdentities:[]}),this.eventEmitter.emit("chat.message.sent",i)}catch(i){const r=new se("Failed to send message","NETWORK_ERROR",i);throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}}async sendAttachments(t,n){if(!this.room){const r=new se("No room connection","CONNECTION_FAILED");throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}if(!this.room.localParticipant){const r=new se("No local participant","CONNECTION_FAILED");throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}if(!t||t.length===0){const r=new se("No files provided","INVALID_PARAMETER");throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}const i=t.filter(r=>r.type.startsWith("image/"));if(i.length===0){const r=new se("Only image files are allowed","INVALID_PARAMETER");throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}i.length!==t.length&&(this.eventEmitter.emit("connection.error",new se("Some non-image files were filtered out","WARN")),oe.warn("ChatManager: Some non-image files were filtered out"));try{const r=i.map(async(s,o)=>{const c={id:`att_${Date.now()}_${o}`,content:`📎 ${s.name}`,sender:{id:"user",name:this.participantName,type:"participant"},timestamp:new Date,metadata:{...n,type:"attachment",fileName:s.name,fileSize:s.size,mimeType:s.type,uploading:!0}};this.eventEmitter.emit("chat.message.sent",c);const l=await this.room.localParticipant.sendFile(s,{mimeType:s.type,topic:"images",onProgress:d=>{const h={...c,metadata:{...c.metadata,uploadProgress:d}};this.eventEmitter.emit("chat.message.updated",h)}});try{const d=new FileReader,h=new Promise((p,x)=>{d.onload=()=>{typeof d.result=="string"?p(d.result):x(new Error("Failed to convert to base64"))},d.onerror=x});d.readAsDataURL(s);const g={type:"image",data:await h,filename:s.name,mimeType:s.type,size:s.size};await this.room.localParticipant.sendText(JSON.stringify(g),{topic:"images",destinationIdentities:[]})}catch(d){oe.warn(`Send attachments error ${d}`);try{const h=`I've shared an image: ${s.name}`;await this.room.localParticipant.sendText(h,{topic:"lk.chat",destinationIdentities:[]})}catch(h){const f=new se("ChatManager: Failed to send image notification to agent","UNKNOWN_ERROR",h);this.eventEmitter.emit("connection.error",new se("Failed to send image notification to agent","WARN",h)),oe.error(f)}}const u={...c,metadata:{...c.metadata,uploading:!1,uploadProgress:1,streamId:l.id}};return this.eventEmitter.emit("chat.message.updated",u),l});await Promise.all(r)}catch(r){const s=new se("Failed to send attachments","NETWORK_ERROR",r);throw oe.error(s),this.eventEmitter.emit("connection.error",s),s}}async sendAttachment(t,n){return this.sendAttachments([t],n)}convertMarkdownToText(t){if(!t)return"";let n=t;return n=n.replace(/\*\*(.*?)\*\*/g,"$1"),n=n.replace(/__(.*?)__/g,"$1"),n=n.replace(/\*(.*?)\*/g,"$1"),n=n.replace(/_(.*?)_/g,"$1"),n=n.replace(/~~(.*?)~~/g,"$1"),n=n.replace(/`([^`]+)`/g,"$1"),n=n.replace(/```[\s\S]*?```/g,""),n=n.replace(/^#{1,6}\s+/gm,""),n=n.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),n.trim()}}class zA{constructor(t){Be(this,"room",null);Be(this,"eventEmitter");Be(this,"silencePreventionNode",null);Be(this,"silencePreventionOscillator",null);Be(this,"audioContext",null);this.eventEmitter=t,this.initializeAudioContext()}initializeAudioContext(){try{if(this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioContext.state==="suspended"){const t=async()=>{this.audioContext&&this.audioContext.state==="suspended"&&await this.audioContext.resume(),document.removeEventListener("click",t),document.removeEventListener("touchstart",t),document.removeEventListener("keydown",t)};document.addEventListener("click",t,{once:!0}),document.addEventListener("touchstart",t,{once:!0}),document.addEventListener("keydown",t,{once:!0})}}catch(t){const n=new se("MediaManager: Failed to initialize AudioContext:","UNKNOWN_ERROR",t);this.eventEmitter.emit("connection.error",new se("Audiocontext initialize failed","WARN",t)),oe.error(n)}}async ensureAudioContextRunning(){if(this.audioContext||this.initializeAudioContext(),this.audioContext&&this.audioContext.state==="suspended")try{await this.audioContext.resume()}catch(t){const n=new se("Failed to resume AudioContext","WARN",t);oe.error(n),this.eventEmitter.emit("connection.error",n)}}setRoom(t){this.room=t}getLocalParticipant(){var t;return((t=this.room)==null?void 0:t.localParticipant)??null}getRemoteParticipants(){var t;return Array.from(((t=this.room)==null?void 0:t.remoteParticipants.values())??[])}async toggleMicrophone(t){return this.setMicrophoneEnabled(t!==!1)}async setMicrophoneEnabled(t){var n,i;try{if(!this.room||this.room.state!=="connected"){const o=new se("Cannot enable microphone: room not connected","CONNECTION_FAILED");throw this.eventEmitter.emit("connection.error",o),oe.error(o),o}await this.ensureAudioContextRunning();const r=(n=this.room)==null?void 0:n.localParticipant.isMicrophoneEnabled,s=t??!r;s&&this.startSilencePrevention(),await((i=this.room)==null?void 0:i.localParticipant.setMicrophoneEnabled(s,{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0})),s?this.eventEmitter.emit("track.unmuted",{source:"microphone",enabled:!0}):(this.eventEmitter.emit("track.muted",{source:"microphone",enabled:!1}),this.stopSilencePrevention())}catch(r){this.stopSilencePrevention();const s=new se("Failed to toggle microphone","PERMISSION_DENIED",r);throw this.eventEmitter.emit("connection.error",s),oe.error(s),s}}startSilencePrevention(){try{if(this.audioContext||(this.audioContext=new AudioContext),this.silencePreventionOscillator)return;this.silencePreventionOscillator=this.audioContext.createOscillator(),this.silencePreventionNode=this.audioContext.createGain(),this.silencePreventionOscillator.frequency.value=20,this.silencePreventionNode.gain.value=.001,this.silencePreventionOscillator.connect(this.silencePreventionNode),this.silencePreventionNode.connect(this.audioContext.destination),this.silencePreventionOscillator.start()}catch(t){const n=new se("MediaManager: Failed to start silence prevention","UNKNOWN_ERROR",t);oe.error(n),this.eventEmitter.emit("connection.error",new se("Failed to start silence prevention","WARN",t))}}stopSilencePrevention(){try{this.silencePreventionOscillator&&(this.silencePreventionOscillator.stop(),this.silencePreventionOscillator.disconnect(),this.silencePreventionOscillator=null),this.silencePreventionNode&&(this.silencePreventionNode.disconnect(),this.silencePreventionNode=null)}catch(t){const n=new se("MediaManager: Failed to stop silence prevention","UNKNOWN_ERROR",t);oe.error(n),this.eventEmitter.emit("connection.error",new se("Failed to stop silence prevention","WARN",t))}}async toggleCamera(t){return this.setCameraEnabled(t!==!1)}async setCameraEnabled(t){var n,i;try{const r=(n=this.room)==null?void 0:n.localParticipant.isCameraEnabled,s=t??!r;await((i=this.room)==null?void 0:i.localParticipant.setCameraEnabled(s)),s?this.eventEmitter.emit("track.unmuted",{source:"camera",enabled:!0}):this.eventEmitter.emit("track.muted",{source:"camera",enabled:!1})}catch(r){const s=new se("Failed to toggle camera","PERMISSION_DENIED",r);throw oe.error(s),this.eventEmitter.emit("connection.error",s),s}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var t;try{await((t=this.room)==null?void 0:t.localParticipant.setScreenShareEnabled(!0)),this.eventEmitter.emit("track.unmuted",{source:"screenShare",enabled:!0})}catch(n){const i=new se("Failed to start screen share","PERMISSION_DENIED",n);throw oe.error(i),this.eventEmitter.emit("connection.error",i),i}}async stopScreenShare(){var t;try{await((t=this.room)==null?void 0:t.localParticipant.setScreenShareEnabled(!1)),this.eventEmitter.emit("track.muted",{source:"screenShare",enabled:!1})}catch(n){const i=new se("Failed to stop screen share","PERMISSION_DENIED",n);throw oe.error(i),this.eventEmitter.emit("connection.error",i),i}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="audioinput")}catch(t){const n=new se("Failed to get audio input devices","DEVICE_ERROR",t);throw oe.error(n),this.eventEmitter.emit("connection.error",n),n}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="videoinput")}catch(t){const n=new se("Failed to get video input devices","DEVICE_ERROR",t);throw oe.error(n),this.eventEmitter.emit("connection.error",n),n}}async setAudioInputDevice(t){var n;try{if(!((n=this.room)!=null&&n.localParticipant))throw new Error("Not connected to room")}catch(i){const r=new se("Failed to set audio input device","DEVICE_ERROR",i);throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}}async setVideoInputDevice(t){var n;try{if(!((n=this.room)!=null&&n.localParticipant))throw new Error("Not connected to room")}catch(i){const r=new se("Failed to set video input device","DEVICE_ERROR",i);throw oe.error(r),this.eventEmitter.emit("connection.error",r),r}}getMicrophoneTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===z.Source.Microphone)return n.track;return null}getCameraTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===z.Source.Camera)return n.track;return null}getScreenShareTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===z.Source.ScreenShare)return n.track;return null}get isMicrophoneEnabled(){const t=this.getMicrophoneTrack();return t?!t.isMuted:!1}get isCameraEnabled(){const t=this.getCameraTrack();return t?!t.isMuted:!1}get isScreenShareEnabled(){const t=this.getScreenShareTrack();return t?!t.isMuted:!1}getAgentAudioTrack(){const t=this.getRemoteParticipants();for(const n of t){const i=n.getTrackPublication(z.Source.Microphone);if(i!=null&&i.track)return{source:z.Source.Microphone,participant:n,publication:i}}return null}getAgentVideoTrack(){const t=this.getRemoteParticipants();for(const n of t){const i=n.getTrackPublication(z.Source.Camera);if(i!=null&&i.track)return{source:z.Source.Camera,participant:n,publication:i}}return null}getVideoTrackRefs(){const t=[],n=this.getLocalParticipant();if(n){const r=n.getTrackPublication(z.Source.Camera);r!=null&&r.track&&t.push({source:z.Source.Camera,participant:n,publication:r});const s=n.getTrackPublication(z.Source.ScreenShare);s!=null&&s.track&&t.push({source:z.Source.ScreenShare,participant:n,publication:s})}const i=this.getRemoteParticipants();for(const r of i){const s=r.getTrackPublication(z.Source.Camera);s!=null&&s.track&&t.push({source:z.Source.Camera,participant:r,publication:s});const o=r.getTrackPublication(z.Source.ScreenShare);o!=null&&o.track&&t.push({source:z.Source.ScreenShare,participant:r,publication:o})}return t}getCameraTrackRefs(){return this.getVideoTrackRefs().filter(t=>t.source===z.Source.Camera)}getScreenShareTrackRefs(){return this.getVideoTrackRefs().filter(t=>t.source===z.Source.ScreenShare)}getPublishPermissions(){const t=this.getLocalParticipant();if(!t)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const n=t.permissions;if(!n)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const i=r=>!!n.canPublish&&(n.canPublishSources.length===0||n.canPublishSources.includes(r));return{camera:i(1),microphone:i(2),screenShare:i(3),data:n.canPublishData??!1}}canPublishSource(t){return this.getPublishPermissions()[t]}}class GA{constructor(t,n){Be(this,"room",null);Be(this,"config");Be(this,"eventEmitter");Be(this,"connectionState",Je.Disconnected);Be(this,"isConnected",!1);Be(this,"currentAgentInfo",null);this.config=t,this.eventEmitter=n,this.initializeRoom()}initializeRoom(){this.room=new Ki({adaptiveStream:!1,stopLocalTrackOnUnpublish:!1,audioCaptureDefaults:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},publishDefaults:{stopMicTrackOnMute:!1,preConnectBuffer:!0}}),this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(U.Connected,()=>{this.connectionState=Je.Connected,this.isConnected=!0,this.eventEmitter.emit("connection.connected")}),this.room.on(U.Disconnected,t=>{this.connectionState=Je.Disconnected,this.isConnected=!1,this.eventEmitter.emit("connection.disconnected",t==null?void 0:t.toString())}),this.room.on(U.ConnectionStateChanged,t=>{this.connectionState=t,t===Je.Connecting&&this.eventEmitter.emit("connection.connecting")}),this.room.on(U.ParticipantConnected,t=>{const n={id:t.identity,name:t.name||t.identity,isLocal:!1};this.eventEmitter.emit("participant.joined",n)}),this.room.on(U.ParticipantDisconnected,t=>{const n={id:t.identity,name:t.name||t.identity,isLocal:!1};this.eventEmitter.emit("participant.left",n)}),this.room.on(U.LocalTrackPublished,t=>{t.source===z.Source.ScreenShare&&this.eventEmitter.emit("track.unmuted",{source:"screenShare",enabled:!0})}),this.room.on(U.LocalTrackUnpublished,t=>{t.source===z.Source.ScreenShare&&this.eventEmitter.emit("track.muted",{source:"screenShare",enabled:!1})}),this.room.on(U.LocalAudioSilenceDetected,()=>{var t;(t=this.room)==null||t.remoteParticipants.forEach(n=>{this.eventEmitter.emit("connection.error",new se("Audio disabled detected!","WARN",{identity:n.identity,audioTracks:n.audioTrackPublications.size,hasAudio:Array.from(n.audioTrackPublications.values()).some(i=>i.track)}))})}),this.room.on(U.TrackSubscribed,(t,n,i)=>{var r;this.eventEmitter.emit("media.track.subscribed",{id:t.sid||n.trackSid,kind:t.kind,source:((r=t.source)==null?void 0:r.toString())||"unknown",participantId:i.identity,isEnabled:!t.isMuted,isMuted:t.isMuted})}),this.room.on(U.TrackUnsubscribed,(t,n,i)=>{var r;this.eventEmitter.emit("media.track.unsubscribed",{id:t.sid||n.trackSid,kind:t.kind,source:((r=t.source)==null?void 0:r.toString())||"unknown",participantId:i.identity,isEnabled:!1,isMuted:!0})}))}async fetchConnectionDetails(t,n,i,r){var s;try{const o={agent_id:t,participant_name:n,participant_metadata:r||{user_id:""},modality:i[0],modalities:i},a={accept:"application/json","Content-Type":"application/json"};if(this.config.authToken)a.Authorization=`Bearer ${this.config.authToken}`;else if(this.config.appId&&this.config.appSecret)a["X-APP-ID"]=this.config.appId,a["X-APP-SECRET"]=this.config.appSecret;else{const d=new se("Either authToken or both appId and appSecret must be provided","UNKNOWN_ERROR");throw oe.error(d),this.eventEmitter.emit("connection.error",d),d}const c=await fetch(`${this.config.baseUrl}/api/live/agent/session`,{method:"POST",headers:a,body:JSON.stringify(o)});if(!c.ok){let d=`HTTP ${c.status}: Failed to fetch connection details`;try{const h=await c.json();h&&(h.error?d=`API Error: ${h.error}`:h.detail?d=`API Error: ${h.detail}`:h.message&&(d=`API Error: ${h.message}`))}catch{try{const f=await c.text();f&&(d=`API Error: ${f}`)}catch{}}throw new Error(d)}const l=await c.json();let u;return l.agent_info&&(u={id:l.agent_info.agent_info.id,name:l.agent_info.agent_info.name,capabilities:l.agent_info.capabilities,modality_supported:l.agent_info.modality_supported,session_settings:l.agent_info.session_settings||{}},this.currentAgentInfo=u),{serverUrl:l.wss_url,participantToken:l.token,voxketSessionId:l.session_id,agentInfo:u}}catch(o){const a=new se(`Failed to fetch connection details: ${o instanceof Error?o.message:"Unknown error"}`,"CONNECTION_FAILED",o);throw this.eventEmitter.emit("connection.error",new se(((s=o.message)==null?void 0:s.split("API Error: ")[1])||"Failed to connect","CONNECTION_FAILED",o)),a}}async connect(t,n,i,r){var s;try{this.eventEmitter.emit("connection.connecting");const o=await this.fetchConnectionDetails(t,n,i,r);return await((s=this.room)==null?void 0:s.connect(o.serverUrl,o.participantToken)),this.isConnected=!0,o}catch(o){throw new se(`Failed to connect to Voxket services: ${o instanceof Error?o.message:"Unknown error"}`,"CONNECTION_FAILED",o)}}async disconnect(){try{this.room&&await this.room.disconnect(),this.isConnected=!1,this.currentAgentInfo=null,this.initializeRoom(),this.eventEmitter.emit("connection.disconnected")}catch(t){const n=new se("Failed to disconnect properly","NETWORK_ERROR",t);throw this.eventEmitter.emit("connection.error",n),n}}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===Je.Connected}getCurrentAgentInfo(){return this.currentAgentInfo}getParticipants(){if(!this.room)return[];const t=[];return this.room.localParticipant&&t.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(n=>{t.push({id:n.identity,name:n.name||n.identity,isLocal:!1})}),t}updateConfig(t){this.config={...this.config,...t}}}class HA{constructor(t,n,i){Be(this,"room",null);Be(this,"eventEmitter");Be(this,"chatManager");Be(this,"agentManager");Be(this,"textStreamHandlersRegistered",!1);Be(this,"_eventEmitters",new Map);this.eventEmitter=t,this.chatManager=n,this.agentManager=i}setRoom(t){this.room=t,t&&!this.textStreamHandlersRegistered&&this.setupTextStreamHandlers()}areHandlersRegistered(){return this.textStreamHandlersRegistered}resetHandlersFlag(){this.textStreamHandlersRegistered=!1}setupTextStreamHandlers(){this.room&&(this.registerChatHandler(),this.registerTranscriptionHandler(),this.registerSuggestedResponseHandler(),this.registerAgentStateHandler(),this.registerFunctionToolsHandler(),this.registerImageTextStreamHandler(),this.registerImageByteStreamHandler(),this.registerCommonTopicHandlers(),this.registerWildcardHandler(),this.textStreamHandlersRegistered=!0)}registerChatHandler(){try{this.room.registerTextStreamHandler("lk.chat",async(t,n)=>{try{const i=await t.readAll(),r={id:`msg_${Date.now()}_${n.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:i,timestamp:new Date,sender:{id:n.identity||"user",name:n.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.eventEmitter.emit("chat.message.received",r)}catch(i){const r=new se("StreamHandlerManager: Failed to process lk.chat message","UNKNOWN_ERROR",i);this.eventEmitter.emit("connection.error",new se("Failed to process lk.chat message","WARN",i)),oe.error(r)}})}catch(t){const n=new se("StreamHandlerManager: lk.chat handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerTranscriptionHandler(){try{this.room.registerTextStreamHandler("lk.transcription",async(t,n)=>{var i,r;try{const s=n.identity===((r=(i=this.room)==null?void 0:i.localParticipant)==null?void 0:r.identity),o=n.identity,a=this.chatManager.getActiveTranscription(o);let c,l=!0;a?(c=a.messageId,l=!1):(c=`msg_${s?"user":"agent"}_${n.identity}_${Date.now()}`,this.chatManager.trackTranscription(o,c));let u="";const d=this.agentManager.getCurrentAgentInfo(),h=(d==null?void 0:d.name)||n.identity||"AI Assistant",f=s?"participant":"agent",g=s?"User":h,p={id:c,content:"",timestamp:new Date,sender:{id:n.identity||"unknown",name:g,type:f},metadata:{topic:"lk.transcription",streaming:!0}};l&&this.eventEmitter.emit("chat.message.received",p);for await(const w of t){u+=w;const S=this.chatManager.convertMarkdownToText(u),v={...p,content:S,metadata:{...p.metadata,streaming:!0}};this.eventEmitter.emit("chat.message.updated",v)}const x=this.chatManager.convertMarkdownToText(u),y={...p,content:x,metadata:{...p.metadata,streaming:!1}};this.eventEmitter.emit("chat.message.updated",y);const E={id:c,text:x,isFinal:!0,startTime:p.timestamp.getTime(),participantId:n.identity||"agent"};this.eventEmitter.emit("transcription.received",E)}catch(s){const o=new se("StreamHandlerManager: Failed to process lk.transcription message","UNKNOWN_ERROR",s);oe.error(o);try{const a=await t.readAll(),c=this.agentManager.getCurrentAgentInfo(),l=(c==null?void 0:c.name)||n.identity||"AI Assistant",u={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:a,timestamp:new Date,sender:{id:n.identity||"agent",name:l,type:"agent"},metadata:{topic:"lk.transcription"}};this.eventEmitter.emit("chat.message.received",u);const d={id:u.id,text:u.content,isFinal:!0,startTime:u.timestamp.getTime(),participantId:n.identity||"agent"};this.eventEmitter.emit("transcription.received",d)}catch(a){const c=new se("StreamHandlerManager: Fallback failed for lk.transcription","UNKNOWN_ERROR",a);oe.error(c)}}})}catch(t){const n=new se("StreamHandlerManager: lk.transcription handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerSuggestedResponseHandler(){try{this.room.registerTextStreamHandler("suggested_response",async t=>{const n=await t.readAll();let i=[];try{i=["tes","hello how are you","algebra make me learn that","what is the meaning of life"]}catch(r){const s=new se("StreamHandlerManager: Failed to parse suggested_response","UNKNOWN_ERROR",r);oe.error(s)}this.eventEmitter.emit("suggested.response",i)})}catch(t){const n=new se("StreamHandlerManager: suggested_response handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerAgentStateHandler(){try{this.room.registerTextStreamHandler("agent_state_changed",async(t,n)=>{const i=await t.readAll();let r={};try{r=typeof i=="string"?JSON.parse(i.replace(/'/g,'"')):i}catch(s){const o=new se("StreamHandlerManager: Failed to parse agent_state_changed","UNKNOWN_ERROR",s);oe.error(o)}this.agentManager.handleAgentStateChanged(r)})}catch(t){const n=new se("StreamHandlerManager: agent_state_changed handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerFunctionToolsHandler(){try{this.room.registerTextStreamHandler("function_tools_executed",async(t,n)=>{const i=await t.readAll();let r={};try{if(typeof i=="string")try{r=JSON.parse(i)}catch{let o=i;try{o=o.replace(/\bTrue\b/g,"true"),o=o.replace(/\bFalse\b/g,"false"),o=o.replace(/\bNone\b/g,"null");const a=o.replace(/\\"/g,"___ESCAPED_QUOTE___");let c="",l=!1;for(let u=0;u<a.length;u++){const d=a[u],h=u>0?a[u-1]:"";d==='"'&&h!=="\\"?(l=!l,c+=d):d==="'"&&h!=="\\"&&!l?c+='"':c+=d}o=c.replace(/___ESCAPED_QUOTE___/g,'\\"'),r=JSON.parse(o)}catch(a){const c=new se("StreamHandlerManager: Enhanced parsing also failed","UNKNOWN_ERROR",a);oe.error(c);try{let l=i.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null");r=new Function("return "+l)()}catch(l){const u=new se("StreamHandlerManager: All parsing methods failed","UNKNOWN_ERROR",l);throw oe.error(u),u}}}else r=i}catch(s){const o=new se("StreamHandlerManager: Failed to parse function_tool_executed","UNKNOWN_ERROR",s);oe.error(o);let a=null;if(typeof i=="string"&&i.includes("visualization_data"))try{const c=i.match(/"arguments":\s*"({.*?})"/);if(c){const l=c[1].replace(/\\"/g,'"');a=JSON.parse(l)}}catch(c){const l=new se("StreamHandlerManager: Failed to extract visualization data","UNKNOWN_ERROR",c);oe.error(l)}r={type:"function_tools_executed",function_calls:[],function_call_outputs:[],created_at:Date.now()/1e3,parseError:!0,rawData:i,extractedVisualizationData:a}}this.eventEmitter.emit("tool.executed",r)})}catch(t){const n=new se("StreamHandlerManager: function_tool_executed handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerImageTextStreamHandler(){try{this.room.registerTextStreamHandler("images",async(t,n)=>{try{const i=await t.readAll()}catch(i){const r=new se("StreamHandlerManager: Error processing images stream","UNKNOWN_ERROR",i);oe.error(r)}})}catch(t){const n=new se("StreamHandlerManager: images text handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerImageByteStreamHandler(){try{this.room.registerByteStreamHandler("images",async(t,n)=>{var i,r;try{const s=t.info,o={id:`img_${Date.now()}_${n.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`🖼️ ${s.name||"Image"}`,sender:{id:n.identity||"agent",name:n.identity||"Agent",type:n.identity===((r=(i=this.room)==null?void 0:i.localParticipant)==null?void 0:r.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:s.name,fileSize:s.size,mimeType:s.mimeType,streamId:s.id,downloading:!0}};this.eventEmitter.emit("chat.message.received",o),t.onProgress&&(t.onProgress=d=>{const h={...o,metadata:{...o.metadata,downloadProgress:d||0}};this.eventEmitter.emit("chat.message.updated",h)});const a=[];for await(const d of t)a.push(d);const c=new Blob(a,{type:s.mimeType||"application/octet-stream"}),l=URL.createObjectURL(c),u={...o,metadata:{...o.metadata,downloading:!1,downloadProgress:1,downloadUrl:l,blob:c}};this.eventEmitter.emit("chat.message.updated",u)}catch(s){const o=new se("StreamHandlerManager: Error processing image attachment","UNKNOWN_ERROR",s);oe.error(o)}})}catch(t){const n=new se("StreamHandlerManager: image byte handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerCommonTopicHandlers(){["error","warning","status","system","debug","info"].forEach(n=>{try{this.room.registerTextStreamHandler(n,async(i,r)=>{try{const s=await i.readAll();if(n==="error"){let o={};try{o=typeof s=="string"?JSON.parse(s):s}catch{o={message:s}}this.eventEmitter.emit("agent.error",o)}else this.eventEmitter.emit("text.stream.received",{topic:n,data:s,participantInfo:r})}catch(s){const o=new se(`StreamHandlerManager: Failed to process '${n}' stream`,"UNKNOWN_ERROR",s);oe.error(o)}})}catch(i){const r=new se(`StreamHandlerManager: Handler for '${n}' already registered, skipping`,"UNKNOWN_ERROR",i);oe.error(r)}})}registerWildcardHandler(){try{this.room.registerTextStreamHandler("*",async(t,n)=>{var i;try{const r=await t.readAll(),s=((i=t.info)==null?void 0:i.topic)||"unknown";if(this._eventEmitters.has(s)){const o=this._eventEmitters.get(s);try{o(r)}catch(a){const c=new se(`StreamHandlerManager: Error in custom handler for topic '${s}'`,"UNKNOWN_ERROR",a);oe.error(c)}}else this.eventEmitter.emit("text.stream.unhandled",{topic:s,data:r,participantInfo:n})}catch(r){const s=new se("StreamHandlerManager: Failed to process unhandled text stream","UNKNOWN_ERROR",r);oe.error(s)}})}catch(t){const n=new se("StreamHandlerManager: Generic text stream handler already registered, skipping","UNKNOWN_ERROR",t);oe.error(n)}}registerEventEmitter(t,n){if(!this.room)throw new Error("Room not available");this._eventEmitters.set(t,n);try{this.room.registerTextStreamHandler(t,async i=>{try{const r=await i.readAll();n(r)}catch(r){const s=new se(`Error processing event for topic '${t}'`,"UNKNOWN_ERROR",r);oe.error(s)}})}catch(i){const r=new se(`StreamHandlerManager: Direct handler registration failed for topic '${t}'`,"UNKNOWN_ERROR",i);oe.error(r)}}getRegisteredEventEmitters(){return Array.from(this._eventEmitters.keys())}hasEventEmitter(t){return this._eventEmitters.has(t)}}const KA=M.createContext(null);function Yc({config:e,children:t,autoConnect:n=!1,client:i}){const[r,s]=M.useState(null),[o,a]=M.useState(!1),[c,l]=M.useState(!1),[u,d]=M.useState(null),[h,f]=M.useState(null),[g,p]=M.useState("idle"),[x,y]=M.useState(null),[E,w]=M.useState([]),[S,v]=M.useState([]),[k,_]=M.useState([]);M.useEffect(()=>{const Q=i||new Ba(e);s(Q);const C=T(Q);return n&&!i&&I(Q),()=>{C(),i||Q.disconnect().catch(console.error)}},[e,n,i]);const T=Q=>{const C=()=>{l(!0),d(null)},K=()=>{a(!0),l(!1),d(null)},X=()=>{a(!1),l(!1),f(null),p("idle"),w([]),v([]),_([])},R=Z=>{d(Z),l(!1)},ae=Z=>{f(Z),p(Z.state)},he=Z=>{p(Z),h&&f({...h,state:Z})},ce=(Z,Re)=>{f(null),p("idle"),y(Re),w([]),v([]),_([])},ee=Z=>{w(Re=>[...Re,Z])},te=Z=>{w(Re=>Re.filter(tt=>tt.id!==Z.id))},ue=Z=>{v(Re=>[...Re,Z])},me=Z=>{v(Re=>[...Re,Z])},Me=Z=>{console.log("📝 VoxketProvider: Received transcription:",Z),_(Re=>Re.find(ge=>ge.id===Z.id)?(console.log("📝 VoxketProvider: Duplicate transcription detected, skipping:",Z.id),Re):(console.log("📝 VoxketProvider: Adding new transcription:",Z.id),[...Re,Z]))},ne=()=>{console.log("🧹 VoxketProvider: Clearing chat messages and transcriptions"),v([]),_([])};return Q.on("connection.connecting",C),Q.on("connection.connected",K),Q.on("connection.disconnected",X),Q.on("connection.error",R),Q.on("session.created",ae),Q.on("session.state.changed",he),Q.on("session.ended",ce),Q.on("participant.joined",ee),Q.on("participant.left",te),Q.on("chat.message.received",ue),Q.on("chat.message.sent",me),Q.on("transcription.received",Me),Q.on("chat.history.cleared",ne),()=>{console.log("📝 VoxketProvider: Cleaning up event listeners"),Q.off("connection.connecting",C),Q.off("connection.connected",K),Q.off("connection.disconnected",X),Q.off("connection.error",R),Q.off("session.created",ae),Q.off("session.state.changed",he),Q.off("session.ended",ce),Q.off("participant.joined",ee),Q.off("participant.left",te),Q.off("chat.message.received",ue),Q.off("chat.message.sent",me),Q.off("chat.history.cleared",ne),Q.off("transcription.received",Me)}},I=async Q=>{const C=Q||r;if(C)try{await C.connect()}catch(K){console.error("Failed to connect:",K)}},G={client:r,isConnected:o,isConnecting:c,connectionError:u,currentSession:h,sessionState:g,sessionMetrics:x,participants:E,chatMessages:S,transcriptions:k,connect:()=>I(),disconnect:async()=>{if(r)try{await r.disconnect()}catch(Q){console.error("Failed to disconnect:",Q)}},createSession:async(Q,C={})=>{if(!r)throw new Error("Client not initialized");const K={agentId:Q,participantName:C.participantName||"User",metadata:C.metadata,modalities:C.modalities||["voice"]};return await r.createSession(K)},endSession:async()=>r?await r.endSession():null,sendChatMessage:async Q=>{if(!r)throw new Error("Client not initialized");await r.sendChatMessage(Q)},setMicrophoneEnabled:async Q=>{if(!r)throw new Error("Client not initialized");await r.setMicrophoneEnabled(Q)},setCameraEnabled:async Q=>{if(!r)throw new Error("Client not initialized");await r.setCameraEnabled(Q)},startScreenShare:async()=>{if(!r)throw new Error("Client not initialized");await r.startScreenShare()},stopScreenShare:async()=>{if(!r)throw new Error("Client not initialized");await r.stopScreenShare()}};return m.jsx(KA.Provider,{value:G,children:t})}function Ii(){const e=M.useContext(KA);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}const pi=new WeakSet,ih=new WeakSet,kc=new WeakSet;class WA{constructor(t,n){Be(this,"renderedComponents",new Map);Be(this,"config");Be(this,"voxketClient");this.config=t,this.voxketClient=n}renderUI(t={}){const n=this.resolveTarget(t.target||"body"),i=this.getTargetKey(n);if(ih.has(n))return;if(kc.has(n)){setTimeout(()=>this.renderUI(t),100);return}if(pi.has(n)){const s=this.renderedComponents.get(i);if(s&&s.root){const o=this.buildWidgetProps(t);try{s.root.render(M.createElement(Yc,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:M.createElement(Jc,o)}));return}catch(a){const c=new se("Error re-rendering existing widget","UNKNOWN_ERROR",a);throw this.voxketClient.emit("connection.error",c),oe.error(c),c}}else pi.delete(n)}let r=this.renderedComponents.get(i);if(r&&r.target===n&&pi.has(n)){const s=r.root,o=this.buildWidgetProps(t);try{s.render(M.createElement(Yc,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:M.createElement(Jc,o)}))}catch(a){const c=new se("Error rendering Voxket widget","UNKNOWN_ERROR",a);throw this.voxketClient.emit("connection.error",c),oe.error(c),c}return}ih.add(n);try{if(r)try{r.root.unmount(),this.renderedComponents.delete(i),pi.delete(r.target),n.innerHTML=""}catch(a){const c=new se("Failed to cleanup existing root","UNKNOWN_ERROR",a);this.voxketClient.emit("connection.error",c),oe.error(c)}if(pi.has(n))return;const s=AR.createRoot(n);this.renderedComponents.set(i,{root:s,target:n}),pi.add(n);const o=this.buildWidgetProps(t);if(!s||typeof s.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{s.render(M.createElement(Yc,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:M.createElement(Jc,o)}))}catch(a){const c=new se("Error rendering Voxket widget","UNKNOWN_ERROR",a);throw this.voxketClient.emit("connection.error",c),oe.error(c),c}}finally{ih.delete(n)}}removeUI(t){const n=t?this.resolveTarget(t):null;if(n){const i=this.getTargetKey(n),r=this.renderedComponents.get(i);if(r){kc.add(n),this.renderedComponents.delete(i),pi.delete(n);const s=r.root,o=r.target;setTimeout(()=>{(l=>{typeof requestIdleCallback<"u"?requestIdleCallback(l,{timeout:100}):setTimeout(l,50)})(()=>{try{if(o&&o.isConnected&&!pi.has(o)&&s&&typeof s.unmount=="function")try{s.unmount()}catch{}}catch{}requestAnimationFrame(()=>{try{n&&n.isConnected&&n.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(u=>{try{u.parentNode&&u.parentNode.contains(u)&&u.remove()}catch{}})}catch{}finally{kc.delete(n)}})})},0)}else pi.delete(n),kc.delete(n);n===document.body&&n.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(o=>{if(o.classList.contains("bg-black")&&(o.classList.contains("backdrop-blur-sm")||o.classList.contains("bg-opacity-30")))try{o.remove()}catch(a){const c=new se("Failed to remove fixed element","UNKNOWN_ERROR",a);this.voxketClient.emit("connection.error",c),oe.error(c)}})}}removeAllUI(){const t=Array.from(this.renderedComponents.entries());this.renderedComponents.clear(),setTimeout(()=>{for(const[n,i]of t)try{i.target&&i.target.isConnected&&!pi.has(i.target)&&i.root.unmount()}catch{}this.forceCleanupFullscreenOverlays()},0)}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(n=>{if(n.classList.contains("bg-black")&&(n.classList.contains("backdrop-blur-sm")||n.classList.contains("bg-opacity-30")))try{n.remove()}catch(i){const r=new se("Failed to remove overlay","UNKNOWN_ERROR",i);this.voxketClient.emit("connection.error",r),oe.error(r)}})}resolveTarget(t){if(typeof t=="string"){const n=document.querySelector(t);if(!n)throw new Error(`Target element not found: ${t}`);return n}return t}getTargetKey(t){return t.id?t.id:t.className?t.tagName+"_"+t.className.replace(/\s+/g,"_"):t.tagName+"_"+t.outerHTML.length%1e3}buildWidgetProps(t){var i,r,s;const n=this.config;return{agentId:t.agentId||n.agentId||"default-agent",participantName:t.participantName||n.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:t.className,theme:typeof t.theme=="string"?t.theme:void 0,modalities:t.modality||n.modalities||["voice"],suportsChatInput:((i=t.modality)==null?void 0:i.includes("chat"))!==!1,suportsVideoInput:((r=t.modality)==null?void 0:r.includes("video"))===!0,suportsScreenShare:((s=t.modality)==null?void 0:s.includes("screen_share"))===!0,autoStart:t.autoStart,displayType:t.displayType||"widget",popupPosition:t.popupPosition||"bottom-right",popupTriggerText:t.popupTriggerText||"Open Chat",popupModalityMode:t.popupModalityMode||"all",width:t.width,height:t.height,onDisplayTypeChange:t.onDisplayTypeChange,prompts:t.prompts,statusMessage:t.statusMessage,welcomeTitle:t.welcomeTitle,welcomeSubTitle:t.welcomeSubTitle,loadingText:t.loadingText,voxketClient:this.voxketClient,participantMetadata:t.participantMetadata}}updateConfig(t){this.config=t}}class qA{constructor(t){Be(this,"agentState","idle");Be(this,"isAgentConnected",!1);Be(this,"currentAgentInfo",null);Be(this,"eventEmitter");this.eventEmitter=t}getAgentState(){return this.agentState}setAgentState(t){this.agentState!==t&&(this.agentState=t,this.eventEmitter.emit("agent.state.changed",{state:t}))}getIsAgentConnected(){return this.isAgentConnected}setAgentConnected(t){this.isAgentConnected=t}getCurrentAgentInfo(){return this.currentAgentInfo}setCurrentAgentInfo(t){this.currentAgentInfo=t}reset(){this.agentState="idle",this.isAgentConnected=!1,this.currentAgentInfo=null}handleAgentStateChanged(t){this.isAgentConnected||(this.setAgentConnected(!0),this.eventEmitter.emit("agent.connected",t)),t.new_state==="speaking"?(this.setAgentState("speaking"),this.eventEmitter.emit("agent.speaking",t)):t.new_state==="thinking"?(this.setAgentState("thinking"),this.eventEmitter.emit("agent.thinking",t)):(t.new_state==="idle"||t.new_state==="listening")&&this.setAgentState("idle")}}class Ba extends qm{constructor(n){super();Be(this,"config");Be(this,"pluginManager");Be(this,"rpcManager");Be(this,"chatManager");Be(this,"mediaManager");Be(this,"connectionManager");Be(this,"streamHandlerManager");Be(this,"uiRenderer");Be(this,"agentManager");Be(this,"currentSession",null);if(!n.authToken&&(!n.appId||!n.appSecret))throw new Error("Either authToken or both appId and appSecret must be provided");this.config=n,this.chatManager=new VA(this,n.participantName||"User"),this.mediaManager=new zA(this),this.agentManager=new qA(this),this.connectionManager=new GA({baseUrl:n.baseUrl,appId:n.appId,appSecret:n.appSecret,authToken:n.authToken},this),this.streamHandlerManager=new HA(this,this.chatManager,this.agentManager),this.uiRenderer=new WA(n,this),this.pluginManager=new UA(this),this.rpcManager=new jA(this),this.setupEventListeners(),this.setupRpcEventForwarding()}setupEventListeners(){this.on("connection.connected",()=>{var i,r,s,o,a;if((r=(i=this.config).onConnected)==null||r.call(i),this.currentSession&&this.currentSession.state==="connecting"){const c=this.currentSession.state;this.currentSession.state="connected",this.emit("session.state.changed","connected",c)}else oe.warn("⚠️ VoxketClient: Cannot update session state",{hasSession:!!this.currentSession,currentState:(s=this.currentSession)==null?void 0:s.state});const n=this.connectionManager.getRoom();if(n){this.rpcManager.setRoom(n);const c=Array.from(n.remoteParticipants.values()).find(l=>{var u;return(u=l.identity)==null?void 0:u.startsWith("agent-")});c&&(this.agentManager.getIsAgentConnected()||(this.agentManager.setAgentConnected(!0),this.emit("agent.connected",{identity:c.identity})))}(a=(o=this.currentSession)==null?void 0:o.activeModalities)!=null&&a.includes("voice")&&setTimeout(async()=>{try{this.mediaManager.getLocalParticipant()&&(this.mediaManager.isMicrophoneEnabled||(await this.mediaManager.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0})))}catch(c){const l=new se("VoxketClient: Failed to enable microphone after room connection:","UNKNOWN_ERROR",c);oe.error(l)}},100)}),this.on("connection.disconnected",n=>{var i,r,s;(r=(i=this.config).onDisconnected)==null||r.call(i,n),this.streamHandlerManager.resetHandlersFlag(),this.agentManager.reset(),this.chatManager.clearChatMessages(),n&&oe.warn("🔍 VoxketClient: Disconnect reason details:",{reason:n.toString(),currentSession:(s=this.currentSession)==null?void 0:s.id})}),this.on("connection.error",n=>{var i,r;(r=(i=this.config).onError)==null||r.call(i,n)}),this.on("chat.message.received",n=>{var i,r;this.chatManager.addChatMessage(n),(r=(i=this.config).onMessageReceived)==null||r.call(i,n)}),this.on("chat.message.updated",n=>{this.chatManager.updateChatMessage(n)}),this.on("chat.message.sent",n=>{this.chatManager.addChatMessage(n)}),this.on("transcription.received",n=>{var i,r;(r=(i=this.config).onTranscriptionReceived)==null||r.call(i,n)}),this.on("session.state.changed",n=>{var i,r;(r=(i=this.config).onSessionStateChanged)==null||r.call(i,n)}),this.on("session.created",n=>{var i,r;(r=(i=this.config).onSessionStart)==null||r.call(i,n.id)}),this.on("session.ended",(n,i)=>{var r,s;(s=(r=this.config).onSessionEnd)==null||s.call(r,i)}),this.on("participant.joined",n=>{var i,r;(r=(i=this.config).onUserJoined)==null||r.call(i,n.id)}),this.on("participant.left",n=>{var i,r;(r=(i=this.config).onUserLeft)==null||r.call(i,n.id)})}setupRpcEventForwarding(){if(!this.rpcManager){oe.warn("RpcManager not initialized, skipping event forwarding setup");return}this.rpcManager.on("rpc.method.registered",n=>this.emit("rpc.method.registered",n)),this.rpcManager.on("rpc.method.called",n=>this.emit("rpc.method.called",n)),this.rpcManager.on("rpc.interaction.started",n=>this.emit("rpc.interaction.started",n)),this.rpcManager.on("rpc.interaction.completed",n=>this.emit("rpc.interaction.completed",n)),this.rpcManager.on("rpc.interaction.timeout",n=>this.emit("rpc.interaction.timeout",n)),this.rpcManager.on("rpc.interaction.dismissed",n=>this.emit("rpc.interaction.dismissed",n))}async connect(n,i,r,s){const o=n||this.config.agentId||"default-agent",a=i||this.config.participantName||"User",c=r||this.config.modalities||["voice"],l=s||this.config.participantMetadata,u=await this.connectionManager.connect(o,a,c,l),d=this.connectionManager.getRoom();return this.chatManager.setRoom(d),this.mediaManager.setRoom(d),this.streamHandlerManager.setRoom(d),u.agentInfo&&this.agentManager.setCurrentAgentInfo(u.agentInfo),u}async disconnect(){await this.connectionManager.disconnect(),this.currentSession=null;const n=this.connectionManager.getRoom();this.chatManager.setRoom(n),this.mediaManager.setRoom(n),this.streamHandlerManager.setRoom(n)}async createSession(n){var i,r;try{const s=await this.connect(n.agentId,n.participantName,n.modalities,n.participantMetadata),o={id:s.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:s.agentInfo||this.agentManager.getCurrentAgentInfo()};this.currentSession=o,this.emit("session.created",o);const a=this.connectionManager.getRoom();if(a&&(a.state!=="connected"&&await new Promise((l,u)=>{const d=setTimeout(()=>{u(new Error("Room connection timeout"))},1e4),h=()=>{clearTimeout(d),a.off("connected",h),a.off("disconnected",f),l()},f=()=>{clearTimeout(d),a.off("connected",h),a.off("disconnected",f),u(new Error("Room disconnected while waiting for connection"))};a.once("connected",h),a.once("disconnected",f)}),this.currentSession.state="connected",this.emit("session.state.changed","connected","connecting"),await new Promise(l=>{const u=setTimeout(()=>{l(!1)},3e4),d=()=>{clearTimeout(u),this.off("agent.connected",d),this.off("participant.joined",h),l(!0)},h=f=>{var g,p;((g=f.id)!=null&&g.startsWith("agent-")||(p=f.name)!=null&&p.toLowerCase().includes("agent"))&&(clearTimeout(u),this.off("agent.connected",d),this.off("participant.joined",h),l(!0))};this.once("agent.connected",d),this.on("participant.joined",h),this.agentManager.getIsAgentConnected()&&(clearTimeout(u),this.off("agent.connected",d),this.off("participant.joined",h),l(!0))})&&(this.currentSession.state="active",this.emit("session.state.changed","active","connected"))),(i=n.modalities)!=null&&i.includes("voice"))try{await this.mediaManager.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0})}catch(c){const l=new se("Failed to enable microphone","WARN",c);oe.error(l)}if((r=n.modalities)!=null&&r.includes("video"))try{await new Promise(c=>setTimeout(c,200)),await this.mediaManager.enableCamera()}catch(c){oe.warn("Failed to enable camera",c)}return o}catch(s){if(s instanceof se)throw oe.error(s),s;if(s instanceof TypeError&&s.message.includes("fetch")){const a=new se("Network connection failed","CONNECTION_FAILED",s);throw oe.error(a),a}if(s instanceof Error&&s.message.includes("Failed to fetch connection details")){const a=new se(`API connection failed: ${s.message}`,"CONNECTION_FAILED",s);throw oe.error(a),a}const o=new se(`Failed to create session: ${s instanceof Error?s.message:"Unknown error"}`,"SESSION_NOT_FOUND",s);throw oe.error(o),o}}async startSession(n,i){const r={agentId:n||this.config.agentId||"default-agent",participantName:(i==null?void 0:i.participantName)||this.config.participantName||"User",modalities:(i==null?void 0:i.modalities)||this.config.modalities||["voice","chat"],metadata:i==null?void 0:i.metadata,participantMetadata:i==null?void 0:i.participantMetadata};return this.createSession(r)}async endSession(){var n,i;if(!this.currentSession)return null;try{const r={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((i=this.connectionManager.getRoom())==null?void 0:i.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]};return this.currentSession.endedAt=new Date,this.currentSession.state="disconnected",this.emit("session.ended",this.currentSession,r),await this.disconnect(),r}catch(r){throw r instanceof se?(oe.error(r),r):new se("Failed to end session","SESSION_NOT_FOUND",r)}}getCurrentSession(){return this.currentSession}getSessionMetrics(){var n,i;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((i=this.connectionManager.getRoom())==null?void 0:i.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]}:null}async sendMessage(n,i){if(!this.currentSession){const r=new se("No active session","SESSION_NOT_FOUND");throw oe.error(r),r}return this.dismissCurrentInteraction(),this.chatManager.sendMessage(n,i)}async sendChatMessage(n,i){return this.sendMessage(n,i)}async sendAttachments(n,i){if(!this.currentSession){const r=new se("No active session","SESSION_NOT_FOUND");throw oe.error(r),r}return this.dismissCurrentInteraction(),this.chatManager.sendAttachments(n,i)}async sendAttachment(n,i){return this.chatManager.sendAttachment(n,i)}getChatMessages(){return this.chatManager.getChatMessages()}addChatMessage(n){this.chatManager.addChatMessage(n)}updateChatMessage(n){this.chatManager.updateChatMessage(n)}clearChatMessages(){this.chatManager.clearChatMessages(),this.dismissCurrentInteraction(),this.uiRenderer.removeAllUI()}toggleMicrophone(n){return this.mediaManager.toggleMicrophone(n)}async setMicrophoneEnabled(n){return this.mediaManager.setMicrophoneEnabled(n)}toggleCamera(n){return this.mediaManager.toggleCamera(n)}async setCameraEnabled(n){return this.mediaManager.setCameraEnabled(n)}async enableCamera(){return this.mediaManager.enableCamera()}async disableCamera(){return this.mediaManager.disableCamera()}async startScreenShare(){return this.mediaManager.startScreenShare()}async stopScreenShare(){return this.mediaManager.stopScreenShare()}async getAudioInputDevices(){return this.mediaManager.getAudioInputDevices()}async getVideoInputDevices(){return this.mediaManager.getVideoInputDevices()}async setAudioInputDevice(n){return this.mediaManager.setAudioInputDevice(n)}async setVideoInputDevice(n){return this.mediaManager.setVideoInputDevice(n)}get isMicrophoneEnabled(){return this.mediaManager.isMicrophoneEnabled}get isCameraEnabled(){return this.mediaManager.isCameraEnabled}get isScreenShareEnabled(){return this.mediaManager.isScreenShareEnabled}getMicrophoneTrack(){return this.mediaManager.getMicrophoneTrack()}getCameraTrack(){return this.mediaManager.getCameraTrack()}getScreenShareTrack(){return this.mediaManager.getScreenShareTrack()}getAgentAudioTrack(){return this.mediaManager.getAgentAudioTrack()}getAgentVideoTrack(){return this.mediaManager.getAgentVideoTrack()}getVideoTrackRefs(){return this.mediaManager.getVideoTrackRefs()}getCameraTrackRefs(){return this.mediaManager.getCameraTrackRefs()}getScreenShareTrackRefs(){return this.mediaManager.getScreenShareTrackRefs()}getPublishPermissions(){return this.mediaManager.getPublishPermissions()}canPublishSource(n){return this.mediaManager.canPublishSource(n)}getLocalParticipant(){return this.mediaManager.getLocalParticipant()}getRemoteParticipants(){return this.mediaManager.getRemoteParticipants()}getParticipants(){return this.connectionManager.getParticipants()}getRoom(){return this.connectionManager.getRoom()}getConnectionState(){return this.connectionManager.getConnectionState()}get connected(){return this.connectionManager.connected}getCurrentAgentInfo(){return this.agentManager.getCurrentAgentInfo()}getIsAgentConnected(){return this.agentManager.getIsAgentConnected()}getAgentState(){return this.agentManager.getAgentState()}renderUI(n={}){this.uiRenderer.renderUI(n)}removeUI(n){this.uiRenderer.removeUI(n)}removeAllUI(){this.uiRenderer.removeAllUI()}async registerFrontendRPC(n,i,r="embedded"){return this.rpcManager.registerFrontendRPC(n,i,r)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}registerPlugin(n){this.pluginManager.register(n)}getPluginManager(){return this.pluginManager}registerEventListener(n,i){return this.on(n,i)}registerEventEmitter(n,i){return this.streamHandlerManager.registerEventEmitter(n,i)}getRegisteredEventEmitters(){return this.streamHandlerManager.getRegisteredEventEmitters()}hasEventEmitter(n){return this.streamHandlerManager.hasEventEmitter(n)}updateConfig(n){this.config={...this.config,...n},this.uiRenderer.updateConfig(this.config),this.connectionManager.updateConfig({baseUrl:this.config.baseUrl,appId:this.config.appId,appSecret:this.config.appSecret}),this.chatManager.setParticipantName(this.config.participantName||"User")}setParticipantMetadata(n){this.config.participantMetadata=n}getParticipantMetadata(){return this.config.participantMetadata}async startRecording(){var n;try{this.emit("recording.started",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(i){const r=new se("Failed to start recording","RECORDING_ERROR",i);throw oe.error(r),r}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(i){const r=new se("Failed to stop recording","RECORDING_ERROR",i);throw oe.error(r),r}}}let Ax=!1;function QA(){if(Ax||typeof document>"u")return;if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",QA);return}const e=document.createElement("div");e.className="flex",e.style.cssText="position:absolute;visibility:hidden;pointer-events:none;",document.body.appendChild(e);const n=window.getComputedStyle(e).display==="flex";document.body.removeChild(e),n||(Ax=!0)}Ve.create(vm);Ve.create(ou);Ve.create(wT);Ve.create(_m);function YA({theme:e,mode:t,loadingText:n,sessionState:i}){const r=wn(e),s=()=>{if(i==="connected")return"Connecting to agent...";if(n)return n;switch(t){case"voice":return"Connecting to voice agent...";case"chat":return"Starting chat session...";default:return"Connecting..."}};return m.jsxs("div",{className:"flex flex-col items-center justify-center h-full w-full p-8",children:[m.jsxs("div",{className:"text-center",children:[m.jsx("h3",{className:`text-lg font-semibold mb-2 ${r.text.accent}`,children:s()}),m.jsx("p",{className:`text-sm ${r.text.muted}`,children:"Please wait a moment..."})]}),m.jsxs("div",{className:"flex space-x-1 mt-4",children:[m.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"0ms"}}),m.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"150ms"}}),m.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"300ms"}})]})]})}Ve.create(YA);function rh({theme:e}){const t=e==="light";return m.jsxs("div",{className:`font-bold left-0 right-0 flex-shrink-0 text-center py-1 px-2 text-[10px] mt-auto ${t?"text-gray-400 bg-white/80":"text-white/40 bg-black/40"}`,style:{lineHeight:"1.2",backdropFilter:"blur(4px)"},children:[m.jsx("span",{children:"Powered by "}),m.jsx("a",{href:"https://voxket.ai",target:"_blank",rel:"noopener noreferrer",className:`hover:underline font-bold ${t?"text-gray-500":"text-white/50"}`,children:"voxket.ai"}),m.jsx("span",{className:"mx-1",children:"·"}),m.jsx("span",{children:"AI can make mistakes"})]})}function Rx({children:e,theme:t,displayType:n="widget",onClose:i,popupPosition:r="bottom-right",onExpand:s,width:o,height:a}){const c=wn(t),l=o||"350px",u=a||"500px";if(n==="fullscreen")return m.jsx("div",{className:"fixed inset-0 z-[9999] bg-black/40 bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",onClick:d=>{d.target===d.currentTarget&&i&&i()},children:m.jsxs("div",{className:"w-full h-full max-w-7xl max-h-[95vh] rounded-2xl relative bg-transparent flex flex-col",onClick:d=>{d.stopPropagation()},children:[i&&m.jsx("button",{onClick:d=>{d.preventDefault(),d.stopPropagation(),i()},className:`absolute top-4 cursor-pointer right-4 z-[10000] w-12 h-12 rounded-full flex items-center justify-center transition-all duration-200 shadow-lg border backdrop-blur-sm ${t==="light"?"bg-white bg-opacity-90 text-gray-900 hover:bg-gray-100 border-gray-300":"bg-gray-900 bg-opacity-90 text-white hover:bg-gray-800 border-gray-700"}`,title:"Exit Fullscreen",type:"button",children:m.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:m.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),m.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${c.card} w-full h-full flex flex-col rounded-xl shadow-2xl relative overflow-hidden`,"data-theme":t,style:{minHeight:"600px",height:"100%",contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0},children:[m.jsx("div",{className:c.cardTopGradient}),m.jsx("div",{className:c.cardPurpleBlur}),m.jsx("div",{className:c.cardPinkBlur}),m.jsxs("div",{className:"relative z-10 flex flex-col h-full",style:{flex:"1 1 auto"},children:[e,m.jsx(rh,{theme:t})]}),m.jsx("div",{className:c.cardPulse1}),m.jsx("div",{className:c.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(n==="popup"){const d={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"};return m.jsx("div",{className:"fixed rounded-2xl inset-0 z-[9999] pointer-events-none",children:m.jsxs("div",{className:`fixed rounded-2xl ${d[r]} pointer-events-auto`,children:[i&&m.jsx("button",{onClick:i,className:`absolute -top-2 -right-2 z-10 w-8 h-8 rounded-full flex items-center justify-center transition-all duration-200 text-sm shadow-lg border ${t==="light"?"bg-white bg-opacity-90 text-gray-900 hover:bg-gray-100 border-gray-300":"bg-gray-900 bg-opacity-90 text-white hover:bg-gray-800 border-gray-700"}`,children:"×"}),m.jsxs("div",{id:"voice-card",className:`voxket-widget-root voxket-popup-mode theme-${t} ${c.card} rounded-2xl flex flex-col relative overflow-hidden`,"data-theme":t,"data-display-type":"popup",style:{width:l,height:u,minWidth:l,maxWidth:l,minHeight:u,maxHeight:u,contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0,display:"flex",flexDirection:"column"},children:[m.jsx("div",{className:c.cardTopGradient}),m.jsx("div",{className:c.cardPurpleBlur}),m.jsx("div",{className:c.cardPinkBlur}),m.jsxs("div",{className:"relative z-10 flex flex-col w-full min-h-0 overflow-hidden voxket-popup-content",style:{display:"flex",flexDirection:"column",flex:"1 1 auto"},children:[e,m.jsx(rh,{theme:t})]}),m.jsx("div",{className:c.cardPulse1}),m.jsx("div",{className:c.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return m.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${c.card} relative overflow-hidden w-full h-full`,"data-theme":t,style:{height:"100%",maxHeight:"100%",contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0},children:[m.jsx("div",{className:c.cardTopGradient}),m.jsx("div",{className:c.cardPurpleBlur}),m.jsx("div",{className:c.cardPinkBlur}),m.jsxs("div",{className:"relative z-10 flex flex-col h-full w-full",style:{flex:"1 1 auto"},children:[e,m.jsx(rh,{theme:t})]}),m.jsx("div",{className:c.cardPulse1}),m.jsx("div",{className:c.cardPulse2,style:{animationDelay:"1s"}})]})}function vq(e){if(typeof window>"u")return null;D.useEffect(()=>{QA()},[]);const{agentId:t,participantName:n,baseUrl:i,appSecret:r,appId:s,authToken:o,prompts:a,statusMessage:c,welcomeTitle:l,welcomeSubTitle:u,className:d,width:h,height:f,loadingText:g,suportsChatInput:p=!0,suportsVideoInput:x=!0,suportsScreenShare:y=!0,theme:E="vox",onError:w,onSessionStart:S,onSessionEnd:v,enableSessionLogging:k=!0,onSessionLogsUpdate:_,onSessionMetricsUpdate:T,modalities:I=["voice"],displayType:b="widget",popupPosition:A="bottom-right",popupTriggerText:P="Open Chat",onPopupToggle:B,voxketClient:L,onDisplayTypeChange:V,participantMetadata:J,popupModalityMode:re="all",popupTriggerLogoUrl:G}=e,[Q,C]=D.useState(null),K=D.useRef({x:0,y:0,isSwiping:!1}),X=Q||A,R=D.useRef(X);R.current=X;const ae=D.useCallback(j=>{window.removeEventListener("mouseup",ae),window.removeEventListener("touchend",ae);const ie=j.changedTouches?j.changedTouches[0].clientX:j.clientX,_e=j.changedTouches?j.changedTouches[0].clientY:j.clientY,st=ie-K.current.x,un=_e-K.current.y,ui=50;if(Math.abs(st)>ui||Math.abs(un)>ui){K.current.isSwiping=!0;let[tr,us]=R.current.split("-");Math.abs(st)>ui&&(us=st>0?"right":"left"),Math.abs(un)>ui&&(tr=un>0?"bottom":"top"),C(`${tr}-${us}`)}},[]),he=(j,ie)=>{K.current={x:j,y:ie,isSwiping:!1},window.addEventListener("mouseup",ae),window.addEventListener("touchend",ae)},[ce,ee]=D.useState(!1),[te,ue]=D.useState(null),[me,Me]=D.useState(()=>{try{if(L)return!!L.getCurrentSession()}catch(j){const ie=new se("Error checking existing session","UNKNOWN_ERROR",j);oe.error(ie)}return!1}),[ne,Z]=D.useState(!1),[Re,tt]=D.useState(t||""),[ge,Le]=D.useState(n||"User"),[ve,Pe]=D.useState(()=>{try{if(L)return L.getCurrentSession()}catch(j){const ie=new se("Error getting current session","UNKNOWN_ERROR",j);oe.error(ie)}return null}),[Te,rt]=D.useState(()=>{var j,ie;try{if(L){const _e=L.getCurrentSession();if((j=_e==null?void 0:_e.activeModalities)!=null&&j.includes("chat"))return"chat";if((ie=_e==null?void 0:_e.activeModalities)!=null&&ie.includes("voice"))return"voice"}}catch(_e){const st=new se("Error determining current mode","UNKNOWN_ERROR",_e);oe.error(st)}return"welcome"}),[Ht,ct]=D.useState(!1),[Mt,Qt]=D.useState(!1),[H,le]=D.useState(()=>I.length===1?I[0]:null),[Ue,Ke]=D.useState(!1);D.useEffect(()=>{},[b]);const $e=D.useRef(null);if(!$e.current)try{if(L)$e.current=L;else if(!o&&(!s||!r)){const j="Missing required props: Either provide 'authToken' or both 'appId' and 'appSecret'",ie=new se(j,"UNKNOWN_ERROR");oe.error(ie),ue(new Error(j)),ee(!0)}else if(i){const j={...o?{authToken:o}:{appId:s,appSecret:r},baseUrl:i,agentId:Re,onError:w,participantName:ge||"User",modalities:I,participantMetadata:J};$e.current=new Ba(j)}else{const j="Missing required prop: baseUrl",ie=new se(j,"UNKNOWN_ERROR");oe.error(ie),ue(new Error(j)),ee(!0)}}catch(j){const ie=new se("Failed to create VoxketClient","UNKNOWN_ERROR",j);oe.error(ie),ue(j),ee(!0)}const Ce=$e.current;D.useEffect(()=>{const j=$e.current;return()=>{j&&!L&&j.disconnect().catch(ie=>{const _e=new se("Error during widget cleanup disconnect","UNKNOWN_ERROR",ie);oe.error(_e)})}},[L]);const Jn=D.useMemo(()=>b==="popup"&&H?[H]:I,[b,H,I]),bt=D.useMemo(()=>{try{return Ce?Ce.getRoom()||new Ki:new Ki}catch(j){const ie=new se("Error getting room from client","UNKNOWN_ERROR",j);return oe.error(ie),new Ki}},[Ce,me,Te]);D.useEffect(()=>{if(bt){const j=()=>{},ie=(_e,st,un)=>{};return bt.on(U.Connected,j),bt.on(U.Disconnected,j),bt.on(U.TrackSubscribed,ie),()=>{bt.off(U.Connected,j),bt.off(U.Disconnected,j),bt.off(U.TrackSubscribed,ie)}}},[bt,ve==null?void 0:ve.id]),D.useEffect(()=>{(Te==="voice"||Te==="chat")&&!ve&&!me&&!ne&&Ce&&!Ce.connected&&(rt("welcome"),Z(!1))},[Te,ve,me,ne,Ce]);const{sessionMetrics:Un,sessionLogs:li,logEvent:en}=HT({room:bt,onSessionStart:S,onSessionEnd:v,enableConsoleLogging:k,enableLocalStorage:k,voxketSessionId:ve==null?void 0:ve.id});D.useEffect(()=>{_&&_(li)},[li,_]),D.useEffect(()=>{T&&Un&&T(Un)},[Un,T]),D.useEffect(()=>{if(!Ce)return;const j=(ie,_e)=>{(ie==="connecting"||ie==="connected")&&(ne||Z(!0)),ie==="active"&&(Z(!1),Me(!0)),(ie==="disconnected"||ie==="error")&&(Z(!1),Me(!1),Pe(null),rt("welcome"))};return Ce.on("session.state.changed",j),()=>{Ce.off("session.state.changed",j)}},[Ce,ne]),D.useEffect(()=>{if(!Ce)return;const j=()=>{const ie=Ce.connected,_e=Ce.getCurrentSession();!ie&&me&&!ne&&(Z(!1),Me(!1),Pe(null),rt("welcome")),ie&&_e&&ne&&(Z(!1),Me(!0),Pe(_e))};return Ce.on("connectionStateChanged",j),Ce.on("sessionEnded",()=>{Z(!1),Me(!1),Pe(null),rt("welcome")}),()=>{Ce.off("connectionStateChanged",j),Ce.off("sessionEnded",()=>{})}},[Ce,Te,ne,me]);const ln=!!(!!(Ce!=null&&Ce.connected)&&me&&ve);D.useEffect(()=>{const j=_e=>{Z(!1),Me(!1),Pe(null),rt("welcome")},ie=_e=>{const st=new se("Media devices error","UNKNOWN_ERROR",_e);oe.error(st)};return bt.on(U.MediaDevicesError,ie),bt.on(U.Disconnected,j),()=>{bt.off(U.Disconnected,j),bt.off(U.MediaDevicesError,ie)}},[bt,Te,me,ve==null?void 0:ve.id,ne]);const Ua=async()=>{try{if(!Ce){const ie=new se("VoxketClient not initialized","UNKNOWN_ERROR");oe.error(ie),ue(new Error("VoxketClient not initialized")),ee(!0);return}Z(!0),rt("voice"),en("USER_STARTED_VOICE_SESSION",{agentId:Re,participantName:ge});const j=await Ce.startSession(Re,{participantName:ge||"User",modalities:["voice"],participantMetadata:Ce.getParticipantMetadata()||J});Pe(j),Me(!0),Z(!1),S&&S(j.id)}catch(j){const ie=new se("Failed to start voice session","UNKNOWN_ERROR",j);oe.error(ie),Z(!1),Me(!1),rt("welcome")}},ja=async()=>{try{if(!Ce){const ie=new se("VoxketClient not initialized","UNKNOWN_ERROR");oe.error(ie),ue(new Error("VoxketClient not initialized")),ee(!0);return}Z(!0),rt("chat"),en("USER_STARTED_CHAT_SESSION",{agentId:Re,participantName:ge});const j=await Ce.startSession(Re,{participantName:ge||"User",modalities:["chat"],participantMetadata:Ce.getParticipantMetadata()||J});Pe(j),Me(!0),Z(!1),S&&S(j.id)}catch(j){const ie=new se("Failed to start chat session","UNKNOWN_ERROR",j);oe.error(ie),Z(!1),Me(!1),rt("welcome")}},yo=()=>{rt("welcome"),Z(!1),V&&V(e.displayType||"widget"),ve&&me?(Me(!1),Pe(null),Ce&&Ce.disconnect().catch(j=>{const ie=new se("Widget: Error during disconnect","UNKNOWN_ERROR",j);oe.error(ie)})):Ce&&Ce.connected&&Ce.disconnect().catch(j=>{const ie=new se("Widget: Error during force disconnect","UNKNOWN_ERROR",j);oe.error(ie)}),b==="popup"&&!Ht&&ct(!0)},ls=()=>{const j=!Ht;ct(j),B&&B(j),!j&&!(ve&&me)&&(rt("welcome"),Me(!1),Pe(null))},er=()=>{e.onDisplayTypeChange&&e.onDisplayTypeChange("widget")},O=()=>{if(e.onDisplayTypeChange)e.onDisplayTypeChange("fullscreen");else{const j=document.getElementById("voice-card")||document.querySelector(".voxket-widget-container");j&&j.requestFullscreen&&j.requestFullscreen().catch(ie=>{})}};D.useEffect(()=>{var j,ie;if(L&&Ce){const _e=Ce.getCurrentSession();Ce.connected,_e&&(Pe(_e),Me(!0),Z(!1),(j=_e.activeModalities)!=null&&j.includes("chat")?rt("chat"):(ie=_e.activeModalities)!=null&&ie.includes("voice")&&rt("voice"))}},[L,Ce]),D.useEffect(()=>()=>{!L&&Ce&&Ce.disconnect()},[Ce,L]);let q="w-96",ye="h-[25rem]",Fe={};if(h&&(h.startsWith("w-")?q=h:(Fe.width=h,q="")),f&&(f.startsWith("h-")?ye=f:(Fe.height=f,ye="")),b==="popup"&&!Ht)return m.jsxs("div",{onMouseDown:j=>he(j.clientX,j.clientY),onTouchStart:j=>he(j.touches[0].clientX,j.touches[0].clientY),style:{display:"contents"},children:[m.jsx(GT,{onClick:j=>{if(K.current.isSwiping){j.preventDefault(),j.stopPropagation(),K.current.isSwiping=!1;return}if(ln){!H&&(ve!=null&&ve.activeModalities)&&(ve.activeModalities.includes("chat")?le("chat"):ve.activeModalities.includes("voice")&&le("voice")),Qt(!1),ct(!0),B&&B(!0);return}if(re!=="all"){le(re),Qt(!1),ct(!0),B&&B(!0);return}if(I.length===1){le(I[0]),Qt(!1),ct(!0),B&&B(!0);return}Qt(ie=>!ie),le(null),Ke(!1)},position:X,ariaLabel:P,size:64,isRunning:ln,logoUrl:G,theme:E}),Mt&&re==="all"&&(()=>{const _e={};X==="bottom-right"?(_e.bottom=88,_e.right=16):X==="bottom-left"?(_e.bottom=88,_e.left=16):X==="top-right"?(_e.top=88,_e.right=16):(_e.top=88,_e.left=16);const st="absolute w-0 h-0 border-8",un=E==="light",ui=un?"border-t-white":"border-t-black",tr=un?"border-b-white":"border-b-black",us=X.startsWith("bottom")?m.jsx("div",{className:`${st} border-transparent ${ui}`,style:{bottom:-16,right:X.endsWith("right")?16:void 0,left:X.endsWith("left")?16:void 0}}):m.jsx("div",{className:`${st} border-transparent ${tr}`,style:{top:-16,right:X.endsWith("right")?16:void 0,left:X.endsWith("left")?16:void 0}}),vo=un?"bg-white text-gray-900 border-[2px] border-indigo-200/60 shadow-2xl shadow-indigo-200/30":"bg-black text-white shadow-2xl",Va=un?"bg-indigo-50 hover:bg-indigo-100 text-indigo-700 border border-indigo-200/50":"bg-white/10 hover:bg-white/20 text-white",Au=un?"text-gray-500":"text-white/70";return m.jsx("div",{className:`fixed z-[51] rounded-2xl ${vo}`,style:{..._e,padding:"10px"},onMouseDown:xo=>xo.stopPropagation(),onTouchStart:xo=>xo.stopPropagation(),children:m.jsxs("div",{className:"relative ",children:[us,m.jsx("div",{className:`text-xs uppercase tracking-wide mb-2 ${Au}`,children:"Choose modality"}),m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("button",{type:"button",onClick:()=>{le("voice"),Qt(!1),ct(!0),B&&B(!0)},className:`px-3 py-2 rounded-md text-sm transition-colors ${Va}`,title:"Voice",children:"Voice"}),m.jsx("button",{type:"button",onClick:()=>{le("chat"),Qt(!1),ct(!0),B&&B(!0)},className:`px-3 py-2 rounded-md text-sm transition-colors ${Va}`,title:"Chat",children:"Chat"})]})]})})})()]});if(ce||!Ce){const j=(te==null?void 0:te.message)||"VoxketWidget encountered an error. Please check your configuration.";return m.jsx("div",{className:`voxket-widget-root theme-${E} flex items-center justify-center p-8 ${d||""}`,style:{width:h||"400px",height:f||"500px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"},children:m.jsxs("div",{className:"text-center",children:[m.jsx("div",{className:"text-4xl mb-4",children:"⚠️"}),m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Widget Error"}),m.jsx("p",{className:"text-sm mb-4",children:j}),m.jsx("button",{onClick:()=>{ee(!1),ue(null),window.location.reload()},className:"px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"Retry"})]})})}let At=`voxket-widget-root theme-${E}`,Et={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};b==="widget"?(At+=` flex min-h-fit ${q} ${ye} ${d}`,Et={...Et,...Fe}):(At=`${d||""}`,Et={});const we=m.jsx("div",{className:"h-full w-full flex flex-col overflow-hidden z-10",children:m.jsxs(Ys,{mode:"wait",children:[Te==="welcome"&&!ne&&m.jsx(Ve.div,{initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"},className:"h-screen w-full",style:{height:"100%"},children:m.jsx(_m,{agentId:Re,participantName:ge||"",onAgentIdChange:tt,onParticipantNameChange:Le,onStartCall:Ua,onStartChat:ja,disabled:me||ne,prompts:a,statusMessage:c,title:l,subTitle:u,theme:E,modalities:Jn})},"welcome"),ne&&(Te==="voice"||Te==="chat")&&m.jsx(Ve.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.3,ease:"easeInOut"},className:"h-screen w-full",style:{height:"100%"},children:m.jsx(YA,{theme:E,mode:Te,loadingText:g,sessionState:ve==null?void 0:ve.state})},`loading-${Te}`),Te==="voice"&&!ne&&me&&Ce&&m.jsxs(Jp.Provider,{value:bt,children:[m.jsx(tB,{},`audio-${(ve==null?void 0:ve.id)||"no-session"}`),m.jsx(QL,{label:"Start Audio"},`start-audio-${(ve==null?void 0:ve.id)||"no-session"}`),m.jsx(Ve.div,{initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"},className:"h-screen w-full",style:{height:"100%"},children:m.jsx(vm,{loadingText:g,participantName:ge||"User",sessionStarted:me,disabled:!1,theme:E,client:Ce,displayType:b,onBack:b==="popup"?ls:yo})},"voice-session")]}),Te==="chat"&&!ne&&me&&Ce&&m.jsx(Ve.div,{initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"},className:"h-screen w-full",style:{height:"100%"},children:m.jsx(ou,{client:Ce,theme:E,displayType:b,onBack:b==="popup"?ls:yo,onEndChat:yo,disabled:!1})},"chat-view")]})});return b==="fullscreen"||b==="popup"?m.jsx(Rx,{theme:E,displayType:b,popupPosition:X,onClose:b==="fullscreen"?er:ls,width:h,height:f,children:we}):m.jsx("div",{className:At,style:Et,children:m.jsx(Rx,{theme:E,displayType:b,popupPosition:X,onExpand:O,children:we})})}function Jc(e){return m.jsx(fq,{fallback:m.jsx(gG,{}),children:m.jsx(vq,{...e})})}function xq({logs:e,onClear:t,onExport:n}){const[i,r]=M.useState(!1),[s,o]=M.useState(""),a=e.filter(c=>!s||c.event.toLowerCase().includes(s.toLowerCase()));return i?m.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:m.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[m.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[m.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("input",{type:"text",placeholder:"Filter events...",value:s,onChange:c=>o(c.target.value),className:"px-3 py-1 border rounded text-sm"}),m.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),m.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),m.jsx("button",{onClick:()=>r(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),m.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?m.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):m.jsx("div",{className:"space-y-2",children:a.map((c,l)=>m.jsxs("div",{className:"border rounded p-3 text-sm",children:[m.jsxs("div",{className:"flex items-center justify-between mb-1",children:[m.jsx("span",{className:"font-semibold text-blue-600",children:c.event}),m.jsx("span",{className:"text-gray-500 text-xs",children:new Date(c.timestamp).toLocaleTimeString()})]}),c.sessionId&&m.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",c.sessionId]}),c.data&&m.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:m.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(c.data,null,2)})})]},l))})})]})}):m.jsxs("button",{onClick:()=>r(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",e.length,")"]})}function Sq({metrics:e}){return e?m.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[m.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),m.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Session ID:"}),m.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Start Time:"}),m.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Messages:"}),m.jsx("div",{children:e.totalMessages})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Participants:"}),m.jsx("div",{children:e.participantCount})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),m.jsx("div",{children:e.connectionIssues})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Duration:"}),m.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function cs(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:i,endSession:r}=Ii(),s=M.useCallback(async(a,c)=>await i(a,c),[i]),o=M.useCallback(async()=>await r(),[r]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:s,stop:o}}function JA(){const{sessionMetrics:e,currentSession:t}=Ii();return{metrics:e,sessionId:t==null?void 0:t.id,duration:e==null?void 0:e.duration,participantCount:e==null?void 0:e.participantCount,messageCount:e==null?void 0:e.messageCount,audioQuality:e==null?void 0:e.audioQuality,networkStats:e==null?void 0:e.networkStats}}function XA(){const{setMicrophoneEnabled:e,client:t}=Ii(),[n,i]=M.useState(!1),[r,s]=M.useState(!1),o=M.useCallback(async()=>{if(!r){s(!0);try{const l=!n;await e(l),i(l)}catch(l){console.error("Failed to toggle microphone:",l)}finally{s(!1)}}},[n,r,e]),a=M.useCallback(async()=>{if(!(n||r)){s(!0);try{await e(!0),i(!0)}catch(l){console.error("Failed to enable microphone:",l)}finally{s(!1)}}},[n,r,e]),c=M.useCallback(async()=>{if(!(!n||r)){s(!0);try{await e(!1),i(!1)}catch(l){console.error("Failed to disable microphone:",l)}finally{s(!1)}}},[n,r,e]);return{isEnabled:n,isLoading:r,toggle:o,enable:a,disable:c}}function ZA(){const{setCameraEnabled:e}=Ii(),[t,n]=M.useState(!1),[i,r]=M.useState(!1),s=M.useCallback(async()=>{if(!i){r(!0);try{const c=!t;await e(c),n(c)}catch(c){console.error("Failed to toggle camera:",c)}finally{r(!1)}}},[t,i,e]),o=M.useCallback(async()=>{if(!(t||i)){r(!0);try{await e(!0),n(!0)}catch(c){console.error("Failed to enable camera:",c)}finally{r(!1)}}},[t,i,e]),a=M.useCallback(async()=>{if(!(!t||i)){r(!0);try{await e(!1),n(!1)}catch(c){console.error("Failed to disable camera:",c)}finally{r(!1)}}},[t,i,e]);return{isEnabled:t,isLoading:i,toggle:s,enable:o,disable:a}}function $A(){const{startScreenShare:e,stopScreenShare:t}=Ii(),[n,i]=M.useState(!1),[r,s]=M.useState(!1),o=M.useCallback(async()=>{if(!(n||r)){s(!0);try{await e(),i(!0)}catch(l){console.error("Failed to start screen share:",l)}finally{s(!1)}}},[n,r,e]),a=M.useCallback(async()=>{if(!(!n||r)){s(!0);try{await t(),i(!1)}catch(l){console.error("Failed to stop screen share:",l)}finally{s(!1)}}},[n,r,t]),c=M.useCallback(async()=>{n?await a():await o()},[n,o,a]);return{isSharing:n,isLoading:r,start:o,stop:a,toggle:c}}function kq(){const{client:e}=Ii(),[t,n]=M.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),i=M.useMemo(()=>t.tracks.find(p=>p.isLocal),[t.tracks]),r=M.useMemo(()=>t.tracks.filter(p=>!p.isLocal),[t.tracks]),s=M.useCallback(async()=>{try{i!=null&&i.isEnabled?await(e==null?void 0:e.disableCamera()):await(e==null?void 0:e.enableCamera())}catch(p){throw console.error("Failed to toggle camera:",p),p}},[e,i]),o=M.useCallback(async()=>{try{t.tracks.find(x=>x.isScreenShare)?await(e==null?void 0:e.stopScreenShare()):await(e==null?void 0:e.startScreenShare())}catch(p){throw console.error("Failed to toggle screen share:",p),p}},[e,t.tracks]),a=M.useCallback(p=>{n(x=>({...x,layout:p}))},[]),c=M.useCallback(p=>{n(x=>({...x,pinnedTrack:p}))},[]),l=M.useCallback(()=>{n(p=>({...p,pinnedTrack:void 0}))},[]),u=M.useCallback(async()=>{try{await(e==null?void 0:e.startRecording()),n(p=>({...p,isRecording:!0}))}catch(p){throw console.error("Failed to start recording:",p),p}},[e]),d=M.useCallback(async()=>{try{await(e==null?void 0:e.stopRecording()),n(p=>({...p,isRecording:!1}))}catch(p){throw console.error("Failed to stop recording:",p),p}},[e]),h=M.useCallback(p=>t.tracks.find(x=>x.id===p),[t.tracks]),f=M.useCallback(p=>t.tracks.filter(x=>x.participantId===p),[t.tracks]),g=M.useCallback(p=>p.isEnabled&&t.tracks.includes(p),[t.tracks]);return M.useEffect(()=>{if(!e)return;const p=E=>{n(w=>({...w,tracks:[...w.tracks.filter(S=>S.id!==E.id),E]}))},x=E=>{n(w=>{var S;return{...w,tracks:w.tracks.filter(v=>v.id!==E),pinnedTrack:((S=w.pinnedTrack)==null?void 0:S.id)===E?void 0:w.pinnedTrack}})},y=E=>{n(w=>({...w,tracks:w.tracks.map(S=>S.id===E.id?E:S)}))};return e.on("videoTrackAdded",p),e.on("videoTrackRemoved",x),e.on("videoTrackUpdated",y),()=>{e.off("videoTrackAdded",p),e.off("videoTrackRemoved",x),e.off("videoTrackUpdated",y)}},[e]),{tracks:t.tracks,localTrack:i,remoteTraracks:r,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:s,toggleScreenShare:o,setLayout:a,pinTrack:c,unpinTrack:l,startRecording:u,stopRecording:d,getTrackById:h,getTracksByParticipant:f,isTrackActive:g}}function Tu(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=Ii(),[i,r]=M.useState(!1),s=M.useCallback(async l=>{if(!(!l.trim()||i||!n)){r(!0);try{await t(l.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{r(!1)}}},[t,i,n]),{userMessages:o,agentMessages:a,allMessages:c}=M.useMemo(()=>{const l=e.filter(d=>d.sender.type==="participant"),u=e.filter(d=>d.sender.type==="agent");return{userMessages:l,agentMessages:u,allMessages:e}},[e]);return{messages:c,userMessages:o,agentMessages:a,messageCount:c.length,isSending:i,canSend:!!n&&!i,send:s}}function Eq(){const{send:e,isSending:t,canSend:n}=Tu(),[i,r]=M.useState(""),s=M.useCallback(async()=>{if(!(!i.trim()||!n))try{await e(i),r("")}catch(a){throw a}},[i,e,n]),o=M.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),s())},[s]);return{value:i,setValue:r,send:s,handleKeyPress:o,isSending:t,canSend:n&&i.trim().length>0}}function Ym(){const{isConnected:e,isConnecting:t,connectionError:n,connect:i,disconnect:r}=Ii(),s=M.useCallback(async()=>{if(!(e||t))try{await i()}catch(a){throw console.error("Failed to connect:",a),a}},[i,e,t]),o=M.useCallback(async()=>{if(e)try{await r()}catch(a){throw console.error("Failed to disconnect:",a),a}},[r,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:s,disconnect:o}}function eR(){const{participants:e}=Ii();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const tR=M.createContext({}),Fa=()=>M.useContext(tR);function nR({children:e,...t}){return m.jsx(tR.Provider,{value:t,children:e})}function Xc({name:e,children:t,fallback:n,className:i}){return m.jsx("div",{className:`voxket-slot voxket-slot--${e} ${i||""}`,children:t||n})}function iR(e,t={}){return Object.assign(e,t)}function rR({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:i=!0,customControls:r,className:s=""}){const o=cs(),a=XA(),c=ZA(),l=$A(),u=Fa(),d=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,o.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",s].filter(Boolean).join(" ");return!o.isActive&&!i?m.jsx("div",{className:d,children:m.jsx("div",{className:"voxket-controls-inactive",children:m.jsx("p",{children:"Controls available during active session"})})}):m.jsxs("div",{className:d,children:[i&&m.jsx("div",{className:"voxket-session-actions",children:o.isActive?m.jsx("button",{onClick:o.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):m.jsx(wq,{})}),o.isActive&&m.jsxs("div",{className:"voxket-media-controls",children:[e&&m.jsxs("button",{onClick:a.toggle,disabled:a.isLoading,className:`voxket-button voxket-button--media ${a.isEnabled?"voxket-button--active":""}`,title:a.isEnabled?"Mute microphone":"Unmute microphone",children:[m.jsx("span",{className:"voxket-icon",children:"🎤"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&m.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isEnabled?"voxket-button--active":""}`,title:c.isEnabled?"Stop camera":"Start camera",children:[m.jsx("span",{className:"voxket-icon",children:"📹"}),c.isLoading?"Loading...":c.isEnabled?"Stop Video":"Start Video"]}),n&&m.jsxs("button",{onClick:l.toggle,disabled:l.isLoading,className:`voxket-button voxket-button--media ${l.isSharing?"voxket-button--active":""}`,title:l.isSharing?"Stop screen share":"Start screen share",children:[m.jsx("span",{className:"voxket-icon",children:"🖥️"}),l.isLoading?"Loading...":l.isSharing?"Stop Share":"Share Screen"]})]}),r&&m.jsx("div",{className:"voxket-custom-controls",children:r})]})}function wq(){cs();const[e,t]=M.useState(!1),n=async()=>{t(!0);try{console.log("Start session - agentId needed")}catch(i){console.error("Failed to start session:",i)}finally{t(!1)}};return m.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function Jm({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:i=""}){const r=cs(),s=Ym(),o=Fa(),a=["voxket-session-header",`voxket-session-header--${o.variant||"default"}`,`voxket-session-header--${o.size||"md"}`,i].filter(Boolean).join(" ");return m.jsxs("div",{className:a,children:[e&&m.jsxs("div",{className:"voxket-connection-status",children:[m.jsx("div",{className:`voxket-status-indicator ${s.isConnected?"connected":"disconnected"}`}),m.jsx("span",{className:"voxket-status-text",children:s.isConnecting?"Connecting...":s.isConnected?"Connected":"Disconnected"})]}),t&&r.session&&m.jsxs("div",{className:"voxket-session-info",children:[m.jsxs("div",{className:"voxket-session-id",children:["Session: ",r.session.id.slice(-8)]}),m.jsxs("div",{className:"voxket-session-state",children:["State: ",r.state]})]}),n&&r.session&&m.jsxs("div",{className:"voxket-agent-info",children:[m.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",r.session.agentId]}),m.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",r.session.activeModalities.join(", ")]})]}),s.error&&m.jsxs("div",{className:"voxket-error-message",children:["Error: ",s.error.message]})]})}function Xm({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:i=""}){const r=cs(),s=Tu(),o=Fa(),a=["voxket-session-content",`voxket-session-content--${o.variant||"default"}`,`voxket-session-content--${o.size||"md"}`,i].filter(Boolean).join(" ");return r.isActive?m.jsx("div",{className:a,children:n||m.jsxs(m.Fragment,{children:[e&&m.jsxs("div",{className:"voxket-chat-container",children:[m.jsxs("div",{className:"voxket-chat-messages",children:[s.messages.map(c=>m.jsxs("div",{className:`voxket-message voxket-message--${c.sender.type}`,children:[m.jsxs("div",{className:"voxket-message-header",children:[m.jsx("span",{className:"voxket-message-sender",children:c.sender.name}),m.jsx("span",{className:"voxket-message-time",children:c.timestamp.toLocaleTimeString()})]}),m.jsx("div",{className:"voxket-message-content",children:c.content})]},c.id)),s.messages.length===0&&m.jsx("div",{className:"voxket-empty-messages",children:m.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),m.jsx(Cq,{})]}),t&&m.jsx("div",{className:"voxket-transcriptions",children:m.jsx("div",{className:"voxket-transcription-placeholder",children:m.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):m.jsx("div",{className:a,children:m.jsx("div",{className:"voxket-inactive-state",children:m.jsxs("div",{className:"voxket-inactive-message",children:[m.jsx("h3",{children:"Start a conversation"}),m.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function Cq(){const e=Tu(),[t,n]=M.useState(""),i=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(s){console.error("Failed to send message:",s)}},r=s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),i())};return m.jsxs("div",{className:"voxket-chat-input",children:[m.jsx("input",{type:"text",value:t,onChange:s=>n(s.target.value),onKeyPress:r,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),m.jsx("button",{onClick:i,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function Zm({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:i,className:r=""}){const s=cs(),o=JA(),a=eR(),c=Fa(),l=["voxket-session-footer",`voxket-session-footer--${c.variant||"default"}`,`voxket-session-footer--${c.size||"md"}`,r].filter(Boolean).join(" ");return s.isActive?m.jsx("div",{className:l,children:i||m.jsxs(m.Fragment,{children:[n&&m.jsxs("div",{className:"voxket-session-status",children:[m.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),m.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&o.metrics&&m.jsxs("div",{className:"voxket-session-metrics",children:[m.jsxs("div",{className:"voxket-metric",children:[m.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),m.jsx("span",{className:"voxket-metric-value",children:Tq(o.duration||0)})]}),m.jsxs("div",{className:"voxket-metric",children:[m.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),m.jsx("span",{className:"voxket-metric-value",children:o.metrics.messageCount})]})]}),t&&m.jsxs("div",{className:"voxket-participants-info",children:[m.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&m.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>m.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):m.jsx("div",{className:l,children:m.jsx("div",{className:"voxket-footer-inactive",children:m.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function Tq(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),i=Math.floor(n/60);return i>0?`${i}:${(n%60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}`:`${n}:${(t%60).toString().padStart(2,"0")}`}function Aq({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:i,onSessionEnd:r,variant:s="default",size:o="md",theme:a,className:c="",children:l}){var f;const u=cs(),d=Ym();M.useEffect(()=>{n&&e&&d.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,d.isConnected,u.isActive]),M.useEffect(()=>{var g;(g=u.session)!=null&&g.id&&i&&i(u.session.id)},[(f=u.session)==null?void 0:f.id,i]),M.useEffect(()=>()=>{u.isActive&&r&&u.stop().then(r).catch(console.error)},[]);const h=["voxket-session",`voxket-session--${s}`,`voxket-session--${o}`,u.isActive?"voxket-session--active":"voxket-session--inactive",c].filter(Boolean).join(" ");return m.jsx(nR,{variant:s,size:o,theme:a,className:c,children:m.jsx("div",{className:h,children:l||m.jsxs(m.Fragment,{children:[m.jsx(Xc,{name:"header",fallback:m.jsx(Jm,{})}),m.jsx(Xc,{name:"content",fallback:m.jsx(Xm,{})}),m.jsx(Xc,{name:"footer",fallback:m.jsx(Zm,{})})]})})})}const sR=iR(Aq,{Header:Jm,Content:Xm,Footer:Zm,Controls:rR}),Qr={name:"default",colors:{primary:"#3B82F6",secondary:"#6B7280",accent:"#8B5CF6",background:"#FFFFFF",surface:"#F9FAFB",text:{primary:"#111827",secondary:"#6B7280",muted:"#9CA3AF",inverse:"#FFFFFF"},status:{success:"#10B981",warning:"#F59E0B",error:"#EF4444",info:"#3B82F6"},border:"#E5E7EB",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},typography:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:{xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700},lineHeight:{tight:1.25,normal:1.5,relaxed:1.75}},spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{none:"0",sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},shadows:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",md:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1)"}},Ff={...Qr,name:"dark",colors:{primary:"#60A5FA",secondary:"#9CA3AF",accent:"#A78BFA",background:"#111827",surface:"#1F2937",text:{primary:"#F9FAFB",secondary:"#D1D5DB",muted:"#9CA3AF",inverse:"#111827"},status:{success:"#34D399",warning:"#FBBF24",error:"#F87171",info:"#60A5FA"},border:"#374151",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.3)"}},Uf={...Qr,name:"enterprise",colors:{primary:"#1E40AF",secondary:"#64748B",accent:"#7C3AED",background:"#FFFFFF",surface:"#F8FAFC",text:{primary:"#0F172A",secondary:"#475569",muted:"#94A3B8",inverse:"#FFFFFF"},status:{success:"#059669",warning:"#D97706",error:"#DC2626",info:"#1E40AF"},border:"#CBD5E1",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},borderRadius:{none:"0",sm:"0.125rem",md:"0.25rem",lg:"0.375rem",full:"9999px"}},oR=M.createContext(null),aR=()=>{const e=M.useContext(oR);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function Rq({theme:e="default",themes:t={},children:n,cssVariables:i=!0,className:r=""}){const[s,o]=M.useState(()=>{const h={default:Qr,dark:Ff,enterprise:Uf,...t};return typeof e=="string"?h[e]||Qr:e}),[a,c]=M.useState(()=>({default:Qr,dark:Ff,enterprise:Uf,...t})),l=h=>{if(typeof h=="string"){const f=a[h];f&&o(f)}else o(h)},u=h=>{c(f=>({...f,[h.name]:h}))};M.useEffect(()=>{if(i&&typeof document<"u"){const h=document.documentElement;Object.entries(cR(s)).forEach(([f,g])=>{h.style.setProperty(`--voxket-${f}`,g)})}},[s,i]);const d={theme:s,setTheme:l,themes:a,registerTheme:u};return m.jsx(oR.Provider,{value:d,children:m.jsx("div",{className:`voxket-theme voxket-theme--${s.name} ${r}`,children:n})})}function cR(e){const t={},n=(i,r="")=>{for(const[s,o]of Object.entries(i)){const a=r?`${r}-${s}`:s;typeof o=="object"&&o!==null&&!Array.isArray(o)?n(o,a):t[a]=String(o)}};return n(e),t}function _q(e=Qr,t){return{...e,...t,colors:{...e.colors,...t.colors},typography:{...e.typography,...t.typography},spacing:{...e.spacing,...t.spacing},borderRadius:{...e.borderRadius,...t.borderRadius},shadows:{...e.shadows,...t.shadows}}}function Iq(e){var n;const{theme:t}=aR();return((n=t.components)==null?void 0:n[e])||{}}const Nq=Qm("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&Mq(e),t.enableVoiceActivation&&Pq(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&Oq(e,t)}});function Mq(e,t){e.on("participant.speaking.started",n=>{console.log("Transcription: Started for",n.name)}),e.on("participant.speaking.stopped",n=>{console.log("Transcription: Stopped for",n.name)})}function Pq(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function Oq(e,t){console.log("Playing audio response:",t.content)}const Dq=Qm("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&Lq(),t.enableFileUpload&&Bq(e),t.enableCustomComponents&&Fq(),console.log("Chat modality activated",t)},onDeactivate:async e=>{console.log("Chat modality deactivated")},onMessage:async(e,t)=>{const n=e.config;t.type==="ui_component"?Uq(e,t):t.type==="text"&&n.enableRichText&&jq(e,t)}});function Lq(e){console.log("Rich text support enabled")}function Bq(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function Fq(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",Vq),t.set("form",zq),t.set("card",Gq),t.set("chart",Hq)}function Uq(e,t){const{componentType:n,props:i}=t.metadata;console.log("Rendering custom component:",n,i),e.emit("chat.component.render",{type:n,props:i,timestamp:new Date})}function jq(e,t){console.log("Processing rich text message:",t.content)}function Vq(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function zq(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function Gq(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function Hq(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function Zc({track:e,participantName:t,showControls:n=!0,showName:i=!0,showMuteIndicator:r=!0,isPinned:s=!1,className:o="",onClick:a,onPin:c,onUnpin:l}){const u=M.useRef(null),[d,h]=M.useState(!1);M.useEffect(()=>{if(!u.current||!e.isEnabled)return;const x=u.current;return x.srcObject=null,()=>{x.srcObject&&(x.srcObject=null)}},[e]);const f=()=>{a==null||a(e)},g=x=>{x.stopPropagation(),s?l==null||l(e):c==null||c(e)},p=["voxket-video-tile",e.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",e.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",s?"voxket-video-tile--pinned":"",e.isEnabled?"":"voxket-video-tile--disabled",d?"voxket-video-tile--hovered":"",o].filter(Boolean).join(" ");return m.jsxs("div",{className:p,onClick:f,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[m.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&m.jsxs("div",{className:"voxket-video-placeholder",children:[m.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"🖥️":"📹"}),m.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),m.jsxs("div",{className:"voxket-video-overlay",children:[i&&t&&m.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),r&&!e.isEnabled&&m.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),n&&(d||s)&&m.jsxs("div",{className:"voxket-video-controls",children:[m.jsx("button",{className:`voxket-video-control-btn ${s?"voxket-video-control-btn--active":""}`,onClick:g,title:s?"Unpin video":"Pin video",children:"📌"}),e.isScreenShare&&m.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),e.source&&m.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&m.jsx("div",{className:"voxket-video-loading",children:m.jsx("div",{className:"voxket-spinner"})})]})}function Kq({tracks:e,layout:t,className:n="",onLayoutChange:i,onTrackClick:r,maxVisibleTracks:s=9,showPagination:o=!0}){const[a,c]=M.useState(0),[l,u]=M.useState(null),d=M.useMemo(()=>{let E=[...e];t.type==="speaker"&&l&&(E=[l,...e.filter(v=>v.id!==l.id)]);const w=a*s,S=w+s;return E.slice(w,S)},[e,t,l,a,s]),h=Math.ceil(e.length/s),f=M.useMemo(()=>{const E=d.length;switch(t.type){case"grid":const w=Math.ceil(Math.sqrt(E)),S=Math.ceil(E/w);return{display:"grid",gridTemplateColumns:`repeat(${w}, 1fr)`,gridTemplateRows:`repeat(${S}, 1fr)`,gap:"8px"};case"speaker":return{display:"flex",flexDirection:"column",gap:"8px"};case"sidebar":return{display:"flex",gap:"8px"};case"gallery":return{display:"flex",flexWrap:"wrap",gap:"8px",justifyContent:"center"};default:return{}}},[t.type,d.length]),g=E=>{u(E)},p=()=>{u(null)},x=E=>{i==null||i({...t,type:E})},y=["voxket-video-grid",`voxket-video-grid--${t.type}`,`voxket-video-grid--${d.length}-tracks`,n].filter(Boolean).join(" ");return e.length===0?m.jsx("div",{className:"voxket-video-grid-empty",children:m.jsxs("div",{className:"voxket-video-grid-empty-content",children:[m.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),m.jsx("p",{children:"No video tracks available"})]})}):m.jsxs("div",{className:y,children:[m.jsxs("div",{className:"voxket-video-grid-controls",children:[m.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(E=>m.jsx("button",{className:`voxket-layout-btn ${t.type===E?"voxket-layout-btn--active":""}`,onClick:()=>x(E),title:`Switch to ${E} layout`,children:Wq(E)},E))}),m.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),m.jsx("div",{className:"voxket-video-grid-content",style:f,children:t.type==="speaker"&&l?m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"voxket-video-speaker-main",children:m.jsx(Zc,{track:l,participantName:`Participant ${l.participantId}`,isPinned:!0,onClick:r,onUnpin:p})}),m.jsx("div",{className:"voxket-video-speaker-sidebar",children:d.filter(E=>E.id!==l.id).map(E=>m.jsx(Zc,{track:E,participantName:`Participant ${E.participantId}`,showControls:!1,onClick:r,onPin:g},E.id))})]}):d.map(E=>m.jsx(Zc,{track:E,participantName:`Participant ${E.participantId}`,isPinned:(l==null?void 0:l.id)===E.id,onClick:r,onPin:g,onUnpin:p},E.id))}),o&&h>1&&m.jsxs("div",{className:"voxket-video-pagination",children:[m.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.max(0,a-1)),disabled:a===0,children:"←"}),m.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",h]}),m.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.min(h-1,a+1)),disabled:a===h-1,children:"→"})]})]})}function Wq(e){switch(e){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function qq({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:i,showLayoutControls:r=!0,showCameraControls:s=!0,showScreenShareControls:o=!0,className:a=""}){const c=["voxket-video-controls",a].filter(Boolean).join(" "),l=u=>{i==null||i({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return m.jsxs("div",{className:c,children:[s&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),m.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isEnabled?"voxket-control-btn--active":""}`,onClick:t,title:e!=null&&e.isEnabled?"Turn off camera":"Turn on camera",children:[m.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"📹":"📷"}),m.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&m.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," × ",e.dimensions.height]})]}),o&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),m.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isScreenShare?"voxket-control-btn--active":""}`,onClick:n,title:e!=null&&e.isScreenShare?"Stop screen sharing":"Start screen sharing",children:[m.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"🛑":"🖥️"}),m.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),r&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),m.jsx("div",{className:"voxket-layout-buttons",children:[{type:"grid",icon:"⊞",label:"Grid"},{type:"speaker",icon:"🎤",label:"Speaker"},{type:"sidebar",icon:"⫸",label:"Sidebar"},{type:"gallery",icon:"⊡",label:"Gallery"}].map(({type:u,icon:d,label:h})=>m.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>l(u),title:`Switch to ${h} layout`,children:[m.jsx("span",{className:"voxket-control-icon",children:d}),m.jsx("span",{className:"voxket-control-label",children:h})]},u))})]}),m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),m.jsxs("div",{className:"voxket-video-settings",children:[m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Quality"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"high",children:"High (720p)"}),m.jsx("option",{value:"medium",children:"Medium (480p)"}),m.jsx("option",{value:"low",children:"Low (240p)"})]})]}),m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"30",children:"30 fps"}),m.jsx("option",{value:"15",children:"15 fps"}),m.jsx("option",{value:"10",children:"10 fps"})]})]}),m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"unlimited",children:"Unlimited"}),m.jsx("option",{value:"1000",children:"1 Mbps"}),m.jsx("option",{value:"500",children:"500 Kbps"}),m.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),m.jsxs("div",{className:"voxket-video-stats",children:[m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),m.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}×${e.dimensions.height}`:"N/A"})]}),m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Source:"}),m.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Status:"}),m.jsx("span",{className:`voxket-stat-value ${e!=null&&e.isEnabled?"voxket-stat-value--active":"voxket-stat-value--inactive"}`,children:e!=null&&e.isEnabled?"Active":"Inactive"})]})]})]})]})}const lR=({handler:e,loadData:t,data:n,client:i,addLocalMessage:r})=>{const[s,o]=D.useState(null),[a,c]=D.useState(!0),[l,u]=D.useState(!1),[d]=D.useState(Date.now()),[h,f]=D.useState("pending");D.useEffect(()=>{(async()=>{try{if(c(!0),n&&typeof n=="object"){const E={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};o(E),console.log("📋 AssignmentView: Assignment loaded from RPC data:",E)}}catch(E){console.error("📋 AssignmentView: Error loading assignment:",E),o({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{c(!1)}})()},[n,t]);const g=({message:y,assignment:E})=>{const w=y.toLowerCase().includes("declined"),S=w?"bg-red-50 border-red-200":"bg-green-50 border-green-200",v=w?"text-red-700":"text-green-700",k=w?"❌":"🎉";return m.jsxs("div",{className:`max-w-sm mx-auto ${S} border rounded-lg shadow p-3 flex flex-col items-center`,children:[m.jsx("div",{className:"text-2xl mb-2",children:k}),m.jsx("div",{className:`${v} font-semibold text-sm mb-1`,children:y}),m.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:E.title}),m.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},p=async()=>{if(!(!s||!e)){u(!0);try{const y={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",y),e.didSuccess(y),f("accepted")}catch(y){console.error("📋 AssignmentView: Error accepting assignment:",y),e.didFail({error:"Failed to accept assignment"}),f("error")}finally{u(!1)}}},x=async()=>{if(!(!s||!e)){u(!0);try{const y={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",y),e.didSuccess(y),f("declined")}catch(y){console.error("📋 AssignmentView: Error declining assignment:",y),e.didFail({error:"Failed to decline assignment"}),f("error")}finally{u(!1)}}};return a?m.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:m.jsxs("div",{className:"flex items-center justify-center py-4",children:[m.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),m.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):s?h==="accepted"||h==="declined"||h==="error"?m.jsx(g,{message:h==="accepted"?"Assignment accepted!":h==="declined"?"Assignment declined":"Assignment error occurred",assignment:s}):m.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[m.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:m.jsx("div",{className:"flex items-center justify-between",children:m.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:s.title})})}),m.jsxs("div",{className:"p-3 text-black",children:[m.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:m.jsx("p",{className:"text-xs text-black leading-snug",children:s.description})}),m.jsx("div",{className:"mb-3 text-black",children:m.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[m.jsx("span",{className:"text-xs mr-1",children:"📅"}),m.jsxs("span",{children:["Est: ",s.estimated_time_of_completion]})]})}),m.jsxs("div",{className:"flex gap-2",children:[m.jsx("button",{onClick:p,disabled:l,className:"flex-1 bg-green-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:l?m.jsxs("span",{className:"flex items-center justify-center",children:[m.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),m.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),m.jsx("button",{onClick:x,disabled:l,className:"flex-1 bg-red-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Decline"})]})]})]}):m.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:m.jsxs("div",{className:"text-center py-4",children:[m.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),m.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function Qq(){const[e,t]=D.useState(null),[n,i]=D.useState([]);D.useEffect(()=>{const a=new Ba({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return t(a),a.on("rpc.method.called",c=>{console.log("RPC Method Called:",c)}),a.on("rpc.interaction.completed",c=>{console.log("RPC Interaction Completed:",c)}),()=>{a.disconnect()}},[]);const r=async()=>{if(e)try{await e.registerFrontendRPC("give_assignment",lR,"embedded");const a=e.getRegisteredRpcMethods();i(a),console.log("✅ Assignment RPC registered successfully")}catch(a){console.error("❌ Failed to register assignment RPC:",a)}},s=async()=>{if(!e)return;const a=({handler:c,timeout:l})=>{const[u,d]=D.useState(""),h=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],f=p=>{d(p)},g=()=>{const p=h.find(x=>x.id===u);c==null||c.didSuccess({selectedProduct:u,productName:p==null?void 0:p.name,price:p==null?void 0:p.price,timestamp:new Date().toISOString()})};return m.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[m.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),m.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),m.jsx("div",{className:"space-y-3 mb-6",children:h.map(p=>m.jsx("div",{onClick:()=>f(p.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${u===p.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:m.jsxs("div",{className:"flex justify-between items-center",children:[m.jsxs("div",{children:[m.jsx("h4",{className:"font-medium",children:p.name}),m.jsx("p",{className:"text-gray-600 text-sm",children:p.price})]}),m.jsx("div",{className:`w-4 h-4 rounded-full ${u===p.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},p.id))}),m.jsxs("div",{className:"flex justify-end space-x-3",children:[m.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),m.jsx("button",{onClick:g,disabled:!u,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),l&&m.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",l," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const c=e.getRegisteredRpcMethods();i(c),console.log("✅ Product Recommendation RPC registered successfully")}catch(c){console.error("❌ Failed to register product recommendation RPC:",c)}},o=async()=>{if(!e)return;const a=({handler:c})=>{const[l,u]=D.useState(0),[d,h]=D.useState(""),f=()=>{c==null||c.didSuccess({rating:l,comment:d,timestamp:new Date().toISOString()})};return m.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),m.jsxs("div",{className:"mb-4",children:[m.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),m.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(g=>m.jsx("button",{onClick:()=>u(g),className:`text-2xl ${g<=l?"text-yellow-400":"text-gray-300"}`,children:"⭐"},g))})]}),m.jsxs("div",{className:"mb-4",children:[m.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),m.jsx("textarea",{value:d,onChange:g=>h(g.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),m.jsxs("div",{className:"flex justify-end space-x-2",children:[m.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),m.jsx("button",{onClick:f,disabled:l===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await e.registerFrontendRPC("collect_feedback",a,"embedded");const c=e.getRegisteredRpcMethods();i(c),console.log("✅ Feedback RPC registered successfully")}catch(c){console.error("❌ Failed to register feedback RPC:",c)}};return m.jsxs("div",{className:"p-6",children:[m.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),m.jsxs("div",{className:"space-y-4 mb-6",children:[m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),m.jsxs("div",{className:"space-x-2",children:[m.jsx("button",{onClick:r,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),m.jsx("button",{onClick:s,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),m.jsx("button",{onClick:o,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?m.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>m.jsx("li",{className:"text-gray-700",children:m.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):m.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),m.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),m.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[m.jsxs("li",{children:["Register RPC methods with React components using ",m.jsx("code",{children:"client.registerFrontendRPC()"})]}),m.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),m.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),m.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),m.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),m.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),m.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),m.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
205
197
  const response = await participant.performRpc({
206
198
  method: 'give_assignment',
207
199
  data: JSON.stringify({