@voxket-ai/voxket-live 1.1.11 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -6,7 +6,7 @@
6
6
  ${p}px !important;
7
7
  top: ${u}px !important;
8
8
  }
9
- `),()=>{m.contains(g)&&m.removeChild(g)}},[t]),h.jsx(Yy,{isPresent:t,childRef:o,sizeRef:s,children:P.cloneElement(e,{ref:o})})}const Xy=({children:e,initial:t,isPresent:n,onExitComplete:r,custom:i,presenceAffectsLayout:o,mode:s,anchorX:a,root:l})=>{const c=Wa(Qy),u=N.useId();let d=!0,f=N.useMemo(()=>(d=!1,{id:u,initial:t,isPresent:n,custom:i,onExitComplete:p=>{c.set(p,!0);for(const g of c.values())if(!g)return;r&&r()},register:p=>(c.set(p,!1),()=>c.delete(p))}),[n,c,r]);return o&&d&&(f={...f}),N.useMemo(()=>{c.forEach((p,g)=>c.set(g,!1))},[n]),P.useEffect(()=>{!n&&!c.size&&r&&r()},[n]),s==="popLayout"&&(e=h.jsx(Zy,{isPresent:n,anchorX:a,root:l,children:e})),h.jsx(No.Provider,{value:f,children:e})};function Qy(){return new Map}function dh(e=!0){const t=N.useContext(No);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:r,register:i}=t,o=N.useId();N.useEffect(()=>{if(e)return i(o)},[e]);const s=N.useCallback(()=>e&&r&&r(o),[o,r,e]);return!n&&r?[!1,s]:[!0]}const Li=e=>e.key||"";function jc(e){const t=[];return N.Children.forEach(e,n=>{N.isValidElement(n)&&t.push(n)}),t}const Tr=({children:e,custom:t,initial:n=!0,onExitComplete:r,presenceAffectsLayout:i=!0,mode:o="sync",propagate:s=!1,anchorX:a="left",root:l})=>{const[c,u]=dh(s),d=N.useMemo(()=>jc(e),[e]),f=s&&!c?[]:d.map(Li),p=N.useRef(!0),g=N.useRef(d),m=Wa(()=>new Map),[v,y]=N.useState(d),[E,w]=N.useState(d);vf(()=>{p.current=!1,g.current=d;for(let _=0;_<E.length;_++){const R=Li(E[_]);f.includes(R)?m.delete(R):m.get(R)!==!0&&m.set(R,!1)}},[E,f.length,f.join("-")]);const C=[];if(d!==v){let _=[...d];for(let R=0;R<E.length;R++){const A=E[R],O=Li(A);f.includes(O)||(_.splice(R,0,A),C.push(A))}return o==="wait"&&C.length&&(_=C),w(jc(_)),y(d),null}process.env.NODE_ENV!=="production"&&o==="wait"&&E.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:k}=N.useContext(Ha);return h.jsx(h.Fragment,{children:E.map(_=>{const R=Li(_),A=s&&!c?!1:d===E||f.includes(R),O=()=>{if(m.has(R))m.set(R,!0);else return;let b=!0;m.forEach(M=>{M||(b=!1)}),b&&(k==null||k(),w(g.current),s&&(u==null||u()),r&&r())};return h.jsx(Xy,{isPresent:A,initial:!p.current||n?void 0:!1,custom:t,presenceAffectsLayout:i,mode:o,root:l,onExitComplete:A?void 0:O,anchorX:a,children:_},R)})})},fh=N.createContext({strict:!1}),Bc={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"]},Nr={};for(const e in Bc)Nr[e]={isEnabled:t=>Bc[e].some(n=>!!t[n])};function Jy(e){for(const t in e)Nr[t]={...Nr[t],...e[t]}}const e0=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 go(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||e0.has(e)}let hh=e=>!go(e);function t0(e){typeof e=="function"&&(hh=t=>t.startsWith("on")?!go(t):e(t))}try{t0(require("@emotion/is-prop-valid").default)}catch{}function n0(e,t,n){const r={};for(const i in e)i==="values"&&typeof e.values=="object"||(hh(i)||n===!0&&go(i)||!t&&!go(i)||e.draggable&&i.startsWith("onDrag"))&&(r[i]=e[i]);return r}const Ao=N.createContext({});function Mo(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function ci(e){return typeof e=="string"||Array.isArray(e)}const ml=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],gl=["initial",...ml];function Ro(e){return Mo(e.animate)||gl.some(t=>ci(e[t]))}function ph(e){return!!(Ro(e)||e.variants)}function r0(e,t){if(Ro(e)){const{initial:n,animate:r}=e;return{initial:n===!1||ci(n)?n:void 0,animate:ci(r)?r:void 0}}return e.inherit!==!1?t:{}}function i0(e){const{initial:t,animate:n}=r0(e,N.useContext(Ao));return N.useMemo(()=>({initial:t,animate:n}),[$c(t),$c(n)])}function $c(e){return Array.isArray(e)?e.join(" "):e}const ui={};function o0(e){for(const t in e)ui[t]=e[t],el(t)&&(ui[t].isCSSVariable=!0)}function mh(e,{layout:t,layoutId:n}){return Pr.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!ui[e]||e==="opacity")}const s0={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},a0=Or.length;function l0(e,t,n){let r="",i=!0;for(let o=0;o<a0;o++){const s=Or[o],a=e[s];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(s.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const c=oh(a,dl[s]);if(!l){i=!1;const u=s0[s]||s;r+=`${u}(${c}) `}n&&(t[s]=c)}}return r=r.trim(),n?r=n(t,i?"":r):i&&(r="none"),r}function bl(e,t,n){const{style:r,vars:i,transformOrigin:o}=e;let s=!1,a=!1;for(const l in t){const c=t[l];if(Pr.has(l)){s=!0;continue}else if(el(l)){i[l]=c;continue}else{const u=oh(c,dl[l]);l.startsWith("origin")?(a=!0,o[l]=u):r[l]=u}}if(t.transform||(s||n?r.transform=l0(t,e.transform,n):r.transform&&(r.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:u=0}=o;r.transformOrigin=`${l} ${c} ${u}`}}const yl=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function gh(e,t,n){for(const r in t)!At(t[r])&&!mh(r,n)&&(e[r]=t[r])}function c0({transformTemplate:e},t){return N.useMemo(()=>{const n=yl();return bl(n,t,e),Object.assign({},n.vars,n.style)},[t])}function u0(e,t){const n=e.style||{},r={};return gh(r,n,e),Object.assign(r,c0(e,t)),r}function d0(e,t){const n={},r=u0(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.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=r,n}const f0={offset:"stroke-dashoffset",array:"stroke-dasharray"},h0={offset:"strokeDashoffset",array:"strokeDasharray"};function p0(e,t,n=1,r=0,i=!0){e.pathLength=1;const o=i?f0:h0;e[o.offset]=Se.transform(-r);const s=Se.transform(t),a=Se.transform(n);e[o.array]=`${s} ${a}`}function bh(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:o=1,pathOffset:s=0,...a},l,c,u){if(bl(e,a,c),l){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:d,style:f}=e;d.transform&&(f.transform=d.transform,delete d.transform),(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),f.transform&&(f.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox),t!==void 0&&(d.x=t),n!==void 0&&(d.y=n),r!==void 0&&(d.scale=r),i!==void 0&&p0(d,i,o,s,!1)}const yh=()=>({...yl(),attrs:{}}),xh=e=>typeof e=="string"&&e.toLowerCase()==="svg";function m0(e,t,n,r){const i=N.useMemo(()=>{const o=yh();return bh(o,t,xh(r),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};gh(o,e.style,e),i.style={...o,...i.style}}return i}const g0=["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 xl(e){return typeof e!="string"||e.includes("-")?!1:!!(g0.indexOf(e)>-1||/[A-Z]/u.test(e))}function b0(e,t,n,{latestValues:r},i,o=!1){const a=(xl(e)?m0:d0)(t,r,i,e),l=n0(t,typeof e=="string",o),c=e!==N.Fragment?{...l,...a,ref:n}:{},{children:u}=t,d=N.useMemo(()=>At(u)?u.get():u,[u]);return N.createElement(e,{...c,children:d})}function Vc(e){const t=[{},{}];return e==null||e.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function vl(e,t,n,r){if(typeof t=="function"){const[i,o]=Vc(r);t=t(n!==void 0?n:e.custom,i,o)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[i,o]=Vc(r);t=t(n!==void 0?n:e.custom,i,o)}return t}function ro(e){return At(e)?e.get():e}function y0({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:x0(n,r,i,e),renderState:t()}}function x0(e,t,n,r){const i={},o=r(e,{});for(const f in o)i[f]=ro(o[f]);let{initial:s,animate:a}=e;const l=Ro(e),c=ph(e);t&&c&&!l&&e.inherit!==!1&&(s===void 0&&(s=t.initial),a===void 0&&(a=t.animate));let u=n?n.initial===!1:!1;u=u||s===!1;const d=u?a:s;if(d&&typeof d!="boolean"&&!Mo(d)){const f=Array.isArray(d)?d:[d];for(let p=0;p<f.length;p++){const g=vl(e,f[p]);if(g){const{transitionEnd:m,transition:v,...y}=g;for(const E in y){let w=y[E];if(Array.isArray(w)){const C=u?w.length-1:0;w=w[C]}w!==null&&(i[E]=w)}for(const E in m)i[E]=m[E]}}}return i}const vh=e=>(t,n)=>{const r=N.useContext(Ao),i=N.useContext(No),o=()=>y0(e,t,r,i);return n?o():Wa(o)};function wl(e,t,n){var o;const{style:r}=e,i={};for(const s in r)(At(r[s])||t.style&&At(t.style[s])||mh(s,e)||((o=n==null?void 0:n.getValue(s))==null?void 0:o.liveStyle)!==void 0)&&(i[s]=r[s]);return i}const v0=vh({scrapeMotionValuesFromProps:wl,createRenderState:yl});function wh(e,t,n){const r=wl(e,t,n);for(const i in e)if(At(e[i])||At(t[i])){const o=Or.indexOf(i)!==-1?"attr"+i.charAt(0).toUpperCase()+i.substring(1):i;r[o]=e[i]}return r}const w0=vh({scrapeMotionValuesFromProps:wh,createRenderState:yh}),E0=Symbol.for("motionComponentSymbol");function xr(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function S0(e,t,n){return N.useCallback(r=>{r&&e.onMount&&e.onMount(r),t&&(r?t.mount(r):t.unmount()),n&&(typeof n=="function"?n(r):xr(n)&&(n.current=r))},[t])}const El=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),k0="framerAppearId",Eh="data-"+El(k0),Sh=N.createContext({});function C0(e,t,n,r,i){var m,v;const{visualElement:o}=N.useContext(Ao),s=N.useContext(fh),a=N.useContext(No),l=N.useContext(pl).reducedMotion,c=N.useRef(null);r=r||s.renderer,!c.current&&r&&(c.current=r(e,{visualState:t,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const u=c.current,d=N.useContext(Sh);u&&!u.projection&&i&&(u.type==="html"||u.type==="svg")&&_0(c.current,n,i,d);const f=N.useRef(!1);N.useInsertionEffect(()=>{u&&f.current&&u.update(n,a)});const p=n[Eh],g=N.useRef(!!p&&!((m=window.MotionHandoffIsComplete)!=null&&m.call(window,p))&&((v=window.MotionHasOptimisedAnimation)==null?void 0:v.call(window,p)));return vf(()=>{u&&(f.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),u.scheduleRenderMicrotask(),g.current&&u.animationState&&u.animationState.animateChanges())}),N.useEffect(()=>{u&&(!g.current&&u.animationState&&u.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,p)}),g.current=!1),u.enteringChildren=void 0)}),u}function _0(e,t,n,r){const{layoutId:i,layout:o,drag:s,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:u}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:kh(e.parent)),e.projection.setOptions({layoutId:i,layout:o,alwaysMeasureLayout:!!s||a&&xr(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:r,crossfade:u,layoutScroll:l,layoutRoot:c})}function kh(e){if(e)return e.options.allowProjection!==!1?e.projection:kh(e.parent)}function ds(e,{forwardMotionProps:t=!1}={},n,r){n&&Jy(n);const i=xl(e)?w0:v0;function o(a,l){let c;const u={...N.useContext(pl),...a,layoutId:T0(a)},{isStatic:d}=u,f=i0(a),p=i(a,d);if(!d&&Ga){N0(u,n);const g=A0(u);c=g.MeasureLayout,f.visualElement=C0(e,p,u,r,g.ProjectionNode)}return h.jsxs(Ao.Provider,{value:f,children:[c&&f.visualElement?h.jsx(c,{visualElement:f.visualElement,...u}):null,b0(e,a,S0(p,f.visualElement,l),p,d,t)]})}o.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const s=N.forwardRef(o);return s[E0]=e,s}function T0({layoutId:e}){const t=N.useContext(Ha).id;return t&&e!==void 0?t+"-"+e:e}function N0(e,t){const n=N.useContext(fh).strict;if(process.env.NODE_ENV!=="production"&&t&&n){const r="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?Rr(!1,r,"lazy-strict-mode"):Sn(!1,r,"lazy-strict-mode")}}function A0(e){const{drag:t,layout:n}=Nr;if(!t&&!n)return{};const r={...t,...n};return{MeasureLayout:t!=null&&t.isEnabled(e)||n!=null&&n.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function M0(e,t){if(typeof Proxy>"u")return ds;const n=new Map,r=(o,s)=>ds(o,s,e,t),i=(o,s)=>(process.env.NODE_ENV!=="production"&&Xa(!1,"motion() is deprecated. Use motion.create() instead."),r(o,s));return new Proxy(i,{get:(o,s)=>s==="create"?r:(n.has(s)||n.set(s,ds(s,void 0,e,t)),n.get(s))})}function Ch({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function R0({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function I0(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function fs(e){return e===void 0||e===1}function ma({scale:e,scaleX:t,scaleY:n}){return!fs(e)||!fs(t)||!fs(n)}function Gn(e){return ma(e)||_h(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function _h(e){return zc(e.x)||zc(e.y)}function zc(e){return e&&e!=="0%"}function bo(e,t,n){const r=e-n,i=t*r;return n+i}function Uc(e,t,n,r,i){return i!==void 0&&(e=bo(e,i,r)),bo(e,n,r)+t}function ga(e,t=0,n=1,r,i){e.min=Uc(e.min,t,n,r,i),e.max=Uc(e.max,t,n,r,i)}function Th(e,{x:t,y:n}){ga(e.x,t.translate,t.scale,t.originPoint),ga(e.y,n.translate,n.scale,n.originPoint)}const Hc=.999999999999,Wc=1.0000000000001;function O0(e,t,n,r=!1){const i=n.length;if(!i)return;t.x=t.y=1;let o,s;for(let a=0;a<i;a++){o=n[a],s=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(r&&o.options.layoutScroll&&o.scroll&&o!==o.root&&wr(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),s&&(t.x*=s.x.scale,t.y*=s.y.scale,Th(e,s)),r&&Gn(o.latestValues)&&wr(e,o.latestValues))}t.x<Wc&&t.x>Hc&&(t.x=1),t.y<Wc&&t.y>Hc&&(t.y=1)}function vr(e,t){e.min=e.min+t,e.max=e.max+t}function Gc(e,t,n,r,i=.5){const o=at(e.min,e.max,i);ga(e,t,n,o,r)}function wr(e,t){Gc(e.x,t.x,t.scaleX,t.scale,t.originX),Gc(e.y,t.y,t.scaleY,t.scale,t.originY)}function Nh(e,t){return Ch(I0(e.getBoundingClientRect(),t))}function P0(e,t,n){const r=Nh(e,n),{scroll:i}=t;return i&&(vr(r.x,i.offset.x),vr(r.y,i.offset.y)),r}const Kc=()=>({translate:0,scale:1,origin:0,originPoint:0}),Er=()=>({x:Kc(),y:Kc()}),qc=()=>({min:0,max:0}),ft=()=>({x:qc(),y:qc()}),ba={current:null},Ah={current:!1};function D0(){if(Ah.current=!0,!!Ga)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>ba.current=e.matches;e.addEventListener("change",t),t()}else ba.current=!1}const L0=new WeakMap;function F0(e,t,n){for(const r in t){const i=t[r],o=n[r];if(At(i))e.addValue(r,i);else if(At(o))e.addValue(r,_r(i,{owner:e}));else if(o!==i)if(e.hasValue(r)){const s=e.getValue(r);s.liveStyle===!0?s.jump(i):s.hasAnimated||s.set(i)}else{const s=e.getStaticValue(r);e.addValue(r,_r(s!==void 0?s:i,{owner:e}))}}for(const r in n)t[r]===void 0&&e.removeValue(r);return t}const Yc=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class j0{scrapeMotionValuesFromProps(t,n,r){return{}}constructor({parent:t,props:n,presenceContext:r,reducedMotionConfig:i,blockInitialAnimation:o,visualState:s},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=cl,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const f=Bt.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,it.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=s;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,this.parent=t,this.props=n,this.presenceContext=r,this.depth=t?t.depth+1:0,this.reducedMotionConfig=i,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=Ro(n),this.isVariantNode=ph(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in d){const p=d[f];l[f]!==void 0&&At(p)&&p.set(l[f])}}mount(t){var n;this.current=t,L0.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((r,i)=>this.bindToMotionValue(i,r)),Ah.current||D0(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ba.current,process.env.NODE_ENV!=="production"&&Xa(this.shouldReduceMotion!==!0,"You have Reduced Motion enabled on your device. Animations may not appear as expected.","reduced-motion-disabled"),(n=this.parent)==null||n.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var t;this.projection&&this.projection.unmount(),Pn(this.notifyUpdate),Pn(this.render),this.valueSubscriptions.forEach(n=>n()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(t=this.parent)==null||t.removeChild(this);for(const n in this.events)this.events[n].clear();for(const n in this.features){const r=this.features[n];r&&(r.unmount(),r.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const r=Pr.has(t);r&&this.onBindTransform&&this.onBindTransform();const i=n.on("change",s=>{this.latestValues[t]=s,this.props.onUpdate&&it.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{i(),o&&o(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in Nr){const n=Nr[t];if(!n)continue;const{isEnabled:r,Feature:i}=n;if(!this.features[t]&&i&&r(this.props)&&(this.features[t]=new i(this)),this.features[t]){const o=this.features[t];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ft()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let r=0;r<Yc.length;r++){const i=Yc[r];this.propEventSubscriptions[i]&&(this.propEventSubscriptions[i](),delete this.propEventSubscriptions[i]);const o="on"+i,s=t[o];s&&(this.propEventSubscriptions[i]=this.on(i,s))}this.prevMotionValues=F0(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const r=this.values.get(t);n!==r&&(r&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let r=this.values.get(t);return r===void 0&&n!==void 0&&(r=_r(n===null?void 0:n,{owner:this}),this.addValue(t,r)),r}readValue(t,n){let r=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return r!=null&&(typeof r=="string"&&(wf(r)||Sf(r))?r=parseFloat(r):!qy(r)&&Dn.test(n)&&(r=ih(t,n)),this.setBaseTarget(t,At(r)?r.get():r)),At(r)?r.get():r}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){var o;const{initial:n}=this.props;let r;if(typeof n=="string"||typeof n=="object"){const s=vl(this.props,n,(o=this.presenceContext)==null?void 0:o.custom);s&&(r=s[t])}if(n&&r!==void 0)return r;const i=this.getBaseTargetFromProps(this.props,t);return i!==void 0&&!At(i)?i:this.initialValues[t]!==void 0&&r===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new Za),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){fl.render(this.render)}}class Mh extends j0{constructor(){super(...arguments),this.KeyframeResolver=Ly}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:r}){delete n[t],delete r[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;At(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Rh(e,{style:t,vars:n},r,i){const o=e.style;let s;for(s in t)o[s]=t[s];i==null||i.applyProjectionStyles(o,r);for(s in n)o.setProperty(s,n[s])}function B0(e){return window.getComputedStyle(e)}class $0 extends Mh{constructor(){super(...arguments),this.type="html",this.renderInstance=Rh}readValueFromInstance(t,n){var r;if(Pr.has(n))return(r=this.projection)!=null&&r.isProjecting?la(n):ey(t,n);{const i=B0(t),o=(el(n)?i.getPropertyValue(n):i[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Nh(t,n)}build(t,n,r){bl(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return wl(t,n,r)}}const Ih=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function V0(e,t,n,r){Rh(e,t,void 0,r);for(const i in t.attrs)e.setAttribute(Ih.has(i)?i:El(i),t.attrs[i])}class z0 extends Mh{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ft}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(Pr.has(n)){const r=rh(n);return r&&r.default||0}return n=Ih.has(n)?n:El(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return wh(t,n,r)}build(t,n,r){bh(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,i){V0(t,n,r,i)}mount(t){this.isSVGTag=xh(t.tagName),super.mount(t)}}const U0=(e,t)=>xl(e)?new z0(t):new $0(t,{allowProjection:e!==N.Fragment});function Sr(e,t,n){const r=e.getProps();return vl(r,t,n!==void 0?n:r.custom,e)}const ya=e=>Array.isArray(e);function H0(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,_r(n))}function W0(e){return ya(e)?e[e.length-1]||0:e}function G0(e,t){const n=Sr(e,t);let{transitionEnd:r={},transition:i={},...o}=n||{};o={...o,...r};for(const s in o){const a=W0(o[s]);H0(e,s,a)}}function K0(e){return!!(At(e)&&e.add)}function xa(e,t){const n=e.getValue("willChange");if(K0(n))return n.add(t);if(!n&&kn.WillChange){const r=new kn.WillChange("auto");e.addValue("willChange",r),r.add(t)}}function Oh(e){return e.props[Eh]}const q0=e=>e!==null;function Y0(e,{repeat:t,repeatType:n="loop"},r){const i=e.filter(q0),o=t&&n!=="loop"&&t%2===1?0:i.length-1;return i[o]}const Z0={type:"spring",stiffness:500,damping:25,restSpeed:10},X0=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),Q0={type:"keyframes",duration:.8},J0={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},ex=(e,{keyframes:t})=>t.length>2?Q0:Pr.has(e)?e.startsWith("scale")?X0(t[1]):Z0:J0;function tx({when:e,delay:t,delayChildren:n,staggerChildren:r,staggerDirection:i,repeat:o,repeatType:s,repeatDelay:a,from:l,elapsed:c,...u}){return!!Object.keys(u).length}const Sl=(e,t,n,r={},i,o)=>s=>{const a=ul(r,e)||{},l=a.delay||r.delay||0;let{elapsed:c=0}=r;c=c-on(l);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-c,onUpdate:f=>{t.set(f),a.onUpdate&&a.onUpdate(f)},onComplete:()=>{s(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:o?void 0:i};tx(a)||Object.assign(u,ex(e,u)),u.duration&&(u.duration=on(u.duration)),u.repeatDelay&&(u.repeatDelay=on(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(ha(u),u.delay===0&&(d=!0)),(kn.instantAnimations||kn.skipAnimations)&&(d=!0,ha(u),u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&t.get()!==void 0){const f=Y0(u.keyframes,a);if(f!==void 0){it.update(()=>{u.onUpdate(f),u.onComplete()});return}}return a.isSync?new ll(u):new Sy(u)};function nx({protectedKeys:e,needsAnimating:t},n){const r=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function Ph(e,t,{delay:n=0,transitionOverride:r,type:i}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:s,...a}=t;r&&(o=r);const l=[],c=i&&e.animationState&&e.animationState.getState()[i];for(const u in a){const d=e.getValue(u,e.latestValues[u]??null),f=a[u];if(f===void 0||c&&nx(c,u))continue;const p={delay:n,...ul(o||{},u)},g=d.get();if(g!==void 0&&!d.isAnimating&&!Array.isArray(f)&&f===g&&!p.velocity)continue;let m=!1;if(window.MotionHandoffAnimation){const y=Oh(e);if(y){const E=window.MotionHandoffAnimation(y,u,it);E!==null&&(p.startTime=E,m=!0)}}xa(e,u),d.start(Sl(u,d,f,e.shouldReduceMotion&&eh.has(u)?{type:!1}:p,e,m));const v=d.animation;v&&l.push(v)}return s&&Promise.all(l).then(()=>{it.update(()=>{s&&G0(e,s)})}),l}function Dh(e,t,n,r=0,i=1){const o=Array.from(e).sort((c,u)=>c.sortNodePosition(u)).indexOf(t),s=e.size,a=(s-1)*r;return typeof n=="function"?n(o,s):i===1?o*r:a-o*r}function va(e,t,n={}){var l;const r=Sr(e,t,n.type==="exit"?(l=e.presenceContext)==null?void 0:l.custom:void 0);let{transition:i=e.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(i=n.transitionOverride);const o=r?()=>Promise.all(Ph(e,r,n)):()=>Promise.resolve(),s=e.variantChildren&&e.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:f}=i;return rx(e,t,c,u,d,f,n)}:()=>Promise.resolve(),{when:a}=i;if(a){const[c,u]=a==="beforeChildren"?[o,s]:[s,o];return c().then(()=>u())}else return Promise.all([o(),s(n.delay)])}function rx(e,t,n=0,r=0,i=0,o=1,s){const a=[];for(const l of e.variantChildren)l.notify("AnimationStart",t),a.push(va(l,t,{...s,delay:n+(typeof r=="function"?0:r)+Dh(e.variantChildren,l,r,i,o)}).then(()=>l.notify("AnimationComplete",t)));return Promise.all(a)}function ix(e,t,n={}){e.notify("AnimationStart",t);let r;if(Array.isArray(t)){const i=t.map(o=>va(e,o,n));r=Promise.all(i)}else if(typeof t=="string")r=va(e,t,n);else{const i=typeof t=="function"?Sr(e,t,n.custom):t;r=Promise.all(Ph(e,i,n))}return r.then(()=>{e.notify("AnimationComplete",t)})}function Lh(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let r=0;r<n;r++)if(t[r]!==e[r])return!1;return!0}const ox=gl.length;function Fh(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?Fh(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<ox;n++){const r=gl[n],i=e.props[r];(ci(i)||i===!1)&&(t[r]=i)}return t}const sx=[...ml].reverse(),ax=ml.length;function lx(e){return t=>Promise.all(t.map(({animation:n,options:r})=>ix(e,n,r)))}function cx(e){let t=lx(e),n=Zc(),r=!0;const i=l=>(c,u)=>{var f;const d=Sr(e,u,l==="exit"?(f=e.presenceContext)==null?void 0:f.custom:void 0);if(d){const{transition:p,transitionEnd:g,...m}=d;c={...c,...m,...g}}return c};function o(l){t=l(e)}function s(l){const{props:c}=e,u=Fh(e.parent)||{},d=[],f=new Set;let p={},g=1/0;for(let v=0;v<ax;v++){const y=sx[v],E=n[y],w=c[y]!==void 0?c[y]:u[y],C=ci(w),k=y===l?E.isActive:null;k===!1&&(g=v);let _=w===u[y]&&w!==c[y]&&C;if(_&&r&&e.manuallyAnimateOnMount&&(_=!1),E.protectedKeys={...p},!E.isActive&&k===null||!w&&!E.prevProp||Mo(w)||typeof w=="boolean")continue;const R=ux(E.prevProp,w);let A=R||y===l&&E.isActive&&!_&&C||v>g&&C,O=!1;const b=Array.isArray(w)?w:[w];let M=b.reduce(i(y),{});k===!1&&(M={});const{prevResolvedValues:I={}}=E,F={...I,...M},D=X=>{A=!0,f.has(X)&&(O=!0,f.delete(X)),E.needsAnimating[X]=!0;const $=e.getValue(X);$&&($.liveStyle=!1)};for(const X in F){const $=M[X],z=I[X];if(p.hasOwnProperty(X))continue;let x=!1;ya($)&&ya(z)?x=!Lh($,z):x=$!==z,x?$!=null?D(X):f.add(X):$!==void 0&&f.has(X)?D(X):E.protectedKeys[X]=!0}E.prevProp=w,E.prevResolvedValues=M,E.isActive&&(p={...p,...M}),r&&e.blockInitialAnimation&&(A=!1);const G=_&&R;A&&(!G||O)&&d.push(...b.map(X=>{const $={type:y};if(typeof X=="string"&&r&&!G&&e.manuallyAnimateOnMount&&e.parent){const{parent:z}=e,x=Sr(z,X);if(z.enteringChildren&&x){const{delayChildren:B}=x.transition||{};$.delay=Dh(z.enteringChildren,e,B)}}return{animation:X,options:$}}))}if(f.size){const v={};if(typeof c.initial!="boolean"){const y=Sr(e,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(v.transition=y.transition)}f.forEach(y=>{const E=e.getBaseTarget(y),w=e.getValue(y);w&&(w.liveStyle=!0),v[y]=E??null}),d.push({animation:v})}let m=!!d.length;return r&&(c.initial===!1||c.initial===c.animate)&&!e.manuallyAnimateOnMount&&(m=!1),r=!1,m?t(d):Promise.resolve()}function a(l,c){var d;if(n[l].isActive===c)return Promise.resolve();(d=e.variantChildren)==null||d.forEach(f=>{var p;return(p=f.animationState)==null?void 0:p.setActive(l,c)}),n[l].isActive=c;const u=s(l);for(const f in n)n[f].protectedKeys={};return u}return{animateChanges:s,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Zc(),r=!0}}}function ux(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!Lh(t,e):!1}function Un(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Zc(){return{animate:Un(!0),whileInView:Un(),whileHover:Un(),whileTap:Un(),whileDrag:Un(),whileFocus:Un(),exit:Un()}}class jn{constructor(t){this.isMounted=!1,this.node=t}update(){}}class dx extends jn{constructor(t){super(t),t.animationState||(t.animationState=cx(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Mo(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 fx=0;class hx extends jn{constructor(){super(...arguments),this.id=fx++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===r)return;const i=this.node.animationState.setActive("exit",!t);n&&!t&&i.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 px={animation:{Feature:dx},exit:{Feature:hx}};function di(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}function vi(e){return{point:{x:e.pageX,y:e.pageY}}}const mx=e=>t=>hl(t)&&e(t,vi(t));function Jr(e,t,n,r){return di(e,t,mx(n),r)}const jh=1e-4,gx=1-jh,bx=1+jh,Bh=.01,yx=0-Bh,xx=0+Bh;function Dt(e){return e.max-e.min}function vx(e,t,n){return Math.abs(e-t)<=n}function Xc(e,t,n,r=.5){e.origin=r,e.originPoint=at(t.min,t.max,e.origin),e.scale=Dt(n)/Dt(t),e.translate=at(n.min,n.max,e.origin)-e.originPoint,(e.scale>=gx&&e.scale<=bx||isNaN(e.scale))&&(e.scale=1),(e.translate>=yx&&e.translate<=xx||isNaN(e.translate))&&(e.translate=0)}function ei(e,t,n,r){Xc(e.x,t.x,n.x,r?r.originX:void 0),Xc(e.y,t.y,n.y,r?r.originY:void 0)}function Qc(e,t,n){e.min=n.min+t.min,e.max=e.min+Dt(t)}function wx(e,t,n){Qc(e.x,t.x,n.x),Qc(e.y,t.y,n.y)}function Jc(e,t,n){e.min=t.min-n.min,e.max=e.min+Dt(t)}function ti(e,t,n){Jc(e.x,t.x,n.x),Jc(e.y,t.y,n.y)}function Yt(e){return[e("x"),e("y")]}const $h=({current:e})=>e?e.ownerDocument.defaultView:null,eu=(e,t)=>Math.abs(e-t);function Ex(e,t){const n=eu(e.x,t.x),r=eu(e.y,t.y);return Math.sqrt(n**2+r**2)}class Vh{constructor(t,n,{transformPagePoint:r,contextWindow:i=window,dragSnapToOrigin:o=!1,distanceThreshold:s=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=ps(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,g=Ex(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!g)return;const{point:m}=f,{timestamp:v}=Tt;this.history.push({...m,timestamp:v});const{onStart:y,onMove:E}=this.handlers;p||(y&&y(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),E&&E(this.lastMoveEvent,f)},this.handlePointerMove=(f,p)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=hs(p,this.transformPagePoint),it.update(this.updatePoint,!0)},this.handlePointerUp=(f,p)=>{this.end();const{onEnd:g,onSessionEnd:m,resumeAnimation:v}=this.handlers;if(this.dragSnapToOrigin&&v&&v(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=ps(f.type==="pointercancel"?this.lastMoveEventInfo:hs(p,this.transformPagePoint),this.history);this.startEvent&&g&&g(f,y),m&&m(f,y)},!hl(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=s,this.contextWindow=i||window;const a=vi(t),l=hs(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Tt;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=n;d&&d(t,ps(l,this.history)),this.removeListeners=bi(Jr(this.contextWindow,"pointermove",this.handlePointerMove),Jr(this.contextWindow,"pointerup",this.handlePointerUp),Jr(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),Pn(this.updatePoint)}}function hs(e,t){return t?{point:t(e.point)}:e}function tu(e,t){return{x:e.x-t.x,y:e.y-t.y}}function ps({point:e},t){return{point:e,delta:tu(e,zh(t)),offset:tu(e,Sx(t)),velocity:kx(t,.1)}}function Sx(e){return e[0]}function zh(e){return e[e.length-1]}function kx(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null;const i=zh(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>on(t)));)n--;if(!r)return{x:0,y:0};const o=hn(i.timestamp-r.timestamp);if(o===0)return{x:0,y:0};const s={x:(i.x-r.x)/o,y:(i.y-r.y)/o};return s.x===1/0&&(s.x=0),s.y===1/0&&(s.y=0),s}function Cx(e,{min:t,max:n},r){return t!==void 0&&e<t?e=r?at(t,e,r.min):Math.max(e,t):n!==void 0&&e>n&&(e=r?at(n,e,r.max):Math.min(e,n)),e}function nu(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 _x(e,{top:t,left:n,bottom:r,right:i}){return{x:nu(e.x,n,i),y:nu(e.y,t,r)}}function ru(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,r]=[r,n]),{min:n,max:r}}function Tx(e,t){return{x:ru(e.x,t.x),y:ru(e.y,t.y)}}function Nx(e,t){let n=.5;const r=Dt(e),i=Dt(t);return i>r?n=si(t.min,t.max-r,e.min):r>i&&(n=si(e.min,e.max-i,t.min)),En(0,1,n)}function Ax(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 wa=.35;function Mx(e=wa){return e===!1?e=0:e===!0&&(e=wa),{x:iu(e,"left","right"),y:iu(e,"top","bottom")}}function iu(e,t,n){return{min:ou(e,t),max:ou(e,n)}}function ou(e,t){return typeof e=="number"?e:e[t]||0}const Rx=new WeakMap;class Ix{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=ft(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:r}={}){const{presenceContext:i}=this.visualElement;if(i&&i.isPresent===!1)return;const o=d=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(vi(d).point)},s=(d,f)=>{const{drag:p,dragPropagation:g,onDragStart:m}=this.getProps();if(p&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=$y(p),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Yt(y=>{let E=this.getAxisMotionValue(y).get()||0;if(pn.test(E)){const{projection:w}=this.visualElement;if(w&&w.layout){const C=w.layout.layoutBox[y];C&&(E=Dt(C)*(parseFloat(E)/100))}}this.originPoint[y]=E}),m&&it.postRender(()=>m(d,f)),xa(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},a=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f;const{dragPropagation:p,dragDirectionLock:g,onDirectionLock:m,onDrag:v}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:y}=f;if(g&&this.currentDirection===null){this.currentDirection=Ox(y),this.currentDirection!==null&&m&&m(this.currentDirection);return}this.updateAxis("x",f.point,y),this.updateAxis("y",f.point,y),this.visualElement.render(),v&&v(d,f)},l=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f,this.stop(d,f),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Yt(d=>{var f;return this.getAnimationState(d)==="paused"&&((f=this.getAxisMotionValue(d).animation)==null?void 0:f.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new Vh(t,{onSessionStart:o,onStart:s,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:$h(this.visualElement)})}stop(t,n){const r=t||this.latestPointerEvent,i=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!i||!r)return;const{velocity:s}=i;this.startAnimation(s);const{onDragEnd:a}=this.getProps();a&&it.postRender(()=>a(r,i))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,r){const{drag:i}=this.getProps();if(!r||!Fi(t,i,this.currentDirection))return;const o=this.getAxisMotionValue(t);let s=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(s=Cx(s,this.constraints[t],this.elastic[t])),o.set(s)}resolveConstraints(){var o;const{dragConstraints:t,dragElastic:n}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(o=this.visualElement.projection)==null?void 0:o.layout,i=this.constraints;t&&xr(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=_x(r.layoutBox,t):this.constraints=!1,this.elastic=Mx(n),i!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&Yt(s=>{this.constraints!==!1&&this.getAxisMotionValue(s)&&(this.constraints[s]=Ax(r.layoutBox[s],this.constraints[s]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!xr(t))return!1;const r=t.current;Sn(r!==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:i}=this.visualElement;if(!i||!i.layout)return!1;const o=P0(r,i.root,this.visualElement.getTransformPagePoint());let s=Tx(i.layout.layoutBox,o);if(n){const a=n(R0(s));this.hasMutatedConstraints=!!a,a&&(s=Ch(a))}return s}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:i,dragTransition:o,dragSnapToOrigin:s,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Yt(u=>{if(!Fi(u,n,this.currentDirection))return;let d=l&&l[u]||{};s&&(d={min:0,max:0});const f=i?200:1e6,p=i?40:1e7,g={type:"inertia",velocity:r?t[u]:0,bounceStiffness:f,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,g)});return Promise.all(c).then(a)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return xa(this.visualElement,t),r.start(Sl(t,r,0,n,this.visualElement,!1))}stopAnimation(){Yt(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Yt(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()}`,r=this.visualElement.getProps(),i=r[n];return i||this.visualElement.getValue(t,(r.initial?r.initial[t]:void 0)||0)}snapToCursor(t){Yt(n=>{const{drag:r}=this.getProps();if(!Fi(n,r,this.currentDirection))return;const{projection:i}=this.visualElement,o=this.getAxisMotionValue(n);if(i&&i.layout){const{min:s,max:a}=i.layout.layoutBox[n];o.set(t[n]-at(s,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!xr(n)||!r||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};Yt(s=>{const a=this.getAxisMotionValue(s);if(a&&this.constraints!==!1){const l=a.get();i[s]=Nx({min:l,max:l},this.constraints[s])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),Yt(s=>{if(!Fi(s,t,null))return;const a=this.getAxisMotionValue(s),{min:l,max:c}=this.constraints[s];a.set(at(l,c,i[s]))})}addListeners(){if(!this.visualElement.current)return;Rx.set(this.visualElement,this);const t=this.visualElement.current,n=Jr(t,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),r=()=>{const{dragConstraints:l}=this.getProps();xr(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:i}=this.visualElement,o=i.addEventListener("measure",r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),it.read(r);const s=di(window,"resize",()=>this.scalePositionWithinConstraints()),a=i.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Yt(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=l[u].translate,d.set(d.get()+l[u].translate))}),this.visualElement.render())});return()=>{s(),n(),o(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:r=!1,dragPropagation:i=!1,dragConstraints:o=!1,dragElastic:s=wa,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:i,dragConstraints:o,dragElastic:s,dragMomentum:a}}}function Fi(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Ox(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Px extends jn{constructor(t){super(t),this.removeGroupControls=Qt,this.removeListeners=Qt,this.controls=new Ix(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Qt}unmount(){this.removeGroupControls(),this.removeListeners()}}const su=e=>(t,n)=>{e&&it.postRender(()=>e(t,n))};class Dx extends jn{constructor(){super(...arguments),this.removePointerDownListener=Qt}onPointerDown(t){this.session=new Vh(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:$h(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:i}=this.node.getProps();return{onSessionStart:su(t),onStart:su(n),onMove:r,onEnd:(o,s)=>{delete this.session,i&&it.postRender(()=>i(o,s))}}}mount(){this.removePointerDownListener=Jr(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const io={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function au(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Vr={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(Se.test(e))e=parseFloat(e);else return e;const n=au(e,t.target.x),r=au(e,t.target.y);return`${n}% ${r}%`}},Lx={correct:(e,{treeScale:t,projectionDelta:n})=>{const r=e,i=Dn.parse(e);if(i.length>5)return r;const o=Dn.createTransformer(e),s=typeof i[0]!="number"?1:0,a=n.x.scale*t.x,l=n.y.scale*t.y;i[0+s]/=a,i[1+s]/=l;const c=at(a,l,.5);return typeof i[2+s]=="number"&&(i[2+s]/=c),typeof i[3+s]=="number"&&(i[3+s]/=c),o(i)}};let ms=!1;class Fx extends N.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r,layoutId:i}=this.props,{projection:o}=t;o0(jx),o&&(n.group&&n.group.add(o),r&&r.register&&i&&r.register(o),ms&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),io.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:r,drag:i,isPresent:o}=this.props,{projection:s}=r;return s&&(s.isPresent=o,ms=!0,i||t.layoutDependency!==n||n===void 0||t.isPresent!==o?s.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?s.promote():s.relegate()||it.postRender(()=>{const a=s.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),fl.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:i}=t;ms=!0,i&&(i.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(i),r&&r.deregister&&r.deregister(i))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Uh(e){const[t,n]=dh(),r=N.useContext(Ha);return h.jsx(Fx,{...e,layoutGroup:r,switchLayoutGroup:N.useContext(Sh),isPresent:t,safeToRemove:n})}const jx={borderRadius:{...Vr,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Vr,borderTopRightRadius:Vr,borderBottomLeftRadius:Vr,borderBottomRightRadius:Vr,boxShadow:Lx};function Bx(e,t,n){const r=At(e)?e:_r(e);return r.start(Sl("",r,t,n)),r.animation}const $x=(e,t)=>e.depth-t.depth;class Vx{constructor(){this.children=[],this.isDirty=!1}add(t){Ka(this.children,t),this.isDirty=!0}remove(t){qa(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort($x),this.isDirty=!1,this.children.forEach(t)}}function zx(e,t){const n=Bt.now(),r=({timestamp:i})=>{const o=i-n;o>=t&&(Pn(r),e(o-t))};return it.setup(r,!0),()=>Pn(r)}const Hh=["TopLeft","TopRight","BottomLeft","BottomRight"],Ux=Hh.length,lu=e=>typeof e=="string"?parseFloat(e):e,cu=e=>typeof e=="number"||Se.test(e);function Hx(e,t,n,r,i,o){i?(e.opacity=at(0,n.opacity??1,Wx(r)),e.opacityExit=at(t.opacity??1,0,Gx(r))):o&&(e.opacity=at(t.opacity??1,n.opacity??1,r));for(let s=0;s<Ux;s++){const a=`border${Hh[s]}Radius`;let l=uu(t,a),c=uu(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||cu(l)===cu(c)?(e[a]=Math.max(at(lu(l),lu(c),r),0),(pn.test(c)||pn.test(l))&&(e[a]+="%")):e[a]=c}(t.rotate||n.rotate)&&(e.rotate=at(t.rotate||0,n.rotate||0,r))}function uu(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Wx=Wh(0,.5,Rf),Gx=Wh(.5,.95,Qt);function Wh(e,t,n){return r=>r<e?0:r>t?1:n(si(e,t,r))}function du(e,t){e.min=t.min,e.max=t.max}function qt(e,t){du(e.x,t.x),du(e.y,t.y)}function fu(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function hu(e,t,n,r,i){return e-=t,e=bo(e,1/n,r),i!==void 0&&(e=bo(e,1/i,r)),e}function Kx(e,t=0,n=1,r=.5,i,o=e,s=e){if(pn.test(t)&&(t=parseFloat(t),t=at(s.min,s.max,t/100)-s.min),typeof t!="number")return;let a=at(o.min,o.max,r);e===o&&(a-=t),e.min=hu(e.min,t,n,a,i),e.max=hu(e.max,t,n,a,i)}function pu(e,t,[n,r,i],o,s){Kx(e,t[n],t[r],t[i],t.scale,o,s)}const qx=["x","scaleX","originX"],Yx=["y","scaleY","originY"];function mu(e,t,n,r){pu(e.x,t,qx,n?n.x:void 0,r?r.x:void 0),pu(e.y,t,Yx,n?n.y:void 0,r?r.y:void 0)}function gu(e){return e.translate===0&&e.scale===1}function Gh(e){return gu(e.x)&&gu(e.y)}function bu(e,t){return e.min===t.min&&e.max===t.max}function Zx(e,t){return bu(e.x,t.x)&&bu(e.y,t.y)}function yu(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Kh(e,t){return yu(e.x,t.x)&&yu(e.y,t.y)}function xu(e){return Dt(e.x)/Dt(e.y)}function vu(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class Xx{constructor(){this.members=[]}add(t){Ka(this.members,t),t.scheduleRender()}remove(t){if(qa(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(i=>t===i);if(n===0)return!1;let r;for(let i=n;i>=0;i--){const o=this.members[i];if(o.isPresent!==!1){r=o;break}}return r?(this.promote(r),!0):!1}promote(t,n){const r=this.lead;if(t!==r&&(this.prevLead=r,this.lead=t,t.show(),r)){r.instance&&r.scheduleRender(),t.scheduleRender(),t.resumeFrom=r,n&&(t.resumeFrom.preserveOpacity=!0),r.snapshot&&(t.snapshot=r.snapshot,t.snapshot.latestValues=r.animationValues||r.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:i}=t.options;i===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:r}=t;n.onExitComplete&&n.onExitComplete(),r&&r.options.onExitComplete&&r.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function Qx(e,t,n){let r="";const i=e.x.translate/t.x,o=e.y.translate/t.y,s=(n==null?void 0:n.z)||0;if((i||o||s)&&(r=`translate3d(${i}px, ${o}px, ${s}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:f,skewX:p,skewY:g}=n;c&&(r=`perspective(${c}px) ${r}`),u&&(r+=`rotate(${u}deg) `),d&&(r+=`rotateX(${d}deg) `),f&&(r+=`rotateY(${f}deg) `),p&&(r+=`skewX(${p}deg) `),g&&(r+=`skewY(${g}deg) `)}const a=e.x.scale*t.x,l=e.y.scale*t.y;return(a!==1||l!==1)&&(r+=`scale(${a}, ${l})`),r||"none"}const gs=["","X","Y","Z"],Jx=1e3;let ev=0;function bs(e,t,n,r){const{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),r&&(r[e]=0))}function qh(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=Oh(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:i,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",it,!(i||o))}const{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&qh(r)}function Yh({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(s={},a=t==null?void 0:t()){this.id=ev++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(rv),this.nodes.forEach(av),this.nodes.forEach(lv),this.nodes.forEach(iv)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=s,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new Vx)}addEventListener(s,a){return this.eventHandlers.has(s)||this.eventHandlers.set(s,new Za),this.eventHandlers.get(s).add(a)}notifyListeners(s,...a){const l=this.eventHandlers.get(s);l&&l.notify(...a)}hasListeners(s){return this.eventHandlers.has(s)}mount(s){if(this.instance)return;this.isSVG=uh(s)&&!Gy(s),this.instance=s;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(s),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),e){let u,d=0;const f=()=>this.root.updateBlockedByResize=!1;it.read(()=>{d=window.innerWidth}),e(s,()=>{const p=window.innerWidth;p!==d&&(d=p,this.root.updateBlockedByResize=!0,u&&u(),u=zx(f,250),io.hasAnimatedSinceResize&&(io.hasAnimatedSinceResize=!1,this.nodes.forEach(Su)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:f,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||c.getDefaultTransition()||hv,{onLayoutAnimationStart:m,onLayoutAnimationComplete:v}=c.getProps(),y=!this.targetLayout||!Kh(this.targetLayout,p),E=!d&&f;if(this.options.layoutRoot||this.resumeFrom||E||d&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...ul(g,"layout"),onPlay:m,onComplete:v};(c.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(u,E)}else d||Su(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const s=this.getStack();s&&s.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Pn(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(cv),this.animationId++)}getTransformTemplate(){const{visualElement:s}=this.options;return s&&s.getProps().transformTemplate}willUpdate(s=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&qh(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),s&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(wu);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Eu);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(sv),this.nodes.forEach(tv),this.nodes.forEach(nv)):this.nodes.forEach(Eu),this.clearAllSnapshots();const a=Bt.now();Tt.delta=En(0,1e3/60,a-Tt.timestamp),Tt.timestamp=a,Tt.isProcessing=!0,os.update.process(Tt),os.preRender.process(Tt),os.render.process(Tt),Tt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,fl.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(ov),this.sharedNodes.forEach(uv)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,it.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){it.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Dt(this.snapshot.measuredBox.x)&&!Dt(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const s=this.layout;this.layout=this.measure(!1),this.layoutCorrected=ft(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,s?s.layoutBox:void 0)}updateScroll(s="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===s&&(a=!1),a&&this.instance){const l=r(this.instance);this.scroll={animationId:this.root.animationId,phase:s,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!i)return;const s=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Gh(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;s&&this.instance&&(a||Gn(this.latestValues)||u)&&(i(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(s=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return s&&(l=this.removeTransform(l)),pv(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:s}=this.options;if(!s)return ft();const a=s.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(mv))){const{scroll:u}=this.root;u&&(vr(a.x,u.offset.x),vr(a.y,u.offset.y))}return a}removeElementScroll(s){var l;const a=ft();if(qt(a,s),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:d,options:f}=u;u!==this.root&&d&&f.layoutScroll&&(d.wasRoot&&qt(a,s),vr(a.x,d.offset.x),vr(a.y,d.offset.y))}return a}applyTransform(s,a=!1){const l=ft();qt(l,s);for(let c=0;c<this.path.length;c++){const u=this.path[c];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&wr(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Gn(u.latestValues)&&wr(l,u.latestValues)}return Gn(this.latestValues)&&wr(l,this.latestValues),l}removeTransform(s){const a=ft();qt(a,s);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Gn(c.latestValues))continue;ma(c.latestValues)&&c.updateSnapshot();const u=ft(),d=c.measurePageBox();qt(u,d),mu(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return Gn(this.latestValues)&&mu(a,this.latestValues),a}setTargetDelta(s){this.targetDelta=s,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(s){this.options={...this.options,...s,crossfade:s.crossfade!==void 0?s.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Tt.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(s=!1){var f;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(s||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(f=this.parent)!=null&&f.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=Tt.timestamp,!this.targetDelta&&!this.relativeTarget){const p=this.getClosestProjectingParent();p&&p.layout&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ft(),this.relativeTargetOrigin=ft(),ti(this.relativeTargetOrigin,this.layout.layoutBox,p.layout.layoutBox),qt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ft(),this.targetWithTransforms=ft()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),wx(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):qt(this.target,this.layout.layoutBox),Th(this.target,this.targetDelta)):qt(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const p=this.getClosestProjectingParent();p&&!!p.resumingFrom==!!this.resumingFrom&&!p.options.layoutScroll&&p.target&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ft(),this.relativeTargetOrigin=ft(),ti(this.relativeTargetOrigin,this.target,p.target),qt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||ma(this.parent.latestValues)||_h(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var g;const s=this.getLead(),a=!!this.resumingFrom||this!==s;let l=!0;if((this.isProjectionDirty||(g=this.parent)!=null&&g.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===Tt.timestamp&&(l=!1),l)return;const{layout:c,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||u))return;qt(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,f=this.treeScale.y;O0(this.layoutCorrected,this.treeScale,this.path,a),s.layout&&!s.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(s.target=s.layout.layoutBox,s.targetWithTransforms=ft());const{target:p}=s;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(fu(this.prevProjectionDelta.x,this.projectionDelta.x),fu(this.prevProjectionDelta.y,this.projectionDelta.y)),ei(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==f||!vu(this.projectionDelta.x,this.prevProjectionDelta.x)||!vu(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",p))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(s=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),s){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Er(),this.projectionDelta=Er(),this.projectionDeltaWithTransform=Er()}setAnimationOrigin(s,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=Er();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=ft(),p=l?l.source:void 0,g=this.layout?this.layout.source:void 0,m=p!==g,v=this.getStack(),y=!v||v.members.length<=1,E=!!(m&&!y&&this.options.crossfade===!0&&!this.path.some(fv));this.animationProgress=0;let w;this.mixTargetDelta=C=>{const k=C/1e3;ku(d.x,s.x,k),ku(d.y,s.y,k),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ti(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),dv(this.relativeTarget,this.relativeTargetOrigin,f,k),w&&Zx(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=ft()),qt(w,this.relativeTarget)),m&&(this.animationValues=u,Hx(u,c,this.latestValues,k,E,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=k},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(s){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(Pn(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=it.update(()=>{io.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=_r(0)),this.currentAnimation=Bx(this.motionValue,[0,1e3],{...s,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),s.onUpdate&&s.onUpdate(u)},onStop:()=>{},onComplete:()=>{s.onComplete&&s.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const s=this.getStack();s&&s.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(Jx),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const s=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:u}=s;if(!(!a||!l||!c)){if(this!==s&&this.layout&&c&&Zh(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ft();const d=Dt(this.layout.layoutBox.x);l.x.min=s.target.x.min,l.x.max=l.x.min+d;const f=Dt(this.layout.layoutBox.y);l.y.min=s.target.y.min,l.y.max=l.y.min+f}qt(a,l),wr(a,u),ei(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(s,a){this.sharedNodes.has(s)||this.sharedNodes.set(s,new Xx),this.sharedNodes.get(s).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const s=this.getStack();return s?s.lead===this:!0}getLead(){var a;const{layoutId:s}=this.options;return s?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:s}=this.options;return s?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:s}=this.options;if(s)return this.root.sharedNodes.get(s)}promote({needsReset:s,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),s&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const s=this.getStack();return s?s.relegate(this):!1}resetSkewAndRotation(){const{visualElement:s}=this.options;if(!s)return;let a=!1;const{latestValues:l}=s;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&bs("z",s,c,this.animationValues);for(let u=0;u<gs.length;u++)bs(`rotate${gs[u]}`,s,c,this.animationValues),bs(`skew${gs[u]}`,s,c,this.animationValues);s.render();for(const u in c)s.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);s.scheduleRender()}applyProjectionStyles(s,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){s.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,s.visibility="",s.opacity="",s.pointerEvents=ro(a==null?void 0:a.pointerEvents)||"",s.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(s.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,s.pointerEvents=ro(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Gn(this.latestValues)&&(s.transform=l?l({},""):"none",this.hasProjected=!1);return}s.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=Qx(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),s.transform=d;const{x:f,y:p}=this.projectionDelta;s.transformOrigin=`${f.origin*100}% ${p.origin*100}% 0`,c.animationValues?s.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:s.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const g in ui){if(u[g]===void 0)continue;const{correct:m,applyTo:v,isCSSVariable:y}=ui[g],E=d==="none"?u[g]:m(u[g],c);if(v){const w=v.length;for(let C=0;C<w;C++)s[v[C]]=E}else y?this.options.visualElement.renderState.vars[g]=E:s[g]=E}this.options.layoutId&&(s.pointerEvents=c===this?ro(a==null?void 0:a.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(s=>{var a;return(a=s.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach(wu),this.root.sharedNodes.clear()}}}function tv(e){e.updateLayout()}function nv(e){var n;const t=((n=e.resumeFrom)==null?void 0:n.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:i}=e.layout,{animationType:o}=e.options,s=t.source!==e.layout.source;o==="size"?Yt(d=>{const f=s?t.measuredBox[d]:t.layoutBox[d],p=Dt(f);f.min=r[d].min,f.max=f.min+p}):Zh(o,t.layoutBox,r)&&Yt(d=>{const f=s?t.measuredBox[d]:t.layoutBox[d],p=Dt(r[d]);f.max=f.min+p,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[d].max=e.relativeTarget[d].min+p)});const a=Er();ei(a,r,t.layoutBox);const l=Er();s?ei(l,e.applyTransform(i,!0),t.measuredBox):ei(l,r,t.layoutBox);const c=!Gh(a);let u=!1;if(!e.resumeFrom){const d=e.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:f,layout:p}=d;if(f&&p){const g=ft();ti(g,t.layoutBox,f.layoutBox);const m=ft();ti(m,r,p.layoutBox),Kh(g,m)||(u=!0),d.options.layoutRoot&&(e.relativeTarget=m,e.relativeTargetOrigin=g,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:r,snapshot:t,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:r}=e.options;r&&r()}e.options.transition=void 0}function rv(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function iv(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function ov(e){e.clearSnapshot()}function wu(e){e.clearMeasurements()}function Eu(e){e.isLayoutDirty=!1}function sv(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function Su(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function av(e){e.resolveTargetDelta()}function lv(e){e.calcProjection()}function cv(e){e.resetSkewAndRotation()}function uv(e){e.removeLeadSnapshot()}function ku(e,t,n){e.translate=at(t.translate,0,n),e.scale=at(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Cu(e,t,n,r){e.min=at(t.min,n.min,r),e.max=at(t.max,n.max,r)}function dv(e,t,n,r){Cu(e.x,t.x,n.x,r),Cu(e.y,t.y,n.y,r)}function fv(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const hv={duration:.45,ease:[.4,0,.1,1]},_u=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),Tu=_u("applewebkit/")&&!_u("chrome/")?Math.round:Qt;function Nu(e){e.min=Tu(e.min),e.max=Tu(e.max)}function pv(e){Nu(e.x),Nu(e.y)}function Zh(e,t,n){return e==="position"||e==="preserve-aspect"&&!vx(xu(t),xu(n),.2)}function mv(e){var t;return e!==e.root&&((t=e.scroll)==null?void 0:t.wasRoot)}const gv=Yh({attachResizeListener:(e,t)=>di(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),ys={current:void 0},Xh=Yh({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!ys.current){const e=new gv({});e.mount(window),e.setOptions({layoutScroll:!0}),ys.current=e}return ys.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),bv={pan:{Feature:Dx},drag:{Feature:Px,ProjectionNode:Xh,MeasureLayout:Uh}};function Au(e,t,n){const{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive("whileHover",n==="Start");const i="onHover"+n,o=r[i];o&&it.postRender(()=>o(t,vi(t)))}class yv extends jn{mount(){const{current:t}=this.node;t&&(this.unmount=Vy(t,(n,r)=>(Au(this.node,r,"Start"),i=>Au(this.node,i,"End"))))}unmount(){}}class xv extends jn{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=bi(di(this.node.current,"focus",()=>this.onFocus()),di(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Mu(e,t,n){const{props:r}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&r.whileTap&&e.animationState.setActive("whileTap",n==="Start");const i="onTap"+(n==="End"?"":n),o=r[i];o&&it.postRender(()=>o(t,vi(t)))}class vv extends jn{mount(){const{current:t}=this.node;t&&(this.unmount=Wy(t,(n,r)=>(Mu(this.node,r,"Start"),(i,{success:o})=>Mu(this.node,i,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Ea=new WeakMap,xs=new WeakMap,wv=e=>{const t=Ea.get(e.target);t&&t(e)},Ev=e=>{e.forEach(wv)};function Sv({root:e,...t}){const n=e||document;xs.has(n)||xs.set(n,{});const r=xs.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(Ev,{root:e,...t})),r[i]}function kv(e,t,n){const r=Sv(t);return Ea.set(e,n),r.observe(e),()=>{Ea.delete(e),r.unobserve(e)}}const Cv={some:0,all:1};class _v extends jn{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:r,amount:i="some",once:o}=t,s={root:n?n.current:void 0,rootMargin:r,threshold:typeof i=="number"?i:Cv[i]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),f=c?u:d;f&&f(l)};return kv(this.node.current,s,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(Tv(t,n))&&this.startObserver()}unmount(){}}function Tv({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Nv={inView:{Feature:_v},tap:{Feature:vv},focus:{Feature:xv},hover:{Feature:yv}},Av={layout:{ProjectionNode:Xh,MeasureLayout:Uh}},Mv={...px,...Nv,...bv,...Av},De=M0(Mv,U0);function Rv(e){const[t,n]=N.useState(()=>e.getLocalParticipant()),[r,i]=N.useState(()=>e.getMicrophoneTrack());return N.useEffect(()=>{const o=()=>{const a=e.getLocalParticipant(),l=e.getMicrophoneTrack();console.log("🎤 useVoxketLocalParticipant: Updating state:",{hasParticipant:!!a,hasMicTrack:!!l,isMicEnabled:e.isMicrophoneEnabled,trackPublications:a?a.trackPublications.size:0}),n(a),i(l)};o(),e.on("connection.connected",o),e.on("connection.disconnected",o),e.on("track.muted",o),e.on("track.unmuted",o);const s=e.getRoom();if(s){const a=()=>{console.log("🎤 Track published, updating participant state"),o()},l=()=>{console.log("🎤 Track unpublished, updating participant state"),o()};return s.on("localTrackPublished",a),s.on("localTrackUnpublished",l),()=>{e.off("connection.connected",o),e.off("connection.disconnected",o),e.off("track.muted",o),e.off("track.unmuted",o),s.off("localTrackPublished",a),s.off("localTrackUnpublished",l)}}else return()=>{e.off("connection.connected",o),e.off("connection.disconnected",o),e.off("track.muted",o),e.off("track.unmuted",o)}},[e]),{localParticipant:t,microphoneTrack:r}}function oo(e,t,n){const[r,i]=N.useState(!1),[o,s]=N.useState(!1);return N.useEffect(()=>{const l=()=>{let c=!1;switch(t){case"microphone":c=e.isMicrophoneEnabled;break;case"camera":c=e.isCameraEnabled;break;case"screenShare":c=e.isScreenShareEnabled;break}console.log(`🎬 useVoxketTrackToggle: ${t} enabled state updated:`,{oldEnabled:r,newEnabled:c,changed:r!==c}),i(c)};return l(),e.on("track.muted",l),e.on("track.unmuted",l),e.on("connection.connected",l),()=>{e.off("track.muted",l),e.off("track.unmuted",l),e.off("connection.connected",l)}},[e,t]),{enabled:r,pending:o,toggle:async l=>{try{s(!0);const c=l!==void 0?l:!r;switch(console.log(`🎬 useVoxketTrackToggle: ${t} toggle called`,{currentEnabled:r,targetEnabled:c,forceEnabled:l}),t){case"microphone":await e.toggleMicrophone(c);break;case"camera":await e.toggleCamera(c);break;case"screenShare":c?(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(c){console.error(`🎬 useVoxketTrackToggle: ${t} toggle failed:`,c)}finally{s(!1)}}}}function Iv(e){const[t,n]=N.useState(()=>e.getRoom()),[r,i]=N.useState(()=>e.getConnectionState());return N.useEffect(()=>{const o=()=>{n(e.getRoom()),i(e.getConnectionState())};return e.on("connection.connected",o),e.on("connection.disconnected",o),e.on("connection.connecting",o),()=>{e.off("connection.connected",o),e.off("connection.disconnected",o),e.off("connection.connecting",o)}},[e]),t}function kl(e){const[t,n]=N.useState(()=>e.getIsAgentConnected()),[r,i]=N.useState(()=>e.getCurrentSession()),[o,s]=N.useState(()=>e.getCurrentAgentInfo()),[a,l]=N.useState(()=>e.getAgentState()),[c,u]=N.useState(()=>e.getAgentAudioTrack()),[d,f]=N.useState(()=>e.getAgentVideoTrack());return N.useEffect(()=>{const p=()=>{const C=e.getIsAgentConnected(),k=e.getCurrentSession(),_=e.getCurrentAgentInfo(),R=e.getAgentState(),A=e.getAgentAudioTrack(),O=e.getAgentVideoTrack();console.log("🤖 useVoxketVoiceAssistant: Updating state:",{isAgentConnected:C,hasSession:!!k,sessionId:k==null?void 0:k.id,sessionState:k==null?void 0:k.state,hasAgentInfo:!!_,agentState:R,hasAudioTrack:!!A,hasVideoTrack:!!O}),n(C),i(k),s(_),l(R),u(A),f(O)};p();const g=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent connected event"),p()},m=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent disconnected event"),p()},v=()=>{console.log("🤖 useVoxketVoiceAssistant: Session changed event"),p()},y=()=>{console.log("🤖 useVoxketVoiceAssistant: Connection changed event"),p()},E=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent state changed event"),p()},w=()=>{console.log("🎵 useVoxketVoiceAssistant: Track subscribed event - updating audio/video tracks"),p()};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",m),e.on("session.created",v),e.on("session.ended",v),e.on("session.state.changed",v),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",m),e.off("session.created",v),e.off("session.ended",v),e.off("session.state.changed",v),e.off("connection.connected",y),e.off("media.track.subscribed",w),e.off("media.track.unsubscribed",w)}},[e]),{agent:{isActive:t,info:o},session:r,state:a,audioTrack:c,videoTrack:d}}function Ov(e){const[t,n]=N.useState(()=>e.getVideoTrackRefs()),[r,i]=N.useState(()=>e.getCameraTrackRefs()),[o,s]=N.useState(()=>e.getScreenShareTrackRefs());return N.useEffect(()=>{const a=()=>{const c=e.getVideoTrackRefs(),u=e.getCameraTrackRefs(),d=e.getScreenShareTrackRefs();console.log("📹 useVoxketVideoTracks: Updating tracks:",{videoCount:c.length,cameraCount:u.length,screenShareCount:d.length}),n(c),i(u),s(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 l=e.getRoom();if(l){const c=()=>{console.log("📹 Track event, updating video tracks"),a()};return l.on("localTrackPublished",c),l.on("localTrackUnpublished",c),l.on("trackPublished",c),l.on("trackUnpublished",c),l.on("trackSubscribed",c),l.on("trackUnsubscribed",c),()=>{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),l.off("localTrackPublished",c),l.off("localTrackUnpublished",c),l.off("trackPublished",c),l.off("trackUnpublished",c),l.off("trackSubscribed",c),l.off("trackUnsubscribed",c)}}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:r,screenShareTrackRefs:o}}const Cl="-",Pv=e=>{const t=Lv(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:s=>{const a=s.split(Cl);return a[0]===""&&a.length!==1&&a.shift(),Qh(a,t)||Dv(s)},getConflictingClassGroupIds:(s,a)=>{const l=n[s]||[];return a&&r[s]?[...l,...r[s]]:l}}},Qh=(e,t)=>{var s;if(e.length===0)return t.classGroupId;const n=e[0],r=t.nextPart.get(n),i=r?Qh(e.slice(1),r):void 0;if(i)return i;if(t.validators.length===0)return;const o=e.join(Cl);return(s=t.validators.find(({validator:a})=>a(o)))==null?void 0:s.classGroupId},Ru=/^\[(.+)\]$/,Dv=e=>{if(Ru.test(e)){const t=Ru.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},Lv=e=>{const{theme:t,classGroups:n}=e,r={nextPart:new Map,validators:[]};for(const i in n)Sa(n[i],r,i,t);return r},Sa=(e,t,n,r)=>{e.forEach(i=>{if(typeof i=="string"){const o=i===""?t:Iu(t,i);o.classGroupId=n;return}if(typeof i=="function"){if(Fv(i)){Sa(i(r),t,n,r);return}t.validators.push({validator:i,classGroupId:n});return}Object.entries(i).forEach(([o,s])=>{Sa(s,Iu(t,o),n,r)})})},Iu=(e,t)=>{let n=e;return t.split(Cl).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},Fv=e=>e.isThemeGetter,jv=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;const i=(o,s)=>{n.set(o,s),t++,t>e&&(t=0,r=n,n=new Map)};return{get(o){let s=n.get(o);if(s!==void 0)return s;if((s=r.get(o))!==void 0)return i(o,s),s},set(o,s){n.has(o)?n.set(o,s):i(o,s)}}},ka="!",Ca=":",Bv=Ca.length,$v=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const o=[];let s=0,a=0,l=0,c;for(let g=0;g<i.length;g++){let m=i[g];if(s===0&&a===0){if(m===Ca){o.push(i.slice(l,g)),l=g+Bv;continue}if(m==="/"){c=g;continue}}m==="["?s++:m==="]"?s--:m==="("?a++:m===")"&&a--}const u=o.length===0?i:i.substring(l),d=Vv(u),f=d!==u,p=c&&c>l?c-l:void 0;return{modifiers:o,hasImportantModifier:f,baseClassName:d,maybePostfixModifierPosition:p}};if(t){const i=t+Ca,o=r;r=s=>s.startsWith(i)?o(s.substring(i.length)):{isExternal:!0,modifiers:[],hasImportantModifier:!1,baseClassName:s,maybePostfixModifierPosition:void 0}}if(n){const i=r;r=o=>n({className:o,parseClassName:i})}return r},Vv=e=>e.endsWith(ka)?e.substring(0,e.length-1):e.startsWith(ka)?e.substring(1):e,zv=e=>{const t=Object.fromEntries(e.orderSensitiveModifiers.map(r=>[r,!0]));return r=>{if(r.length<=1)return r;const i=[];let o=[];return r.forEach(s=>{s[0]==="["||t[s]?(i.push(...o.sort(),s),o=[]):o.push(s)}),i.push(...o.sort()),i}},Uv=e=>({cache:jv(e.cacheSize),parseClassName:$v(e),sortModifiers:zv(e),...Pv(e)}),Hv=/\s+/,Wv=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:o}=t,s=[],a=e.trim().split(Hv);let l="";for(let c=a.length-1;c>=0;c-=1){const u=a[c],{isExternal:d,modifiers:f,hasImportantModifier:p,baseClassName:g,maybePostfixModifierPosition:m}=n(u);if(d){l=u+(l.length>0?" "+l:l);continue}let v=!!m,y=r(v?g.substring(0,m):g);if(!y){if(!v){l=u+(l.length>0?" "+l:l);continue}if(y=r(g),!y){l=u+(l.length>0?" "+l:l);continue}v=!1}const E=o(f).join(":"),w=p?E+ka:E,C=w+y;if(s.includes(C))continue;s.push(C);const k=i(y,v);for(let _=0;_<k.length;++_){const R=k[_];s.push(w+R)}l=u+(l.length>0?" "+l:l)}return l};function Gv(){let e=0,t,n,r="";for(;e<arguments.length;)(t=arguments[e++])&&(n=Jh(t))&&(r&&(r+=" "),r+=n);return r}const Jh=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Jh(e[r]))&&(n&&(n+=" "),n+=t);return n};function Kv(e,...t){let n,r,i,o=s;function s(l){const c=t.reduce((u,d)=>d(u),e());return n=Uv(c),r=n.cache.get,i=n.cache.set,o=a,a(l)}function a(l){const c=r(l);if(c)return c;const u=Wv(l,n);return i(l,u),u}return function(){return o(Gv.apply(null,arguments))}}const Et=e=>{const t=n=>n[e]||[];return t.isThemeGetter=!0,t},ep=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,tp=/^\((?:(\w[\w-]*):)?(.+)\)$/i,qv=/^\d+\/\d+$/,Yv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Zv=/\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$/,Xv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Qv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Jv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,or=e=>qv.test(e),Pe=e=>!!e&&!Number.isNaN(Number(e)),An=e=>!!e&&Number.isInteger(Number(e)),vs=e=>e.endsWith("%")&&Pe(e.slice(0,-1)),yn=e=>Yv.test(e),ew=()=>!0,tw=e=>Zv.test(e)&&!Xv.test(e),np=()=>!1,nw=e=>Qv.test(e),rw=e=>Jv.test(e),iw=e=>!fe(e)&&!he(e),ow=e=>Dr(e,op,np),fe=e=>ep.test(e),Hn=e=>Dr(e,sp,tw),ws=e=>Dr(e,uw,Pe),Ou=e=>Dr(e,rp,np),sw=e=>Dr(e,ip,rw),ji=e=>Dr(e,ap,nw),he=e=>tp.test(e),zr=e=>Lr(e,sp),aw=e=>Lr(e,dw),Pu=e=>Lr(e,rp),lw=e=>Lr(e,op),cw=e=>Lr(e,ip),Bi=e=>Lr(e,ap,!0),Dr=(e,t,n)=>{const r=ep.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Lr=(e,t,n=!1)=>{const r=tp.exec(e);return r?r[1]?t(r[1]):n:!1},rp=e=>e==="position"||e==="percentage",ip=e=>e==="image"||e==="url",op=e=>e==="length"||e==="size"||e==="bg-size",sp=e=>e==="length",uw=e=>e==="number",dw=e=>e==="family-name",ap=e=>e==="shadow",fw=()=>{const e=Et("color"),t=Et("font"),n=Et("text"),r=Et("font-weight"),i=Et("tracking"),o=Et("leading"),s=Et("breakpoint"),a=Et("container"),l=Et("spacing"),c=Et("radius"),u=Et("shadow"),d=Et("inset-shadow"),f=Et("text-shadow"),p=Et("drop-shadow"),g=Et("blur"),m=Et("perspective"),v=Et("aspect"),y=Et("ease"),E=Et("animate"),w=()=>["auto","avoid","all","avoid-page","page","left","right","column"],C=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],k=()=>[...C(),he,fe],_=()=>["auto","hidden","clip","visible","scroll"],R=()=>["auto","contain","none"],A=()=>[he,fe,l],O=()=>[or,"full","auto",...A()],b=()=>[An,"none","subgrid",he,fe],M=()=>["auto",{span:["full",An,he,fe]},An,he,fe],I=()=>[An,"auto",he,fe],F=()=>["auto","min","max","fr",he,fe],D=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],G=()=>["start","end","center","stretch","center-safe","end-safe"],re=()=>["auto",...A()],X=()=>[or,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...A()],$=()=>[e,he,fe],z=()=>[...C(),Pu,Ou,{position:[he,fe]}],x=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",lw,ow,{size:[he,fe]}],K=()=>[vs,zr,Hn],S=()=>["","none","full",c,he,fe],Y=()=>["",Pe,zr,Hn],te=()=>["solid","dashed","dotted","double"],j=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],q=()=>[Pe,vs,Pu,Ou],W=()=>["","none",g,he,fe],ue=()=>["none",Pe,he,fe],Q=()=>["none",Pe,he,fe],ve=()=>[Pe,he,fe],L=()=>[or,"full",...A()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[yn],breakpoint:[yn],color:[ew],container:[yn],"drop-shadow":[yn],ease:["in","out","in-out"],font:[iw],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[yn],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[yn],shadow:[yn],spacing:["px",Pe],text:[yn],"text-shadow":[yn],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",or,fe,he,v]}],container:["container"],columns:[{columns:[Pe,fe,he,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:k()}],overflow:[{overflow:_()}],"overflow-x":[{"overflow-x":_()}],"overflow-y":[{"overflow-y":_()}],overscroll:[{overscroll:R()}],"overscroll-x":[{"overscroll-x":R()}],"overscroll-y":[{"overscroll-y":R()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:O()}],"inset-x":[{"inset-x":O()}],"inset-y":[{"inset-y":O()}],start:[{start:O()}],end:[{end:O()}],top:[{top:O()}],right:[{right:O()}],bottom:[{bottom:O()}],left:[{left:O()}],visibility:["visible","invisible","collapse"],z:[{z:[An,"auto",he,fe]}],basis:[{basis:[or,"full","auto",a,...A()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Pe,or,"auto","initial","none",fe]}],grow:[{grow:["",Pe,he,fe]}],shrink:[{shrink:["",Pe,he,fe]}],order:[{order:[An,"first","last","none",he,fe]}],"grid-cols":[{"grid-cols":b()}],"col-start-end":[{col:M()}],"col-start":[{"col-start":I()}],"col-end":[{"col-end":I()}],"grid-rows":[{"grid-rows":b()}],"row-start-end":[{row:M()}],"row-start":[{"row-start":I()}],"row-end":[{"row-end":I()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":F()}],"auto-rows":[{"auto-rows":F()}],gap:[{gap:A()}],"gap-x":[{"gap-x":A()}],"gap-y":[{"gap-y":A()}],"justify-content":[{justify:[...D(),"normal"]}],"justify-items":[{"justify-items":[...G(),"normal"]}],"justify-self":[{"justify-self":["auto",...G()]}],"align-content":[{content:["normal",...D()]}],"align-items":[{items:[...G(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...G(),{baseline:["","last"]}]}],"place-content":[{"place-content":D()}],"place-items":[{"place-items":[...G(),"baseline"]}],"place-self":[{"place-self":["auto",...G()]}],p:[{p:A()}],px:[{px:A()}],py:[{py:A()}],ps:[{ps:A()}],pe:[{pe:A()}],pt:[{pt:A()}],pr:[{pr:A()}],pb:[{pb:A()}],pl:[{pl:A()}],m:[{m:re()}],mx:[{mx:re()}],my:[{my:re()}],ms:[{ms:re()}],me:[{me:re()}],mt:[{mt:re()}],mr:[{mr:re()}],mb:[{mb:re()}],ml:[{ml:re()}],"space-x":[{"space-x":A()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":A()}],"space-y-reverse":["space-y-reverse"],size:[{size:X()}],w:[{w:[a,"screen",...X()]}],"min-w":[{"min-w":[a,"screen","none",...X()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...X()]}],h:[{h:["screen","lh",...X()]}],"min-h":[{"min-h":["screen","lh","none",...X()]}],"max-h":[{"max-h":["screen","lh",...X()]}],"font-size":[{text:["base",n,zr,Hn]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,he,ws]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",vs,fe]}],"font-family":[{font:[aw,fe,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:[i,he,fe]}],"line-clamp":[{"line-clamp":[Pe,"none",he,ws]}],leading:[{leading:[o,...A()]}],"list-image":[{"list-image":["none",he,fe]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",he,fe]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:$()}],"text-color":[{text:$()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...te(),"wavy"]}],"text-decoration-thickness":[{decoration:[Pe,"from-font","auto",he,Hn]}],"text-decoration-color":[{decoration:$()}],"underline-offset":[{"underline-offset":[Pe,"auto",he,fe]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:A()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",he,fe]}],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",he,fe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:z()}],"bg-repeat":[{bg:x()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},An,he,fe],radial:["",he,fe],conic:[An,he,fe]},cw,sw]}],"bg-color":[{bg:$()}],"gradient-from-pos":[{from:K()}],"gradient-via-pos":[{via:K()}],"gradient-to-pos":[{to:K()}],"gradient-from":[{from:$()}],"gradient-via":[{via:$()}],"gradient-to":[{to:$()}],rounded:[{rounded:S()}],"rounded-s":[{"rounded-s":S()}],"rounded-e":[{"rounded-e":S()}],"rounded-t":[{"rounded-t":S()}],"rounded-r":[{"rounded-r":S()}],"rounded-b":[{"rounded-b":S()}],"rounded-l":[{"rounded-l":S()}],"rounded-ss":[{"rounded-ss":S()}],"rounded-se":[{"rounded-se":S()}],"rounded-ee":[{"rounded-ee":S()}],"rounded-es":[{"rounded-es":S()}],"rounded-tl":[{"rounded-tl":S()}],"rounded-tr":[{"rounded-tr":S()}],"rounded-br":[{"rounded-br":S()}],"rounded-bl":[{"rounded-bl":S()}],"border-w":[{border:Y()}],"border-w-x":[{"border-x":Y()}],"border-w-y":[{"border-y":Y()}],"border-w-s":[{"border-s":Y()}],"border-w-e":[{"border-e":Y()}],"border-w-t":[{"border-t":Y()}],"border-w-r":[{"border-r":Y()}],"border-w-b":[{"border-b":Y()}],"border-w-l":[{"border-l":Y()}],"divide-x":[{"divide-x":Y()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Y()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...te(),"hidden","none"]}],"divide-style":[{divide:[...te(),"hidden","none"]}],"border-color":[{border:$()}],"border-color-x":[{"border-x":$()}],"border-color-y":[{"border-y":$()}],"border-color-s":[{"border-s":$()}],"border-color-e":[{"border-e":$()}],"border-color-t":[{"border-t":$()}],"border-color-r":[{"border-r":$()}],"border-color-b":[{"border-b":$()}],"border-color-l":[{"border-l":$()}],"divide-color":[{divide:$()}],"outline-style":[{outline:[...te(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Pe,he,fe]}],"outline-w":[{outline:["",Pe,zr,Hn]}],"outline-color":[{outline:$()}],shadow:[{shadow:["","none",u,Bi,ji]}],"shadow-color":[{shadow:$()}],"inset-shadow":[{"inset-shadow":["none",d,Bi,ji]}],"inset-shadow-color":[{"inset-shadow":$()}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:$()}],"ring-offset-w":[{"ring-offset":[Pe,Hn]}],"ring-offset-color":[{"ring-offset":$()}],"inset-ring-w":[{"inset-ring":Y()}],"inset-ring-color":[{"inset-ring":$()}],"text-shadow":[{"text-shadow":["none",f,Bi,ji]}],"text-shadow-color":[{"text-shadow":$()}],opacity:[{opacity:[Pe,he,fe]}],"mix-blend":[{"mix-blend":[...j(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":j()}],"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":[Pe]}],"mask-image-linear-from-pos":[{"mask-linear-from":q()}],"mask-image-linear-to-pos":[{"mask-linear-to":q()}],"mask-image-linear-from-color":[{"mask-linear-from":$()}],"mask-image-linear-to-color":[{"mask-linear-to":$()}],"mask-image-t-from-pos":[{"mask-t-from":q()}],"mask-image-t-to-pos":[{"mask-t-to":q()}],"mask-image-t-from-color":[{"mask-t-from":$()}],"mask-image-t-to-color":[{"mask-t-to":$()}],"mask-image-r-from-pos":[{"mask-r-from":q()}],"mask-image-r-to-pos":[{"mask-r-to":q()}],"mask-image-r-from-color":[{"mask-r-from":$()}],"mask-image-r-to-color":[{"mask-r-to":$()}],"mask-image-b-from-pos":[{"mask-b-from":q()}],"mask-image-b-to-pos":[{"mask-b-to":q()}],"mask-image-b-from-color":[{"mask-b-from":$()}],"mask-image-b-to-color":[{"mask-b-to":$()}],"mask-image-l-from-pos":[{"mask-l-from":q()}],"mask-image-l-to-pos":[{"mask-l-to":q()}],"mask-image-l-from-color":[{"mask-l-from":$()}],"mask-image-l-to-color":[{"mask-l-to":$()}],"mask-image-x-from-pos":[{"mask-x-from":q()}],"mask-image-x-to-pos":[{"mask-x-to":q()}],"mask-image-x-from-color":[{"mask-x-from":$()}],"mask-image-x-to-color":[{"mask-x-to":$()}],"mask-image-y-from-pos":[{"mask-y-from":q()}],"mask-image-y-to-pos":[{"mask-y-to":q()}],"mask-image-y-from-color":[{"mask-y-from":$()}],"mask-image-y-to-color":[{"mask-y-to":$()}],"mask-image-radial":[{"mask-radial":[he,fe]}],"mask-image-radial-from-pos":[{"mask-radial-from":q()}],"mask-image-radial-to-pos":[{"mask-radial-to":q()}],"mask-image-radial-from-color":[{"mask-radial-from":$()}],"mask-image-radial-to-color":[{"mask-radial-to":$()}],"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":C()}],"mask-image-conic-pos":[{"mask-conic":[Pe]}],"mask-image-conic-from-pos":[{"mask-conic-from":q()}],"mask-image-conic-to-pos":[{"mask-conic-to":q()}],"mask-image-conic-from-color":[{"mask-conic-from":$()}],"mask-image-conic-to-color":[{"mask-conic-to":$()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:x()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",he,fe]}],filter:[{filter:["","none",he,fe]}],blur:[{blur:W()}],brightness:[{brightness:[Pe,he,fe]}],contrast:[{contrast:[Pe,he,fe]}],"drop-shadow":[{"drop-shadow":["","none",p,Bi,ji]}],"drop-shadow-color":[{"drop-shadow":$()}],grayscale:[{grayscale:["",Pe,he,fe]}],"hue-rotate":[{"hue-rotate":[Pe,he,fe]}],invert:[{invert:["",Pe,he,fe]}],saturate:[{saturate:[Pe,he,fe]}],sepia:[{sepia:["",Pe,he,fe]}],"backdrop-filter":[{"backdrop-filter":["","none",he,fe]}],"backdrop-blur":[{"backdrop-blur":W()}],"backdrop-brightness":[{"backdrop-brightness":[Pe,he,fe]}],"backdrop-contrast":[{"backdrop-contrast":[Pe,he,fe]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Pe,he,fe]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Pe,he,fe]}],"backdrop-invert":[{"backdrop-invert":["",Pe,he,fe]}],"backdrop-opacity":[{"backdrop-opacity":[Pe,he,fe]}],"backdrop-saturate":[{"backdrop-saturate":[Pe,he,fe]}],"backdrop-sepia":[{"backdrop-sepia":["",Pe,he,fe]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":A()}],"border-spacing-x":[{"border-spacing-x":A()}],"border-spacing-y":[{"border-spacing-y":A()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",he,fe]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Pe,"initial",he,fe]}],ease:[{ease:["linear","initial",y,he,fe]}],delay:[{delay:[Pe,he,fe]}],animate:[{animate:["none",E,he,fe]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[m,he,fe]}],"perspective-origin":[{"perspective-origin":k()}],rotate:[{rotate:ue()}],"rotate-x":[{"rotate-x":ue()}],"rotate-y":[{"rotate-y":ue()}],"rotate-z":[{"rotate-z":ue()}],scale:[{scale:Q()}],"scale-x":[{"scale-x":Q()}],"scale-y":[{"scale-y":Q()}],"scale-z":[{"scale-z":Q()}],"scale-3d":["scale-3d"],skew:[{skew:ve()}],"skew-x":[{"skew-x":ve()}],"skew-y":[{"skew-y":ve()}],transform:[{transform:[he,fe,"","none","gpu","cpu"]}],"transform-origin":[{origin:k()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:L()}],"translate-x":[{"translate-x":L()}],"translate-y":[{"translate-y":L()}],"translate-z":[{"translate-z":L()}],"translate-none":["translate-none"],accent:[{accent:$()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:$()}],"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",he,fe]}],"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":A()}],"scroll-mx":[{"scroll-mx":A()}],"scroll-my":[{"scroll-my":A()}],"scroll-ms":[{"scroll-ms":A()}],"scroll-me":[{"scroll-me":A()}],"scroll-mt":[{"scroll-mt":A()}],"scroll-mr":[{"scroll-mr":A()}],"scroll-mb":[{"scroll-mb":A()}],"scroll-ml":[{"scroll-ml":A()}],"scroll-p":[{"scroll-p":A()}],"scroll-px":[{"scroll-px":A()}],"scroll-py":[{"scroll-py":A()}],"scroll-ps":[{"scroll-ps":A()}],"scroll-pe":[{"scroll-pe":A()}],"scroll-pt":[{"scroll-pt":A()}],"scroll-pr":[{"scroll-pr":A()}],"scroll-pb":[{"scroll-pb":A()}],"scroll-pl":[{"scroll-pl":A()}],"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",he,fe]}],fill:[{fill:["none",...$()]}],"stroke-w":[{stroke:[Pe,zr,Hn,ws]}],stroke:[{stroke:["none",...$()]}],"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"]}},hw=Kv(fw);function ze(...e){return hw(Ua.clsx(e))}function Io(e){var i;if(!e)return{sessionSettings:{},capabilities:{},modality:"voice"};const t={session_timer:((i=e.session_settings)==null?void 0:i.session_timer)||null},n=e.capabilities||{},r=e.modality||"voice";return{sessionSettings:t,capabilities:n,modality:r}}function pw(e,t){return e.capabilities[t]===!0}function Oo(e){return e.sessionSettings.session_timer||null}function lp(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 cp(e){const t=e.capabilities;return{suggestedReplyEnabled:t.suggested_reply_enabled!==!1,attachmentsEnabled:t.support_in_chat_attachments!==!1}}function up(e){return{...e.capabilities}}function dp(e){const t=Math.floor(e/60),n=e%60;return`${t}:${n.toString().padStart(2,"0")}`}const fp=N.forwardRef(({state:e,audioTrack:t,className:n,theme:r="vox"},i)=>{var c,u,d,f,p;const o=N.useRef(null),[s,a]=N.useState(!1);N.useEffect(()=>{o.current&&(console.log("🔊 AgentTile: Audio element created:",{autoplay:o.current.autoplay,muted:o.current.muted,volume:o.current.volume,readyState:o.current.readyState,paused:o.current.paused}),a(!0))},[t]),N.useEffect(()=>{const g=o.current;if(!g)return;const m=()=>console.log("▶️ AgentTile: Audio started playing"),v=()=>console.log("⏸️ AgentTile: Audio paused"),y=()=>console.log("⏹️ AgentTile: Audio ended"),E=k=>console.error("❌ AgentTile: Audio error:",k),w=()=>console.log("⏳ AgentTile: Audio load started"),C=()=>console.log("✅ AgentTile: Audio can play");return g.addEventListener("play",m),g.addEventListener("pause",v),g.addEventListener("ended",y),g.addEventListener("error",E),g.addEventListener("loadstart",w),g.addEventListener("canplay",C),()=>{g.removeEventListener("play",m),g.removeEventListener("pause",v),g.removeEventListener("ended",y),g.removeEventListener("error",E),g.removeEventListener("loadstart",w),g.removeEventListener("canplay",C)}},[s]),console.log("🎤 AgentTile render:",{state:e,hasAudioTrack:!!t,trackSource:t==null?void 0:t.source,participantId:(c=t==null?void 0:t.participant)==null?void 0:c.identity,publicationMuted:(u=t==null?void 0:t.publication)==null?void 0:u.isMuted,audioElementReady:s,trackMediaStreamTrack:(p=(f=(d=t==null?void 0:t.publication)==null?void 0:d.track)==null?void 0:f.mediaStreamTrack)==null?void 0:p.readyState});const l=N.useMemo(()=>r==="light"?{base:"bg-black/90",highlighted:"bg-black",muted:"bg-black/30"}:{base:"bg-white/90",highlighted:"bg-white",muted:"bg-white/30"},[r]);return h.jsxs("div",{ref:i,className:ze("",n),children:[t&&h.jsxs(h.Fragment,{children:[h.jsx(Ot.AudioTrack,{ref:o,trackRef:t,volume:1}),h.jsx(Ot.BarVisualizer,{barCount:5,state:e,options:{minHeight:5},trackRef:t,className:ze("flex aspect-video w-40 items-center justify-center gap-1.5"),children:h.jsx("span",{className:ze([`${l.base} min-h-2 w-2 rounded-full`,"origin-center transition-colors duration-250 ease-linear",`data-[lk-highlighted=true]:${l.highlighted}`,`data-[lk-muted=true]:${l.muted}`])})})]}),!t&&h.jsx("div",{className:ze("flex aspect-video w-40 items-center justify-center"),children:h.jsx("div",{className:"flex flex-col items-center justify-center",children:h.jsx("div",{className:"flex gap-1.5",children:Array.from({length:5}).map((g,m)=>h.jsx("span",{className:ze([`${l.base} min-h-2 w-2 rounded-full`,"origin-center transition-colors duration-250 ease-linear",e==="speaking"&&`animate-pulse ${l.highlighted}`,e==="thinking"&&`animate-pulse ${l.muted}`])},m))})})})]})});fp.displayName="AgentTile";const mw=({videoTrack:e,className:t,ref:n})=>{var r,i;return!e||!e.publication||!e.participant?h.jsx("div",{ref:n,className:ze(t),children:h.jsx("div",{className:"w-full h-full bg-gray-200 rounded-md flex items-center justify-center",children:h.jsx("span",{className:"text-gray-500",children:"No video available"})})}):h.jsx("div",{ref:n,className:ze(t),children:h.jsx(Ot.VideoTrack,{trackRef:e,width:((r=e.publication.dimensions)==null?void 0:r.width)??0,height:((i=e.publication.dimensions)==null?void 0:i.height)??0,className:"rounded-md"})})},gw=P.forwardRef(function({trackRef:t,className:n,...r},i){var o,s;return h.jsx("div",{ref:i,className:ze("bg-muted overflow-hidden rounded-md",n),children:h.jsx(Ot.VideoTrack,{trackRef:t,width:((o=t==null?void 0:t.publication.dimensions)==null?void 0:o.width)??0,height:((s=t==null?void 0:t.publication.dimensions)==null?void 0:s.height)??0,className:ze("h-full w-auto"),...r})})}),Du=De.create(gw),bw=De.create(fp),yw=De.create(mw),xn={initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},exit:{opacity:0,scale:0},transition:{type:"spring",stiffness:675,damping:75,mass:1}},sr={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 xw(e,t){const{localParticipant:n}=Rv(t),r=n==null?void 0:n.getTrackPublication(e);return N.useMemo(()=>r&&n?{source:e,participant:n,publication:r}:void 0,[e,r,n])}function vw({chatOpen:e,client:t,theme:n="vox"}){const{agent:{isActive:r=!1}={},session:i,state:o="idle",audioTrack:s,videoTrack:a}=t?kl(t):{agent:{isActive:!1},session:null,state:"idle",audioTrack:null,videoTrack:null};console.log("🎨 MediaTiles render:",{chatOpen:e,isAgentActive:r,hasSession:!!i,sessionState:i==null?void 0:i.state,agentState:o,hasAudioTrack:!!s,hasVideoTrack:!!a});const[l]=Ot.useTracks([ae.Track.Source.ScreenShare]),c=xw(ae.Track.Source.Camera,t),u=c&&!c.publication.isMuted,d=l&&!l.publication.isMuted,f=u||d,p=r||i&&i.state==="active",g={...xn.transition,delay:e?0:.15},m={...xn.animate,scale:e?1:3,transition:g},v={...xn.animate,transition:g},y=g,E=g,w=a&&a.publication&&a.participant;return h.jsx("div",{className:"relative w-full h-full z-10 flex items-center justify-center",children:h.jsx("div",{className:"relative w-full h-full max-w-2xl px-4 md:px-0",children:h.jsxs("div",{className:ze(sr.grid),children:[p&&h.jsx("div",{className:ze(["grid",!e&&sr.agentChatClosed,e&&f&&sr.agentChatOpenWithSecondTile,e&&!f&&sr.agentChatOpenWithoutSecondTile]),children:h.jsxs("div",{className:"h-full flex items-center justify-center",children:[!w&&h.jsx(bw,{layoutId:"agent",...xn,animate:m,transition:y,state:o,audioTrack:s||void 0,theme:n,className:ze(e?"h-[90px]":"h-auto w-full")},"agent"),w&&a&&h.jsx(yw,{layoutId:"avatar",...xn,animate:v,transition:E,videoTrack:a,className:ze(e?"h-[90px] [&>video]:h-[90px] [&>video]:w-auto":"h-auto w-full")},"avatar")]})}),h.jsx("div",{className:ze(["grid",e&&sr.secondTileChatOpen,!e&&sr.secondTileChatClosed]),children:h.jsxs("div",{className:"w-full px-10 flex items-center shadow-2xl justify-between",children:[c&&u&&h.jsx(Du,{layout:"position",layoutId:"camera",...xn,trackRef:c,transition:{...xn.transition,delay:e?0:.15},className:"h-[60px] order-1"},"camera"),d&&h.jsx(Du,{layout:"position",layoutId:"screen",...xn,trackRef:l,transition:{...xn.transition,delay:e?0:.15},className:"h-[70px] order-2"},"screen")]})})]})})})}const ww={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-center 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"}},Ew={card:"text-gray-900 bg-gradient-to-b from-[#fafafa] via-[#ffffff] to-[#fafafa] border border-gray-200/80 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-white/90 via-white/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(59,130,246,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-blue-400/[0.12] via-purple-400/[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-pink-400/[0.08] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-b from-[#fafafa] via-[#ffffff] to-[#fafafa] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-gray-900 font-semibold",secondary:"text-gray-800",muted:"text-gray-600",accent:"text-transparent bg-clip-text bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600"},micButton:"relative w-20 h-20 bg-black/90 backdrop-blur-xl border-2 border-black/80 rounded-3xl flex items-center justify-center hover:bg-black hover:border-black hover:scale-105 hover:shadow-2xl hover:shadow-blue-500/30 transition-all duration-500 ease-out group overflow-hidden text-white",chatButton:"relative w-20 h-20 bg-black/90 backdrop-blur-xl border-2 border-black/80 rounded-3xl flex items-center justify-center hover:bg-black hover:border-black hover:scale-105 hover:shadow-2xl hover:shadow-green-500/30 transition-all duration-500 ease-out group overflow-hidden text-white",videoButton:"relative w-20 h-20 bg-black/90 backdrop-blur-xl border-2 border-black/80 rounded-3xl flex items-center justify-center hover:bg-black hover:border-black hover:scale-105 hover:shadow-2xl hover:shadow-purple-500/30 transition-all duration-500 ease-out group overflow-hidden text-white",popupTrigger:"bg-black/90 backdrop-blur-xl border-2 border-black/80 text-white font-bold hover:bg-black hover:border-black hover:scale-[1.02] hover:shadow-2xl hover:shadow-blue-500/30 focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2 focus:ring-offset-white transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-white/60 backdrop-blur-xl rounded-2xl text-center text-gray-900 text-sm font-medium transition-all duration-700 ease-in-out border border-gray-300/80 ",statusIndicator:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse shadow-lg shadow-green-500/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-gray-300/80 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-gray-300/80 shadow-xl",textarea:"bg-white/60 border border-gray-300/50 rounded-xl text-gray-900 placeholder-gray-500 font-medium px-4 py-3",sendButton:"bg-white/90 hover:bg-white border-2 border-gray-300/80 hover:border-gray-400 disabled:border-gray-200 disabled:opacity-40 text-gray-900 font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-blue-500/20",attachButton:"text-gray-600 hover:text-gray-900 hover:bg-gray-100/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-blue-50/70 text-gray-900 backdrop-blur-md shadow-lg border border-blue-200/80",other:"bg-white/60 text-gray-900 border border-gray-300/80 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-white/80 border-gray-300/80 backdrop-blur-xl shadow-xl",backButton:"text-gray-600 hover:text-gray-900 hover:bg-gray-100/50 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-blue-500 mb-2",suggestedResponse:{container:"bg-white/70 text-blue-700 border-gray-300/80 backdrop-blur-md hover:bg-white/80 hover:border-blue-300 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#fafafa] via-[#ffffff] to-[#fafafa] text-gray-900",header:"border-gray-300/80 bg-white/80 backdrop-blur-xl shadow-xl",headerButton:"bg-white/90 hover:bg-white border-2 border-gray-300/80 hover:border-gray-400 text-gray-900 hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-green-500 animate-pulse shadow-lg shadow-green-500/60",controlsBackground:"bg-gradient-to-t from-white via-white/90 to-white/60 backdrop-blur-xl border-t border-gray-300/80 shadow-2xl",controlEnabled:"bg-white/90 hover:bg-white border-2 border-gray-300/80 hover:border-gray-400 text-gray-900 hover:scale-105 hover:shadow-xl hover:shadow-blue-500/20 transition-all duration-300 font-semibold",controlDisabled:"bg-white/50 hover:bg-white/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/70 border border-gray-300/80 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-white/60 text-gray-700",avatar:"bg-gray-100/80 text-gray-700 border-2 border-gray-300/80",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"}},Sw={card:" text-white bg-black border border-white/[0.12] w-full h-full flex flex-col justify-between overflow-hidden relative shadow-[0_8px_32px_rgba(0,0,0,0.8),0_0_0_1px_rgba(255,255,255,0.06)_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-center 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"}},kw={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-center 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"}},Lu={dark:ww,light:Ew,vox:Sw,midnight:kw};function Lt(e){return Lu[e]||Lu.vox}function Fu({timeout:e}){const[t,n]=N.useState(100),r=N.useRef(null),i=N.useRef(null);return N.useEffect(()=>{if(!e||e<=0)return;n(100),i.current=Date.now();const o=()=>{if(!e||i.current===null)return;const s=Date.now()-i.current,a=Math.max(0,100-s/e*100);n(a),a>0&&(r.current=requestAnimationFrame(o))};return r.current=requestAnimationFrame(o),()=>{r.current&&cancelAnimationFrame(r.current)}},[e]),!e||e<=0?null:h.jsx("div",{className:"w-full h-1 relative top-1 rounded-t-4xl bg-gray-700 overflow-hidden",children:h.jsx(De.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 fi({interaction:e,theme:t,onDismiss:n,client:r,addLocalMessage:i}){var a;if(!e||!e.isVisible||!e.component)return null;const[o]=P.useState(()=>Date.now()),s=()=>e.component?P.createElement(e.component,{handler:e.handler||void 0,timeout:e.timeout,loadData:async c=>{console.log("InteractiveComponent: Loading data:",c)},presentationMode:e.presentationMode,data:e.data,client:r,addLocalMessage:i}):h.jsx("div",{className:"p-4 text-red-500",children:"Component not found"});switch(e.presentationMode){case"fullscreen":return h.jsx(Tr,{children:h.jsxs(De.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[9999] bg-black",children:[h.jsxs("div",{className:"flex flex-col",children:[h.jsx(Fu,{timeout:e.timeout}),h.jsxs("div",{className:"flex items-center justify-between p-4 bg-black/80 text-white border-b border-gray-700",children:[h.jsx("h3",{className:"text-lg font-semibold",children:e.methodName.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase())}),h.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:h.jsx(st.X,{className:"w-5 h-5"})})]})]}),h.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:s()})]})});case"embedded":default:return h.jsx(Tr,{children:h.jsx(De.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"w-fit rounded-lg ",children:h.jsxs("div",{children:[h.jsx(Fu,{timeout:e.timeout}),s()]})})})}}function hi({duration:e,theme:t="vox",onTimerExpired:n,className:r="",showIcon:i=!0}){const[o,s]=N.useState(e),[a,l]=N.useState(!1);N.useEffect(()=>{if(o<=0){l(!0),n==null||n();return}const u=setInterval(()=>{s(d=>{const f=d-1;return f<=0?(l(!0),n==null||n(),0):f})},1e3);return()=>clearInterval(u)},[o,n]),N.useEffect(()=>{s(e),l(!1)},[e]);const c=()=>a?"text-red-500":o<=60?"text-orange-500":o<=300?"text-yellow-500":t==="dark"?"text-gray-300":"text-gray-600";return h.jsxs("div",{className:`flex items-center gap-1 text-sm ${c()} ${r}`,children:[i&&h.jsx(st.Clock,{className:"w-4 h-4"}),h.jsx("span",{className:"font-mono",children:dp(o)}),a&&h.jsx("span",{className:"text-xs ml-1 text-red-500",children:"(Expired)"})]})}function Po({modality:e,theme:t,disabled:n=!1,showMicrophone:r=!1,microphoneEnabled:i=!0,microphoneLoading:o=!1,onToggleMicrophone:s,showCamera:a=!1,cameraEnabled:l=!0,cameraLoading:c=!1,onToggleCamera:u,showScreenShare:d=!1,screenShareEnabled:f=!1,screenShareLoading:p=!1,onToggleScreenShare:g,showChatToggle:m=!1,chatOpen:v=!1,onToggleChat:y,showTextInput:E=!1,textInputPlaceholder:w="Type a message...",onSendText:C,onSendAttachments:k,supportsAttachments:_=!1,showEndCall:R=!0,onEndCall:A}){var z;const O=Lt(t),[b,M]=N.useState(""),I=N.useRef(null),F=()=>{const x=b.trim();x&&C&&(C(x),M(""))},D=x=>{x.key==="Enter"&&!x.shiftKey&&(x.preventDefault(),F())},G=x=>{const B=Array.from(x.target.files||[]);B.length>0&&k&&k(B),I.current&&(I.current.value="")},re=ze("flex items-center gap-3 px-3 py-2 w-full backdrop-blur-xl border-t",E?"justify-between":"justify-center",t==="light"?"bg-white/95 border-gray-200":"bg-black/90 border-gray-800"),X=(x,B)=>{var K,S,Y;return B==="end-call"?ze("p-3 rounded-full transition-all duration-200",((K=O.video)==null?void 0:K.endCall)||"bg-red-500 text-white hover:bg-red-600",n?"opacity-50 cursor-not-allowed":"hover:scale-105"):ze("p-3 rounded-full transition-all duration-200",x?((S=O.video)==null?void 0:S.controlEnabled)||"bg-green-500 text-white":((Y=O.video)==null?void 0:Y.controlDisabled)||"bg-gray-500 text-white",n?"opacity-50 cursor-not-allowed":"hover:scale-105")},$=()=>h.jsx("div",{className:"w-5 h-5 animate-spin rounded-full border-2 border-current border-t-transparent"});return h.jsxs("div",{className:re,children:[E&&h.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[_&&k&&h.jsxs(h.Fragment,{children:[h.jsx("button",{onClick:()=>{var x;return(x=I.current)==null?void 0:x.click()},disabled:n,className:ze("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:h.jsx(st.Paperclip,{className:"w-5 h-5"})}),h.jsx("input",{ref:I,type:"file",multiple:!0,accept:"image/*",onChange:G,className:"hidden"})]}),h.jsx("input",{type:"text",value:b,onChange:x=>M(x.target.value),onKeyDown:D,disabled:n,placeholder:w,className:ze("flex-1 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")}),h.jsx("button",{onClick:F,disabled:n||!b.trim(),className:ze("p-2 rounded-full transition-all duration-200",b.trim()?((z=O.video)==null?void 0:z.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:h.jsx(st.SendHorizontal,{className:"w-5 h-5"})})]}),!E&&h.jsxs(h.Fragment,{children:[r&&s&&h.jsx("button",{onClick:s,disabled:n||o,className:X(i),title:i?"Mute microphone":"Unmute microphone",children:o?h.jsx($,{}):i?h.jsx(st.Mic,{className:"w-5 h-5"}):h.jsx(st.MicOff,{className:"w-5 h-5"})}),a&&u&&h.jsx("button",{onClick:u,disabled:n||c,className:X(l),title:l?"Turn off camera":"Turn on camera",children:c?h.jsx($,{}):l?h.jsx(st.Camera,{className:"w-5 h-5"}):h.jsx(st.CameraOff,{className:"w-5 h-5"})}),d&&g&&h.jsx("button",{onClick:g,disabled:n||p,className:X(f),title:f?"Stop screen share":"Share screen",children:p?h.jsx($,{}):h.jsx(st.Monitor,{className:"w-5 h-5"})}),m&&y&&h.jsx("button",{onClick:y,disabled:n,className:X(v),title:e==="voice"?v?"Hide transcription":"Show transcription":v?"Hide chat":"Show chat",children:h.jsx(st.MessageCircle,{className:"w-5 h-5"})})]}),R&&A&&h.jsx("button",{onClick:A,disabled:n,className:X(!1,"end-call"),title:"End call",children:h.jsx(st.PhoneOff,{className:"w-5 h-5"})})]})}Po.displayName="UnifiedControlBar";const Cw=({logLevel:e}={})=>{const t=Ot.useRoomContext();P.useEffect(()=>(ae.setLogLevel(e??"debug"),window.__lk_room=t,()=>{window.__lk_room=void 0}),[t,e])},hp=P.forwardRef((e,t)=>{const{alt:n,color:r="currentColor",size:i="1em",weight:o="regular",mirrored:s=!1,children:a,weights:l,...c}=e;return P.createElement("svg",{ref:t,xmlns:"http://www.w3.org/2000/svg",width:i,height:i,fill:r,viewBox:"0 0 256 256",transform:s?"scale(-1, 1)":void 0,...c},!!n&&P.createElement("title",null,n),a,l.get(o))});hp.displayName="SSRBase";const _w=new Map([["bold",P.createElement(P.Fragment,null,P.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",P.createElement(P.Fragment,null,P.createElement("path",{d:"M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z",opacity:"0.2"}),P.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",P.createElement(P.Fragment,null,P.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",P.createElement(P.Fragment,null,P.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",P.createElement(P.Fragment,null,P.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",P.createElement(P.Fragment,null,P.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"}))]]),_l=P.forwardRef((e,t)=>P.createElement(hp,{ref:t,...e,weights:_w}));_l.displayName="SpinnerIcon";function Tw({text:e,isComplete:t,isRealTimeStream:n=!1,speed:r=50}){const[i,o]=P.useState(""),[s,a]=P.useState(0);return P.useEffect(()=>{if(n){o(e);return}if(t){o(e);return}if(s<e.length){const l=setTimeout(()=>{o(e.slice(0,s+1)),a(s+1)},r);return()=>clearTimeout(l)}},[e,s,t,r,n]),P.useEffect(()=>{n||(a(0),o(""))},[e,n]),h.jsxs("span",{className:"relative",children:[h.jsx("span",{className:"inline-block",children:i}),!t&&h.jsx("span",{className:"inline-flex items-center ml-1",children:[0,1,2].map(l=>h.jsx(De.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:l*.2,ease:"easeInOut"}},l))})]})}function Nw(e,t){return e.startsWith("image/")?st.Image:e.startsWith("video/")?st.Video:e.startsWith("audio/")?st.Music:e.includes("zip")||e.includes("rar")||e.includes("archive")?st.Archive:st.FileText}function Aw(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+n[r]}function Mw({message:e,theme:t,isOwn:n}){const r=Lt(t),i=e.metadata,o=(i==null?void 0:i.fileName)||"Unknown file",s=(i==null?void 0:i.fileSize)||0,a=(i==null?void 0:i.mimeType)||"application/octet-stream",l=i==null?void 0:i.downloading,c=i==null?void 0:i.uploading,u=(i==null?void 0:i.downloadProgress)||0,d=(i==null?void 0:i.uploadProgress)||0,f=i==null?void 0:i.downloadUrl,p=i==null?void 0:i.file,g=Nw(a),m=l||c,v=l?u:d,y=l?"Downloading...":c?"Uploading...":"Complete",[E,w]=P.useState(null);P.useEffect(()=>{if(f)w(f);else if(p&&a.startsWith("image/")){const R=URL.createObjectURL(p);return w(R),()=>URL.revokeObjectURL(R)}else w(null)},[f,p,a]);const C=()=>{if(f){const R=document.createElement("a");R.href=f,R.download=o,R.click()}},_=a.startsWith("image/")&&E;return h.jsxs("div",{className:"flex flex-col gap-2 max-w-full sm:max-w-sm",children:[_&&h.jsxs("div",{className:"relative rounded-lg overflow-hidden",children:[h.jsx("img",{src:E,alt:o,className:"max-w-full h-auto max-h-48 object-cover rounded-lg cursor-pointer",onClick:C}),h.jsx("div",{className:"absolute inset-0 bg-black/0 hover:bg-black/10 transition-colors duration-200 cursor-pointer"})]}),h.jsxs("div",{className:`
9
+ `),()=>{m.contains(g)&&m.removeChild(g)}},[t]),h.jsx(Yy,{isPresent:t,childRef:o,sizeRef:s,children:P.cloneElement(e,{ref:o})})}const Xy=({children:e,initial:t,isPresent:n,onExitComplete:r,custom:i,presenceAffectsLayout:o,mode:s,anchorX:a,root:l})=>{const c=Wa(Qy),u=N.useId();let d=!0,f=N.useMemo(()=>(d=!1,{id:u,initial:t,isPresent:n,custom:i,onExitComplete:p=>{c.set(p,!0);for(const g of c.values())if(!g)return;r&&r()},register:p=>(c.set(p,!1),()=>c.delete(p))}),[n,c,r]);return o&&d&&(f={...f}),N.useMemo(()=>{c.forEach((p,g)=>c.set(g,!1))},[n]),P.useEffect(()=>{!n&&!c.size&&r&&r()},[n]),s==="popLayout"&&(e=h.jsx(Zy,{isPresent:n,anchorX:a,root:l,children:e})),h.jsx(No.Provider,{value:f,children:e})};function Qy(){return new Map}function dh(e=!0){const t=N.useContext(No);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:r,register:i}=t,o=N.useId();N.useEffect(()=>{if(e)return i(o)},[e]);const s=N.useCallback(()=>e&&r&&r(o),[o,r,e]);return!n&&r?[!1,s]:[!0]}const Li=e=>e.key||"";function jc(e){const t=[];return N.Children.forEach(e,n=>{N.isValidElement(n)&&t.push(n)}),t}const Tr=({children:e,custom:t,initial:n=!0,onExitComplete:r,presenceAffectsLayout:i=!0,mode:o="sync",propagate:s=!1,anchorX:a="left",root:l})=>{const[c,u]=dh(s),d=N.useMemo(()=>jc(e),[e]),f=s&&!c?[]:d.map(Li),p=N.useRef(!0),g=N.useRef(d),m=Wa(()=>new Map),[v,y]=N.useState(d),[E,w]=N.useState(d);vf(()=>{p.current=!1,g.current=d;for(let _=0;_<E.length;_++){const R=Li(E[_]);f.includes(R)?m.delete(R):m.get(R)!==!0&&m.set(R,!1)}},[E,f.length,f.join("-")]);const C=[];if(d!==v){let _=[...d];for(let R=0;R<E.length;R++){const A=E[R],O=Li(A);f.includes(O)||(_.splice(R,0,A),C.push(A))}return o==="wait"&&C.length&&(_=C),w(jc(_)),y(d),null}process.env.NODE_ENV!=="production"&&o==="wait"&&E.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:k}=N.useContext(Ha);return h.jsx(h.Fragment,{children:E.map(_=>{const R=Li(_),A=s&&!c?!1:d===E||f.includes(R),O=()=>{if(m.has(R))m.set(R,!0);else return;let b=!0;m.forEach(M=>{M||(b=!1)}),b&&(k==null||k(),w(g.current),s&&(u==null||u()),r&&r())};return h.jsx(Xy,{isPresent:A,initial:!p.current||n?void 0:!1,custom:t,presenceAffectsLayout:i,mode:o,root:l,onExitComplete:A?void 0:O,anchorX:a,children:_},R)})})},fh=N.createContext({strict:!1}),Bc={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"]},Nr={};for(const e in Bc)Nr[e]={isEnabled:t=>Bc[e].some(n=>!!t[n])};function Jy(e){for(const t in e)Nr[t]={...Nr[t],...e[t]}}const e0=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 go(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||e0.has(e)}let hh=e=>!go(e);function t0(e){typeof e=="function"&&(hh=t=>t.startsWith("on")?!go(t):e(t))}try{t0(require("@emotion/is-prop-valid").default)}catch{}function n0(e,t,n){const r={};for(const i in e)i==="values"&&typeof e.values=="object"||(hh(i)||n===!0&&go(i)||!t&&!go(i)||e.draggable&&i.startsWith("onDrag"))&&(r[i]=e[i]);return r}const Ao=N.createContext({});function Mo(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function ci(e){return typeof e=="string"||Array.isArray(e)}const ml=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],gl=["initial",...ml];function Ro(e){return Mo(e.animate)||gl.some(t=>ci(e[t]))}function ph(e){return!!(Ro(e)||e.variants)}function r0(e,t){if(Ro(e)){const{initial:n,animate:r}=e;return{initial:n===!1||ci(n)?n:void 0,animate:ci(r)?r:void 0}}return e.inherit!==!1?t:{}}function i0(e){const{initial:t,animate:n}=r0(e,N.useContext(Ao));return N.useMemo(()=>({initial:t,animate:n}),[$c(t),$c(n)])}function $c(e){return Array.isArray(e)?e.join(" "):e}const ui={};function o0(e){for(const t in e)ui[t]=e[t],el(t)&&(ui[t].isCSSVariable=!0)}function mh(e,{layout:t,layoutId:n}){return Pr.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!ui[e]||e==="opacity")}const s0={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},a0=Or.length;function l0(e,t,n){let r="",i=!0;for(let o=0;o<a0;o++){const s=Or[o],a=e[s];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(s.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const c=oh(a,dl[s]);if(!l){i=!1;const u=s0[s]||s;r+=`${u}(${c}) `}n&&(t[s]=c)}}return r=r.trim(),n?r=n(t,i?"":r):i&&(r="none"),r}function bl(e,t,n){const{style:r,vars:i,transformOrigin:o}=e;let s=!1,a=!1;for(const l in t){const c=t[l];if(Pr.has(l)){s=!0;continue}else if(el(l)){i[l]=c;continue}else{const u=oh(c,dl[l]);l.startsWith("origin")?(a=!0,o[l]=u):r[l]=u}}if(t.transform||(s||n?r.transform=l0(t,e.transform,n):r.transform&&(r.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:u=0}=o;r.transformOrigin=`${l} ${c} ${u}`}}const yl=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function gh(e,t,n){for(const r in t)!At(t[r])&&!mh(r,n)&&(e[r]=t[r])}function c0({transformTemplate:e},t){return N.useMemo(()=>{const n=yl();return bl(n,t,e),Object.assign({},n.vars,n.style)},[t])}function u0(e,t){const n=e.style||{},r={};return gh(r,n,e),Object.assign(r,c0(e,t)),r}function d0(e,t){const n={},r=u0(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.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=r,n}const f0={offset:"stroke-dashoffset",array:"stroke-dasharray"},h0={offset:"strokeDashoffset",array:"strokeDasharray"};function p0(e,t,n=1,r=0,i=!0){e.pathLength=1;const o=i?f0:h0;e[o.offset]=Se.transform(-r);const s=Se.transform(t),a=Se.transform(n);e[o.array]=`${s} ${a}`}function bh(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:o=1,pathOffset:s=0,...a},l,c,u){if(bl(e,a,c),l){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:d,style:f}=e;d.transform&&(f.transform=d.transform,delete d.transform),(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),f.transform&&(f.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox),t!==void 0&&(d.x=t),n!==void 0&&(d.y=n),r!==void 0&&(d.scale=r),i!==void 0&&p0(d,i,o,s,!1)}const yh=()=>({...yl(),attrs:{}}),xh=e=>typeof e=="string"&&e.toLowerCase()==="svg";function m0(e,t,n,r){const i=N.useMemo(()=>{const o=yh();return bh(o,t,xh(r),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};gh(o,e.style,e),i.style={...o,...i.style}}return i}const g0=["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 xl(e){return typeof e!="string"||e.includes("-")?!1:!!(g0.indexOf(e)>-1||/[A-Z]/u.test(e))}function b0(e,t,n,{latestValues:r},i,o=!1){const a=(xl(e)?m0:d0)(t,r,i,e),l=n0(t,typeof e=="string",o),c=e!==N.Fragment?{...l,...a,ref:n}:{},{children:u}=t,d=N.useMemo(()=>At(u)?u.get():u,[u]);return N.createElement(e,{...c,children:d})}function Vc(e){const t=[{},{}];return e==null||e.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function vl(e,t,n,r){if(typeof t=="function"){const[i,o]=Vc(r);t=t(n!==void 0?n:e.custom,i,o)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[i,o]=Vc(r);t=t(n!==void 0?n:e.custom,i,o)}return t}function ro(e){return At(e)?e.get():e}function y0({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:x0(n,r,i,e),renderState:t()}}function x0(e,t,n,r){const i={},o=r(e,{});for(const f in o)i[f]=ro(o[f]);let{initial:s,animate:a}=e;const l=Ro(e),c=ph(e);t&&c&&!l&&e.inherit!==!1&&(s===void 0&&(s=t.initial),a===void 0&&(a=t.animate));let u=n?n.initial===!1:!1;u=u||s===!1;const d=u?a:s;if(d&&typeof d!="boolean"&&!Mo(d)){const f=Array.isArray(d)?d:[d];for(let p=0;p<f.length;p++){const g=vl(e,f[p]);if(g){const{transitionEnd:m,transition:v,...y}=g;for(const E in y){let w=y[E];if(Array.isArray(w)){const C=u?w.length-1:0;w=w[C]}w!==null&&(i[E]=w)}for(const E in m)i[E]=m[E]}}}return i}const vh=e=>(t,n)=>{const r=N.useContext(Ao),i=N.useContext(No),o=()=>y0(e,t,r,i);return n?o():Wa(o)};function wl(e,t,n){var o;const{style:r}=e,i={};for(const s in r)(At(r[s])||t.style&&At(t.style[s])||mh(s,e)||((o=n==null?void 0:n.getValue(s))==null?void 0:o.liveStyle)!==void 0)&&(i[s]=r[s]);return i}const v0=vh({scrapeMotionValuesFromProps:wl,createRenderState:yl});function wh(e,t,n){const r=wl(e,t,n);for(const i in e)if(At(e[i])||At(t[i])){const o=Or.indexOf(i)!==-1?"attr"+i.charAt(0).toUpperCase()+i.substring(1):i;r[o]=e[i]}return r}const w0=vh({scrapeMotionValuesFromProps:wh,createRenderState:yh}),E0=Symbol.for("motionComponentSymbol");function xr(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function S0(e,t,n){return N.useCallback(r=>{r&&e.onMount&&e.onMount(r),t&&(r?t.mount(r):t.unmount()),n&&(typeof n=="function"?n(r):xr(n)&&(n.current=r))},[t])}const El=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),k0="framerAppearId",Eh="data-"+El(k0),Sh=N.createContext({});function C0(e,t,n,r,i){var m,v;const{visualElement:o}=N.useContext(Ao),s=N.useContext(fh),a=N.useContext(No),l=N.useContext(pl).reducedMotion,c=N.useRef(null);r=r||s.renderer,!c.current&&r&&(c.current=r(e,{visualState:t,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const u=c.current,d=N.useContext(Sh);u&&!u.projection&&i&&(u.type==="html"||u.type==="svg")&&_0(c.current,n,i,d);const f=N.useRef(!1);N.useInsertionEffect(()=>{u&&f.current&&u.update(n,a)});const p=n[Eh],g=N.useRef(!!p&&!((m=window.MotionHandoffIsComplete)!=null&&m.call(window,p))&&((v=window.MotionHasOptimisedAnimation)==null?void 0:v.call(window,p)));return vf(()=>{u&&(f.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),u.scheduleRenderMicrotask(),g.current&&u.animationState&&u.animationState.animateChanges())}),N.useEffect(()=>{u&&(!g.current&&u.animationState&&u.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,p)}),g.current=!1),u.enteringChildren=void 0)}),u}function _0(e,t,n,r){const{layoutId:i,layout:o,drag:s,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:u}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:kh(e.parent)),e.projection.setOptions({layoutId:i,layout:o,alwaysMeasureLayout:!!s||a&&xr(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:r,crossfade:u,layoutScroll:l,layoutRoot:c})}function kh(e){if(e)return e.options.allowProjection!==!1?e.projection:kh(e.parent)}function ds(e,{forwardMotionProps:t=!1}={},n,r){n&&Jy(n);const i=xl(e)?w0:v0;function o(a,l){let c;const u={...N.useContext(pl),...a,layoutId:T0(a)},{isStatic:d}=u,f=i0(a),p=i(a,d);if(!d&&Ga){N0(u,n);const g=A0(u);c=g.MeasureLayout,f.visualElement=C0(e,p,u,r,g.ProjectionNode)}return h.jsxs(Ao.Provider,{value:f,children:[c&&f.visualElement?h.jsx(c,{visualElement:f.visualElement,...u}):null,b0(e,a,S0(p,f.visualElement,l),p,d,t)]})}o.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const s=N.forwardRef(o);return s[E0]=e,s}function T0({layoutId:e}){const t=N.useContext(Ha).id;return t&&e!==void 0?t+"-"+e:e}function N0(e,t){const n=N.useContext(fh).strict;if(process.env.NODE_ENV!=="production"&&t&&n){const r="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?Rr(!1,r,"lazy-strict-mode"):Sn(!1,r,"lazy-strict-mode")}}function A0(e){const{drag:t,layout:n}=Nr;if(!t&&!n)return{};const r={...t,...n};return{MeasureLayout:t!=null&&t.isEnabled(e)||n!=null&&n.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function M0(e,t){if(typeof Proxy>"u")return ds;const n=new Map,r=(o,s)=>ds(o,s,e,t),i=(o,s)=>(process.env.NODE_ENV!=="production"&&Xa(!1,"motion() is deprecated. Use motion.create() instead."),r(o,s));return new Proxy(i,{get:(o,s)=>s==="create"?r:(n.has(s)||n.set(s,ds(s,void 0,e,t)),n.get(s))})}function Ch({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function R0({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function I0(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function fs(e){return e===void 0||e===1}function ma({scale:e,scaleX:t,scaleY:n}){return!fs(e)||!fs(t)||!fs(n)}function Gn(e){return ma(e)||_h(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function _h(e){return zc(e.x)||zc(e.y)}function zc(e){return e&&e!=="0%"}function bo(e,t,n){const r=e-n,i=t*r;return n+i}function Uc(e,t,n,r,i){return i!==void 0&&(e=bo(e,i,r)),bo(e,n,r)+t}function ga(e,t=0,n=1,r,i){e.min=Uc(e.min,t,n,r,i),e.max=Uc(e.max,t,n,r,i)}function Th(e,{x:t,y:n}){ga(e.x,t.translate,t.scale,t.originPoint),ga(e.y,n.translate,n.scale,n.originPoint)}const Hc=.999999999999,Wc=1.0000000000001;function O0(e,t,n,r=!1){const i=n.length;if(!i)return;t.x=t.y=1;let o,s;for(let a=0;a<i;a++){o=n[a],s=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(r&&o.options.layoutScroll&&o.scroll&&o!==o.root&&wr(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),s&&(t.x*=s.x.scale,t.y*=s.y.scale,Th(e,s)),r&&Gn(o.latestValues)&&wr(e,o.latestValues))}t.x<Wc&&t.x>Hc&&(t.x=1),t.y<Wc&&t.y>Hc&&(t.y=1)}function vr(e,t){e.min=e.min+t,e.max=e.max+t}function Gc(e,t,n,r,i=.5){const o=at(e.min,e.max,i);ga(e,t,n,o,r)}function wr(e,t){Gc(e.x,t.x,t.scaleX,t.scale,t.originX),Gc(e.y,t.y,t.scaleY,t.scale,t.originY)}function Nh(e,t){return Ch(I0(e.getBoundingClientRect(),t))}function P0(e,t,n){const r=Nh(e,n),{scroll:i}=t;return i&&(vr(r.x,i.offset.x),vr(r.y,i.offset.y)),r}const Kc=()=>({translate:0,scale:1,origin:0,originPoint:0}),Er=()=>({x:Kc(),y:Kc()}),qc=()=>({min:0,max:0}),ft=()=>({x:qc(),y:qc()}),ba={current:null},Ah={current:!1};function D0(){if(Ah.current=!0,!!Ga)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>ba.current=e.matches;e.addEventListener("change",t),t()}else ba.current=!1}const L0=new WeakMap;function F0(e,t,n){for(const r in t){const i=t[r],o=n[r];if(At(i))e.addValue(r,i);else if(At(o))e.addValue(r,_r(i,{owner:e}));else if(o!==i)if(e.hasValue(r)){const s=e.getValue(r);s.liveStyle===!0?s.jump(i):s.hasAnimated||s.set(i)}else{const s=e.getStaticValue(r);e.addValue(r,_r(s!==void 0?s:i,{owner:e}))}}for(const r in n)t[r]===void 0&&e.removeValue(r);return t}const Yc=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class j0{scrapeMotionValuesFromProps(t,n,r){return{}}constructor({parent:t,props:n,presenceContext:r,reducedMotionConfig:i,blockInitialAnimation:o,visualState:s},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=cl,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const f=Bt.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,it.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=s;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,this.parent=t,this.props=n,this.presenceContext=r,this.depth=t?t.depth+1:0,this.reducedMotionConfig=i,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=Ro(n),this.isVariantNode=ph(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in d){const p=d[f];l[f]!==void 0&&At(p)&&p.set(l[f])}}mount(t){var n;this.current=t,L0.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((r,i)=>this.bindToMotionValue(i,r)),Ah.current||D0(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ba.current,process.env.NODE_ENV!=="production"&&Xa(this.shouldReduceMotion!==!0,"You have Reduced Motion enabled on your device. Animations may not appear as expected.","reduced-motion-disabled"),(n=this.parent)==null||n.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var t;this.projection&&this.projection.unmount(),Pn(this.notifyUpdate),Pn(this.render),this.valueSubscriptions.forEach(n=>n()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(t=this.parent)==null||t.removeChild(this);for(const n in this.events)this.events[n].clear();for(const n in this.features){const r=this.features[n];r&&(r.unmount(),r.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const r=Pr.has(t);r&&this.onBindTransform&&this.onBindTransform();const i=n.on("change",s=>{this.latestValues[t]=s,this.props.onUpdate&&it.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{i(),o&&o(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in Nr){const n=Nr[t];if(!n)continue;const{isEnabled:r,Feature:i}=n;if(!this.features[t]&&i&&r(this.props)&&(this.features[t]=new i(this)),this.features[t]){const o=this.features[t];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ft()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let r=0;r<Yc.length;r++){const i=Yc[r];this.propEventSubscriptions[i]&&(this.propEventSubscriptions[i](),delete this.propEventSubscriptions[i]);const o="on"+i,s=t[o];s&&(this.propEventSubscriptions[i]=this.on(i,s))}this.prevMotionValues=F0(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const r=this.values.get(t);n!==r&&(r&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let r=this.values.get(t);return r===void 0&&n!==void 0&&(r=_r(n===null?void 0:n,{owner:this}),this.addValue(t,r)),r}readValue(t,n){let r=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return r!=null&&(typeof r=="string"&&(wf(r)||Sf(r))?r=parseFloat(r):!qy(r)&&Dn.test(n)&&(r=ih(t,n)),this.setBaseTarget(t,At(r)?r.get():r)),At(r)?r.get():r}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){var o;const{initial:n}=this.props;let r;if(typeof n=="string"||typeof n=="object"){const s=vl(this.props,n,(o=this.presenceContext)==null?void 0:o.custom);s&&(r=s[t])}if(n&&r!==void 0)return r;const i=this.getBaseTargetFromProps(this.props,t);return i!==void 0&&!At(i)?i:this.initialValues[t]!==void 0&&r===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new Za),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){fl.render(this.render)}}class Mh extends j0{constructor(){super(...arguments),this.KeyframeResolver=Ly}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:r}){delete n[t],delete r[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;At(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Rh(e,{style:t,vars:n},r,i){const o=e.style;let s;for(s in t)o[s]=t[s];i==null||i.applyProjectionStyles(o,r);for(s in n)o.setProperty(s,n[s])}function B0(e){return window.getComputedStyle(e)}class $0 extends Mh{constructor(){super(...arguments),this.type="html",this.renderInstance=Rh}readValueFromInstance(t,n){var r;if(Pr.has(n))return(r=this.projection)!=null&&r.isProjecting?la(n):ey(t,n);{const i=B0(t),o=(el(n)?i.getPropertyValue(n):i[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Nh(t,n)}build(t,n,r){bl(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return wl(t,n,r)}}const Ih=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function V0(e,t,n,r){Rh(e,t,void 0,r);for(const i in t.attrs)e.setAttribute(Ih.has(i)?i:El(i),t.attrs[i])}class z0 extends Mh{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ft}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(Pr.has(n)){const r=rh(n);return r&&r.default||0}return n=Ih.has(n)?n:El(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return wh(t,n,r)}build(t,n,r){bh(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,i){V0(t,n,r,i)}mount(t){this.isSVGTag=xh(t.tagName),super.mount(t)}}const U0=(e,t)=>xl(e)?new z0(t):new $0(t,{allowProjection:e!==N.Fragment});function Sr(e,t,n){const r=e.getProps();return vl(r,t,n!==void 0?n:r.custom,e)}const ya=e=>Array.isArray(e);function H0(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,_r(n))}function W0(e){return ya(e)?e[e.length-1]||0:e}function G0(e,t){const n=Sr(e,t);let{transitionEnd:r={},transition:i={},...o}=n||{};o={...o,...r};for(const s in o){const a=W0(o[s]);H0(e,s,a)}}function K0(e){return!!(At(e)&&e.add)}function xa(e,t){const n=e.getValue("willChange");if(K0(n))return n.add(t);if(!n&&kn.WillChange){const r=new kn.WillChange("auto");e.addValue("willChange",r),r.add(t)}}function Oh(e){return e.props[Eh]}const q0=e=>e!==null;function Y0(e,{repeat:t,repeatType:n="loop"},r){const i=e.filter(q0),o=t&&n!=="loop"&&t%2===1?0:i.length-1;return i[o]}const Z0={type:"spring",stiffness:500,damping:25,restSpeed:10},X0=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),Q0={type:"keyframes",duration:.8},J0={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},ex=(e,{keyframes:t})=>t.length>2?Q0:Pr.has(e)?e.startsWith("scale")?X0(t[1]):Z0:J0;function tx({when:e,delay:t,delayChildren:n,staggerChildren:r,staggerDirection:i,repeat:o,repeatType:s,repeatDelay:a,from:l,elapsed:c,...u}){return!!Object.keys(u).length}const Sl=(e,t,n,r={},i,o)=>s=>{const a=ul(r,e)||{},l=a.delay||r.delay||0;let{elapsed:c=0}=r;c=c-on(l);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-c,onUpdate:f=>{t.set(f),a.onUpdate&&a.onUpdate(f)},onComplete:()=>{s(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:o?void 0:i};tx(a)||Object.assign(u,ex(e,u)),u.duration&&(u.duration=on(u.duration)),u.repeatDelay&&(u.repeatDelay=on(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(ha(u),u.delay===0&&(d=!0)),(kn.instantAnimations||kn.skipAnimations)&&(d=!0,ha(u),u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&t.get()!==void 0){const f=Y0(u.keyframes,a);if(f!==void 0){it.update(()=>{u.onUpdate(f),u.onComplete()});return}}return a.isSync?new ll(u):new Sy(u)};function nx({protectedKeys:e,needsAnimating:t},n){const r=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function Ph(e,t,{delay:n=0,transitionOverride:r,type:i}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:s,...a}=t;r&&(o=r);const l=[],c=i&&e.animationState&&e.animationState.getState()[i];for(const u in a){const d=e.getValue(u,e.latestValues[u]??null),f=a[u];if(f===void 0||c&&nx(c,u))continue;const p={delay:n,...ul(o||{},u)},g=d.get();if(g!==void 0&&!d.isAnimating&&!Array.isArray(f)&&f===g&&!p.velocity)continue;let m=!1;if(window.MotionHandoffAnimation){const y=Oh(e);if(y){const E=window.MotionHandoffAnimation(y,u,it);E!==null&&(p.startTime=E,m=!0)}}xa(e,u),d.start(Sl(u,d,f,e.shouldReduceMotion&&eh.has(u)?{type:!1}:p,e,m));const v=d.animation;v&&l.push(v)}return s&&Promise.all(l).then(()=>{it.update(()=>{s&&G0(e,s)})}),l}function Dh(e,t,n,r=0,i=1){const o=Array.from(e).sort((c,u)=>c.sortNodePosition(u)).indexOf(t),s=e.size,a=(s-1)*r;return typeof n=="function"?n(o,s):i===1?o*r:a-o*r}function va(e,t,n={}){var l;const r=Sr(e,t,n.type==="exit"?(l=e.presenceContext)==null?void 0:l.custom:void 0);let{transition:i=e.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(i=n.transitionOverride);const o=r?()=>Promise.all(Ph(e,r,n)):()=>Promise.resolve(),s=e.variantChildren&&e.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:f}=i;return rx(e,t,c,u,d,f,n)}:()=>Promise.resolve(),{when:a}=i;if(a){const[c,u]=a==="beforeChildren"?[o,s]:[s,o];return c().then(()=>u())}else return Promise.all([o(),s(n.delay)])}function rx(e,t,n=0,r=0,i=0,o=1,s){const a=[];for(const l of e.variantChildren)l.notify("AnimationStart",t),a.push(va(l,t,{...s,delay:n+(typeof r=="function"?0:r)+Dh(e.variantChildren,l,r,i,o)}).then(()=>l.notify("AnimationComplete",t)));return Promise.all(a)}function ix(e,t,n={}){e.notify("AnimationStart",t);let r;if(Array.isArray(t)){const i=t.map(o=>va(e,o,n));r=Promise.all(i)}else if(typeof t=="string")r=va(e,t,n);else{const i=typeof t=="function"?Sr(e,t,n.custom):t;r=Promise.all(Ph(e,i,n))}return r.then(()=>{e.notify("AnimationComplete",t)})}function Lh(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let r=0;r<n;r++)if(t[r]!==e[r])return!1;return!0}const ox=gl.length;function Fh(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?Fh(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<ox;n++){const r=gl[n],i=e.props[r];(ci(i)||i===!1)&&(t[r]=i)}return t}const sx=[...ml].reverse(),ax=ml.length;function lx(e){return t=>Promise.all(t.map(({animation:n,options:r})=>ix(e,n,r)))}function cx(e){let t=lx(e),n=Zc(),r=!0;const i=l=>(c,u)=>{var f;const d=Sr(e,u,l==="exit"?(f=e.presenceContext)==null?void 0:f.custom:void 0);if(d){const{transition:p,transitionEnd:g,...m}=d;c={...c,...m,...g}}return c};function o(l){t=l(e)}function s(l){const{props:c}=e,u=Fh(e.parent)||{},d=[],f=new Set;let p={},g=1/0;for(let v=0;v<ax;v++){const y=sx[v],E=n[y],w=c[y]!==void 0?c[y]:u[y],C=ci(w),k=y===l?E.isActive:null;k===!1&&(g=v);let _=w===u[y]&&w!==c[y]&&C;if(_&&r&&e.manuallyAnimateOnMount&&(_=!1),E.protectedKeys={...p},!E.isActive&&k===null||!w&&!E.prevProp||Mo(w)||typeof w=="boolean")continue;const R=ux(E.prevProp,w);let A=R||y===l&&E.isActive&&!_&&C||v>g&&C,O=!1;const b=Array.isArray(w)?w:[w];let M=b.reduce(i(y),{});k===!1&&(M={});const{prevResolvedValues:I={}}=E,F={...I,...M},D=X=>{A=!0,f.has(X)&&(O=!0,f.delete(X)),E.needsAnimating[X]=!0;const $=e.getValue(X);$&&($.liveStyle=!1)};for(const X in F){const $=M[X],z=I[X];if(p.hasOwnProperty(X))continue;let x=!1;ya($)&&ya(z)?x=!Lh($,z):x=$!==z,x?$!=null?D(X):f.add(X):$!==void 0&&f.has(X)?D(X):E.protectedKeys[X]=!0}E.prevProp=w,E.prevResolvedValues=M,E.isActive&&(p={...p,...M}),r&&e.blockInitialAnimation&&(A=!1);const G=_&&R;A&&(!G||O)&&d.push(...b.map(X=>{const $={type:y};if(typeof X=="string"&&r&&!G&&e.manuallyAnimateOnMount&&e.parent){const{parent:z}=e,x=Sr(z,X);if(z.enteringChildren&&x){const{delayChildren:B}=x.transition||{};$.delay=Dh(z.enteringChildren,e,B)}}return{animation:X,options:$}}))}if(f.size){const v={};if(typeof c.initial!="boolean"){const y=Sr(e,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(v.transition=y.transition)}f.forEach(y=>{const E=e.getBaseTarget(y),w=e.getValue(y);w&&(w.liveStyle=!0),v[y]=E??null}),d.push({animation:v})}let m=!!d.length;return r&&(c.initial===!1||c.initial===c.animate)&&!e.manuallyAnimateOnMount&&(m=!1),r=!1,m?t(d):Promise.resolve()}function a(l,c){var d;if(n[l].isActive===c)return Promise.resolve();(d=e.variantChildren)==null||d.forEach(f=>{var p;return(p=f.animationState)==null?void 0:p.setActive(l,c)}),n[l].isActive=c;const u=s(l);for(const f in n)n[f].protectedKeys={};return u}return{animateChanges:s,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Zc(),r=!0}}}function ux(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!Lh(t,e):!1}function Un(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Zc(){return{animate:Un(!0),whileInView:Un(),whileHover:Un(),whileTap:Un(),whileDrag:Un(),whileFocus:Un(),exit:Un()}}class jn{constructor(t){this.isMounted=!1,this.node=t}update(){}}class dx extends jn{constructor(t){super(t),t.animationState||(t.animationState=cx(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Mo(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 fx=0;class hx extends jn{constructor(){super(...arguments),this.id=fx++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===r)return;const i=this.node.animationState.setActive("exit",!t);n&&!t&&i.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 px={animation:{Feature:dx},exit:{Feature:hx}};function di(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}function vi(e){return{point:{x:e.pageX,y:e.pageY}}}const mx=e=>t=>hl(t)&&e(t,vi(t));function Jr(e,t,n,r){return di(e,t,mx(n),r)}const jh=1e-4,gx=1-jh,bx=1+jh,Bh=.01,yx=0-Bh,xx=0+Bh;function Dt(e){return e.max-e.min}function vx(e,t,n){return Math.abs(e-t)<=n}function Xc(e,t,n,r=.5){e.origin=r,e.originPoint=at(t.min,t.max,e.origin),e.scale=Dt(n)/Dt(t),e.translate=at(n.min,n.max,e.origin)-e.originPoint,(e.scale>=gx&&e.scale<=bx||isNaN(e.scale))&&(e.scale=1),(e.translate>=yx&&e.translate<=xx||isNaN(e.translate))&&(e.translate=0)}function ei(e,t,n,r){Xc(e.x,t.x,n.x,r?r.originX:void 0),Xc(e.y,t.y,n.y,r?r.originY:void 0)}function Qc(e,t,n){e.min=n.min+t.min,e.max=e.min+Dt(t)}function wx(e,t,n){Qc(e.x,t.x,n.x),Qc(e.y,t.y,n.y)}function Jc(e,t,n){e.min=t.min-n.min,e.max=e.min+Dt(t)}function ti(e,t,n){Jc(e.x,t.x,n.x),Jc(e.y,t.y,n.y)}function Yt(e){return[e("x"),e("y")]}const $h=({current:e})=>e?e.ownerDocument.defaultView:null,eu=(e,t)=>Math.abs(e-t);function Ex(e,t){const n=eu(e.x,t.x),r=eu(e.y,t.y);return Math.sqrt(n**2+r**2)}class Vh{constructor(t,n,{transformPagePoint:r,contextWindow:i=window,dragSnapToOrigin:o=!1,distanceThreshold:s=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=ps(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,g=Ex(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!g)return;const{point:m}=f,{timestamp:v}=Tt;this.history.push({...m,timestamp:v});const{onStart:y,onMove:E}=this.handlers;p||(y&&y(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),E&&E(this.lastMoveEvent,f)},this.handlePointerMove=(f,p)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=hs(p,this.transformPagePoint),it.update(this.updatePoint,!0)},this.handlePointerUp=(f,p)=>{this.end();const{onEnd:g,onSessionEnd:m,resumeAnimation:v}=this.handlers;if(this.dragSnapToOrigin&&v&&v(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=ps(f.type==="pointercancel"?this.lastMoveEventInfo:hs(p,this.transformPagePoint),this.history);this.startEvent&&g&&g(f,y),m&&m(f,y)},!hl(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=s,this.contextWindow=i||window;const a=vi(t),l=hs(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Tt;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=n;d&&d(t,ps(l,this.history)),this.removeListeners=bi(Jr(this.contextWindow,"pointermove",this.handlePointerMove),Jr(this.contextWindow,"pointerup",this.handlePointerUp),Jr(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),Pn(this.updatePoint)}}function hs(e,t){return t?{point:t(e.point)}:e}function tu(e,t){return{x:e.x-t.x,y:e.y-t.y}}function ps({point:e},t){return{point:e,delta:tu(e,zh(t)),offset:tu(e,Sx(t)),velocity:kx(t,.1)}}function Sx(e){return e[0]}function zh(e){return e[e.length-1]}function kx(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null;const i=zh(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>on(t)));)n--;if(!r)return{x:0,y:0};const o=hn(i.timestamp-r.timestamp);if(o===0)return{x:0,y:0};const s={x:(i.x-r.x)/o,y:(i.y-r.y)/o};return s.x===1/0&&(s.x=0),s.y===1/0&&(s.y=0),s}function Cx(e,{min:t,max:n},r){return t!==void 0&&e<t?e=r?at(t,e,r.min):Math.max(e,t):n!==void 0&&e>n&&(e=r?at(n,e,r.max):Math.min(e,n)),e}function nu(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 _x(e,{top:t,left:n,bottom:r,right:i}){return{x:nu(e.x,n,i),y:nu(e.y,t,r)}}function ru(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,r]=[r,n]),{min:n,max:r}}function Tx(e,t){return{x:ru(e.x,t.x),y:ru(e.y,t.y)}}function Nx(e,t){let n=.5;const r=Dt(e),i=Dt(t);return i>r?n=si(t.min,t.max-r,e.min):r>i&&(n=si(e.min,e.max-i,t.min)),En(0,1,n)}function Ax(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 wa=.35;function Mx(e=wa){return e===!1?e=0:e===!0&&(e=wa),{x:iu(e,"left","right"),y:iu(e,"top","bottom")}}function iu(e,t,n){return{min:ou(e,t),max:ou(e,n)}}function ou(e,t){return typeof e=="number"?e:e[t]||0}const Rx=new WeakMap;class Ix{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=ft(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:r}={}){const{presenceContext:i}=this.visualElement;if(i&&i.isPresent===!1)return;const o=d=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(vi(d).point)},s=(d,f)=>{const{drag:p,dragPropagation:g,onDragStart:m}=this.getProps();if(p&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=$y(p),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Yt(y=>{let E=this.getAxisMotionValue(y).get()||0;if(pn.test(E)){const{projection:w}=this.visualElement;if(w&&w.layout){const C=w.layout.layoutBox[y];C&&(E=Dt(C)*(parseFloat(E)/100))}}this.originPoint[y]=E}),m&&it.postRender(()=>m(d,f)),xa(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},a=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f;const{dragPropagation:p,dragDirectionLock:g,onDirectionLock:m,onDrag:v}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:y}=f;if(g&&this.currentDirection===null){this.currentDirection=Ox(y),this.currentDirection!==null&&m&&m(this.currentDirection);return}this.updateAxis("x",f.point,y),this.updateAxis("y",f.point,y),this.visualElement.render(),v&&v(d,f)},l=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f,this.stop(d,f),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Yt(d=>{var f;return this.getAnimationState(d)==="paused"&&((f=this.getAxisMotionValue(d).animation)==null?void 0:f.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new Vh(t,{onSessionStart:o,onStart:s,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:$h(this.visualElement)})}stop(t,n){const r=t||this.latestPointerEvent,i=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!i||!r)return;const{velocity:s}=i;this.startAnimation(s);const{onDragEnd:a}=this.getProps();a&&it.postRender(()=>a(r,i))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,r){const{drag:i}=this.getProps();if(!r||!Fi(t,i,this.currentDirection))return;const o=this.getAxisMotionValue(t);let s=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(s=Cx(s,this.constraints[t],this.elastic[t])),o.set(s)}resolveConstraints(){var o;const{dragConstraints:t,dragElastic:n}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(o=this.visualElement.projection)==null?void 0:o.layout,i=this.constraints;t&&xr(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=_x(r.layoutBox,t):this.constraints=!1,this.elastic=Mx(n),i!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&Yt(s=>{this.constraints!==!1&&this.getAxisMotionValue(s)&&(this.constraints[s]=Ax(r.layoutBox[s],this.constraints[s]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!xr(t))return!1;const r=t.current;Sn(r!==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:i}=this.visualElement;if(!i||!i.layout)return!1;const o=P0(r,i.root,this.visualElement.getTransformPagePoint());let s=Tx(i.layout.layoutBox,o);if(n){const a=n(R0(s));this.hasMutatedConstraints=!!a,a&&(s=Ch(a))}return s}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:i,dragTransition:o,dragSnapToOrigin:s,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Yt(u=>{if(!Fi(u,n,this.currentDirection))return;let d=l&&l[u]||{};s&&(d={min:0,max:0});const f=i?200:1e6,p=i?40:1e7,g={type:"inertia",velocity:r?t[u]:0,bounceStiffness:f,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,g)});return Promise.all(c).then(a)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return xa(this.visualElement,t),r.start(Sl(t,r,0,n,this.visualElement,!1))}stopAnimation(){Yt(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Yt(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()}`,r=this.visualElement.getProps(),i=r[n];return i||this.visualElement.getValue(t,(r.initial?r.initial[t]:void 0)||0)}snapToCursor(t){Yt(n=>{const{drag:r}=this.getProps();if(!Fi(n,r,this.currentDirection))return;const{projection:i}=this.visualElement,o=this.getAxisMotionValue(n);if(i&&i.layout){const{min:s,max:a}=i.layout.layoutBox[n];o.set(t[n]-at(s,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!xr(n)||!r||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};Yt(s=>{const a=this.getAxisMotionValue(s);if(a&&this.constraints!==!1){const l=a.get();i[s]=Nx({min:l,max:l},this.constraints[s])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),Yt(s=>{if(!Fi(s,t,null))return;const a=this.getAxisMotionValue(s),{min:l,max:c}=this.constraints[s];a.set(at(l,c,i[s]))})}addListeners(){if(!this.visualElement.current)return;Rx.set(this.visualElement,this);const t=this.visualElement.current,n=Jr(t,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),r=()=>{const{dragConstraints:l}=this.getProps();xr(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:i}=this.visualElement,o=i.addEventListener("measure",r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),it.read(r);const s=di(window,"resize",()=>this.scalePositionWithinConstraints()),a=i.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Yt(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=l[u].translate,d.set(d.get()+l[u].translate))}),this.visualElement.render())});return()=>{s(),n(),o(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:r=!1,dragPropagation:i=!1,dragConstraints:o=!1,dragElastic:s=wa,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:i,dragConstraints:o,dragElastic:s,dragMomentum:a}}}function Fi(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Ox(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Px extends jn{constructor(t){super(t),this.removeGroupControls=Qt,this.removeListeners=Qt,this.controls=new Ix(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Qt}unmount(){this.removeGroupControls(),this.removeListeners()}}const su=e=>(t,n)=>{e&&it.postRender(()=>e(t,n))};class Dx extends jn{constructor(){super(...arguments),this.removePointerDownListener=Qt}onPointerDown(t){this.session=new Vh(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:$h(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:i}=this.node.getProps();return{onSessionStart:su(t),onStart:su(n),onMove:r,onEnd:(o,s)=>{delete this.session,i&&it.postRender(()=>i(o,s))}}}mount(){this.removePointerDownListener=Jr(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const io={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function au(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Vr={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(Se.test(e))e=parseFloat(e);else return e;const n=au(e,t.target.x),r=au(e,t.target.y);return`${n}% ${r}%`}},Lx={correct:(e,{treeScale:t,projectionDelta:n})=>{const r=e,i=Dn.parse(e);if(i.length>5)return r;const o=Dn.createTransformer(e),s=typeof i[0]!="number"?1:0,a=n.x.scale*t.x,l=n.y.scale*t.y;i[0+s]/=a,i[1+s]/=l;const c=at(a,l,.5);return typeof i[2+s]=="number"&&(i[2+s]/=c),typeof i[3+s]=="number"&&(i[3+s]/=c),o(i)}};let ms=!1;class Fx extends N.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r,layoutId:i}=this.props,{projection:o}=t;o0(jx),o&&(n.group&&n.group.add(o),r&&r.register&&i&&r.register(o),ms&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),io.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:r,drag:i,isPresent:o}=this.props,{projection:s}=r;return s&&(s.isPresent=o,ms=!0,i||t.layoutDependency!==n||n===void 0||t.isPresent!==o?s.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?s.promote():s.relegate()||it.postRender(()=>{const a=s.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),fl.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:i}=t;ms=!0,i&&(i.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(i),r&&r.deregister&&r.deregister(i))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Uh(e){const[t,n]=dh(),r=N.useContext(Ha);return h.jsx(Fx,{...e,layoutGroup:r,switchLayoutGroup:N.useContext(Sh),isPresent:t,safeToRemove:n})}const jx={borderRadius:{...Vr,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Vr,borderTopRightRadius:Vr,borderBottomLeftRadius:Vr,borderBottomRightRadius:Vr,boxShadow:Lx};function Bx(e,t,n){const r=At(e)?e:_r(e);return r.start(Sl("",r,t,n)),r.animation}const $x=(e,t)=>e.depth-t.depth;class Vx{constructor(){this.children=[],this.isDirty=!1}add(t){Ka(this.children,t),this.isDirty=!0}remove(t){qa(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort($x),this.isDirty=!1,this.children.forEach(t)}}function zx(e,t){const n=Bt.now(),r=({timestamp:i})=>{const o=i-n;o>=t&&(Pn(r),e(o-t))};return it.setup(r,!0),()=>Pn(r)}const Hh=["TopLeft","TopRight","BottomLeft","BottomRight"],Ux=Hh.length,lu=e=>typeof e=="string"?parseFloat(e):e,cu=e=>typeof e=="number"||Se.test(e);function Hx(e,t,n,r,i,o){i?(e.opacity=at(0,n.opacity??1,Wx(r)),e.opacityExit=at(t.opacity??1,0,Gx(r))):o&&(e.opacity=at(t.opacity??1,n.opacity??1,r));for(let s=0;s<Ux;s++){const a=`border${Hh[s]}Radius`;let l=uu(t,a),c=uu(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||cu(l)===cu(c)?(e[a]=Math.max(at(lu(l),lu(c),r),0),(pn.test(c)||pn.test(l))&&(e[a]+="%")):e[a]=c}(t.rotate||n.rotate)&&(e.rotate=at(t.rotate||0,n.rotate||0,r))}function uu(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Wx=Wh(0,.5,Rf),Gx=Wh(.5,.95,Qt);function Wh(e,t,n){return r=>r<e?0:r>t?1:n(si(e,t,r))}function du(e,t){e.min=t.min,e.max=t.max}function qt(e,t){du(e.x,t.x),du(e.y,t.y)}function fu(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function hu(e,t,n,r,i){return e-=t,e=bo(e,1/n,r),i!==void 0&&(e=bo(e,1/i,r)),e}function Kx(e,t=0,n=1,r=.5,i,o=e,s=e){if(pn.test(t)&&(t=parseFloat(t),t=at(s.min,s.max,t/100)-s.min),typeof t!="number")return;let a=at(o.min,o.max,r);e===o&&(a-=t),e.min=hu(e.min,t,n,a,i),e.max=hu(e.max,t,n,a,i)}function pu(e,t,[n,r,i],o,s){Kx(e,t[n],t[r],t[i],t.scale,o,s)}const qx=["x","scaleX","originX"],Yx=["y","scaleY","originY"];function mu(e,t,n,r){pu(e.x,t,qx,n?n.x:void 0,r?r.x:void 0),pu(e.y,t,Yx,n?n.y:void 0,r?r.y:void 0)}function gu(e){return e.translate===0&&e.scale===1}function Gh(e){return gu(e.x)&&gu(e.y)}function bu(e,t){return e.min===t.min&&e.max===t.max}function Zx(e,t){return bu(e.x,t.x)&&bu(e.y,t.y)}function yu(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Kh(e,t){return yu(e.x,t.x)&&yu(e.y,t.y)}function xu(e){return Dt(e.x)/Dt(e.y)}function vu(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class Xx{constructor(){this.members=[]}add(t){Ka(this.members,t),t.scheduleRender()}remove(t){if(qa(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(i=>t===i);if(n===0)return!1;let r;for(let i=n;i>=0;i--){const o=this.members[i];if(o.isPresent!==!1){r=o;break}}return r?(this.promote(r),!0):!1}promote(t,n){const r=this.lead;if(t!==r&&(this.prevLead=r,this.lead=t,t.show(),r)){r.instance&&r.scheduleRender(),t.scheduleRender(),t.resumeFrom=r,n&&(t.resumeFrom.preserveOpacity=!0),r.snapshot&&(t.snapshot=r.snapshot,t.snapshot.latestValues=r.animationValues||r.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:i}=t.options;i===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:r}=t;n.onExitComplete&&n.onExitComplete(),r&&r.options.onExitComplete&&r.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function Qx(e,t,n){let r="";const i=e.x.translate/t.x,o=e.y.translate/t.y,s=(n==null?void 0:n.z)||0;if((i||o||s)&&(r=`translate3d(${i}px, ${o}px, ${s}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:f,skewX:p,skewY:g}=n;c&&(r=`perspective(${c}px) ${r}`),u&&(r+=`rotate(${u}deg) `),d&&(r+=`rotateX(${d}deg) `),f&&(r+=`rotateY(${f}deg) `),p&&(r+=`skewX(${p}deg) `),g&&(r+=`skewY(${g}deg) `)}const a=e.x.scale*t.x,l=e.y.scale*t.y;return(a!==1||l!==1)&&(r+=`scale(${a}, ${l})`),r||"none"}const gs=["","X","Y","Z"],Jx=1e3;let ev=0;function bs(e,t,n,r){const{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),r&&(r[e]=0))}function qh(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=Oh(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:i,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",it,!(i||o))}const{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&qh(r)}function Yh({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(s={},a=t==null?void 0:t()){this.id=ev++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(rv),this.nodes.forEach(av),this.nodes.forEach(lv),this.nodes.forEach(iv)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=s,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new Vx)}addEventListener(s,a){return this.eventHandlers.has(s)||this.eventHandlers.set(s,new Za),this.eventHandlers.get(s).add(a)}notifyListeners(s,...a){const l=this.eventHandlers.get(s);l&&l.notify(...a)}hasListeners(s){return this.eventHandlers.has(s)}mount(s){if(this.instance)return;this.isSVG=uh(s)&&!Gy(s),this.instance=s;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(s),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),e){let u,d=0;const f=()=>this.root.updateBlockedByResize=!1;it.read(()=>{d=window.innerWidth}),e(s,()=>{const p=window.innerWidth;p!==d&&(d=p,this.root.updateBlockedByResize=!0,u&&u(),u=zx(f,250),io.hasAnimatedSinceResize&&(io.hasAnimatedSinceResize=!1,this.nodes.forEach(Su)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:f,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||c.getDefaultTransition()||hv,{onLayoutAnimationStart:m,onLayoutAnimationComplete:v}=c.getProps(),y=!this.targetLayout||!Kh(this.targetLayout,p),E=!d&&f;if(this.options.layoutRoot||this.resumeFrom||E||d&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...ul(g,"layout"),onPlay:m,onComplete:v};(c.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(u,E)}else d||Su(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const s=this.getStack();s&&s.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Pn(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(cv),this.animationId++)}getTransformTemplate(){const{visualElement:s}=this.options;return s&&s.getProps().transformTemplate}willUpdate(s=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&qh(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),s&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(wu);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Eu);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(sv),this.nodes.forEach(tv),this.nodes.forEach(nv)):this.nodes.forEach(Eu),this.clearAllSnapshots();const a=Bt.now();Tt.delta=En(0,1e3/60,a-Tt.timestamp),Tt.timestamp=a,Tt.isProcessing=!0,os.update.process(Tt),os.preRender.process(Tt),os.render.process(Tt),Tt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,fl.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(ov),this.sharedNodes.forEach(uv)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,it.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){it.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Dt(this.snapshot.measuredBox.x)&&!Dt(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const s=this.layout;this.layout=this.measure(!1),this.layoutCorrected=ft(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,s?s.layoutBox:void 0)}updateScroll(s="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===s&&(a=!1),a&&this.instance){const l=r(this.instance);this.scroll={animationId:this.root.animationId,phase:s,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!i)return;const s=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Gh(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;s&&this.instance&&(a||Gn(this.latestValues)||u)&&(i(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(s=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return s&&(l=this.removeTransform(l)),pv(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:s}=this.options;if(!s)return ft();const a=s.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(mv))){const{scroll:u}=this.root;u&&(vr(a.x,u.offset.x),vr(a.y,u.offset.y))}return a}removeElementScroll(s){var l;const a=ft();if(qt(a,s),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:d,options:f}=u;u!==this.root&&d&&f.layoutScroll&&(d.wasRoot&&qt(a,s),vr(a.x,d.offset.x),vr(a.y,d.offset.y))}return a}applyTransform(s,a=!1){const l=ft();qt(l,s);for(let c=0;c<this.path.length;c++){const u=this.path[c];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&wr(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Gn(u.latestValues)&&wr(l,u.latestValues)}return Gn(this.latestValues)&&wr(l,this.latestValues),l}removeTransform(s){const a=ft();qt(a,s);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Gn(c.latestValues))continue;ma(c.latestValues)&&c.updateSnapshot();const u=ft(),d=c.measurePageBox();qt(u,d),mu(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return Gn(this.latestValues)&&mu(a,this.latestValues),a}setTargetDelta(s){this.targetDelta=s,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(s){this.options={...this.options,...s,crossfade:s.crossfade!==void 0?s.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Tt.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(s=!1){var f;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(s||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(f=this.parent)!=null&&f.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=Tt.timestamp,!this.targetDelta&&!this.relativeTarget){const p=this.getClosestProjectingParent();p&&p.layout&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ft(),this.relativeTargetOrigin=ft(),ti(this.relativeTargetOrigin,this.layout.layoutBox,p.layout.layoutBox),qt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ft(),this.targetWithTransforms=ft()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),wx(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):qt(this.target,this.layout.layoutBox),Th(this.target,this.targetDelta)):qt(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const p=this.getClosestProjectingParent();p&&!!p.resumingFrom==!!this.resumingFrom&&!p.options.layoutScroll&&p.target&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ft(),this.relativeTargetOrigin=ft(),ti(this.relativeTargetOrigin,this.target,p.target),qt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||ma(this.parent.latestValues)||_h(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var g;const s=this.getLead(),a=!!this.resumingFrom||this!==s;let l=!0;if((this.isProjectionDirty||(g=this.parent)!=null&&g.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===Tt.timestamp&&(l=!1),l)return;const{layout:c,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||u))return;qt(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,f=this.treeScale.y;O0(this.layoutCorrected,this.treeScale,this.path,a),s.layout&&!s.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(s.target=s.layout.layoutBox,s.targetWithTransforms=ft());const{target:p}=s;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(fu(this.prevProjectionDelta.x,this.projectionDelta.x),fu(this.prevProjectionDelta.y,this.projectionDelta.y)),ei(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==f||!vu(this.projectionDelta.x,this.prevProjectionDelta.x)||!vu(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",p))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(s=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),s){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Er(),this.projectionDelta=Er(),this.projectionDeltaWithTransform=Er()}setAnimationOrigin(s,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=Er();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=ft(),p=l?l.source:void 0,g=this.layout?this.layout.source:void 0,m=p!==g,v=this.getStack(),y=!v||v.members.length<=1,E=!!(m&&!y&&this.options.crossfade===!0&&!this.path.some(fv));this.animationProgress=0;let w;this.mixTargetDelta=C=>{const k=C/1e3;ku(d.x,s.x,k),ku(d.y,s.y,k),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ti(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),dv(this.relativeTarget,this.relativeTargetOrigin,f,k),w&&Zx(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=ft()),qt(w,this.relativeTarget)),m&&(this.animationValues=u,Hx(u,c,this.latestValues,k,E,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=k},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(s){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(Pn(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=it.update(()=>{io.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=_r(0)),this.currentAnimation=Bx(this.motionValue,[0,1e3],{...s,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),s.onUpdate&&s.onUpdate(u)},onStop:()=>{},onComplete:()=>{s.onComplete&&s.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const s=this.getStack();s&&s.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(Jx),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const s=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:u}=s;if(!(!a||!l||!c)){if(this!==s&&this.layout&&c&&Zh(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ft();const d=Dt(this.layout.layoutBox.x);l.x.min=s.target.x.min,l.x.max=l.x.min+d;const f=Dt(this.layout.layoutBox.y);l.y.min=s.target.y.min,l.y.max=l.y.min+f}qt(a,l),wr(a,u),ei(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(s,a){this.sharedNodes.has(s)||this.sharedNodes.set(s,new Xx),this.sharedNodes.get(s).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const s=this.getStack();return s?s.lead===this:!0}getLead(){var a;const{layoutId:s}=this.options;return s?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:s}=this.options;return s?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:s}=this.options;if(s)return this.root.sharedNodes.get(s)}promote({needsReset:s,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),s&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const s=this.getStack();return s?s.relegate(this):!1}resetSkewAndRotation(){const{visualElement:s}=this.options;if(!s)return;let a=!1;const{latestValues:l}=s;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&bs("z",s,c,this.animationValues);for(let u=0;u<gs.length;u++)bs(`rotate${gs[u]}`,s,c,this.animationValues),bs(`skew${gs[u]}`,s,c,this.animationValues);s.render();for(const u in c)s.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);s.scheduleRender()}applyProjectionStyles(s,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){s.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,s.visibility="",s.opacity="",s.pointerEvents=ro(a==null?void 0:a.pointerEvents)||"",s.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(s.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,s.pointerEvents=ro(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Gn(this.latestValues)&&(s.transform=l?l({},""):"none",this.hasProjected=!1);return}s.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=Qx(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),s.transform=d;const{x:f,y:p}=this.projectionDelta;s.transformOrigin=`${f.origin*100}% ${p.origin*100}% 0`,c.animationValues?s.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:s.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const g in ui){if(u[g]===void 0)continue;const{correct:m,applyTo:v,isCSSVariable:y}=ui[g],E=d==="none"?u[g]:m(u[g],c);if(v){const w=v.length;for(let C=0;C<w;C++)s[v[C]]=E}else y?this.options.visualElement.renderState.vars[g]=E:s[g]=E}this.options.layoutId&&(s.pointerEvents=c===this?ro(a==null?void 0:a.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(s=>{var a;return(a=s.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach(wu),this.root.sharedNodes.clear()}}}function tv(e){e.updateLayout()}function nv(e){var n;const t=((n=e.resumeFrom)==null?void 0:n.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:i}=e.layout,{animationType:o}=e.options,s=t.source!==e.layout.source;o==="size"?Yt(d=>{const f=s?t.measuredBox[d]:t.layoutBox[d],p=Dt(f);f.min=r[d].min,f.max=f.min+p}):Zh(o,t.layoutBox,r)&&Yt(d=>{const f=s?t.measuredBox[d]:t.layoutBox[d],p=Dt(r[d]);f.max=f.min+p,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[d].max=e.relativeTarget[d].min+p)});const a=Er();ei(a,r,t.layoutBox);const l=Er();s?ei(l,e.applyTransform(i,!0),t.measuredBox):ei(l,r,t.layoutBox);const c=!Gh(a);let u=!1;if(!e.resumeFrom){const d=e.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:f,layout:p}=d;if(f&&p){const g=ft();ti(g,t.layoutBox,f.layoutBox);const m=ft();ti(m,r,p.layoutBox),Kh(g,m)||(u=!0),d.options.layoutRoot&&(e.relativeTarget=m,e.relativeTargetOrigin=g,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:r,snapshot:t,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:r}=e.options;r&&r()}e.options.transition=void 0}function rv(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function iv(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function ov(e){e.clearSnapshot()}function wu(e){e.clearMeasurements()}function Eu(e){e.isLayoutDirty=!1}function sv(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function Su(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function av(e){e.resolveTargetDelta()}function lv(e){e.calcProjection()}function cv(e){e.resetSkewAndRotation()}function uv(e){e.removeLeadSnapshot()}function ku(e,t,n){e.translate=at(t.translate,0,n),e.scale=at(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Cu(e,t,n,r){e.min=at(t.min,n.min,r),e.max=at(t.max,n.max,r)}function dv(e,t,n,r){Cu(e.x,t.x,n.x,r),Cu(e.y,t.y,n.y,r)}function fv(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const hv={duration:.45,ease:[.4,0,.1,1]},_u=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),Tu=_u("applewebkit/")&&!_u("chrome/")?Math.round:Qt;function Nu(e){e.min=Tu(e.min),e.max=Tu(e.max)}function pv(e){Nu(e.x),Nu(e.y)}function Zh(e,t,n){return e==="position"||e==="preserve-aspect"&&!vx(xu(t),xu(n),.2)}function mv(e){var t;return e!==e.root&&((t=e.scroll)==null?void 0:t.wasRoot)}const gv=Yh({attachResizeListener:(e,t)=>di(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),ys={current:void 0},Xh=Yh({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!ys.current){const e=new gv({});e.mount(window),e.setOptions({layoutScroll:!0}),ys.current=e}return ys.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),bv={pan:{Feature:Dx},drag:{Feature:Px,ProjectionNode:Xh,MeasureLayout:Uh}};function Au(e,t,n){const{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive("whileHover",n==="Start");const i="onHover"+n,o=r[i];o&&it.postRender(()=>o(t,vi(t)))}class yv extends jn{mount(){const{current:t}=this.node;t&&(this.unmount=Vy(t,(n,r)=>(Au(this.node,r,"Start"),i=>Au(this.node,i,"End"))))}unmount(){}}class xv extends jn{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=bi(di(this.node.current,"focus",()=>this.onFocus()),di(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Mu(e,t,n){const{props:r}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&r.whileTap&&e.animationState.setActive("whileTap",n==="Start");const i="onTap"+(n==="End"?"":n),o=r[i];o&&it.postRender(()=>o(t,vi(t)))}class vv extends jn{mount(){const{current:t}=this.node;t&&(this.unmount=Wy(t,(n,r)=>(Mu(this.node,r,"Start"),(i,{success:o})=>Mu(this.node,i,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Ea=new WeakMap,xs=new WeakMap,wv=e=>{const t=Ea.get(e.target);t&&t(e)},Ev=e=>{e.forEach(wv)};function Sv({root:e,...t}){const n=e||document;xs.has(n)||xs.set(n,{});const r=xs.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(Ev,{root:e,...t})),r[i]}function kv(e,t,n){const r=Sv(t);return Ea.set(e,n),r.observe(e),()=>{Ea.delete(e),r.unobserve(e)}}const Cv={some:0,all:1};class _v extends jn{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:r,amount:i="some",once:o}=t,s={root:n?n.current:void 0,rootMargin:r,threshold:typeof i=="number"?i:Cv[i]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),f=c?u:d;f&&f(l)};return kv(this.node.current,s,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(Tv(t,n))&&this.startObserver()}unmount(){}}function Tv({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Nv={inView:{Feature:_v},tap:{Feature:vv},focus:{Feature:xv},hover:{Feature:yv}},Av={layout:{ProjectionNode:Xh,MeasureLayout:Uh}},Mv={...px,...Nv,...bv,...Av},De=M0(Mv,U0);function Rv(e){const[t,n]=N.useState(()=>e.getLocalParticipant()),[r,i]=N.useState(()=>e.getMicrophoneTrack());return N.useEffect(()=>{const o=()=>{const a=e.getLocalParticipant(),l=e.getMicrophoneTrack();console.log("🎤 useVoxketLocalParticipant: Updating state:",{hasParticipant:!!a,hasMicTrack:!!l,isMicEnabled:e.isMicrophoneEnabled,trackPublications:a?a.trackPublications.size:0}),n(a),i(l)};o(),e.on("connection.connected",o),e.on("connection.disconnected",o),e.on("track.muted",o),e.on("track.unmuted",o);const s=e.getRoom();if(s){const a=()=>{console.log("🎤 Track published, updating participant state"),o()},l=()=>{console.log("🎤 Track unpublished, updating participant state"),o()};return s.on("localTrackPublished",a),s.on("localTrackUnpublished",l),()=>{e.off("connection.connected",o),e.off("connection.disconnected",o),e.off("track.muted",o),e.off("track.unmuted",o),s.off("localTrackPublished",a),s.off("localTrackUnpublished",l)}}else return()=>{e.off("connection.connected",o),e.off("connection.disconnected",o),e.off("track.muted",o),e.off("track.unmuted",o)}},[e]),{localParticipant:t,microphoneTrack:r}}function oo(e,t,n){const[r,i]=N.useState(!1),[o,s]=N.useState(!1);return N.useEffect(()=>{const l=()=>{let c=!1;switch(t){case"microphone":c=e.isMicrophoneEnabled;break;case"camera":c=e.isCameraEnabled;break;case"screenShare":c=e.isScreenShareEnabled;break}console.log(`🎬 useVoxketTrackToggle: ${t} enabled state updated:`,{oldEnabled:r,newEnabled:c,changed:r!==c}),i(c)};return l(),e.on("track.muted",l),e.on("track.unmuted",l),e.on("connection.connected",l),()=>{e.off("track.muted",l),e.off("track.unmuted",l),e.off("connection.connected",l)}},[e,t]),{enabled:r,pending:o,toggle:async l=>{try{s(!0);const c=l!==void 0?l:!r;switch(console.log(`🎬 useVoxketTrackToggle: ${t} toggle called`,{currentEnabled:r,targetEnabled:c,forceEnabled:l}),t){case"microphone":await e.toggleMicrophone(c);break;case"camera":await e.toggleCamera(c);break;case"screenShare":c?(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(c){console.error(`🎬 useVoxketTrackToggle: ${t} toggle failed:`,c)}finally{s(!1)}}}}function Iv(e){const[t,n]=N.useState(()=>e.getRoom()),[r,i]=N.useState(()=>e.getConnectionState());return N.useEffect(()=>{const o=()=>{n(e.getRoom()),i(e.getConnectionState())};return e.on("connection.connected",o),e.on("connection.disconnected",o),e.on("connection.connecting",o),()=>{e.off("connection.connected",o),e.off("connection.disconnected",o),e.off("connection.connecting",o)}},[e]),t}function kl(e){const[t,n]=N.useState(()=>e.getIsAgentConnected()),[r,i]=N.useState(()=>e.getCurrentSession()),[o,s]=N.useState(()=>e.getCurrentAgentInfo()),[a,l]=N.useState(()=>e.getAgentState()),[c,u]=N.useState(()=>e.getAgentAudioTrack()),[d,f]=N.useState(()=>e.getAgentVideoTrack());return N.useEffect(()=>{const p=()=>{const C=e.getIsAgentConnected(),k=e.getCurrentSession(),_=e.getCurrentAgentInfo(),R=e.getAgentState(),A=e.getAgentAudioTrack(),O=e.getAgentVideoTrack();console.log("🤖 useVoxketVoiceAssistant: Updating state:",{isAgentConnected:C,hasSession:!!k,sessionId:k==null?void 0:k.id,sessionState:k==null?void 0:k.state,hasAgentInfo:!!_,agentState:R,hasAudioTrack:!!A,hasVideoTrack:!!O}),n(C),i(k),s(_),l(R),u(A),f(O)};p();const g=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent connected event"),p()},m=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent disconnected event"),p()},v=()=>{console.log("🤖 useVoxketVoiceAssistant: Session changed event"),p()},y=()=>{console.log("🤖 useVoxketVoiceAssistant: Connection changed event"),p()},E=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent state changed event"),p()},w=()=>{console.log("🎵 useVoxketVoiceAssistant: Track subscribed event - updating audio/video tracks"),p()};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",m),e.on("session.created",v),e.on("session.ended",v),e.on("session.state.changed",v),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",m),e.off("session.created",v),e.off("session.ended",v),e.off("session.state.changed",v),e.off("connection.connected",y),e.off("media.track.subscribed",w),e.off("media.track.unsubscribed",w)}},[e]),{agent:{isActive:t,info:o},session:r,state:a,audioTrack:c,videoTrack:d}}function Ov(e){const[t,n]=N.useState(()=>e.getVideoTrackRefs()),[r,i]=N.useState(()=>e.getCameraTrackRefs()),[o,s]=N.useState(()=>e.getScreenShareTrackRefs());return N.useEffect(()=>{const a=()=>{const c=e.getVideoTrackRefs(),u=e.getCameraTrackRefs(),d=e.getScreenShareTrackRefs();console.log("📹 useVoxketVideoTracks: Updating tracks:",{videoCount:c.length,cameraCount:u.length,screenShareCount:d.length}),n(c),i(u),s(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 l=e.getRoom();if(l){const c=()=>{console.log("📹 Track event, updating video tracks"),a()};return l.on("localTrackPublished",c),l.on("localTrackUnpublished",c),l.on("trackPublished",c),l.on("trackUnpublished",c),l.on("trackSubscribed",c),l.on("trackUnsubscribed",c),()=>{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),l.off("localTrackPublished",c),l.off("localTrackUnpublished",c),l.off("trackPublished",c),l.off("trackUnpublished",c),l.off("trackSubscribed",c),l.off("trackUnsubscribed",c)}}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:r,screenShareTrackRefs:o}}const Cl="-",Pv=e=>{const t=Lv(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:s=>{const a=s.split(Cl);return a[0]===""&&a.length!==1&&a.shift(),Qh(a,t)||Dv(s)},getConflictingClassGroupIds:(s,a)=>{const l=n[s]||[];return a&&r[s]?[...l,...r[s]]:l}}},Qh=(e,t)=>{var s;if(e.length===0)return t.classGroupId;const n=e[0],r=t.nextPart.get(n),i=r?Qh(e.slice(1),r):void 0;if(i)return i;if(t.validators.length===0)return;const o=e.join(Cl);return(s=t.validators.find(({validator:a})=>a(o)))==null?void 0:s.classGroupId},Ru=/^\[(.+)\]$/,Dv=e=>{if(Ru.test(e)){const t=Ru.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},Lv=e=>{const{theme:t,classGroups:n}=e,r={nextPart:new Map,validators:[]};for(const i in n)Sa(n[i],r,i,t);return r},Sa=(e,t,n,r)=>{e.forEach(i=>{if(typeof i=="string"){const o=i===""?t:Iu(t,i);o.classGroupId=n;return}if(typeof i=="function"){if(Fv(i)){Sa(i(r),t,n,r);return}t.validators.push({validator:i,classGroupId:n});return}Object.entries(i).forEach(([o,s])=>{Sa(s,Iu(t,o),n,r)})})},Iu=(e,t)=>{let n=e;return t.split(Cl).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},Fv=e=>e.isThemeGetter,jv=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;const i=(o,s)=>{n.set(o,s),t++,t>e&&(t=0,r=n,n=new Map)};return{get(o){let s=n.get(o);if(s!==void 0)return s;if((s=r.get(o))!==void 0)return i(o,s),s},set(o,s){n.has(o)?n.set(o,s):i(o,s)}}},ka="!",Ca=":",Bv=Ca.length,$v=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const o=[];let s=0,a=0,l=0,c;for(let g=0;g<i.length;g++){let m=i[g];if(s===0&&a===0){if(m===Ca){o.push(i.slice(l,g)),l=g+Bv;continue}if(m==="/"){c=g;continue}}m==="["?s++:m==="]"?s--:m==="("?a++:m===")"&&a--}const u=o.length===0?i:i.substring(l),d=Vv(u),f=d!==u,p=c&&c>l?c-l:void 0;return{modifiers:o,hasImportantModifier:f,baseClassName:d,maybePostfixModifierPosition:p}};if(t){const i=t+Ca,o=r;r=s=>s.startsWith(i)?o(s.substring(i.length)):{isExternal:!0,modifiers:[],hasImportantModifier:!1,baseClassName:s,maybePostfixModifierPosition:void 0}}if(n){const i=r;r=o=>n({className:o,parseClassName:i})}return r},Vv=e=>e.endsWith(ka)?e.substring(0,e.length-1):e.startsWith(ka)?e.substring(1):e,zv=e=>{const t=Object.fromEntries(e.orderSensitiveModifiers.map(r=>[r,!0]));return r=>{if(r.length<=1)return r;const i=[];let o=[];return r.forEach(s=>{s[0]==="["||t[s]?(i.push(...o.sort(),s),o=[]):o.push(s)}),i.push(...o.sort()),i}},Uv=e=>({cache:jv(e.cacheSize),parseClassName:$v(e),sortModifiers:zv(e),...Pv(e)}),Hv=/\s+/,Wv=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:o}=t,s=[],a=e.trim().split(Hv);let l="";for(let c=a.length-1;c>=0;c-=1){const u=a[c],{isExternal:d,modifiers:f,hasImportantModifier:p,baseClassName:g,maybePostfixModifierPosition:m}=n(u);if(d){l=u+(l.length>0?" "+l:l);continue}let v=!!m,y=r(v?g.substring(0,m):g);if(!y){if(!v){l=u+(l.length>0?" "+l:l);continue}if(y=r(g),!y){l=u+(l.length>0?" "+l:l);continue}v=!1}const E=o(f).join(":"),w=p?E+ka:E,C=w+y;if(s.includes(C))continue;s.push(C);const k=i(y,v);for(let _=0;_<k.length;++_){const R=k[_];s.push(w+R)}l=u+(l.length>0?" "+l:l)}return l};function Gv(){let e=0,t,n,r="";for(;e<arguments.length;)(t=arguments[e++])&&(n=Jh(t))&&(r&&(r+=" "),r+=n);return r}const Jh=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Jh(e[r]))&&(n&&(n+=" "),n+=t);return n};function Kv(e,...t){let n,r,i,o=s;function s(l){const c=t.reduce((u,d)=>d(u),e());return n=Uv(c),r=n.cache.get,i=n.cache.set,o=a,a(l)}function a(l){const c=r(l);if(c)return c;const u=Wv(l,n);return i(l,u),u}return function(){return o(Gv.apply(null,arguments))}}const Et=e=>{const t=n=>n[e]||[];return t.isThemeGetter=!0,t},ep=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,tp=/^\((?:(\w[\w-]*):)?(.+)\)$/i,qv=/^\d+\/\d+$/,Yv=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Zv=/\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$/,Xv=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Qv=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Jv=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,or=e=>qv.test(e),Pe=e=>!!e&&!Number.isNaN(Number(e)),An=e=>!!e&&Number.isInteger(Number(e)),vs=e=>e.endsWith("%")&&Pe(e.slice(0,-1)),yn=e=>Yv.test(e),ew=()=>!0,tw=e=>Zv.test(e)&&!Xv.test(e),np=()=>!1,nw=e=>Qv.test(e),rw=e=>Jv.test(e),iw=e=>!fe(e)&&!he(e),ow=e=>Dr(e,op,np),fe=e=>ep.test(e),Hn=e=>Dr(e,sp,tw),ws=e=>Dr(e,uw,Pe),Ou=e=>Dr(e,rp,np),sw=e=>Dr(e,ip,rw),ji=e=>Dr(e,ap,nw),he=e=>tp.test(e),zr=e=>Lr(e,sp),aw=e=>Lr(e,dw),Pu=e=>Lr(e,rp),lw=e=>Lr(e,op),cw=e=>Lr(e,ip),Bi=e=>Lr(e,ap,!0),Dr=(e,t,n)=>{const r=ep.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Lr=(e,t,n=!1)=>{const r=tp.exec(e);return r?r[1]?t(r[1]):n:!1},rp=e=>e==="position"||e==="percentage",ip=e=>e==="image"||e==="url",op=e=>e==="length"||e==="size"||e==="bg-size",sp=e=>e==="length",uw=e=>e==="number",dw=e=>e==="family-name",ap=e=>e==="shadow",fw=()=>{const e=Et("color"),t=Et("font"),n=Et("text"),r=Et("font-weight"),i=Et("tracking"),o=Et("leading"),s=Et("breakpoint"),a=Et("container"),l=Et("spacing"),c=Et("radius"),u=Et("shadow"),d=Et("inset-shadow"),f=Et("text-shadow"),p=Et("drop-shadow"),g=Et("blur"),m=Et("perspective"),v=Et("aspect"),y=Et("ease"),E=Et("animate"),w=()=>["auto","avoid","all","avoid-page","page","left","right","column"],C=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],k=()=>[...C(),he,fe],_=()=>["auto","hidden","clip","visible","scroll"],R=()=>["auto","contain","none"],A=()=>[he,fe,l],O=()=>[or,"full","auto",...A()],b=()=>[An,"none","subgrid",he,fe],M=()=>["auto",{span:["full",An,he,fe]},An,he,fe],I=()=>[An,"auto",he,fe],F=()=>["auto","min","max","fr",he,fe],D=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],G=()=>["start","end","center","stretch","center-safe","end-safe"],re=()=>["auto",...A()],X=()=>[or,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...A()],$=()=>[e,he,fe],z=()=>[...C(),Pu,Ou,{position:[he,fe]}],x=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",lw,ow,{size:[he,fe]}],K=()=>[vs,zr,Hn],S=()=>["","none","full",c,he,fe],Y=()=>["",Pe,zr,Hn],te=()=>["solid","dashed","dotted","double"],j=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],q=()=>[Pe,vs,Pu,Ou],W=()=>["","none",g,he,fe],ue=()=>["none",Pe,he,fe],Q=()=>["none",Pe,he,fe],ve=()=>[Pe,he,fe],L=()=>[or,"full",...A()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[yn],breakpoint:[yn],color:[ew],container:[yn],"drop-shadow":[yn],ease:["in","out","in-out"],font:[iw],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[yn],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[yn],shadow:[yn],spacing:["px",Pe],text:[yn],"text-shadow":[yn],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",or,fe,he,v]}],container:["container"],columns:[{columns:[Pe,fe,he,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:k()}],overflow:[{overflow:_()}],"overflow-x":[{"overflow-x":_()}],"overflow-y":[{"overflow-y":_()}],overscroll:[{overscroll:R()}],"overscroll-x":[{"overscroll-x":R()}],"overscroll-y":[{"overscroll-y":R()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:O()}],"inset-x":[{"inset-x":O()}],"inset-y":[{"inset-y":O()}],start:[{start:O()}],end:[{end:O()}],top:[{top:O()}],right:[{right:O()}],bottom:[{bottom:O()}],left:[{left:O()}],visibility:["visible","invisible","collapse"],z:[{z:[An,"auto",he,fe]}],basis:[{basis:[or,"full","auto",a,...A()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Pe,or,"auto","initial","none",fe]}],grow:[{grow:["",Pe,he,fe]}],shrink:[{shrink:["",Pe,he,fe]}],order:[{order:[An,"first","last","none",he,fe]}],"grid-cols":[{"grid-cols":b()}],"col-start-end":[{col:M()}],"col-start":[{"col-start":I()}],"col-end":[{"col-end":I()}],"grid-rows":[{"grid-rows":b()}],"row-start-end":[{row:M()}],"row-start":[{"row-start":I()}],"row-end":[{"row-end":I()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":F()}],"auto-rows":[{"auto-rows":F()}],gap:[{gap:A()}],"gap-x":[{"gap-x":A()}],"gap-y":[{"gap-y":A()}],"justify-content":[{justify:[...D(),"normal"]}],"justify-items":[{"justify-items":[...G(),"normal"]}],"justify-self":[{"justify-self":["auto",...G()]}],"align-content":[{content:["normal",...D()]}],"align-items":[{items:[...G(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...G(),{baseline:["","last"]}]}],"place-content":[{"place-content":D()}],"place-items":[{"place-items":[...G(),"baseline"]}],"place-self":[{"place-self":["auto",...G()]}],p:[{p:A()}],px:[{px:A()}],py:[{py:A()}],ps:[{ps:A()}],pe:[{pe:A()}],pt:[{pt:A()}],pr:[{pr:A()}],pb:[{pb:A()}],pl:[{pl:A()}],m:[{m:re()}],mx:[{mx:re()}],my:[{my:re()}],ms:[{ms:re()}],me:[{me:re()}],mt:[{mt:re()}],mr:[{mr:re()}],mb:[{mb:re()}],ml:[{ml:re()}],"space-x":[{"space-x":A()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":A()}],"space-y-reverse":["space-y-reverse"],size:[{size:X()}],w:[{w:[a,"screen",...X()]}],"min-w":[{"min-w":[a,"screen","none",...X()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...X()]}],h:[{h:["screen","lh",...X()]}],"min-h":[{"min-h":["screen","lh","none",...X()]}],"max-h":[{"max-h":["screen","lh",...X()]}],"font-size":[{text:["base",n,zr,Hn]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,he,ws]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",vs,fe]}],"font-family":[{font:[aw,fe,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:[i,he,fe]}],"line-clamp":[{"line-clamp":[Pe,"none",he,ws]}],leading:[{leading:[o,...A()]}],"list-image":[{"list-image":["none",he,fe]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",he,fe]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:$()}],"text-color":[{text:$()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...te(),"wavy"]}],"text-decoration-thickness":[{decoration:[Pe,"from-font","auto",he,Hn]}],"text-decoration-color":[{decoration:$()}],"underline-offset":[{"underline-offset":[Pe,"auto",he,fe]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:A()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",he,fe]}],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",he,fe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:z()}],"bg-repeat":[{bg:x()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},An,he,fe],radial:["",he,fe],conic:[An,he,fe]},cw,sw]}],"bg-color":[{bg:$()}],"gradient-from-pos":[{from:K()}],"gradient-via-pos":[{via:K()}],"gradient-to-pos":[{to:K()}],"gradient-from":[{from:$()}],"gradient-via":[{via:$()}],"gradient-to":[{to:$()}],rounded:[{rounded:S()}],"rounded-s":[{"rounded-s":S()}],"rounded-e":[{"rounded-e":S()}],"rounded-t":[{"rounded-t":S()}],"rounded-r":[{"rounded-r":S()}],"rounded-b":[{"rounded-b":S()}],"rounded-l":[{"rounded-l":S()}],"rounded-ss":[{"rounded-ss":S()}],"rounded-se":[{"rounded-se":S()}],"rounded-ee":[{"rounded-ee":S()}],"rounded-es":[{"rounded-es":S()}],"rounded-tl":[{"rounded-tl":S()}],"rounded-tr":[{"rounded-tr":S()}],"rounded-br":[{"rounded-br":S()}],"rounded-bl":[{"rounded-bl":S()}],"border-w":[{border:Y()}],"border-w-x":[{"border-x":Y()}],"border-w-y":[{"border-y":Y()}],"border-w-s":[{"border-s":Y()}],"border-w-e":[{"border-e":Y()}],"border-w-t":[{"border-t":Y()}],"border-w-r":[{"border-r":Y()}],"border-w-b":[{"border-b":Y()}],"border-w-l":[{"border-l":Y()}],"divide-x":[{"divide-x":Y()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Y()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...te(),"hidden","none"]}],"divide-style":[{divide:[...te(),"hidden","none"]}],"border-color":[{border:$()}],"border-color-x":[{"border-x":$()}],"border-color-y":[{"border-y":$()}],"border-color-s":[{"border-s":$()}],"border-color-e":[{"border-e":$()}],"border-color-t":[{"border-t":$()}],"border-color-r":[{"border-r":$()}],"border-color-b":[{"border-b":$()}],"border-color-l":[{"border-l":$()}],"divide-color":[{divide:$()}],"outline-style":[{outline:[...te(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Pe,he,fe]}],"outline-w":[{outline:["",Pe,zr,Hn]}],"outline-color":[{outline:$()}],shadow:[{shadow:["","none",u,Bi,ji]}],"shadow-color":[{shadow:$()}],"inset-shadow":[{"inset-shadow":["none",d,Bi,ji]}],"inset-shadow-color":[{"inset-shadow":$()}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:$()}],"ring-offset-w":[{"ring-offset":[Pe,Hn]}],"ring-offset-color":[{"ring-offset":$()}],"inset-ring-w":[{"inset-ring":Y()}],"inset-ring-color":[{"inset-ring":$()}],"text-shadow":[{"text-shadow":["none",f,Bi,ji]}],"text-shadow-color":[{"text-shadow":$()}],opacity:[{opacity:[Pe,he,fe]}],"mix-blend":[{"mix-blend":[...j(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":j()}],"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":[Pe]}],"mask-image-linear-from-pos":[{"mask-linear-from":q()}],"mask-image-linear-to-pos":[{"mask-linear-to":q()}],"mask-image-linear-from-color":[{"mask-linear-from":$()}],"mask-image-linear-to-color":[{"mask-linear-to":$()}],"mask-image-t-from-pos":[{"mask-t-from":q()}],"mask-image-t-to-pos":[{"mask-t-to":q()}],"mask-image-t-from-color":[{"mask-t-from":$()}],"mask-image-t-to-color":[{"mask-t-to":$()}],"mask-image-r-from-pos":[{"mask-r-from":q()}],"mask-image-r-to-pos":[{"mask-r-to":q()}],"mask-image-r-from-color":[{"mask-r-from":$()}],"mask-image-r-to-color":[{"mask-r-to":$()}],"mask-image-b-from-pos":[{"mask-b-from":q()}],"mask-image-b-to-pos":[{"mask-b-to":q()}],"mask-image-b-from-color":[{"mask-b-from":$()}],"mask-image-b-to-color":[{"mask-b-to":$()}],"mask-image-l-from-pos":[{"mask-l-from":q()}],"mask-image-l-to-pos":[{"mask-l-to":q()}],"mask-image-l-from-color":[{"mask-l-from":$()}],"mask-image-l-to-color":[{"mask-l-to":$()}],"mask-image-x-from-pos":[{"mask-x-from":q()}],"mask-image-x-to-pos":[{"mask-x-to":q()}],"mask-image-x-from-color":[{"mask-x-from":$()}],"mask-image-x-to-color":[{"mask-x-to":$()}],"mask-image-y-from-pos":[{"mask-y-from":q()}],"mask-image-y-to-pos":[{"mask-y-to":q()}],"mask-image-y-from-color":[{"mask-y-from":$()}],"mask-image-y-to-color":[{"mask-y-to":$()}],"mask-image-radial":[{"mask-radial":[he,fe]}],"mask-image-radial-from-pos":[{"mask-radial-from":q()}],"mask-image-radial-to-pos":[{"mask-radial-to":q()}],"mask-image-radial-from-color":[{"mask-radial-from":$()}],"mask-image-radial-to-color":[{"mask-radial-to":$()}],"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":C()}],"mask-image-conic-pos":[{"mask-conic":[Pe]}],"mask-image-conic-from-pos":[{"mask-conic-from":q()}],"mask-image-conic-to-pos":[{"mask-conic-to":q()}],"mask-image-conic-from-color":[{"mask-conic-from":$()}],"mask-image-conic-to-color":[{"mask-conic-to":$()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:x()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",he,fe]}],filter:[{filter:["","none",he,fe]}],blur:[{blur:W()}],brightness:[{brightness:[Pe,he,fe]}],contrast:[{contrast:[Pe,he,fe]}],"drop-shadow":[{"drop-shadow":["","none",p,Bi,ji]}],"drop-shadow-color":[{"drop-shadow":$()}],grayscale:[{grayscale:["",Pe,he,fe]}],"hue-rotate":[{"hue-rotate":[Pe,he,fe]}],invert:[{invert:["",Pe,he,fe]}],saturate:[{saturate:[Pe,he,fe]}],sepia:[{sepia:["",Pe,he,fe]}],"backdrop-filter":[{"backdrop-filter":["","none",he,fe]}],"backdrop-blur":[{"backdrop-blur":W()}],"backdrop-brightness":[{"backdrop-brightness":[Pe,he,fe]}],"backdrop-contrast":[{"backdrop-contrast":[Pe,he,fe]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Pe,he,fe]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Pe,he,fe]}],"backdrop-invert":[{"backdrop-invert":["",Pe,he,fe]}],"backdrop-opacity":[{"backdrop-opacity":[Pe,he,fe]}],"backdrop-saturate":[{"backdrop-saturate":[Pe,he,fe]}],"backdrop-sepia":[{"backdrop-sepia":["",Pe,he,fe]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":A()}],"border-spacing-x":[{"border-spacing-x":A()}],"border-spacing-y":[{"border-spacing-y":A()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",he,fe]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Pe,"initial",he,fe]}],ease:[{ease:["linear","initial",y,he,fe]}],delay:[{delay:[Pe,he,fe]}],animate:[{animate:["none",E,he,fe]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[m,he,fe]}],"perspective-origin":[{"perspective-origin":k()}],rotate:[{rotate:ue()}],"rotate-x":[{"rotate-x":ue()}],"rotate-y":[{"rotate-y":ue()}],"rotate-z":[{"rotate-z":ue()}],scale:[{scale:Q()}],"scale-x":[{"scale-x":Q()}],"scale-y":[{"scale-y":Q()}],"scale-z":[{"scale-z":Q()}],"scale-3d":["scale-3d"],skew:[{skew:ve()}],"skew-x":[{"skew-x":ve()}],"skew-y":[{"skew-y":ve()}],transform:[{transform:[he,fe,"","none","gpu","cpu"]}],"transform-origin":[{origin:k()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:L()}],"translate-x":[{"translate-x":L()}],"translate-y":[{"translate-y":L()}],"translate-z":[{"translate-z":L()}],"translate-none":["translate-none"],accent:[{accent:$()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:$()}],"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",he,fe]}],"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":A()}],"scroll-mx":[{"scroll-mx":A()}],"scroll-my":[{"scroll-my":A()}],"scroll-ms":[{"scroll-ms":A()}],"scroll-me":[{"scroll-me":A()}],"scroll-mt":[{"scroll-mt":A()}],"scroll-mr":[{"scroll-mr":A()}],"scroll-mb":[{"scroll-mb":A()}],"scroll-ml":[{"scroll-ml":A()}],"scroll-p":[{"scroll-p":A()}],"scroll-px":[{"scroll-px":A()}],"scroll-py":[{"scroll-py":A()}],"scroll-ps":[{"scroll-ps":A()}],"scroll-pe":[{"scroll-pe":A()}],"scroll-pt":[{"scroll-pt":A()}],"scroll-pr":[{"scroll-pr":A()}],"scroll-pb":[{"scroll-pb":A()}],"scroll-pl":[{"scroll-pl":A()}],"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",he,fe]}],fill:[{fill:["none",...$()]}],"stroke-w":[{stroke:[Pe,zr,Hn,ws]}],stroke:[{stroke:["none",...$()]}],"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"]}},hw=Kv(fw);function ze(...e){return hw(Ua.clsx(e))}function Io(e){var i;if(!e)return{sessionSettings:{},capabilities:{},modality:"voice"};const t={session_timer:((i=e.session_settings)==null?void 0:i.session_timer)||null},n=e.capabilities||{},r=e.modality||"voice";return{sessionSettings:t,capabilities:n,modality:r}}function pw(e,t){return e.capabilities[t]===!0}function Oo(e){return e.sessionSettings.session_timer||null}function lp(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 cp(e){const t=e.capabilities;return{suggestedReplyEnabled:t.suggested_reply_enabled!==!1,attachmentsEnabled:t.support_in_chat_attachments!==!1}}function up(e){return{...e.capabilities}}function dp(e){const t=Math.floor(e/60),n=e%60;return`${t}:${n.toString().padStart(2,"0")}`}const fp=N.forwardRef(({state:e,audioTrack:t,className:n,theme:r="vox"},i)=>{var c,u,d,f,p;const o=N.useRef(null),[s,a]=N.useState(!1);N.useEffect(()=>{o.current&&(console.log("🔊 AgentTile: Audio element created:",{autoplay:o.current.autoplay,muted:o.current.muted,volume:o.current.volume,readyState:o.current.readyState,paused:o.current.paused}),a(!0))},[t]),N.useEffect(()=>{const g=o.current;if(!g)return;const m=()=>console.log("▶️ AgentTile: Audio started playing"),v=()=>console.log("⏸️ AgentTile: Audio paused"),y=()=>console.log("⏹️ AgentTile: Audio ended"),E=k=>console.error("❌ AgentTile: Audio error:",k),w=()=>console.log("⏳ AgentTile: Audio load started"),C=()=>console.log("✅ AgentTile: Audio can play");return g.addEventListener("play",m),g.addEventListener("pause",v),g.addEventListener("ended",y),g.addEventListener("error",E),g.addEventListener("loadstart",w),g.addEventListener("canplay",C),()=>{g.removeEventListener("play",m),g.removeEventListener("pause",v),g.removeEventListener("ended",y),g.removeEventListener("error",E),g.removeEventListener("loadstart",w),g.removeEventListener("canplay",C)}},[s]),console.log("🎤 AgentTile render:",{state:e,hasAudioTrack:!!t,trackSource:t==null?void 0:t.source,participantId:(c=t==null?void 0:t.participant)==null?void 0:c.identity,publicationMuted:(u=t==null?void 0:t.publication)==null?void 0:u.isMuted,audioElementReady:s,trackMediaStreamTrack:(p=(f=(d=t==null?void 0:t.publication)==null?void 0:d.track)==null?void 0:f.mediaStreamTrack)==null?void 0:p.readyState});const l=N.useMemo(()=>r==="light"?{base:"bg-black/90",highlighted:"bg-black",muted:"bg-black/30"}:{base:"bg-white/90",highlighted:"bg-white",muted:"bg-white/30"},[r]);return h.jsxs("div",{ref:i,className:ze("",n),children:[t&&h.jsxs(h.Fragment,{children:[h.jsx(Ot.AudioTrack,{ref:o,trackRef:t,volume:1}),h.jsx(Ot.BarVisualizer,{barCount:5,state:e,options:{minHeight:5},trackRef:t,className:ze("flex aspect-video w-40 items-center justify-center gap-1.5"),children:h.jsx("span",{className:ze([`${l.base} min-h-2 w-2 rounded-full`,"origin-center transition-colors duration-250 ease-linear",`data-[lk-highlighted=true]:${l.highlighted}`,`data-[lk-muted=true]:${l.muted}`])})})]}),!t&&h.jsx("div",{className:ze("flex aspect-video w-40 items-center justify-center"),children:h.jsx("div",{className:"flex flex-col items-center justify-center",children:h.jsx("div",{className:"flex gap-1.5",children:Array.from({length:5}).map((g,m)=>h.jsx("span",{className:ze([`${l.base} min-h-2 w-2 rounded-full`,"origin-center transition-colors duration-250 ease-linear",e==="speaking"&&`animate-pulse ${l.highlighted}`,e==="thinking"&&`animate-pulse ${l.muted}`])},m))})})})]})});fp.displayName="AgentTile";const mw=({videoTrack:e,className:t,ref:n})=>{var r,i;return!e||!e.publication||!e.participant?h.jsx("div",{ref:n,className:ze(t),children:h.jsx("div",{className:"w-full h-full bg-gray-200 rounded-md flex items-center justify-center",children:h.jsx("span",{className:"text-gray-500",children:"No video available"})})}):h.jsx("div",{ref:n,className:ze(t),children:h.jsx(Ot.VideoTrack,{trackRef:e,width:((r=e.publication.dimensions)==null?void 0:r.width)??0,height:((i=e.publication.dimensions)==null?void 0:i.height)??0,className:"rounded-md"})})},gw=P.forwardRef(function({trackRef:t,className:n,...r},i){var o,s;return h.jsx("div",{ref:i,className:ze("bg-muted overflow-hidden rounded-md",n),children:h.jsx(Ot.VideoTrack,{trackRef:t,width:((o=t==null?void 0:t.publication.dimensions)==null?void 0:o.width)??0,height:((s=t==null?void 0:t.publication.dimensions)==null?void 0:s.height)??0,className:ze("h-full w-auto"),...r})})}),Du=De.create(gw),bw=De.create(fp),yw=De.create(mw),xn={initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},exit:{opacity:0,scale:0},transition:{type:"spring",stiffness:675,damping:75,mass:1}},sr={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 xw(e,t){const{localParticipant:n}=Rv(t),r=n==null?void 0:n.getTrackPublication(e);return N.useMemo(()=>r&&n?{source:e,participant:n,publication:r}:void 0,[e,r,n])}function vw({chatOpen:e,client:t,theme:n="vox"}){const{agent:{isActive:r=!1}={},session:i,state:o="idle",audioTrack:s,videoTrack:a}=t?kl(t):{agent:{isActive:!1},session:null,state:"idle",audioTrack:null,videoTrack:null};console.log("🎨 MediaTiles render:",{chatOpen:e,isAgentActive:r,hasSession:!!i,sessionState:i==null?void 0:i.state,agentState:o,hasAudioTrack:!!s,hasVideoTrack:!!a});const[l]=Ot.useTracks([ae.Track.Source.ScreenShare]),c=xw(ae.Track.Source.Camera,t),u=c&&!c.publication.isMuted,d=l&&!l.publication.isMuted,f=u||d,p=r||i&&i.state==="active",g={...xn.transition,delay:e?0:.15},m={...xn.animate,scale:e?1:3,transition:g},v={...xn.animate,transition:g},y=g,E=g,w=a&&a.publication&&a.participant;return h.jsx("div",{className:"relative w-full h-full z-10 flex items-center justify-center",children:h.jsx("div",{className:"relative w-full h-full max-w-2xl px-4 md:px-0",children:h.jsxs("div",{className:ze(sr.grid),children:[p&&h.jsx("div",{className:ze(["grid",!e&&sr.agentChatClosed,e&&f&&sr.agentChatOpenWithSecondTile,e&&!f&&sr.agentChatOpenWithoutSecondTile]),children:h.jsxs("div",{className:"h-full flex items-center justify-center",children:[!w&&h.jsx(bw,{layoutId:"agent",...xn,animate:m,transition:y,state:o,audioTrack:s||void 0,theme:n,className:ze(e?"h-[90px]":"h-auto w-full")},"agent"),w&&a&&h.jsx(yw,{layoutId:"avatar",...xn,animate:v,transition:E,videoTrack:a,className:ze(e?"h-[90px] [&>video]:h-[90px] [&>video]:w-auto":"h-auto w-full")},"avatar")]})}),h.jsx("div",{className:ze(["grid",e&&sr.secondTileChatOpen,!e&&sr.secondTileChatClosed]),children:h.jsxs("div",{className:"w-full px-10 flex items-center shadow-2xl justify-between",children:[c&&u&&h.jsx(Du,{layout:"position",layoutId:"camera",...xn,trackRef:c,transition:{...xn.transition,delay:e?0:.15},className:"h-[60px] order-1"},"camera"),d&&h.jsx(Du,{layout:"position",layoutId:"screen",...xn,trackRef:l,transition:{...xn.transition,delay:e?0:.15},className:"h-[70px] order-2"},"screen")]})})]})})})}const ww={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-center 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"}},Ew={card:"text-gray-900 bg-gradient-to-b from-[#fafafa] via-[#ffffff] to-[#fafafa] border border-gray-200/80 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-white/90 via-white/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(59,130,246,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-blue-400/[0.12] via-purple-400/[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-pink-400/[0.08] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-b from-[#fafafa] via-[#ffffff] to-[#fafafa] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-gray-900 font-semibold",secondary:"text-gray-800",muted:"text-gray-600",accent:"text-transparent bg-clip-text bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600"},micButton:"relative w-20 h-20 bg-gradient-to-br from-blue-600 to-blue-700 backdrop-blur-xl border-2 border-blue-500/50 rounded-3xl flex items-center justify-center hover:from-blue-700 hover:to-blue-800 hover:border-blue-500 hover:scale-105 hover:shadow-2xl hover:shadow-blue-500/30 transition-all duration-500 ease-out group overflow-hidden text-white",chatButton:"relative w-20 h-20 bg-black/90 backdrop-blur-xl border-2 border-black/80 rounded-3xl flex items-center justify-center hover:bg-black hover:border-black hover:scale-105 hover:shadow-2xl hover:shadow-green-500/30 transition-all duration-500 ease-out group overflow-hidden text-white",videoButton:"relative w-20 h-20 bg-black/90 backdrop-blur-xl border-2 border-black/80 rounded-3xl flex items-center justify-center hover:bg-black hover:border-black hover:scale-105 hover:shadow-2xl hover:shadow-purple-500/30 transition-all duration-500 ease-out group overflow-hidden text-white",popupTrigger:"bg-black/90 backdrop-blur-xl border-2 border-black/80 text-white font-bold hover:bg-black hover:border-black hover:scale-[1.02] hover:shadow-2xl hover:shadow-blue-500/30 focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2 focus:ring-offset-white transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-white/60 backdrop-blur-xl rounded-2xl text-center text-gray-900 text-sm font-medium transition-all duration-700 ease-in-out border border-gray-300/80 ",statusIndicator:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse shadow-lg shadow-green-500/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-gray-300/80 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-gray-300/80 shadow-xl",textarea:"bg-white/60 border border-gray-300/50 rounded-xl text-gray-900 placeholder-gray-500 font-medium px-4 py-3",sendButton:"bg-white/90 hover:bg-white border-2 border-gray-300/80 hover:border-gray-400 disabled:border-gray-200 disabled:opacity-40 text-gray-900 font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-blue-500/20",attachButton:"text-gray-600 hover:text-gray-900 hover:bg-gray-100/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-blue-50/70 text-gray-900 backdrop-blur-md shadow-lg border border-blue-200/80",other:"bg-white/60 text-gray-900 border border-gray-300/80 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-white/80 border-gray-300/80 backdrop-blur-xl shadow-xl",backButton:"text-gray-600 hover:text-gray-900 hover:bg-gray-100/50 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-blue-500 mb-2",suggestedResponse:{container:"bg-white/70 text-blue-700 border-gray-300/80 backdrop-blur-md hover:bg-white/80 hover:border-blue-300 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#fafafa] via-[#ffffff] to-[#fafafa] text-gray-900",header:"border-gray-300/80 bg-white/80 backdrop-blur-xl shadow-xl",headerButton:"bg-white/90 hover:bg-white border-2 border-gray-300/80 hover:border-gray-400 text-gray-900 hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-green-500 animate-pulse shadow-lg shadow-green-500/60",controlsBackground:"bg-gradient-to-t from-white via-white/90 to-white/60 backdrop-blur-xl border-t border-gray-300/80 shadow-2xl",controlEnabled:"bg-white/90 hover:bg-white border-2 border-gray-300/80 hover:border-gray-400 text-gray-900 hover:scale-105 hover:shadow-xl hover:shadow-blue-500/20 transition-all duration-300 font-semibold",controlDisabled:"bg-white/50 hover:bg-white/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/70 border border-gray-300/80 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-white/60 text-gray-700",avatar:"bg-gray-100/80 text-gray-700 border-2 border-gray-300/80",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"}},Sw={card:" text-white bg-black border border-white/[0.12] w-full h-full flex flex-col justify-between overflow-hidden relative shadow-[0_8px_32px_rgba(0,0,0,0.8),0_0_0_1px_rgba(255,255,255,0.06)_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-center 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"}},kw={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-center 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"}},Lu={dark:ww,light:Ew,vox:Sw,midnight:kw};function Lt(e){return Lu[e]||Lu.vox}function Fu({timeout:e}){const[t,n]=N.useState(100),r=N.useRef(null),i=N.useRef(null);return N.useEffect(()=>{if(!e||e<=0)return;n(100),i.current=Date.now();const o=()=>{if(!e||i.current===null)return;const s=Date.now()-i.current,a=Math.max(0,100-s/e*100);n(a),a>0&&(r.current=requestAnimationFrame(o))};return r.current=requestAnimationFrame(o),()=>{r.current&&cancelAnimationFrame(r.current)}},[e]),!e||e<=0?null:h.jsx("div",{className:"w-full h-1 relative top-1 rounded-t-4xl bg-gray-700 overflow-hidden",children:h.jsx(De.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 fi({interaction:e,theme:t,onDismiss:n,client:r,addLocalMessage:i}){var a;if(!e||!e.isVisible||!e.component)return null;const[o]=P.useState(()=>Date.now()),s=()=>e.component?P.createElement(e.component,{handler:e.handler||void 0,timeout:e.timeout,loadData:async c=>{console.log("InteractiveComponent: Loading data:",c)},presentationMode:e.presentationMode,data:e.data,client:r,addLocalMessage:i}):h.jsx("div",{className:"p-4 text-red-500",children:"Component not found"});switch(e.presentationMode){case"fullscreen":return h.jsx(Tr,{children:h.jsxs(De.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[9999] bg-black",children:[h.jsxs("div",{className:"flex flex-col",children:[h.jsx(Fu,{timeout:e.timeout}),h.jsxs("div",{className:"flex items-center justify-between p-4 bg-black/80 text-white border-b border-gray-700",children:[h.jsx("h3",{className:"text-lg font-semibold",children:e.methodName.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase())}),h.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:h.jsx(st.X,{className:"w-5 h-5"})})]})]}),h.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:s()})]})});case"embedded":default:return h.jsx(Tr,{children:h.jsx(De.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"w-fit rounded-lg ",children:h.jsxs("div",{children:[h.jsx(Fu,{timeout:e.timeout}),s()]})})})}}function hi({duration:e,theme:t="vox",onTimerExpired:n,className:r="",showIcon:i=!0}){const[o,s]=N.useState(e),[a,l]=N.useState(!1);N.useEffect(()=>{if(o<=0){l(!0),n==null||n();return}const u=setInterval(()=>{s(d=>{const f=d-1;return f<=0?(l(!0),n==null||n(),0):f})},1e3);return()=>clearInterval(u)},[o,n]),N.useEffect(()=>{s(e),l(!1)},[e]);const c=()=>a?"text-red-500":o<=60?"text-orange-500":o<=300?"text-yellow-500":t==="dark"?"text-gray-300":"text-gray-600";return h.jsxs("div",{className:`flex items-center gap-1 text-sm ${c()} ${r}`,children:[i&&h.jsx(st.Clock,{className:"w-4 h-4"}),h.jsx("span",{className:"font-mono",children:dp(o)}),a&&h.jsx("span",{className:"text-xs ml-1 text-red-500",children:"(Expired)"})]})}function Po({modality:e,theme:t,disabled:n=!1,showMicrophone:r=!1,microphoneEnabled:i=!0,microphoneLoading:o=!1,onToggleMicrophone:s,showCamera:a=!1,cameraEnabled:l=!0,cameraLoading:c=!1,onToggleCamera:u,showScreenShare:d=!1,screenShareEnabled:f=!1,screenShareLoading:p=!1,onToggleScreenShare:g,showChatToggle:m=!1,chatOpen:v=!1,onToggleChat:y,showTextInput:E=!1,textInputPlaceholder:w="Type a message...",onSendText:C,onSendAttachments:k,supportsAttachments:_=!1,showEndCall:R=!0,onEndCall:A}){var z;const O=Lt(t),[b,M]=N.useState(""),I=N.useRef(null),F=()=>{const x=b.trim();x&&C&&(C(x),M(""))},D=x=>{x.key==="Enter"&&!x.shiftKey&&(x.preventDefault(),F())},G=x=>{const B=Array.from(x.target.files||[]);B.length>0&&k&&k(B),I.current&&(I.current.value="")},re=ze("flex items-center gap-3 px-3 py-2 w-full backdrop-blur-xl border-t",E?"justify-between":"justify-center",t==="light"?"bg-white/95 border-gray-200":"bg-black/90 border-gray-800"),X=(x,B)=>{var K,S,Y;return B==="end-call"?ze("p-3 rounded-full transition-all duration-200",((K=O.video)==null?void 0:K.endCall)||"bg-red-500 text-white hover:bg-red-600",n?"opacity-50 cursor-not-allowed":"hover:scale-105"):ze("p-3 rounded-full transition-all duration-200",x?((S=O.video)==null?void 0:S.controlEnabled)||"bg-green-500 text-white":((Y=O.video)==null?void 0:Y.controlDisabled)||"bg-gray-500 text-white",n?"opacity-50 cursor-not-allowed":"hover:scale-105")},$=()=>h.jsx("div",{className:"w-5 h-5 animate-spin rounded-full border-2 border-current border-t-transparent"});return h.jsxs("div",{className:re,children:[E&&h.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[_&&k&&h.jsxs(h.Fragment,{children:[h.jsx("button",{onClick:()=>{var x;return(x=I.current)==null?void 0:x.click()},disabled:n,className:ze("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:h.jsx(st.Paperclip,{className:"w-5 h-5"})}),h.jsx("input",{ref:I,type:"file",multiple:!0,accept:"image/*",onChange:G,className:"hidden"})]}),h.jsx("input",{type:"text",value:b,onChange:x=>M(x.target.value),onKeyDown:D,disabled:n,placeholder:w,className:ze("flex-1 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")}),h.jsx("button",{onClick:F,disabled:n||!b.trim(),className:ze("p-2 rounded-full transition-all duration-200",b.trim()?((z=O.video)==null?void 0:z.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:h.jsx(st.SendHorizontal,{className:"w-5 h-5"})})]}),!E&&h.jsxs(h.Fragment,{children:[r&&s&&h.jsx("button",{onClick:s,disabled:n||o,className:X(i),title:i?"Mute microphone":"Unmute microphone",children:o?h.jsx($,{}):i?h.jsx(st.Mic,{className:"w-5 h-5"}):h.jsx(st.MicOff,{className:"w-5 h-5"})}),a&&u&&h.jsx("button",{onClick:u,disabled:n||c,className:X(l),title:l?"Turn off camera":"Turn on camera",children:c?h.jsx($,{}):l?h.jsx(st.Camera,{className:"w-5 h-5"}):h.jsx(st.CameraOff,{className:"w-5 h-5"})}),d&&g&&h.jsx("button",{onClick:g,disabled:n||p,className:X(f),title:f?"Stop screen share":"Share screen",children:p?h.jsx($,{}):h.jsx(st.Monitor,{className:"w-5 h-5"})}),m&&y&&h.jsx("button",{onClick:y,disabled:n,className:X(v),title:e==="voice"?v?"Hide transcription":"Show transcription":v?"Hide chat":"Show chat",children:h.jsx(st.MessageCircle,{className:"w-5 h-5"})})]}),R&&A&&h.jsx("button",{onClick:A,disabled:n,className:X(!1,"end-call"),title:"End call",children:h.jsx(st.PhoneOff,{className:"w-5 h-5"})})]})}Po.displayName="UnifiedControlBar";const Cw=({logLevel:e}={})=>{const t=Ot.useRoomContext();P.useEffect(()=>(ae.setLogLevel(e??"debug"),window.__lk_room=t,()=>{window.__lk_room=void 0}),[t,e])},hp=P.forwardRef((e,t)=>{const{alt:n,color:r="currentColor",size:i="1em",weight:o="regular",mirrored:s=!1,children:a,weights:l,...c}=e;return P.createElement("svg",{ref:t,xmlns:"http://www.w3.org/2000/svg",width:i,height:i,fill:r,viewBox:"0 0 256 256",transform:s?"scale(-1, 1)":void 0,...c},!!n&&P.createElement("title",null,n),a,l.get(o))});hp.displayName="SSRBase";const _w=new Map([["bold",P.createElement(P.Fragment,null,P.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",P.createElement(P.Fragment,null,P.createElement("path",{d:"M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z",opacity:"0.2"}),P.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",P.createElement(P.Fragment,null,P.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",P.createElement(P.Fragment,null,P.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",P.createElement(P.Fragment,null,P.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",P.createElement(P.Fragment,null,P.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"}))]]),_l=P.forwardRef((e,t)=>P.createElement(hp,{ref:t,...e,weights:_w}));_l.displayName="SpinnerIcon";function Tw({text:e,isComplete:t,isRealTimeStream:n=!1,speed:r=50}){const[i,o]=P.useState(""),[s,a]=P.useState(0);return P.useEffect(()=>{if(n){o(e);return}if(t){o(e);return}if(s<e.length){const l=setTimeout(()=>{o(e.slice(0,s+1)),a(s+1)},r);return()=>clearTimeout(l)}},[e,s,t,r,n]),P.useEffect(()=>{n||(a(0),o(""))},[e,n]),h.jsxs("span",{className:"relative",children:[h.jsx("span",{className:"inline-block",children:i}),!t&&h.jsx("span",{className:"inline-flex items-center ml-1",children:[0,1,2].map(l=>h.jsx(De.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:l*.2,ease:"easeInOut"}},l))})]})}function Nw(e,t){return e.startsWith("image/")?st.Image:e.startsWith("video/")?st.Video:e.startsWith("audio/")?st.Music:e.includes("zip")||e.includes("rar")||e.includes("archive")?st.Archive:st.FileText}function Aw(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+n[r]}function Mw({message:e,theme:t,isOwn:n}){const r=Lt(t),i=e.metadata,o=(i==null?void 0:i.fileName)||"Unknown file",s=(i==null?void 0:i.fileSize)||0,a=(i==null?void 0:i.mimeType)||"application/octet-stream",l=i==null?void 0:i.downloading,c=i==null?void 0:i.uploading,u=(i==null?void 0:i.downloadProgress)||0,d=(i==null?void 0:i.uploadProgress)||0,f=i==null?void 0:i.downloadUrl,p=i==null?void 0:i.file,g=Nw(a),m=l||c,v=l?u:d,y=l?"Downloading...":c?"Uploading...":"Complete",[E,w]=P.useState(null);P.useEffect(()=>{if(f)w(f);else if(p&&a.startsWith("image/")){const R=URL.createObjectURL(p);return w(R),()=>URL.revokeObjectURL(R)}else w(null)},[f,p,a]);const C=()=>{if(f){const R=document.createElement("a");R.href=f,R.download=o,R.click()}},_=a.startsWith("image/")&&E;return h.jsxs("div",{className:"flex flex-col gap-2 max-w-full sm:max-w-sm",children:[_&&h.jsxs("div",{className:"relative rounded-lg overflow-hidden",children:[h.jsx("img",{src:E,alt:o,className:"max-w-full h-auto max-h-48 object-cover rounded-lg cursor-pointer",onClick:C}),h.jsx("div",{className:"absolute inset-0 bg-black/0 hover:bg-black/10 transition-colors duration-200 cursor-pointer"})]}),h.jsxs("div",{className:`
10
10
  flex items-center gap-3 p-3 rounded-lg border transition-all duration-200
11
11
  ${t==="light"?"bg-gray-50 border-gray-200 hover:bg-gray-100":"bg-gray-800/50 border-gray-700 hover:bg-gray-700/50"}
12
12
  `,children:[h.jsx("div",{className:`
@@ -140,7 +140,7 @@ To suppress this warning, you need to explicitly provide the \`palette.${t}Chann
140
140
  ${n.promptSlider}
141
141
  ${s===r?"opacity-100 translate-y-0":"opacity-0 translate-y-4"}
142
142
  whitespace-pre-line break-words transition-all duration-700 ease-out
143
- `,style:{minHeight:"3rem",display:s===r?"flex":"none",alignItems:"center",justifyContent:"center"},children:h.jsx("span",{className:"italic",children:o})},s))})}const ig=N.forwardRef(({disabled:e,onStartCall:t,onStartChat:n,onStartVideo:r,prompts:i=['"Book a meeting with the marketing team"',`"What's the status of project Alpha?"`,`"Summarize yesterday's sales report"`,'"Find a good Italian restaurant nearby"','"Remind me to call John tomorrow at 10 AM"'],statusMessage:o="Agent is ready",title:s="Choose how to interact",subTitle:a="Ask me anything or give me a task to complete",theme:l="vox",modalities:c=["voice","chat","video"]},u)=>{const d=Lt(l),f=c.includes("voice"),p=c.includes("chat"),g=c.includes("video"),m=[f,p,g].filter(Boolean).length;return h.jsxs("div",{className:"flex flex-col items-center h-full justify-center w-full relative px-8 py-16","aria-disabled":e,style:{background:"transparent"},children:[h.jsx("div",{className:"absolute inset-0 opacity-[0.01] pointer-events-none mix-blend-overlay",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 400 400' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulance type='fractalNoise' baseFrequency='2' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E")`,backgroundRepeat:"repeat"}}),h.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] bg-gradient-radial from-white/[0.02] to-transparent blur-3xl pointer-events-none"}),h.jsxs("div",{className:"flex flex-col items-center justify-center w-full max-w-2xl space-y-12 z-10",children:[h.jsx("div",{className:"text-center space-y-2 max-w-md",children:h.jsx("p",{className:`text-base leading-relaxed tracking-wide ${d.text.secondary}`,children:a})}),h.jsx("div",{className:"flex items-center justify-center w-full",children:f&&p&&g?h.jsxs("div",{className:"flex gap-5 items-center justify-center",children:[h.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:t,children:[h.jsx(eo,{onClick:t,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Voice"})]}),h.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:n,children:[h.jsx(Qs,{onClick:n,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Chat"})]}),h.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:r||t,children:[h.jsx(Js,{onClick:r||t,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Video"})]})]}):m>1?h.jsxs("div",{className:"flex gap-6 items-center justify-center",children:[f&&h.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:t,children:[h.jsx(eo,{onClick:t,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Voice"})]}),p&&h.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:n,children:[h.jsx(Qs,{onClick:n,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Chat"})]}),g&&r&&h.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:r,children:[h.jsx(Js,{onClick:r,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Video"})]})]}):h.jsx("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",children:f?h.jsxs(h.Fragment,{children:[h.jsx(eo,{onClick:t,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Voice"})]}):p?h.jsxs(h.Fragment,{children:[h.jsx(Qs,{onClick:n,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Chat"})]}):g&&r?h.jsxs(h.Fragment,{children:[h.jsx(Js,{onClick:r,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Video"})]}):h.jsxs(h.Fragment,{children:[h.jsx(eo,{onClick:t,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Voice"})]})})}),h.jsx("div",{className:"w-full flex justify-center",children:h.jsx(BR,{prompts:i,theme:l})})]})]})});ig.displayName="Welcome";class nc extends P.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("VoxketWidget Error:",t,n)}render(){if(this.state.hasError){if(this.props.fallback){const t=this.props.fallback;return P.createElement(t,{error:this.state.error})}return P.createElement("div",{style:{padding:"20px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"}},"VoxketWidget encountered an error. Please check the console for details.")}return this.props.children}}const og=({onClick:e,position:t="bottom-right",size:n=64,className:r="",style:i,ariaLabel:o="Open Voxket",logoScale:s=.7,isRunning:a=!1,theme:l="vox"})=>{const c={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},u=l==="light"?"#3b82f6":"#000000",d={width:n,height:n,...i},f=P.useMemo(()=>{if(typeof window>"u"||!window.matchMedia)return!1;try{return window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}},[]);return h.jsxs("div",{className:"relative",children:[a&&h.jsxs(h.Fragment,{children:[h.jsx(De.div,{className:"absolute inset-0 rounded-full pointer-events-none",style:{width:n+24,height:n+24,left:-12,top:-12,background:"linear-gradient(45deg, rgba(6,182,212,0.3), rgba(34,211,238,0.3), rgba(6,182,212,0.3))",filter:"blur(8px)"},animate:f?void 0:{scale:[1,1.1,1],opacity:[.6,.9,.6]},transition:f?void 0:{duration:2,repeat:1/0,ease:"easeInOut"}}),h.jsx(De.div,{className:"absolute inset-0 rounded-full pointer-events-none",style:{width:n+16,height:n+16,left:-8,top:-8,background:"linear-gradient(135deg, rgba(6,182,212,0.4), rgba(34,211,238,0.4))",filter:"blur(4px)"},animate:f?void 0:{scale:[1,1.05,1],opacity:[.7,1,.7]},transition:f?void 0:{duration:1.5,repeat:1/0,ease:"easeInOut",delay:.2}})]}),h.jsxs(De.button,{type:"button",onClick:e,"aria-label":o,className:`fixed z-50 rounded-full flex items-center justify-center overflow-hidden focus:outline-none focus:ring-2 focus:ring-cyan-400/60 ${c[t]} ${r}`,style:{...d,backgroundColor:u,boxShadow:a?"0 0 0 2px rgba(6,182,212,0.5), 0 0 20px rgba(6,182,212,0.4), 0 8px 32px rgba(0,0,0,0.3)":l==="light"?"0 8px 32px rgba(59, 130, 246, 0.3)":"0 8px 32px rgba(0,0,0,0.3)",border:a?"2px solid rgba(6,182,212,0.6)":"none"},initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1,...a&&!f?{boxShadow:["0 0 0 2px rgba(6,182,212,0.5), 0 0 20px rgba(6,182,212,0.4), 0 8px 32px rgba(0,0,0,0.3)","0 0 0 2px rgba(6,182,212,0.8), 0 0 30px rgba(6,182,212,0.6), 0 8px 32px rgba(0,0,0,0.3)","0 0 0 2px rgba(6,182,212,0.5), 0 0 20px rgba(6,182,212,0.4), 0 8px 32px rgba(0,0,0,0.3)"]}:{}},exit:{scale:.9,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},"data-position":t,transition:{...!f&&a?{boxShadow:{duration:2,repeat:1/0,ease:"easeInOut"}}:{}},children:[a&&h.jsxs(h.Fragment,{children:[h.jsx(De.span,{"aria-hidden":!0,className:"absolute inset-0 rounded-full pointer-events-none",style:{background:"conic-gradient(from 0deg, rgba(6,182,212,0.0) 0deg, rgba(6,182,212,1) 90deg, rgba(34,211,238,1) 180deg, rgba(6,182,212,0.0) 270deg)",WebkitMask:"radial-gradient(farthest-side, transparent calc(100% - 2px), #000 calc(100% - 2px))",mask:"radial-gradient(farthest-side, transparent calc(100% - 2px), #000 calc(100% - 2px))"},animate:f?void 0:{rotate:360},transition:f?void 0:{duration:3,repeat:1/0,ease:"linear"}}),h.jsx("span",{"aria-hidden":!0,className:"absolute inset-1 rounded-full pointer-events-none",style:{background:"radial-gradient(circle, rgba(6,182,212,0.1) 0%, transparent 70%)"}})]}),h.jsx("img",{src:"/logo.png",alt:"Voxket",className:"object-contain select-none pointer-events-none relative z-10",style:{width:`${Math.max(0,Math.min(1,s))*100}%`,height:`${Math.max(0,Math.min(1,s))*100}%`,filter:a?"brightness(1.1) contrast(1.1)":"none"},draggable:!1})]})]})};function sg({room:e,onSessionEnd:t,onSessionStart:n,enableConsoleLogging:r=!0,enableLocalStorage:i=!0,voxketSessionId:o}={}){const[s,a]=P.useState(null),[l,c]=P.useState([]),[u,d]=P.useState(null),[f,p]=P.useState([]),g=P.useCallback((E,w)=>{const C={timestamp:new Date,event:E,data:w,sessionId:s==null?void 0:s.sessionId,participantId:u==null?void 0:u.identity};if(c(k=>[...k,C]),i){const k=JSON.parse(localStorage.getItem("voxket-session-logs")||"[]");k.push(C),localStorage.setItem("voxket-session-logs",JSON.stringify(k))}return C},[s==null?void 0:s.sessionId,u==null?void 0:u.identity,r,i]);P.useEffect(()=>{if(!e)return;const E=()=>{const b=o||`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,M=new Date,I={sessionId:b,startTime:M,totalMessages:0,connectionIssues:0,participantCount:f.length,events:[]};a(I),g("SESSION_STARTED",{sessionId:b,startTime:M}),n==null||n(b)},w=()=>{if(s){const b=new Date,M=b.getTime()-s.startTime.getTime(),I={...s,endTime:b,duration:M,events:l};g("SESSION_ENDED",{sessionId:s.sessionId,duration:`${Math.round(M/1e3)}s`,totalMessages:s.totalMessages,connectionIssues:s.connectionIssues}),t==null||t(I),a(null),c([])}},C=b=>{g("CONNECTION_STATE_CHANGED",{state:b}),b===ae.ConnectionState.Reconnecting&&s&&(a(M=>M?{...M,connectionIssues:M.connectionIssues+1}:null),g("CONNECTION_ISSUE",{type:"reconnecting"}))},k=b=>{g("TRACK_PUBLISHED",{trackKind:b.kind,trackSource:b.source})},_=b=>{g("TRACK_UNPUBLISHED",{trackKind:b.kind,trackSource:b.source})},R=(b,M)=>{s&&a(I=>I?{...I,totalMessages:I.totalMessages+1}:null),g("DATA_RECEIVED",{participantId:M==null?void 0:M.identity,dataSize:b.length})},A=b=>{g("PARTICIPANT_CONNECTED",{participantId:b.identity,participantName:b.name}),p(M=>[...M,b]),s&&a(M=>M?{...M,participantCount:M.participantCount+1}:null)},O=b=>{g("PARTICIPANT_DISCONNECTED",{participantId:b.identity,participantName:b.name}),p(M=>M.filter(I=>I.identity!==b.identity))};return e.localParticipant&&d(e.localParticipant),e.on(ae.RoomEvent.Connected,E),e.on(ae.RoomEvent.Disconnected,w),e.on(ae.RoomEvent.ConnectionStateChanged,C),e.on(ae.RoomEvent.TrackPublished,k),e.on(ae.RoomEvent.TrackUnpublished,_),e.on(ae.RoomEvent.DataReceived,R),e.on(ae.RoomEvent.ParticipantConnected,A),e.on(ae.RoomEvent.ParticipantDisconnected,O),()=>{e.off(ae.RoomEvent.Connected,E),e.off(ae.RoomEvent.Disconnected,w),e.off(ae.RoomEvent.ConnectionStateChanged,C),e.off(ae.RoomEvent.TrackPublished,k),e.off(ae.RoomEvent.TrackUnpublished,_),e.off(ae.RoomEvent.DataReceived,R),e.off(ae.RoomEvent.ParticipantConnected,A),e.off(ae.RoomEvent.ParticipantDisconnected,O)}},[e,s,l,f.length,g,t,n]);const m=P.useCallback(()=>i?JSON.parse(localStorage.getItem("voxket-session-logs")||"[]"):l,[l,i]),v=P.useCallback(()=>{i&&localStorage.removeItem("voxket-session-logs"),c([])},[i]),y=P.useCallback(()=>{const E=m(),w=JSON.stringify(E,null,2),C="data:application/json;charset=utf-8,"+encodeURIComponent(w),k=`voxket-session-logs-${new Date().toISOString().split("T")[0]}.json`,_=document.createElement("a");_.setAttribute("href",C),_.setAttribute("download",k),_.click()},[m]);return{sessionMetrics:s,sessionLogs:l,logEvent:g,getSessionLogs:m,clearSessionLogs:v,exportSessionLogs:y}}class rc{constructor(){Ee(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 r=(...i)=>{this.off(t,r),n(...i)};return this.on(t,r)}off(t,n){const r=this.listeners[t];if(!r)return;const i=r.indexOf(n);i>-1&&r.splice(i,1)}removeAllListeners(t){t?delete this.listeners[t]:this.listeners={}}emit(t,...n){const r=this.listeners[t];if(!r)return;const i=[...r];for(const o of i)try{o(...n)}catch(s){console.error(`Error in event listener for ${String(t)}:`,s)}}listenerCount(t){var n;return((n=this.listeners[t])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class ag{constructor(t){Ee(this,"plugins",new Map);Ee(this,"installedPlugins",new Set);Ee(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 r=this.plugins.get(t);if(!r)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t))throw new Error(`Plugin '${t}' is already installed`);if(r.dependencies)for(const o of r.dependencies)this.installedPlugins.has(o)||await this.install(o);const i={...this.context,config:{...r.config,...n}};r.install&&await r.install(i),this.installedPlugins.add(t),this.setupPluginEvents(r,i)}async uninstall(t){var r;const n=this.plugins.get(t);if(!n)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t)){for(const[i,o]of this.plugins)if(this.installedPlugins.has(i)&&((r=o.dependencies)!=null&&r.includes(t)))throw new Error(`Cannot uninstall '${t}' because '${i}' 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",r=>{t.onSessionStart(n,r.id)}),t.onSessionEnd&&n.on("session.ended",r=>{t.onSessionEnd(n,r.id)}),t.onAgentResponse&&n.on("agent.response",r=>{t.onAgentResponse(n,r)})}}function $R(e){return e}function ic(e,t,n){return{name:e,version:"1.0.0",description:`${t} modality plugin`,install:async r=>{n.onActivate&&await n.onActivate(r)},uninstall:async r=>{n.onDeactivate&&await n.onDeactivate(r)},onAgentResponse:n.onMessage}}const VR={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)})}},zR={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,...r)=>(console.log(`[Debug] Event: ${String(n)}`,r),t(n,...r))}},UR={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 lg extends rc{constructor(n){super();Ee(this,"room",null);Ee(this,"registeredMethods",new Map);Ee(this,"activeInteractions",new Map);Ee(this,"currentInteraction",null);n&&this.setRoom(n)}setRoom(n){this.room=n}async registerFrontendRPC(n,r,i="embedded"){if(console.log(`RpcManager: Starting registration for method '${n}'`),!this.room)throw console.error(`RpcManager: Cannot register '${n}' - no room instance`),new Error("Room not initialized. Cannot register RPC method.");if(!this.room.localParticipant)throw console.error(`RpcManager: Cannot register '${n}' - no local participant`),new Error("Local participant not available for RPC registration");console.log(`RpcManager: Room state: ${this.room.state}`),console.log(`RpcManager: Local participant: ${this.room.localParticipant.identity}`),console.log(`RpcManager: Registering frontend RPC method: ${n}`);const o={methodName:n,component:r,presentationMode:i};this.registeredMethods.set(n,o);try{this.room.registerRpcMethod(n,async s=>{console.log(`RpcManager: RPC method '${n}' called by ${s.callerIdentity}`),console.log("RpcManager: Payload:",s.payload),this.emit("rpc.method.called",{methodName:n,data:s});let a;console.log(`RpcManager: Current registration for '${n}':`,o);let l=s.responseTimeout||30;try{a=JSON.parse(s.payload)}catch{a=s.payload}try{const c=await this.awaitUserInteraction(n,r,i,a,l);return JSON.stringify(c)}catch(c){throw console.error(`RpcManager: Error in RPC method '${n}':`,c),c}}),this.emit("rpc.method.registered",{methodName:n}),console.log(`RpcManager: Successfully registered RPC method: ${n}`)}catch(s){throw console.error(`RpcManager: Failed to register RPC method '${n}':`,s),s}}async awaitUserInteraction(n,r,i,o,s){return new Promise((a,l)=>{const c=`${n}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${n}, timeout: ${s} seconds`);const u={didSuccess:(f,p)=>{console.log(`RpcManager: User interaction successful for method: ${n}`,f),this.clearInteraction(c),this.currentInteraction=null;const g={success:!0,message:"User interaction completed successfully",data:f,timestamp:new Date,...p?{successView:p}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:g}),a(g)},didFail:f=>{console.log(`RpcManager: User interaction failed for method: ${n}`,f),this.clearInteraction(c);const p={success:!1,message:"User interaction failed",error:f,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:p}),a(p)},dismissView:()=>{var p;console.log(`RpcManager: User dismissed interaction for method: ${n}`),console.log("RpcManager: Current interaction before dismiss:",(p=this.currentInteraction)==null?void 0:p.methodName),this.clearInteraction(c),this.currentInteraction=null,console.log("RpcManager: Current interaction after dismiss:",this.currentInteraction);const f={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:f}),this.emit("rpc.interaction.completed",{methodName:n,response:f}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(f)},didTimeout:f=>{console.log(`RpcManager: User interaction timeout for method: ${n}`),this.clearInteraction(c),this.currentInteraction=null;const p={success:!0,message:`User interaction timed out after ${s} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...f?{timeoutView:f}:{}};this.emit("rpc.interaction.timeout",{methodName:n,response:p}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(p)}},d=setTimeout(()=>{u.didTimeout&&u.didTimeout()},s);this.activeInteractions.set(c,{resolve:f=>a(JSON.parse(f)),reject:l,timeoutId:d}),this.currentInteraction={isVisible:!0,methodName:n,component:r,presentationMode:i,timeout:s,data:o,handler:u},this.emit("rpc.interaction.started",{methodName:n,presentationMode:i}),setTimeout(async()=>{var f;if((f=this.currentInteraction)!=null&&f.handler)try{console.log(`RpcManager: Component created for method: ${n} with data:`,o)}catch(p){console.error("RpcManager: Error loading data into component:",p),u.didFail({error:"Failed to load data into component"})}},100)})}clearInteraction(n){const r=this.activeInteractions.get(n);r&&(console.log(`RpcManager: Clearing interaction: ${n}`),clearTimeout(r.timeoutId),this.activeInteractions.delete(n))}getCurrentInteraction(){return this.currentInteraction}dismissCurrentInteraction(){var n;this.currentInteraction&&(console.log(`RpcManager: Dismissing current interaction: ${this.currentInteraction.methodName}`),(n=this.currentInteraction.handler)==null||n.dismissView(),setTimeout(()=>{this.currentInteraction&&(console.log("RpcManager: Force clearing lingering interaction"),this.currentInteraction=null)},0))}getRegisteredMethods(){return Array.from(this.registeredMethods.keys())}unregisterMethod(n){this.registeredMethods.delete(n),console.log(`RpcManager: Unregistered RPC method: ${n}`)}clear(){for(const[n,r]of this.activeInteractions)clearTimeout(r.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null,console.log("RpcManager: Cleared all registrations and interactions")}}class Ye extends Error{constructor(t,n,r){super(t),this.code=n,this.details=r,this.name="VoxketError"}}class cg{constructor(t,n="User"){Ee(this,"chatMessages",[]);Ee(this,"activeTranscriptions",new Map);Ee(this,"room",null);Ee(this,"eventEmitter");Ee(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(r=>r.id===t.id)||this.chatMessages.push(t)}updateChatMessage(t){const n=this.chatMessages.findIndex(r=>r.id===t.id);n!==-1&&(this.chatMessages[n]=t)}clearChatMessages(){this.chatMessages=[],this.activeTranscriptions.clear(),console.log("🧹 ChatManager: Cleared chat messages and transcription history")}trackTranscription(t,n){this.activeTranscriptions.set(t,{messageId:n,timestamp:Date.now()})}getActiveTranscription(t){const n=Date.now(),r=this.activeTranscriptions.get(t);return r&&n-r.timestamp<1e3?r:null}async sendMessage(t,n){if(!this.room)throw new Ye("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw new Ye("No local participant","CONNECTION_FAILED");try{const r={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",r)}catch(r){throw console.error("ChatManager: Failed to send chat message:",r),new Ye("Failed to send message","NETWORK_ERROR",r)}}async sendAttachments(t,n){if(!this.room)throw new Ye("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw new Ye("No local participant","CONNECTION_FAILED");if(!t||t.length===0)throw new Ye("No files provided","INVALID_PARAMETER");const r=t.filter(i=>i.type.startsWith("image/"));if(r.length===0)throw new Ye("Only image files are allowed","INVALID_PARAMETER");r.length!==t.length&&console.warn("ChatManager: Some non-image files were filtered out");try{const i=r.map(async(o,s)=>{const l={id:`att_${Date.now()}_${s}`,content:`📎 ${o.name}`,sender:{id:"user",name:this.participantName,type:"participant"},timestamp:new Date,metadata:{...n,type:"attachment",fileName:o.name,fileSize:o.size,mimeType:o.type,uploading:!0}};this.eventEmitter.emit("chat.message.sent",l);const c=await this.room.localParticipant.sendFile(o,{mimeType:o.type,topic:"images",onProgress:d=>{const f={...l,metadata:{...l.metadata,uploadProgress:d}};this.eventEmitter.emit("chat.message.updated",f)}});try{const d=new FileReader,f=new Promise((m,v)=>{d.onload=()=>{typeof d.result=="string"?m(d.result):v(new Error("Failed to convert to base64"))},d.onerror=v});d.readAsDataURL(o);const g={type:"image",data:await f,filename:o.name,mimeType:o.type,size:o.size};await this.room.localParticipant.sendText(JSON.stringify(g),{topic:"images",destinationIdentities:[]})}catch(d){console.warn("ChatManager: Failed to send image data to agent:",d);try{const f=`I've shared an image: ${o.name}`;await this.room.localParticipant.sendText(f,{topic:"lk.chat",destinationIdentities:[]})}catch(f){console.warn("ChatManager: Failed to send image notification to agent:",f)}}const u={...l,metadata:{...l.metadata,uploading:!1,uploadProgress:1,streamId:c.id}};return this.eventEmitter.emit("chat.message.updated",u),c});await Promise.all(i)}catch(i){throw console.error("ChatManager: Failed to send attachments:",i),new Ye("Failed to send attachments","NETWORK_ERROR",i)}}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 ug{constructor(t){Ee(this,"room",null);Ee(this,"eventEmitter");Ee(this,"silencePreventionNode",null);Ee(this,"silencePreventionOscillator",null);Ee(this,"audioContext",null);this.eventEmitter=t,this.initializeAudioContext()}initializeAudioContext(){try{if(this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),console.log("🔊 MediaManager: AudioContext created:",{state:this.audioContext.state,sampleRate:this.audioContext.sampleRate})),this.audioContext.state==="suspended"){console.log("🔊 MediaManager: AudioContext suspended, will resume on user interaction");const t=async()=>{this.audioContext&&this.audioContext.state==="suspended"&&(await this.audioContext.resume(),console.log("✅ MediaManager: AudioContext resumed:",this.audioContext.state)),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})}else this.audioContext.state==="running"&&console.log("✅ MediaManager: AudioContext already running")}catch(t){console.error("MediaManager: Failed to initialize AudioContext:",t)}}async ensureAudioContextRunning(){if(this.audioContext||this.initializeAudioContext(),this.audioContext&&this.audioContext.state==="suspended"){console.log("🔊 MediaManager: Attempting to resume suspended AudioContext");try{await this.audioContext.resume(),console.log("✅ MediaManager: AudioContext resumed successfully")}catch(t){console.error("MediaManager: Failed to resume AudioContext:",t)}}}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,r;try{await this.ensureAudioContextRunning();const i=(n=this.room)==null?void 0:n.localParticipant.isMicrophoneEnabled,o=t??!i;o&&this.startSilencePrevention(),await((r=this.room)==null?void 0:r.localParticipant.setMicrophoneEnabled(o,{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0})),o?this.eventEmitter.emit("track.unmuted",{source:"microphone",enabled:!0}):(this.eventEmitter.emit("track.muted",{source:"microphone",enabled:!1}),this.stopSilencePrevention()),console.log("🎤 MediaManager: Microphone",o?"enabled":"disabled")}catch(i){throw console.error("MediaManager: Failed to toggle microphone:",i),this.stopSilencePrevention(),new Ye("Failed to toggle microphone","PERMISSION_DENIED",i)}}startSilencePrevention(){try{if(this.audioContext||(this.audioContext=new AudioContext),this.silencePreventionOscillator)return;console.log("🔇 MediaManager: Starting silence prevention"),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(),console.log("✅ MediaManager: Silence prevention started")}catch(t){console.error("❌ MediaManager: Failed to start silence prevention:",t)}}stopSilencePrevention(){try{this.silencePreventionOscillator&&(console.log("🔇 MediaManager: Stopping silence prevention"),this.silencePreventionOscillator.stop(),this.silencePreventionOscillator.disconnect(),this.silencePreventionOscillator=null),this.silencePreventionNode&&(this.silencePreventionNode.disconnect(),this.silencePreventionNode=null)}catch(t){console.error("❌ MediaManager: Failed to stop silence prevention:",t)}}async toggleCamera(t){return this.setCameraEnabled(t!==!1)}async setCameraEnabled(t){var n,r;try{const i=(n=this.room)==null?void 0:n.localParticipant.isCameraEnabled,o=t??!i;await((r=this.room)==null?void 0:r.localParticipant.setCameraEnabled(o)),o?this.eventEmitter.emit("track.unmuted",{source:"camera",enabled:!0}):this.eventEmitter.emit("track.muted",{source:"camera",enabled:!1})}catch(i){throw new Ye("Failed to toggle camera","PERMISSION_DENIED",i)}}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){throw new Ye("Failed to start screen share","PERMISSION_DENIED",n)}}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){throw new Ye("Failed to stop screen share","PERMISSION_DENIED",n)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="audioinput")}catch(t){throw new Ye("Failed to get audio input devices","DEVICE_ERROR",t)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="videoinput")}catch(t){throw new Ye("Failed to get video input devices","DEVICE_ERROR",t)}}async setAudioInputDevice(t){var n;try{if(!((n=this.room)!=null&&n.localParticipant))throw new Error("Not connected to room")}catch(r){throw new Ye("Failed to set audio input device","DEVICE_ERROR",r)}}async setVideoInputDevice(t){var n;try{if(!((n=this.room)!=null&&n.localParticipant))throw new Error("Not connected to room")}catch(r){throw new Ye("Failed to set video input device","DEVICE_ERROR",r)}}getMicrophoneTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===ae.Track.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===ae.Track.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===ae.Track.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();console.log("🔊 MediaManager.getAgentAudioTrack: Checking remote participants:",{count:t.length,participants:t.map(n=>({identity:n.identity,name:n.name,hasMicTrack:!!n.getTrackPublication(ae.Track.Source.Microphone)}))});for(const n of t){const r=n.getTrackPublication(ae.Track.Source.Microphone);if(r!=null&&r.track)return console.log("✅ MediaManager.getAgentAudioTrack: Found audio track for",n.identity),{source:ae.Track.Source.Microphone,participant:n,publication:r}}return console.log("❌ MediaManager.getAgentAudioTrack: No audio track found"),null}getAgentVideoTrack(){const t=this.getRemoteParticipants();for(const n of t){const r=n.getTrackPublication(ae.Track.Source.Camera);if(r!=null&&r.track)return{source:ae.Track.Source.Camera,participant:n,publication:r}}return null}getVideoTrackRefs(){const t=[],n=this.getLocalParticipant();if(n){const i=n.getTrackPublication(ae.Track.Source.Camera);i!=null&&i.track&&t.push({source:ae.Track.Source.Camera,participant:n,publication:i});const o=n.getTrackPublication(ae.Track.Source.ScreenShare);o!=null&&o.track&&t.push({source:ae.Track.Source.ScreenShare,participant:n,publication:o})}const r=this.getRemoteParticipants();for(const i of r){const o=i.getTrackPublication(ae.Track.Source.Camera);o!=null&&o.track&&t.push({source:ae.Track.Source.Camera,participant:i,publication:o});const s=i.getTrackPublication(ae.Track.Source.ScreenShare);s!=null&&s.track&&t.push({source:ae.Track.Source.ScreenShare,participant:i,publication:s})}return t}getCameraTrackRefs(){return this.getVideoTrackRefs().filter(t=>t.source===ae.Track.Source.Camera)}getScreenShareTrackRefs(){return this.getVideoTrackRefs().filter(t=>t.source===ae.Track.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 r=i=>!!n.canPublish&&(n.canPublishSources.length===0||n.canPublishSources.includes(i));return{camera:r(1),microphone:r(2),screenShare:r(3),data:n.canPublishData??!1}}canPublishSource(t){return this.getPublishPermissions()[t]}}class dg{constructor(t,n){Ee(this,"room",null);Ee(this,"config");Ee(this,"eventEmitter");Ee(this,"connectionState",ae.ConnectionState.Disconnected);Ee(this,"isConnected",!1);Ee(this,"currentAgentInfo",null);this.config=t,this.eventEmitter=n,this.initializeRoom()}initializeRoom(){this.room=new ae.Room({adaptiveStream:!1,stopLocalTrackOnUnpublish:!1,audioCaptureDefaults:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},publishDefaults:{stopMicTrackOnMute:!1,preConnectBuffer:!0}}),this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(ae.RoomEvent.Connected,()=>{this.connectionState=ae.ConnectionState.Connected,this.isConnected=!0,console.log("📡 ConnectionManager: Emitting connection.connected event"),this.eventEmitter.emit("connection.connected")}),this.room.on(ae.RoomEvent.Disconnected,t=>{console.log("ConnectionManager: Room disconnected, reason:",t),this.connectionState=ae.ConnectionState.Disconnected,this.isConnected=!1,t&&console.log("ConnectionManager: Disconnect reason details:",{reason:t.toString(),connectionState:this.connectionState}),this.eventEmitter.emit("connection.disconnected",t==null?void 0:t.toString())}),this.room.on(ae.RoomEvent.ConnectionStateChanged,t=>{this.connectionState=t,t===ae.ConnectionState.Connecting&&this.eventEmitter.emit("connection.connecting")}),this.room.on(ae.RoomEvent.ParticipantConnected,t=>{const n={id:t.identity,name:t.name||t.identity,isLocal:!1};this.eventEmitter.emit("participant.joined",n)}),this.room.on(ae.RoomEvent.ParticipantDisconnected,t=>{const n={id:t.identity,name:t.name||t.identity,isLocal:!1};this.eventEmitter.emit("participant.left",n)}),this.room.on(ae.RoomEvent.LocalTrackPublished,t=>{console.log("ConnectionManager: Local track published:",t.source),t.source===ae.Track.Source.ScreenShare?this.eventEmitter.emit("track.unmuted",{source:"screenShare",enabled:!0}):t.source===ae.Track.Source.Microphone&&(console.log("✅ ConnectionManager: Local MICROPHONE track RE-PUBLISHED at:",new Date().toISOString()),console.log(" Track restart complete - audio should resume"))}),this.room.on(ae.RoomEvent.LocalTrackUnpublished,t=>{console.log(" ConnectionManager: Local track unpublished:",t.source),t.source===ae.Track.Source.ScreenShare?this.eventEmitter.emit("track.muted",{source:"screenShare",enabled:!1}):t.source===ae.Track.Source.Microphone&&(console.warn("⚠️ ConnectionManager: Local MICROPHONE track UNPUBLISHED at:",new Date().toISOString()),console.log(" ⚠️ WARNING: This will cause audio disruption!"))}),this.room.on(ae.RoomEvent.LocalAudioSilenceDetected,()=>{var t,n;console.log("🔇 ConnectionManager: Local audio silence detected at:",new Date().toISOString()),console.log(" Remote participants count:",(t=this.room)==null?void 0:t.remoteParticipants.size),(n=this.room)==null||n.remoteParticipants.forEach(r=>{console.log(" Remote participant:",r.identity,{audioTracks:r.audioTrackPublications.size,hasAudio:Array.from(r.audioTrackPublications.values()).some(i=>i.track)})})}),this.room.on(ae.RoomEvent.TrackSubscribed,(t,n,r)=>{var i,o;console.log("🎵 ConnectionManager: Track subscribed:",{trackKind:t.kind,trackSource:t.source,participantIdentity:r.identity,isAgent:(i=r.identity)==null?void 0:i.startsWith("agent-")}),this.eventEmitter.emit("media.track.subscribed",{id:t.sid||n.trackSid,kind:t.kind,source:((o=t.source)==null?void 0:o.toString())||"unknown",participantId:r.identity,isEnabled:!t.isMuted,isMuted:t.isMuted})}),this.room.on(ae.RoomEvent.TrackUnsubscribed,(t,n,r)=>{var i;console.log("🔇 ConnectionManager: Track unsubscribed:",{trackKind:t.kind,participantIdentity:r.identity}),this.eventEmitter.emit("media.track.unsubscribed",{id:t.sid||n.trackSid,kind:t.kind,source:((i=t.source)==null?void 0:i.toString())||"unknown",participantId:r.identity,isEnabled:!1,isMuted:!0})}))}async fetchConnectionDetails(t,n,r,i){try{const o={agent_id:t,participant_name:n,participant_metadata:i||{user_id:""},modality:r[0],modalities:r},s=await fetch(`${this.config.baseUrl}/api/live/agent/session`,{method:"POST",headers:{accept:"application/json","X-APP-ID":this.config.appId,"X-APP-SECRET":this.config.appSecret,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){let c=`HTTP ${s.status}: Failed to fetch connection details`;try{const u=await s.json();u&&(u.error?c=`API Error: ${u.error}`:u.detail?c=`API Error: ${u.detail}`:u.message&&(c=`API Error: ${u.message}`))}catch{try{const d=await s.text();d&&(c=`API Error: ${d}`)}catch{}}throw new Error(c)}const a=await s.json();let l;return a.agent_info&&(l={id:a.agent_info.agent_info.id,name:a.agent_info.agent_info.name,capabilities:a.agent_info.capabilities,modality_supported:a.agent_info.modality_supported,session_settings:a.agent_info.session_settings||{}},this.currentAgentInfo=l),{serverUrl:a.wss_url,participantToken:a.token,voxketSessionId:a.session_id,agentInfo:l}}catch(o){console.error("ConnectionManager: fetchConnectionDetails failed:",o);const s=new Ye(`Failed to fetch connection details: ${o instanceof Error?o.message:"Unknown error"}`,"CONNECTION_FAILED",o);throw this.eventEmitter.emit("connection.error",s),s}}async connect(t,n,r,i){var o;try{this.eventEmitter.emit("connection.connecting");const s=await this.fetchConnectionDetails(t,n,r,i);return await((o=this.room)==null?void 0:o.connect(s.serverUrl,s.participantToken)),this.isConnected=!0,s}catch(s){console.error("ConnectionManager: Connection failed:",s);const a=new Ye(`Failed to connect to Voxket services: ${s instanceof Error?s.message:"Unknown error"}`,"CONNECTION_FAILED",s);throw this.eventEmitter.emit("connection.error",a),a}}async disconnect(){try{this.room&&await this.room.disconnect(),this.isConnected=!1,this.currentAgentInfo=null,this.initializeRoom(),this.eventEmitter.emit("connection.disconnected")}catch(t){console.error("ConnectionManager: Disconnect failed:",t);const n=new Ye("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===ae.ConnectionState.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 fg{constructor(t,n,r){Ee(this,"room",null);Ee(this,"eventEmitter");Ee(this,"chatManager");Ee(this,"agentManager");Ee(this,"textStreamHandlersRegistered",!1);Ee(this,"_eventEmitters",new Map);this.eventEmitter=t,this.chatManager=n,this.agentManager=r}setRoom(t){this.room=t,t&&!this.textStreamHandlersRegistered&&(console.log("📡 StreamHandlerManager: Auto-registering handlers on room set"),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 r=await t.readAll(),i={id:`msg_${Date.now()}_${n.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:r,timestamp:new Date,sender:{id:n.identity||"user",name:n.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.eventEmitter.emit("chat.message.received",i)}catch(r){console.error("StreamHandlerManager: Failed to process lk.chat message:",r)}})}catch(t){console.warn("StreamHandlerManager: lk.chat handler already registered, skipping:",t)}}registerTranscriptionHandler(){try{console.log("📡 StreamHandlerManager: Registering lk.transcription handler"),this.room.registerTextStreamHandler("lk.transcription",async(t,n)=>{var r,i;console.log("💬 StreamHandlerManager: Received lk.transcription stream from:",n.identity);try{const o=n.identity===((i=(r=this.room)==null?void 0:r.localParticipant)==null?void 0:i.identity),s=n.identity,a=this.chatManager.getActiveTranscription(s);let l,c=!0;a?(l=a.messageId,c=!1):(l=`msg_${o?"user":"agent"}_${n.identity}_${Date.now()}`,this.chatManager.trackTranscription(s,l));let u="";const d=this.agentManager.getCurrentAgentInfo(),f=(d==null?void 0:d.name)||n.identity||"AI Assistant",p=o?"participant":"agent",g=o?"User":f,m={id:l,content:"",timestamp:new Date,sender:{id:n.identity||"unknown",name:g,type:p},metadata:{topic:"lk.transcription",streaming:!0}};c&&this.eventEmitter.emit("chat.message.received",m);for await(const w of t){u+=w;const C=this.chatManager.convertMarkdownToText(u),k={...m,content:C,metadata:{...m.metadata,streaming:!0}};this.eventEmitter.emit("chat.message.updated",k)}const v=this.chatManager.convertMarkdownToText(u),y={...m,content:v,metadata:{...m.metadata,streaming:!1}};this.eventEmitter.emit("chat.message.updated",y);const E={id:l,text:v,isFinal:!0,startTime:m.timestamp.getTime(),participantId:n.identity||"agent"};this.eventEmitter.emit("transcription.received",E)}catch(o){console.error("StreamHandlerManager: Failed to process lk.transcription message:",o);try{const s=await t.readAll(),a=this.agentManager.getCurrentAgentInfo(),l=(a==null?void 0:a.name)||n.identity||"AI Assistant",c={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:s,timestamp:new Date,sender:{id:n.identity||"agent",name:l,type:"agent"},metadata:{topic:"lk.transcription"}};this.eventEmitter.emit("chat.message.received",c),console.log("💬 StreamHandlerManager: Emitted chat.message.received:",{id:c.id,sender:c.sender.name,contentLength:c.content.length,preview:c.content.substring(0,50)});const u={id:c.id,text:c.content,isFinal:!0,startTime:c.timestamp.getTime(),participantId:n.identity||"agent"};this.eventEmitter.emit("transcription.received",u),console.log("📝 StreamHandlerManager: Emitted transcription.received:",{id:u.id,textLength:u.text.length})}catch(s){console.error("StreamHandlerManager: Fallback failed for lk.transcription:",s)}}})}catch(t){console.warn("StreamHandlerManager: lk.transcription handler already registered, skipping:",t)}}registerSuggestedResponseHandler(){try{this.room.registerTextStreamHandler("suggested_response",async t=>{const n=await t.readAll();let r=[];try{r=["tes","hello how are you","algebra make me learn that","what is the meaning of life"]}catch(i){console.warn("StreamHandlerManager: Failed to parse suggested_response:",i,n)}this.eventEmitter.emit("suggested.response",r)})}catch(t){console.warn("StreamHandlerManager: suggested_response handler already registered, skipping:",t)}}registerAgentStateHandler(){try{this.room.registerTextStreamHandler("agent_state_changed",async(t,n)=>{const r=await t.readAll();let i={};try{i=typeof r=="string"?JSON.parse(r.replace(/'/g,'"')):r}catch(o){console.warn("StreamHandlerManager: Failed to parse agent_state_changed:",o,r)}this.agentManager.handleAgentStateChanged(i)})}catch(t){console.warn("StreamHandlerManager: agent_state_changed handler already registered, skipping:",t)}}registerFunctionToolsHandler(){try{this.room.registerTextStreamHandler("function_tools_executed",async(t,n)=>{var o,s,a,l;const r=await t.readAll();console.log("StreamHandlerManager: Raw function_tools_executed data (type, length, first 200 chars):",typeof r,r==null?void 0:r.length,(o=r==null?void 0:r.substring)==null?void 0:o.call(r,0,200));let i={};try{if(typeof r=="string")try{i=JSON.parse(r),console.log("StreamHandlerManager: Direct JSON parse succeeded!")}catch(c){console.warn("StreamHandlerManager: Initial JSON parse failed:",c),console.warn("First 100 chars of raw data:",r.substring(0,100));let u=r;try{console.log("StreamHandlerManager: Starting enhanced parsing..."),u=u.replace(/\bTrue\b/g,"true"),u=u.replace(/\bFalse\b/g,"false"),u=u.replace(/\bNone\b/g,"null"),u=u.replace(/,(\s*[}\]])/g,"$1"),console.log("StreamHandlerManager: After replacements (first 200 chars):",u.substring(0,200));let d="",f=!1,p="",g=0;for(;g<u.length;){const m=u[g],v=g>0?u[g-1]:"",y=g<u.length-1?u[g+1]:"";if(m==="\\"&&(y==="'"||y==='"'))if(f){d+='\\"',g+=2;continue}else{g++;continue}if(v==="\\"&&m!=="'"&&m!=='"'){d+=m,g++;continue}if((m==='"'||m==="'")&&!f&&v!=="\\"){f=!0,p=m,d+='"',g++;continue}if(m===p&&f&&v!=="\\"&&(y===":"||y===","||y==="}"||y==="]"||y===""||/\s/.test(y))){f=!1,d+='"',g++;continue}d+=m,g++}u=d,console.log("StreamHandlerManager: ✅ Quote conversion complete. Length:",u.length),console.log("StreamHandlerManager: After quote conversion (first 500 chars):",u.substring(0,500)),i=JSON.parse(u),console.log("StreamHandlerManager: ✅ Successfully parsed with enhanced logic")}catch(d){console.error("StreamHandlerManager: ❌ Enhanced parsing failed:",d==null?void 0:d.message),console.error("Error position:",(a=(s=d==null?void 0:d.message)==null?void 0:s.match(/position (\d+)/))==null?void 0:a[1]),console.error("After conversion (first 600 chars):",u==null?void 0:u.substring(0,600)),console.error("Characters around error position:",(l=d==null?void 0:d.message)!=null&&l.match(/position (\d+)/)?u==null?void 0:u.substring(Math.max(0,parseInt(d.message.match(/position (\d+)/)[1])-50),parseInt(d.message.match(/position (\d+)/)[1])+50):"N/A");try{let f=r.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null");i=new Function("return "+f)()}catch(f){throw console.error("StreamHandlerManager: All parsing methods failed:",f),c}}}else i=r}catch(c){console.warn("StreamHandlerManager: Failed to parse function_tool_executed:",c,r);let u=null;if(typeof r=="string"&&r.includes("visualization_data"))try{const d=r.match(/"arguments":\s*"({.*?})"/);if(d){const f=d[1].replace(/\\"/g,'"');u=JSON.parse(f),console.log("🛠️ StreamHandlerManager: Extracted visualization data:",u)}}catch(d){console.warn("StreamHandlerManager: Failed to extract visualization data:",d)}i={type:"function_tools_executed",function_calls:[],function_call_outputs:[],created_at:Date.now()/1e3,parseError:!0,rawData:r,extractedVisualizationData:u}}console.log("Tool executed:",i),console.log("Processing tool execution:",`${i.created_at}-${i.type}`),this.eventEmitter.emit("tool.executed",i),console.log("✅ Event emitted: tool.executed")})}catch(t){console.warn("StreamHandlerManager: function_tool_executed handler already registered, skipping:",t)}}registerImageTextStreamHandler(){try{this.room.registerTextStreamHandler("images",async(t,n)=>{try{const r=await t.readAll()}catch(r){console.error("StreamHandlerManager: Error processing images stream:",r)}})}catch(t){console.warn("StreamHandlerManager: images text handler already registered, skipping:",t)}}registerImageByteStreamHandler(){try{this.room.registerByteStreamHandler("images",async(t,n)=>{var r,i;try{const o=t.info,s={id:`img_${Date.now()}_${n.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`🖼️ ${o.name||"Image"}`,sender:{id:n.identity||"agent",name:n.identity||"Agent",type:n.identity===((i=(r=this.room)==null?void 0:r.localParticipant)==null?void 0:i.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:o.name,fileSize:o.size,mimeType:o.mimeType,streamId:o.id,downloading:!0}};this.eventEmitter.emit("chat.message.received",s),t.onProgress&&(t.onProgress=d=>{const f={...s,metadata:{...s.metadata,downloadProgress:d||0}};this.eventEmitter.emit("chat.message.updated",f)});const a=[];for await(const d of t)a.push(d);const l=new Blob(a,{type:o.mimeType||"application/octet-stream"}),c=URL.createObjectURL(l),u={...s,metadata:{...s.metadata,downloading:!1,downloadProgress:1,downloadUrl:c,blob:l}};this.eventEmitter.emit("chat.message.updated",u)}catch(o){console.error("StreamHandlerManager: Error processing image attachment:",o)}})}catch(t){console.warn("StreamHandlerManager: image byte handler already registered, skipping:",t)}}registerCommonTopicHandlers(){["error","warning","status","system","debug","info"].forEach(n=>{try{this.room.registerTextStreamHandler(n,async(r,i)=>{try{const o=await r.readAll();if(console.log(`📝 StreamHandlerManager: Received '${n}' stream:`,o),n==="error"){let s={};try{s=typeof o=="string"?JSON.parse(o):o}catch{s={message:o}}console.warn("⚠️ StreamHandlerManager: Agent error:",s),this.eventEmitter.emit("agent.error",s)}else this.eventEmitter.emit("text.stream.received",{topic:n,data:o,participantInfo:i})}catch(o){console.error(`StreamHandlerManager: Failed to process '${n}' stream:`,o)}})}catch(r){console.warn(`StreamHandlerManager: Handler for '${n}' already registered, skipping:`,r)}})}registerWildcardHandler(){try{this.room.registerTextStreamHandler("*",async(t,n)=>{var r;try{const i=await t.readAll(),o=((r=t.info)==null?void 0:r.topic)||"unknown";if(this._eventEmitters.has(o)){const s=this._eventEmitters.get(o);try{s(i),console.log(`📝 StreamHandlerManager: Processed custom topic '${o}' via event emitter`)}catch(a){console.error(`StreamHandlerManager: Error in custom handler for topic '${o}':`,a)}}else console.log(`📝 StreamHandlerManager: Received unhandled text stream for topic '${o}':`,i),this.eventEmitter.emit("text.stream.unhandled",{topic:o,data:i,participantInfo:n})}catch(i){console.error("StreamHandlerManager: Failed to process unhandled text stream:",i)}})}catch(t){console.warn("StreamHandlerManager: Generic text stream handler already registered, skipping:",t)}}registerEventEmitter(t,n){if(!this.room)throw new Error("Room not available");this._eventEmitters.set(t,n),console.log(`📝 StreamHandlerManager: Stored handler for topic '${t}' in event emitters map`);try{this.room.registerTextStreamHandler(t,async r=>{try{const i=await r.readAll();console.log(`📝 StreamHandlerManager: Direct handler called for topic '${t}'`),n(i)}catch(i){console.error(`Error processing event for topic '${t}':`,i)}}),console.log(`📝 StreamHandlerManager: Successfully registered direct handler for topic '${t}'`)}catch(r){console.warn(`StreamHandlerManager: Direct handler registration failed for topic '${t}':`,r),console.log(`📝 StreamHandlerManager: Wildcard handler will process topic '${t}' instead`)}}getRegisteredEventEmitters(){return Array.from(this._eventEmitters.keys())}hasEventEmitter(t){return this._eventEmitters.has(t)}}const hg=N.createContext(null);function lo({config:e,children:t,autoConnect:n=!1,client:r}){const[i,o]=N.useState(null),[s,a]=N.useState(!1),[l,c]=N.useState(!1),[u,d]=N.useState(null),[f,p]=N.useState(null),[g,m]=N.useState("idle"),[v,y]=N.useState(null),[E,w]=N.useState([]),[C,k]=N.useState([]),[_,R]=N.useState([]);N.useEffect(()=>{const z=r||new Ti(e);o(z);const x=A(z);return n&&!r&&O(z),()=>{x(),r||z.disconnect().catch(console.error)}},[e,n,r]);const A=z=>{const x=()=>{c(!0),d(null)},B=()=>{a(!0),c(!1),d(null)},K=()=>{a(!1),c(!1),p(null),m("idle"),w([]),k([]),R([])},S=se=>{d(se),c(!1)},Y=se=>{p(se),m(se.state)},te=se=>{m(se),f&&p({...f,state:se})},j=(se,ke)=>{p(null),m("idle"),y(ke),w([]),k([]),R([])},q=se=>{w(ke=>[...ke,se])},W=se=>{w(ke=>ke.filter(me=>me.id!==se.id))},ue=se=>{k(ke=>[...ke,se])},Q=se=>{k(ke=>[...ke,se])},ve=se=>{console.log("📝 VoxketProvider: Received transcription:",se),R(ke=>ke.find(ie=>ie.id===se.id)?(console.log("📝 VoxketProvider: Duplicate transcription detected, skipping:",se.id),ke):(console.log("📝 VoxketProvider: Adding new transcription:",se.id),[...ke,se]))},L=()=>{console.log("🧹 VoxketProvider: Clearing chat messages and transcriptions"),k([]),R([])};return z.on("connection.connecting",x),z.on("connection.connected",B),z.on("connection.disconnected",K),z.on("connection.error",S),z.on("session.created",Y),z.on("session.state.changed",te),z.on("session.ended",j),z.on("participant.joined",q),z.on("participant.left",W),z.on("chat.message.received",ue),z.on("chat.message.sent",Q),z.on("transcription.received",ve),z.on("chat.history.cleared",L),()=>{console.log("📝 VoxketProvider: Cleaning up event listeners"),z.off("connection.connecting",x),z.off("connection.connected",B),z.off("connection.disconnected",K),z.off("connection.error",S),z.off("session.created",Y),z.off("session.state.changed",te),z.off("session.ended",j),z.off("participant.joined",q),z.off("participant.left",W),z.off("chat.message.received",ue),z.off("chat.message.sent",Q),z.off("chat.history.cleared",L),z.off("transcription.received",ve)}},O=async z=>{const x=z||i;if(x)try{await x.connect()}catch(B){console.error("Failed to connect:",B)}},$={client:i,isConnected:s,isConnecting:l,connectionError:u,currentSession:f,sessionState:g,sessionMetrics:v,participants:E,chatMessages:C,transcriptions:_,connect:()=>O(),disconnect:async()=>{if(i)try{await i.disconnect()}catch(z){console.error("Failed to disconnect:",z)}},createSession:async(z,x={})=>{if(!i)throw new Error("Client not initialized");const B={agentId:z,participantName:x.participantName||"User",metadata:x.metadata,modalities:x.modalities||["voice"]};return await i.createSession(B)},endSession:async()=>i?await i.endSession():null,sendChatMessage:async z=>{if(!i)throw new Error("Client not initialized");await i.sendChatMessage(z)},setMicrophoneEnabled:async z=>{if(!i)throw new Error("Client not initialized");await i.setMicrophoneEnabled(z)},setCameraEnabled:async z=>{if(!i)throw new Error("Client not initialized");await i.setCameraEnabled(z)},startScreenShare:async()=>{if(!i)throw new Error("Client not initialized");await i.startScreenShare()},stopScreenShare:async()=>{if(!i)throw new Error("Client not initialized");await i.stopScreenShare()}};return h.jsx(hg.Provider,{value:$,children:t})}function gn(){const e=N.useContext(hg);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}const Rn=new WeakSet,ea=new WeakSet;class pg{constructor(t,n){Ee(this,"renderedComponents",new Map);Ee(this,"config");Ee(this,"voxketClient");this.config=t,this.voxketClient=n}renderUI(t={}){const n=this.resolveTarget(t.target||"body"),r=this.getTargetKey(n);if(ea.has(n)){console.warn("⚠️ UIRenderer: Target is already being processed, skipping renderUI");return}if(Rn.has(n)){console.log("✋ UIRenderer: Target already has a React root in registry, updating existing props...");const o=this.renderedComponents.get(r);if(o&&o.root){const s=this.buildWidgetProps(t);try{o.root.render(N.createElement(lo,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:N.createElement(co,s)})),console.log("✅ UIRenderer: Successfully updated existing widget with new props");return}catch(a){throw console.error("Error re-rendering existing widget:",a),new Error(`Failed to update existing widget: ${a instanceof Error?a.message:"Unknown error"}`)}}else console.warn("⚠️ Registry inconsistency detected, cleaning up"),Rn.delete(n)}let i=this.renderedComponents.get(r);if(i&&i.target===n&&Rn.has(n)){console.log("🔄 UIRenderer: Reusing existing React root for target:",r);const o=i.root,s=this.buildWidgetProps(t);try{o.render(N.createElement(lo,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:N.createElement(co,s)}))}catch(a){throw console.error("Error rendering Voxket widget:",a),new Error(`Failed to render Voxket widget: ${a instanceof Error?a.message:"Unknown error"}`)}return}ea.add(n);try{if(i){console.log("🧹 UIRenderer: Cleaning up existing component for different target");try{i.root.unmount(),this.renderedComponents.delete(r),Rn.delete(i.target),n.innerHTML=""}catch(a){console.warn("Failed to cleanup existing root:",a)}}if(Rn.has(n)){console.warn("⚠️ UIRenderer: Target already in registry, skipping root creation");return}console.log("🆕 UIRenderer: Creating new React root for target:",r);const o=Xg.createRoot(n);this.renderedComponents.set(r,{root:o,target:n}),Rn.add(n);const s=this.buildWidgetProps(t);if(!o||typeof o.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{o.render(N.createElement(lo,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:N.createElement(co,s)}))}catch(a){throw console.error("Error rendering Voxket widget:",a),new Error(`Failed to render Voxket widget: ${a instanceof Error?a.message:"Unknown error"}`)}}finally{ea.delete(n)}}removeUI(t){const n=t?this.resolveTarget(t):null;if(n){const r=this.getTargetKey(n),i=this.renderedComponents.get(r);if(i){console.log("🗑️ UIRenderer: Removing UI for target:",r),this.renderedComponents.delete(r);const o=i.target,s=()=>{var a;try{o&&o.isConnected?typeof((a=i.root)==null?void 0:a.unmount)=="function"&&(i.root.unmount(),console.log("✅ UIRenderer: UI unmounted for target:",r)):console.log("ℹ️ UIRenderer: Target element already disconnected, skipping unmount")}catch(l){console.warn("Failed to unmount React root:",l)}finally{requestAnimationFrame(()=>{try{n.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(c=>{try{c.parentNode&&c.remove()}catch(u){console.warn("Failed to remove element:",u)}})}finally{Rn.delete(n)}})}};queueMicrotask(()=>setTimeout(s,0))}else console.log("ℹ️ UIRenderer: No component found for target, cleaning registry:",r),Rn.delete(n),n.isConnected&&n.hasChildNodes()&&(n.innerHTML="");n===document.body&&n.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(s=>{if(s.classList.contains("bg-black")&&(s.classList.contains("backdrop-blur-sm")||s.classList.contains("bg-opacity-30")))try{s.remove()}catch(a){console.warn("Failed to remove fixed element:",a)}})}}removeAllUI(){for(const[t,n]of this.renderedComponents)n.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}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(r){console.warn("Failed to remove overlay:",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 r,i,o;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:((r=t.modality)==null?void 0:r.includes("chat"))!==!1,suportsVideoInput:((i=t.modality)==null?void 0:i.includes("video"))===!0,suportsScreenShare:((o=t.modality)==null?void 0:o.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 mg{constructor(t){Ee(this,"agentState","idle");Ee(this,"isAgentConnected",!1);Ee(this,"currentAgentInfo",null);Ee(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,console.log(t?"🤖 AgentManager: Agent marked as connected":"🤖 AgentManager: Agent marked as disconnected")}getCurrentAgentInfo(){return this.currentAgentInfo}setCurrentAgentInfo(t){this.currentAgentInfo=t,console.log("📝 AgentManager: Agent info updated:",t)}reset(){this.agentState="idle",this.isAgentConnected=!1,this.currentAgentInfo=null,console.log("🔄 AgentManager: Agent state reset")}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 Ti extends rc{constructor(n){super();Ee(this,"config");Ee(this,"pluginManager");Ee(this,"rpcManager");Ee(this,"chatManager");Ee(this,"mediaManager");Ee(this,"connectionManager");Ee(this,"streamHandlerManager");Ee(this,"uiRenderer");Ee(this,"agentManager");Ee(this,"currentSession",null);this.config=n,this.chatManager=new cg(this,n.participantName||"User"),this.mediaManager=new ug(this),this.agentManager=new mg(this),this.connectionManager=new dg({baseUrl:n.baseUrl,appId:n.appId,appSecret:n.appSecret},this),this.streamHandlerManager=new fg(this,this.chatManager,this.agentManager),this.uiRenderer=new pg(n,this),this.pluginManager=new ag(this),this.rpcManager=new lg,this.setupEventListeners(),this.setupRpcEventForwarding()}setupEventListeners(){this.on("connection.connected",()=>{var r,i,o,s,a,l,c;if(console.log("🔌 VoxketClient: connection.connected event fired",{hasSession:!!this.currentSession,sessionState:(r=this.currentSession)==null?void 0:r.state,sessionId:(i=this.currentSession)==null?void 0:i.id}),(s=(o=this.config).onConnected)==null||s.call(o),this.currentSession&&this.currentSession.state==="connecting"){const u=this.currentSession.state;this.currentSession.state="connected",this.emit("session.state.changed","connected",u),console.log("✅ VoxketClient: Session state changed to connected")}else console.log("⚠️ VoxketClient: Cannot update session state",{hasSession:!!this.currentSession,currentState:(a=this.currentSession)==null?void 0:a.state});const n=this.connectionManager.getRoom();if(n){this.rpcManager.setRoom(n);const u=Array.from(n.remoteParticipants.values()).find(d=>{var f;return(f=d.identity)==null?void 0:f.startsWith("agent-")});u&&(console.log("🤖 VoxketClient: Agent already in room, marking as connected",{agentIdentity:u.identity,hasAudioTrack:u.audioTrackPublications.size>0}),this.agentManager.getIsAgentConnected()||(this.agentManager.setAgentConnected(!0),this.emit("agent.connected",{identity:u.identity})))}(c=(l=this.currentSession)==null?void 0:l.activeModalities)!=null&&c.includes("voice")&&setTimeout(async()=>{try{this.mediaManager.getLocalParticipant()&&(this.mediaManager.isMicrophoneEnabled||(await this.mediaManager.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0}),console.log("🎤 VoxketClient: Microphone enabled after connection")))}catch(u){console.warn("VoxketClient: Failed to enable microphone after room connection:",u)}},100)}),this.on("connection.disconnected",n=>{var r,i,o;(i=(r=this.config).onDisconnected)==null||i.call(r,n),this.streamHandlerManager.resetHandlersFlag(),this.agentManager.reset(),this.chatManager.clearChatMessages(),n&&console.log("🔍 VoxketClient: Disconnect reason details:",{reason:n.toString(),currentSession:(o=this.currentSession)==null?void 0:o.id})}),this.on("connection.error",n=>{var r,i;(i=(r=this.config).onError)==null||i.call(r,n)}),this.on("chat.message.received",n=>{var r,i;this.chatManager.addChatMessage(n),(i=(r=this.config).onMessageReceived)==null||i.call(r,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 r,i;(i=(r=this.config).onTranscriptionReceived)==null||i.call(r,n)}),this.on("session.state.changed",n=>{var r,i;(i=(r=this.config).onSessionStateChanged)==null||i.call(r,n)}),this.on("session.created",n=>{var r,i;(i=(r=this.config).onSessionStart)==null||i.call(r,n.id)}),this.on("session.ended",(n,r)=>{var i,o;(o=(i=this.config).onSessionEnd)==null||o.call(i,r)}),this.on("participant.joined",n=>{var r,i;(i=(r=this.config).onUserJoined)==null||i.call(r,n.id)}),this.on("participant.left",n=>{var r,i;(i=(r=this.config).onUserLeft)==null||i.call(r,n.id)})}setupRpcEventForwarding(){if(!this.rpcManager){console.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,r,i,o){const s=n||this.config.agentId||"default-agent",a=r||this.config.participantName||"User",l=i||this.config.modalities||["voice"],c=o||this.config.participantMetadata,u=await this.connectionManager.connect(s,a,l,c),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 r,i;try{const o=await this.connect(n.agentId,n.participantName,n.modalities,n.participantMetadata),s={id:o.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:o.agentInfo||this.agentManager.getCurrentAgentInfo()};this.currentSession=s,this.emit("session.created",s);const a=this.connectionManager.getRoom();if(a&&a.state==="connected"&&(console.log("✅ VoxketClient: Room already connected, updating session state immediately"),this.currentSession.state="connected",this.emit("session.state.changed","connected","connecting")),(r=n.modalities)!=null&&r.includes("voice"))try{await this.mediaManager.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0}),console.log("🎤 VoxketClient: Microphone enabled successfully")}catch(l){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",l)}if((i=n.modalities)!=null&&i.includes("video"))try{await new Promise(l=>setTimeout(l,200)),await this.mediaManager.enableCamera(),console.log("🎥 VoxketClient: Camera enabled successfully")}catch(l){console.warn("VoxketClient: Failed to enable camera, but continuing with session:",l)}return s}catch(o){throw console.error("VoxketClient: Failed to create session:",o),o instanceof Ye?o:o instanceof TypeError&&o.message.includes("fetch")?new Ye("Network connection failed","CONNECTION_FAILED",o):o instanceof Error&&o.message.includes("Failed to fetch connection details")?new Ye(`API connection failed: ${o.message}`,"CONNECTION_FAILED",o):new Ye(`Failed to create session: ${o instanceof Error?o.message:"Unknown error"}`,"SESSION_NOT_FOUND",o)}}async startSession(n,r){const i={agentId:n||this.config.agentId||"default-agent",participantName:(r==null?void 0:r.participantName)||this.config.participantName||"User",modalities:(r==null?void 0:r.modalities)||this.config.modalities||["voice","chat"],metadata:r==null?void 0:r.metadata,participantMetadata:r==null?void 0:r.participantMetadata};return this.createSession(i)}async endSession(){var n,r;if(!this.currentSession)return null;try{const i={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.connectionManager.getRoom())==null?void 0:r.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,i),await this.disconnect(),i}catch(i){throw new Ye("Failed to end session","SESSION_NOT_FOUND",i)}}getCurrentSession(){return this.currentSession}getSessionMetrics(){var n,r;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.connectionManager.getRoom())==null?void 0:r.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,r){if(!this.currentSession)throw new Ye("No active session","SESSION_NOT_FOUND");return this.dismissCurrentInteraction(),this.chatManager.sendMessage(n,r)}async sendChatMessage(n,r){return this.sendMessage(n,r)}async sendAttachments(n,r){if(!this.currentSession)throw new Ye("No active session","SESSION_NOT_FOUND");return this.dismissCurrentInteraction(),this.chatManager.sendAttachments(n,r)}async sendAttachment(n,r){return this.chatManager.sendAttachment(n,r)}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,r,i="embedded"){return this.rpcManager.registerFrontendRPC(n,r,i)}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,r){return this.on(n,r)}registerEventEmitter(n,r){return this.streamHandlerManager.registerEventEmitter(n,r)}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(r){throw new Ye("Failed to start recording","RECORDING_ERROR",r)}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(r){throw new Ye("Failed to stop recording","RECORDING_ERROR",r)}}}const HR=De.create(Bm),WR=De.create(Gl),GR=De.create($m),KR=De.create(ig);function qR({theme:e,mode:t,loadingText:n}){const r=Lt(e),i=()=>{switch(t){case"voice":return n||"Connecting to voice agent...";case"chat":return n||"Starting chat session...";case"video":return n||"Connecting to video call...";default:return n||"Connecting..."}};return h.jsxs("div",{className:"flex flex-col items-center justify-center h-full w-full p-8",children:[h.jsxs("div",{className:"text-center",children:[h.jsx("h3",{className:`text-lg font-semibold mb-2 ${r.text.accent}`,children:i()}),h.jsx("p",{className:`text-sm ${r.text.muted}`,children:"Please wait a moment..."})]}),h.jsxs("div",{className:"flex space-x-1 mt-4",children:[h.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"0ms"}}),h.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"150ms"}}),h.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"300ms"}})]})]})}const YR=De.create(qR);function xf({children:e,theme:t,displayType:n="widget",onClose:r,popupPosition:i="bottom-right",onExpand:o}){const s=Lt(t);if(n==="fullscreen")return h.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:a=>{a.target===a.currentTarget&&r&&r()},children:h.jsxs("div",{className:"w-full h-full max-w-7xl max-h-[95vh] rounded-2xl relative bg-transparent flex flex-col",onClick:a=>{a.stopPropagation()},children:[r&&h.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),r()},className:`absolute top-4 cursor-pointer right-4 z-[10000] w-12 h-12 rounded-full text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 shadow-lg border backdrop-blur-sm ${t==="light"?"bg-gray-100 bg-opacity-90 text-gray-800 hover:bg-gray-200 border-gray-300":"bg-gray-900 bg-opacity-90 hover:bg-gray-800 border-gray-700"}`,title:"Exit Fullscreen",type:"button",children:h.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:h.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"})})}),h.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${s.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:[h.jsx("div",{className:s.cardTopGradient}),h.jsx("div",{className:s.cardPurpleBlur}),h.jsx("div",{className:s.cardPinkBlur}),h.jsx("div",{className:"relative z-10 flex flex-col h-full",children:e}),h.jsx("div",{className:s.cardPulse1}),h.jsx("div",{className:s.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(n==="popup"){const a={"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 h.jsx("div",{className:"fixed rounded-2xl inset-0 z-[9999] pointer-events-none",children:h.jsxs("div",{className:`fixed rounded-2xl ${a[i]} pointer-events-auto`,children:[r&&h.jsx("button",{onClick:r,className:`absolute -top-2 -right-2 z-10 w-8 h-8 rounded-full text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 text-sm shadow-lg border ${t==="light"?"bg-gray-100 bg-opacity-95 text-gray-800 hover:bg-gray-200 border-gray-300":"bg-gray-900 bg-opacity-90 hover:bg-gray-800 border-gray-700"}`,children:"×"}),h.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${s.card} rounded-2xl flex flex-col relative overflow-hidden`,"data-theme":t,style:{width:"350px",height:"500px",contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0},children:[h.jsx("div",{className:s.cardTopGradient}),h.jsx("div",{className:s.cardPurpleBlur}),h.jsx("div",{className:s.cardPinkBlur}),h.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),h.jsx("div",{className:s.cardPulse1}),h.jsx("div",{className:s.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return h.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${s.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:[h.jsx("div",{className:s.cardTopGradient}),h.jsx("div",{className:s.cardPurpleBlur}),h.jsx("div",{className:s.cardPinkBlur}),h.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),h.jsx("div",{className:s.cardPulse1}),h.jsx("div",{className:s.cardPulse2,style:{animationDelay:"1s"}})]})}function ZR(e){if(typeof window>"u")return null;const{agentId:t,participantName:n,baseUrl:r,appSecret:i,appId:o,prompts:s,statusMessage:a,welcomeTitle:l,welcomeSubTitle:c,className:u,width:d,height:f,loadingText:p,suportsChatInput:g=!0,suportsVideoInput:m=!0,suportsScreenShare:v=!0,theme:y="vox",onSessionStart:E,onSessionEnd:w,enableSessionLogging:C=!0,onSessionLogsUpdate:k,onSessionMetricsUpdate:_,modalities:R=["voice"],displayType:A="widget",popupPosition:O="bottom-right",popupTriggerText:b="Open Chat",onPopupToggle:M,voxketClient:I,onDisplayTypeChange:F,participantMetadata:D,popupModalityMode:G="all"}=e,[re,X]=P.useState(!1),[$,z]=P.useState(null),[x,B]=P.useState(()=>{try{if(I)return!!I.getCurrentSession()}catch(le){console.error("Error checking existing session:",le)}return!1}),[K,S]=P.useState(!1),[Y,te]=P.useState(t||""),[j,q]=P.useState(n||"User"),[W,ue]=P.useState(()=>{try{if(I)return I.getCurrentSession()}catch(le){console.error("Error getting current session:",le)}return null}),[Q,ve]=P.useState(()=>{var le,nt,Fe;try{if(I){const T=I.getCurrentSession();if((le=T==null?void 0:T.activeModalities)!=null&&le.includes("chat"))return"chat";if((nt=T==null?void 0:T.activeModalities)!=null&&nt.includes("voice"))return"voice";if((Fe=T==null?void 0:T.activeModalities)!=null&&Fe.includes("video"))return"video"}}catch(T){console.error("Error determining current mode:",T)}return"welcome"}),[L,se]=P.useState(!1),[ke,me]=P.useState(!1),[ie,be]=P.useState(null),[Te,_e]=P.useState(!1);P.useEffect(()=>{A==="fullscreen"&&console.log("🎯 Widget: Switched to fullscreen mode")},[A]),P.useEffect(()=>{x&&!K?console.log("📊 Session started:",{currentMode:Q,sessionId:W==null?void 0:W.id}):!x&&!K&&Q==="welcome"&&console.log("📊 Returned to welcome screen")},[x,Q,K]);const ce=P.useMemo(()=>{try{if(I)return console.log("🔄 Using existing VoxketClient to preserve session state"),I;if(!o||!i||!r){const nt=`Missing required props: ${o?"":"appId "}${i?"":"appSecret "}${r?"":"baseUrl"}`;return console.error("❌ VoxketClient creation failed:",nt),z(new Error(nt)),X(!0),null}const le={appId:o,appSecret:i,baseUrl:r,agentId:Y,participantName:j||"User",modalities:R,participantMetadata:D};return console.log("🔧 Creating new VoxketClient with config:",{appId:o.substring(0,8)+"...",baseUrl:r,agentId:Y,participantName:j||"User",modalities:R}),new Ti(le)}catch(le){return console.error("❌ Failed to create VoxketClient:",le),z(le),X(!0),null}},[I,o,i,r,Y,j,R]),St=P.useMemo(()=>R,[R]),Me=P.useMemo(()=>{try{if(!ce)return console.warn("⚠️ No VoxketClient available, creating fallback room"),new ae.Room;const le=ce.getRoom();return console.log("🏠 Widget: Room reference updated:",{roomExists:!!le,roomState:le==null?void 0:le.state,sessionStarted:x,currentMode:Q}),le||new ae.Room}catch(le){return console.error("❌ Error getting room from client:",le),new ae.Room}},[ce,x,Q]);P.useEffect(()=>{if(Me){const le=()=>{console.log("🏠 Widget: Room state changed:",{state:Me.state,numParticipants:Me.numParticipants,isConnected:Me.state==="connected",sessionId:W==null?void 0:W.id})},nt=(Fe,T,H)=>{console.log("🎵 Widget: Track subscribed:",{trackKind:Fe.kind,trackSource:Fe.source,participantSid:H.sid,participantIdentity:H.identity,sessionId:W==null?void 0:W.id})};return Me.on(ae.RoomEvent.Connected,le),Me.on(ae.RoomEvent.Disconnected,le),Me.on(ae.RoomEvent.TrackSubscribed,nt),()=>{Me.off(ae.RoomEvent.Connected,le),Me.off(ae.RoomEvent.Disconnected,le),Me.off(ae.RoomEvent.TrackSubscribed,nt)}}},[Me,W==null?void 0:W.id]),P.useEffect(()=>{!K&&Q==="welcome"?console.log("🎬 Widget: Welcome screen ready"):x&&Q!=="welcome"&&console.log("🎬 Widget: Session mode active:",Q)},[Q,K,x]),P.useEffect(()=>{(Q==="voice"||Q==="video"||Q==="chat")&&!W&&!x&&!K&&ce&&!ce.connected&&(console.log("🔄 Auto-correcting: Found orphaned mode without session, returning to welcome"),ve("welcome"),S(!1))},[Q,W,x,K,ce]);const{sessionMetrics:pt,sessionLogs:mt,logEvent:en}=sg({room:Me,onSessionStart:E,onSessionEnd:w,enableConsoleLogging:C,enableLocalStorage:C,voxketSessionId:W==null?void 0:W.id});P.useEffect(()=>{k&&k(mt)},[mt,k]),P.useEffect(()=>{_&&pt&&_(pt)},[pt,_]),P.useEffect(()=>{if(!ce)return;const le=()=>{const nt=ce.connected,Fe=ce.getCurrentSession();console.log("🔗 Connection state changed:",{isConnected:nt,currentSessionId:Fe==null?void 0:Fe.id,currentMode:Q,loading:K,sessionStarted:x}),!nt&&x&&!K&&(console.log("🔴 Connection lost during active session - returning to welcome"),S(!1),B(!1),ue(null),ve("welcome")),nt&&Fe&&K&&(console.log("🟢 Connected with active session - removing loader"),S(!1),B(!0),ue(Fe))};return ce.on("connectionStateChanged",le),ce.on("sessionEnded",()=>{console.log("📞 Session ended - returning to welcome"),S(!1),B(!1),ue(null),ve("welcome")}),()=>{ce.off("connectionStateChanged",le),ce.off("sessionEnded",()=>{})}},[ce,Q,K,x]);const J=!!(!!(ce!=null&&ce.connected)&&x&&W);P.useEffect(()=>{const le=Fe=>{console.log("🔴 Widget: Room disconnected:",Fe),console.log("🔍 Widget: Current state on disconnect:",{currentMode:Q,sessionStarted:x,currentSessionId:W==null?void 0:W.id,loading:K}),S(!1),B(!1),ue(null),ve("welcome"),console.log("🏠 Widget: Automatically returning to welcome screen after disconnect")},nt=Fe=>{console.log("📹 Media devices error:",Fe)};return Me.on(ae.RoomEvent.MediaDevicesError,nt),Me.on(ae.RoomEvent.Disconnected,le),()=>{Me.off(ae.RoomEvent.Disconnected,le),Me.off(ae.RoomEvent.MediaDevicesError,nt)}},[Me,Q,x,W==null?void 0:W.id,K]);const we=async()=>{try{if(!ce){console.error("❌ VoxketClient not available"),z(new Error("VoxketClient not initialized")),X(!0);return}S(!0),ve("voice"),console.log("🎤 Starting voice session...",{agentId:Y,participantName:j}),console.log("🎤 Pre-start state:",{currentMode:"voice",sessionStarted:!1,loading:!0}),en("USER_STARTED_VOICE_SESSION",{agentId:Y,participantName:j});const le=await ce.startSession(Y,{participantName:j||"User",modalities:A==="popup"?["voice"]:["voice",...m?["video"]:[]],participantMetadata:ce.getParticipantMetadata()||D});console.log("✅ Voice session started successfully:",le.id),ue(le),B(!0),S(!1),E&&E(le.id)}catch(le){console.error("❌ Failed to start voice session:",le),S(!1),B(!1),ve("welcome")}},Ie=async()=>{try{if(!ce){console.error("❌ VoxketClient not available"),z(new Error("VoxketClient not initialized")),X(!0);return}S(!0),ve("chat"),console.log("💬 Starting chat session...",{agentId:Y,participantName:j}),en("USER_STARTED_CHAT_SESSION",{agentId:Y,participantName:j});const le=await ce.startSession(Y,{participantName:j||"User",modalities:["chat"],participantMetadata:ce.getParticipantMetadata()||D});console.log("✅ Chat session started successfully:",le.id),ue(le),B(!0),S(!1),E&&E(le.id)}catch(le){console.error("❌ Failed to start chat session:",le),S(!1),B(!1),ve("welcome")}},Ve=async()=>{try{if(!ce){console.error("❌ VoxketClient not available"),z(new Error("VoxketClient not initialized")),X(!0);return}S(!0),ve("video"),console.log("📺 Starting video session...",{agentId:Y,participantName:j}),console.log("📺 Pre-start state:",{currentMode:"video",sessionStarted:!1,loading:!0}),en("USER_STARTED_VIDEO_SESSION",{agentId:Y,participantName:j});const le=await ce.startSession(Y,{participantName:j||"User",modalities:["video","voice"],participantMetadata:ce.getParticipantMetadata()||D});console.log("✅ Video session started successfully:",le.id),ue(le),B(!0),S(!1),E&&E(le.id)}catch(le){console.error("❌ Failed to start video session:",le),S(!1),B(!1),ve("welcome")}},xt=()=>{ve("welcome"),S(!1),F&&F(e.displayType||"widget"),W&&x?(console.log("🧹 Widget: Cleaning up active session"),B(!1),ue(null),ce&&(console.log("🔌 Widget: Disconnecting client and cleaning up room"),ce.disconnect().catch(le=>{console.error("❌ Widget: Error during disconnect:",le)}))):(console.log("📝 Widget: No active session to clean up"),ce&&ce.connected&&(console.log("🔌 Widget: Force disconnecting client for fresh state"),ce.disconnect().catch(le=>{console.error("❌ Widget: Error during force disconnect:",le)}))),A==="popup"&&!L&&se(!0),console.log("✅ Widget: handleBackToWelcome completed",{newCurrentMode:"welcome",newLoading:!1,newSessionStarted:!1})},Ft=()=>{const le=!L;se(le),M&&M(le),!le&&!(W&&x)&&(ve("welcome"),B(!1),ue(null))},Vt=()=>{console.log("🔄 Closing fullscreen, switching to widget display type"),e.onDisplayTypeChange?e.onDisplayTypeChange("widget"):console.warn("⚠️ No onDisplayTypeChange callback provided")},an=()=>{if(console.log("🔄 Expand to fullscreen requested"),e.onDisplayTypeChange)e.onDisplayTypeChange("fullscreen");else{console.warn("⚠️ No onDisplayTypeChange callback provided for expand functionality");const le=document.getElementById("voice-card")||document.querySelector(".voxket-widget-container");le&&le.requestFullscreen&&le.requestFullscreen().catch(nt=>{console.warn("⚠️ Fullscreen API not supported or failed:",nt)})}};P.useEffect(()=>{var le,nt,Fe;if(I&&ce){const T=ce.getCurrentSession();ce.connected,T&&(console.log("✅ Restoring session state:",T.id),ue(T),B(!0),S(!1),(le=T.activeModalities)!=null&&le.includes("chat")?ve("chat"):(nt=T.activeModalities)!=null&&nt.includes("voice")?ve("voice"):(Fe=T.activeModalities)!=null&&Fe.includes("video")&&ve("video"))}},[I,ce]),P.useEffect(()=>()=>{!I&&ce&&ce.disconnect()},[ce,I]);let tn=Q==="video"?"w-[32rem]":"w-96",vt=Q==="video"?"h-[30rem]":"h-[25rem]",Kt={};if(d&&(d.startsWith("w-")?tn=d:(Kt.width=d,tn="")),f&&(f.startsWith("h-")?vt=f:(Kt.height=f,vt="")),A==="popup"&&!L)return console.log("🟡 Showing popup trigger button"),h.jsxs(h.Fragment,{children:[h.jsx(og,{onClick:()=>{if(J){!ie&&(W!=null&&W.activeModalities)&&(W.activeModalities.includes("chat")?be("chat"):W.activeModalities.includes("video")?be("video"):W.activeModalities.includes("voice")&&be("voice")),me(!1),se(!0),M&&M(!0);return}me(!1),se(!0),M&&M(!0)},position:O,ariaLabel:b,size:64,isRunning:J,theme:y}),ke&&G==="all"&&(()=>{const Fe={};O==="bottom-right"?(Fe.bottom=88,Fe.right=16):O==="bottom-left"?(Fe.bottom=88,Fe.left=16):O==="top-right"?(Fe.top=88,Fe.right=16):(Fe.top=88,Fe.left=16);const T="absolute w-0 h-0 border-8",H=O.startsWith("bottom")?h.jsx("div",{className:`${T} border-transparent border-t-black`,style:{bottom:-16,right:O.endsWith("right")?16:void 0,left:O.endsWith("left")?16:void 0}}):h.jsx("div",{className:`${T} border-transparent border-b-black`,style:{top:-16,right:O.endsWith("right")?16:void 0,left:O.endsWith("left")?16:void 0}});return h.jsx("div",{className:"fixed z-[51]",style:Fe,children:h.jsxs("div",{className:"relative bg-black text-white rounded-xl shadow-2xl px-3 py-3",children:[H,h.jsx("div",{className:"text-xs uppercase tracking-wide mb-2 opacity-70",children:"Choose modality"}),h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{type:"button",onClick:()=>{be("voice"),me(!1),se(!0),M&&M(!0)},className:"px-3 py-2 rounded-md bg-white/10 hover:bg-white/20 text-white text-sm",title:"Voice",children:"Voice"}),h.jsx("button",{type:"button",onClick:()=>{be("chat"),me(!1),se(!0),M&&M(!0)},className:"px-3 py-2 rounded-md bg-white/10 hover:bg-white/20 text-white text-sm",title:"Chat",children:"Chat"}),h.jsx("button",{type:"button",onClick:()=>{be("video"),me(!1),se(!0),M&&M(!0)},className:"px-3 py-2 rounded-md bg-white/10 hover:bg-white/20 text-white text-sm",title:"Video",children:"Video"})]})]})})})()]});if(re||!ce){const le=($==null?void 0:$.message)||"VoxketWidget encountered an error. Please check your configuration.";return h.jsx("div",{className:`voxket-widget-root theme-${y} flex items-center justify-center p-8 ${u||""}`,style:{width:d||"400px",height:f||"500px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"},children:h.jsxs("div",{className:"text-center",children:[h.jsx("div",{className:"text-4xl mb-4",children:"⚠️"}),h.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Widget Error"}),h.jsx("p",{className:"text-sm mb-4",children:le}),h.jsx("button",{onClick:()=>{X(!1),z(null),window.location.reload()},className:"px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"Retry"})]})})}let Ct=`voxket-widget-root theme-${y}`,Vn={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};A==="widget"?(Ct+=` flex min-h-fit ${tn} ${vt} ${u}`,Vn={...Vn,...Kt}):(Ct=`${u||""}`,Vn={});const Br=h.jsx("div",{className:"h-full w-full flex flex-col overflow-hidden relative z-10",children:h.jsxs(Tr,{mode:"wait",children:[Q==="welcome"&&!K&&h.jsx(KR,{agentId:Y,participantName:j||"",onAgentIdChange:te,onParticipantNameChange:q,onStartCall:we,onStartChat:Ie,onStartVideo:Ve,disabled:x||K,prompts:s,statusMessage:a,title:l,subTitle:c,theme:y,modalities:St,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),K&&(Q==="voice"||Q==="chat"||Q==="video")&&h.jsx(YR,{theme:y,mode:Q,loadingText:p,initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.3,ease:"easeInOut"}},`loading-${Q}`),Q==="voice"&&!K&&x&&ce&&h.jsxs(Ot.RoomContext.Provider,{value:Me,children:[h.jsx(Ot.RoomAudioRenderer,{},`audio-${(W==null?void 0:W.id)||"no-session"}`),h.jsx(Ot.StartAudio,{label:"Start Audio"},`start-audio-${(W==null?void 0:W.id)||"no-session"}`),h.jsx(HR,{loadingText:p,participantName:j||"User",sessionStarted:x,disabled:!1,theme:y,client:ce,displayType:A,onBack:A==="popup"?Ft:xt,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"voice-session")]}),Q==="chat"&&!K&&x&&ce&&h.jsx(WR,{client:ce,theme:y,displayType:A,onBack:A==="popup"?Ft:xt,onEndChat:xt,disabled:!1,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),Q==="video"&&!K&&x&&ce&&h.jsxs(Ot.RoomContext.Provider,{value:Me,children:[h.jsx(Ot.RoomAudioRenderer,{},`audio-video-${(W==null?void 0:W.id)||"no-session"}`),h.jsx(Ot.StartAudio,{label:"Start Audio"},`start-audio-video-${(W==null?void 0:W.id)||"no-session"}`),h.jsx(GR,{client:ce,theme:y,displayType:A,onBack:A==="popup"?Ft:xt,onEndCall:xt,disabled:!1,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-session")]})]})});return A==="fullscreen"||A==="popup"?h.jsx(xf,{theme:y,displayType:A,popupPosition:O,onClose:A==="fullscreen"?Vt:Ft,children:Br}):h.jsx("div",{className:Ct,style:Vn,children:h.jsx(xf,{theme:y,displayType:A,popupPosition:O,onExpand:an,children:Br})})}function co(e){return h.jsx(nc,{children:h.jsx(ZR,{...e})})}function XR({logs:e,onClear:t,onExport:n}){const[r,i]=N.useState(!1),[o,s]=N.useState(""),a=e.filter(l=>!o||l.event.toLowerCase().includes(o.toLowerCase()));return r?h.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:h.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[h.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[h.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("input",{type:"text",placeholder:"Filter events...",value:o,onChange:l=>s(l.target.value),className:"px-3 py-1 border rounded text-sm"}),h.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),h.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),h.jsx("button",{onClick:()=>i(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),h.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?h.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):h.jsx("div",{className:"space-y-2",children:a.map((l,c)=>h.jsxs("div",{className:"border rounded p-3 text-sm",children:[h.jsxs("div",{className:"flex items-center justify-between mb-1",children:[h.jsx("span",{className:"font-semibold text-blue-600",children:l.event}),h.jsx("span",{className:"text-gray-500 text-xs",children:new Date(l.timestamp).toLocaleTimeString()})]}),l.sessionId&&h.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",l.sessionId]}),l.data&&h.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:h.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(l.data,null,2)})})]},c))})})]})}):h.jsxs("button",{onClick:()=>i(!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 QR({metrics:e}){return e?h.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[h.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),h.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[h.jsxs("div",{children:[h.jsx("span",{className:"text-gray-600",children:"Session ID:"}),h.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),h.jsxs("div",{children:[h.jsx("span",{className:"text-gray-600",children:"Start Time:"}),h.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),h.jsxs("div",{children:[h.jsx("span",{className:"text-gray-600",children:"Messages:"}),h.jsx("div",{children:e.totalMessages})]}),h.jsxs("div",{children:[h.jsx("span",{className:"text-gray-600",children:"Participants:"}),h.jsx("div",{children:e.participantCount})]}),h.jsxs("div",{children:[h.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),h.jsx("div",{children:e.connectionIssues})]}),h.jsxs("div",{children:[h.jsx("span",{className:"text-gray-600",children:"Duration:"}),h.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function ir(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:r,endSession:i}=gn(),o=N.useCallback(async(a,l)=>await r(a,l),[r]),s=N.useCallback(async()=>await i(),[i]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:o,stop:s}}function gg(){const{sessionMetrics:e,currentSession:t}=gn();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 bg(){const{setMicrophoneEnabled:e,client:t}=gn(),[n,r]=N.useState(!1),[i,o]=N.useState(!1),s=N.useCallback(async()=>{if(!i){o(!0);try{const c=!n;await e(c),r(c)}catch(c){console.error("Failed to toggle microphone:",c)}finally{o(!1)}}},[n,i,e]),a=N.useCallback(async()=>{if(!(n||i)){o(!0);try{await e(!0),r(!0)}catch(c){console.error("Failed to enable microphone:",c)}finally{o(!1)}}},[n,i,e]),l=N.useCallback(async()=>{if(!(!n||i)){o(!0);try{await e(!1),r(!1)}catch(c){console.error("Failed to disable microphone:",c)}finally{o(!1)}}},[n,i,e]);return{isEnabled:n,isLoading:i,toggle:s,enable:a,disable:l}}function yg(){const{setCameraEnabled:e}=gn(),[t,n]=N.useState(!1),[r,i]=N.useState(!1),o=N.useCallback(async()=>{if(!r){i(!0);try{const l=!t;await e(l),n(l)}catch(l){console.error("Failed to toggle camera:",l)}finally{i(!1)}}},[t,r,e]),s=N.useCallback(async()=>{if(!(t||r)){i(!0);try{await e(!0),n(!0)}catch(l){console.error("Failed to enable camera:",l)}finally{i(!1)}}},[t,r,e]),a=N.useCallback(async()=>{if(!(!t||r)){i(!0);try{await e(!1),n(!1)}catch(l){console.error("Failed to disable camera:",l)}finally{i(!1)}}},[t,r,e]);return{isEnabled:t,isLoading:r,toggle:o,enable:s,disable:a}}function xg(){const{startScreenShare:e,stopScreenShare:t}=gn(),[n,r]=N.useState(!1),[i,o]=N.useState(!1),s=N.useCallback(async()=>{if(!(n||i)){o(!0);try{await e(),r(!0)}catch(c){console.error("Failed to start screen share:",c)}finally{o(!1)}}},[n,i,e]),a=N.useCallback(async()=>{if(!(!n||i)){o(!0);try{await t(),r(!1)}catch(c){console.error("Failed to stop screen share:",c)}finally{o(!1)}}},[n,i,t]),l=N.useCallback(async()=>{n?await a():await s()},[n,s,a]);return{isSharing:n,isLoading:i,start:s,stop:a,toggle:l}}function JR(){const{client:e}=gn(),[t,n]=N.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),r=N.useMemo(()=>t.tracks.find(m=>m.isLocal),[t.tracks]),i=N.useMemo(()=>t.tracks.filter(m=>!m.isLocal),[t.tracks]),o=N.useCallback(async()=>{try{r!=null&&r.isEnabled?await(e==null?void 0:e.disableCamera()):await(e==null?void 0:e.enableCamera())}catch(m){throw console.error("Failed to toggle camera:",m),m}},[e,r]),s=N.useCallback(async()=>{try{t.tracks.find(v=>v.isScreenShare)?await(e==null?void 0:e.stopScreenShare()):await(e==null?void 0:e.startScreenShare())}catch(m){throw console.error("Failed to toggle screen share:",m),m}},[e,t.tracks]),a=N.useCallback(m=>{n(v=>({...v,layout:m}))},[]),l=N.useCallback(m=>{n(v=>({...v,pinnedTrack:m}))},[]),c=N.useCallback(()=>{n(m=>({...m,pinnedTrack:void 0}))},[]),u=N.useCallback(async()=>{try{await(e==null?void 0:e.startRecording()),n(m=>({...m,isRecording:!0}))}catch(m){throw console.error("Failed to start recording:",m),m}},[e]),d=N.useCallback(async()=>{try{await(e==null?void 0:e.stopRecording()),n(m=>({...m,isRecording:!1}))}catch(m){throw console.error("Failed to stop recording:",m),m}},[e]),f=N.useCallback(m=>t.tracks.find(v=>v.id===m),[t.tracks]),p=N.useCallback(m=>t.tracks.filter(v=>v.participantId===m),[t.tracks]),g=N.useCallback(m=>m.isEnabled&&t.tracks.includes(m),[t.tracks]);return N.useEffect(()=>{if(!e)return;const m=E=>{n(w=>({...w,tracks:[...w.tracks.filter(C=>C.id!==E.id),E]}))},v=E=>{n(w=>{var C;return{...w,tracks:w.tracks.filter(k=>k.id!==E),pinnedTrack:((C=w.pinnedTrack)==null?void 0:C.id)===E?void 0:w.pinnedTrack}})},y=E=>{n(w=>({...w,tracks:w.tracks.map(C=>C.id===E.id?E:C)}))};return e.on("videoTrackAdded",m),e.on("videoTrackRemoved",v),e.on("videoTrackUpdated",y),()=>{e.off("videoTrackAdded",m),e.off("videoTrackRemoved",v),e.off("videoTrackUpdated",y)}},[e]),{tracks:t.tracks,localTrack:r,remoteTraracks:i,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:o,toggleScreenShare:s,setLayout:a,pinTrack:l,unpinTrack:c,startRecording:u,stopRecording:d,getTrackById:f,getTracksByParticipant:p,isTrackActive:g}}function Qo(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=gn(),[r,i]=N.useState(!1),o=N.useCallback(async c=>{if(!(!c.trim()||r||!n)){i(!0);try{await t(c.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{i(!1)}}},[t,r,n]),{userMessages:s,agentMessages:a,allMessages:l}=N.useMemo(()=>{const c=e.filter(d=>d.sender.type==="participant"),u=e.filter(d=>d.sender.type==="agent");return{userMessages:c,agentMessages:u,allMessages:e}},[e]);return{messages:l,userMessages:s,agentMessages:a,messageCount:l.length,isSending:r,canSend:!!n&&!r,send:o}}function eI(){const{send:e,isSending:t,canSend:n}=Qo(),[r,i]=N.useState(""),o=N.useCallback(async()=>{if(!(!r.trim()||!n))try{await e(r),i("")}catch(a){throw a}},[r,e,n]),s=N.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),o())},[o]);return{value:r,setValue:i,send:o,handleKeyPress:s,isSending:t,canSend:n&&r.trim().length>0}}function oc(){const{isConnected:e,isConnecting:t,connectionError:n,connect:r,disconnect:i}=gn(),o=N.useCallback(async()=>{if(!(e||t))try{await r()}catch(a){throw console.error("Failed to connect:",a),a}},[r,e,t]),s=N.useCallback(async()=>{if(e)try{await i()}catch(a){throw console.error("Failed to disconnect:",a),a}},[i,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:o,disconnect:s}}function vg(){const{participants:e}=gn();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const wg=N.createContext({}),Ni=()=>N.useContext(wg);function Eg({children:e,...t}){return h.jsx(wg.Provider,{value:t,children:e})}function uo({name:e,children:t,fallback:n,className:r}){return h.jsx("div",{className:`voxket-slot voxket-slot--${e} ${r||""}`,children:t||n})}function Sg(e,t={}){return Object.assign(e,t)}function kg({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:r=!0,customControls:i,className:o=""}){const s=ir(),a=bg(),l=yg(),c=xg(),u=Ni(),d=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,s.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",o].filter(Boolean).join(" ");return!s.isActive&&!r?h.jsx("div",{className:d,children:h.jsx("div",{className:"voxket-controls-inactive",children:h.jsx("p",{children:"Controls available during active session"})})}):h.jsxs("div",{className:d,children:[r&&h.jsx("div",{className:"voxket-session-actions",children:s.isActive?h.jsx("button",{onClick:s.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):h.jsx(tI,{})}),s.isActive&&h.jsxs("div",{className:"voxket-media-controls",children:[e&&h.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:[h.jsx("span",{className:"voxket-icon",children:"🎤"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&h.jsxs("button",{onClick:l.toggle,disabled:l.isLoading,className:`voxket-button voxket-button--media ${l.isEnabled?"voxket-button--active":""}`,title:l.isEnabled?"Stop camera":"Start camera",children:[h.jsx("span",{className:"voxket-icon",children:"📹"}),l.isLoading?"Loading...":l.isEnabled?"Stop Video":"Start Video"]}),n&&h.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isSharing?"voxket-button--active":""}`,title:c.isSharing?"Stop screen share":"Start screen share",children:[h.jsx("span",{className:"voxket-icon",children:"🖥️"}),c.isLoading?"Loading...":c.isSharing?"Stop Share":"Share Screen"]})]}),i&&h.jsx("div",{className:"voxket-custom-controls",children:i})]})}function tI(){ir();const[e,t]=N.useState(!1),n=async()=>{t(!0);try{console.log("Start session - agentId needed")}catch(r){console.error("Failed to start session:",r)}finally{t(!1)}};return h.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function sc({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:r=""}){const i=ir(),o=oc(),s=Ni(),a=["voxket-session-header",`voxket-session-header--${s.variant||"default"}`,`voxket-session-header--${s.size||"md"}`,r].filter(Boolean).join(" ");return h.jsxs("div",{className:a,children:[e&&h.jsxs("div",{className:"voxket-connection-status",children:[h.jsx("div",{className:`voxket-status-indicator ${o.isConnected?"connected":"disconnected"}`}),h.jsx("span",{className:"voxket-status-text",children:o.isConnecting?"Connecting...":o.isConnected?"Connected":"Disconnected"})]}),t&&i.session&&h.jsxs("div",{className:"voxket-session-info",children:[h.jsxs("div",{className:"voxket-session-id",children:["Session: ",i.session.id.slice(-8)]}),h.jsxs("div",{className:"voxket-session-state",children:["State: ",i.state]})]}),n&&i.session&&h.jsxs("div",{className:"voxket-agent-info",children:[h.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",i.session.agentId]}),h.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",i.session.activeModalities.join(", ")]})]}),o.error&&h.jsxs("div",{className:"voxket-error-message",children:["Error: ",o.error.message]})]})}function ac({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:r=""}){const i=ir(),o=Qo(),s=Ni(),a=["voxket-session-content",`voxket-session-content--${s.variant||"default"}`,`voxket-session-content--${s.size||"md"}`,r].filter(Boolean).join(" ");return i.isActive?h.jsx("div",{className:a,children:n||h.jsxs(h.Fragment,{children:[e&&h.jsxs("div",{className:"voxket-chat-container",children:[h.jsxs("div",{className:"voxket-chat-messages",children:[o.messages.map(l=>h.jsxs("div",{className:`voxket-message voxket-message--${l.sender.type}`,children:[h.jsxs("div",{className:"voxket-message-header",children:[h.jsx("span",{className:"voxket-message-sender",children:l.sender.name}),h.jsx("span",{className:"voxket-message-time",children:l.timestamp.toLocaleTimeString()})]}),h.jsx("div",{className:"voxket-message-content",children:l.content})]},l.id)),o.messages.length===0&&h.jsx("div",{className:"voxket-empty-messages",children:h.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),h.jsx(nI,{})]}),t&&h.jsx("div",{className:"voxket-transcriptions",children:h.jsx("div",{className:"voxket-transcription-placeholder",children:h.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):h.jsx("div",{className:a,children:h.jsx("div",{className:"voxket-inactive-state",children:h.jsxs("div",{className:"voxket-inactive-message",children:[h.jsx("h3",{children:"Start a conversation"}),h.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function nI(){const e=Qo(),[t,n]=N.useState(""),r=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(o){console.error("Failed to send message:",o)}},i=o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),r())};return h.jsxs("div",{className:"voxket-chat-input",children:[h.jsx("input",{type:"text",value:t,onChange:o=>n(o.target.value),onKeyPress:i,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),h.jsx("button",{onClick:r,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function lc({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:r,className:i=""}){const o=ir(),s=gg(),a=vg(),l=Ni(),c=["voxket-session-footer",`voxket-session-footer--${l.variant||"default"}`,`voxket-session-footer--${l.size||"md"}`,i].filter(Boolean).join(" ");return o.isActive?h.jsx("div",{className:c,children:r||h.jsxs(h.Fragment,{children:[n&&h.jsxs("div",{className:"voxket-session-status",children:[h.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),h.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&s.metrics&&h.jsxs("div",{className:"voxket-session-metrics",children:[h.jsxs("div",{className:"voxket-metric",children:[h.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),h.jsx("span",{className:"voxket-metric-value",children:rI(s.duration||0)})]}),h.jsxs("div",{className:"voxket-metric",children:[h.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),h.jsx("span",{className:"voxket-metric-value",children:s.metrics.messageCount})]})]}),t&&h.jsxs("div",{className:"voxket-participants-info",children:[h.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&h.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>h.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):h.jsx("div",{className:c,children:h.jsx("div",{className:"voxket-footer-inactive",children:h.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function rI(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60);return r>0?`${r}:${(n%60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}`:`${n}:${(t%60).toString().padStart(2,"0")}`}function iI({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:r,onSessionEnd:i,variant:o="default",size:s="md",theme:a,className:l="",children:c}){var p;const u=ir(),d=oc();N.useEffect(()=>{n&&e&&d.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,d.isConnected,u.isActive]),N.useEffect(()=>{var g;(g=u.session)!=null&&g.id&&r&&r(u.session.id)},[(p=u.session)==null?void 0:p.id,r]),N.useEffect(()=>()=>{u.isActive&&i&&u.stop().then(i).catch(console.error)},[]);const f=["voxket-session",`voxket-session--${o}`,`voxket-session--${s}`,u.isActive?"voxket-session--active":"voxket-session--inactive",l].filter(Boolean).join(" ");return h.jsx(Eg,{variant:o,size:s,theme:a,className:l,children:h.jsx("div",{className:f,children:c||h.jsxs(h.Fragment,{children:[h.jsx(uo,{name:"header",fallback:h.jsx(sc,{})}),h.jsx(uo,{name:"content",fallback:h.jsx(ac,{})}),h.jsx(uo,{name:"footer",fallback:h.jsx(lc,{})})]})})})}const Cg=Sg(iI,{Header:sc,Content:ac,Footer:lc,Controls:kg}),Jn={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)"}},Va={...Jn,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)"}},za={...Jn,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"}},_g=N.createContext(null),Tg=()=>{const e=N.useContext(_g);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function oI({theme:e="default",themes:t={},children:n,cssVariables:r=!0,className:i=""}){const[o,s]=N.useState(()=>{const f={default:Jn,dark:Va,enterprise:za,...t};return typeof e=="string"?f[e]||Jn:e}),[a,l]=N.useState(()=>({default:Jn,dark:Va,enterprise:za,...t})),c=f=>{if(typeof f=="string"){const p=a[f];p&&s(p)}else s(f)},u=f=>{l(p=>({...p,[f.name]:f}))};N.useEffect(()=>{if(r&&typeof document<"u"){const f=document.documentElement;Object.entries(Ng(o)).forEach(([p,g])=>{f.style.setProperty(`--voxket-${p}`,g)})}},[o,r]);const d={theme:o,setTheme:c,themes:a,registerTheme:u};return h.jsx(_g.Provider,{value:d,children:h.jsx("div",{className:`voxket-theme voxket-theme--${o.name} ${i}`,children:n})})}function Ng(e){const t={},n=(r,i="")=>{for(const[o,s]of Object.entries(r)){const a=i?`${i}-${o}`:o;typeof s=="object"&&s!==null&&!Array.isArray(s)?n(s,a):t[a]=String(s)}};return n(e),t}function sI(e=Jn,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 aI(e){var n;const{theme:t}=Tg();return((n=t.components)==null?void 0:n[e])||{}}const lI=ic("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&cI(e),t.enableVoiceActivation&&uI(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&dI(e,t)}});function cI(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 uI(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function dI(e,t){console.log("Playing audio response:",t.content)}const fI=ic("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&hI(),t.enableFileUpload&&pI(e),t.enableCustomComponents&&mI(),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"?gI(e,t):t.type==="text"&&n.enableRichText&&bI(e,t)}});function hI(e){console.log("Rich text support enabled")}function pI(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function mI(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",yI),t.set("form",xI),t.set("card",vI),t.set("chart",wI)}function gI(e,t){const{componentType:n,props:r}=t.metadata;console.log("Rendering custom component:",n,r),e.emit("chat.component.render",{type:n,props:r,timestamp:new Date})}function bI(e,t){console.log("Processing rich text message:",t.content)}function yI(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function xI(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function vI(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function wI(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function fo({track:e,participantName:t,showControls:n=!0,showName:r=!0,showMuteIndicator:i=!0,isPinned:o=!1,className:s="",onClick:a,onPin:l,onUnpin:c}){const u=N.useRef(null),[d,f]=N.useState(!1);N.useEffect(()=>{if(!u.current||!e.isEnabled)return;const v=u.current;return v.srcObject=null,()=>{v.srcObject&&(v.srcObject=null)}},[e]);const p=()=>{a==null||a(e)},g=v=>{v.stopPropagation(),o?c==null||c(e):l==null||l(e)},m=["voxket-video-tile",e.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",e.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",o?"voxket-video-tile--pinned":"",e.isEnabled?"":"voxket-video-tile--disabled",d?"voxket-video-tile--hovered":"",s].filter(Boolean).join(" ");return h.jsxs("div",{className:m,onClick:p,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[h.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&h.jsxs("div",{className:"voxket-video-placeholder",children:[h.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"🖥️":"📹"}),h.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),h.jsxs("div",{className:"voxket-video-overlay",children:[r&&t&&h.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),i&&!e.isEnabled&&h.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),n&&(d||o)&&h.jsxs("div",{className:"voxket-video-controls",children:[h.jsx("button",{className:`voxket-video-control-btn ${o?"voxket-video-control-btn--active":""}`,onClick:g,title:o?"Unpin video":"Pin video",children:"📌"}),e.isScreenShare&&h.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),e.source&&h.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&h.jsx("div",{className:"voxket-video-loading",children:h.jsx("div",{className:"voxket-spinner"})})]})}function EI({tracks:e,layout:t,className:n="",onLayoutChange:r,onTrackClick:i,maxVisibleTracks:o=9,showPagination:s=!0}){const[a,l]=N.useState(0),[c,u]=N.useState(null),d=N.useMemo(()=>{let E=[...e];t.type==="speaker"&&c&&(E=[c,...e.filter(k=>k.id!==c.id)]);const w=a*o,C=w+o;return E.slice(w,C)},[e,t,c,a,o]),f=Math.ceil(e.length/o),p=N.useMemo(()=>{const E=d.length;switch(t.type){case"grid":const w=Math.ceil(Math.sqrt(E)),C=Math.ceil(E/w);return{display:"grid",gridTemplateColumns:`repeat(${w}, 1fr)`,gridTemplateRows:`repeat(${C}, 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)},m=()=>{u(null)},v=E=>{r==null||r({...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?h.jsx("div",{className:"voxket-video-grid-empty",children:h.jsxs("div",{className:"voxket-video-grid-empty-content",children:[h.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),h.jsx("p",{children:"No video tracks available"})]})}):h.jsxs("div",{className:y,children:[h.jsxs("div",{className:"voxket-video-grid-controls",children:[h.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(E=>h.jsx("button",{className:`voxket-layout-btn ${t.type===E?"voxket-layout-btn--active":""}`,onClick:()=>v(E),title:`Switch to ${E} layout`,children:SI(E)},E))}),h.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),h.jsx("div",{className:"voxket-video-grid-content",style:p,children:t.type==="speaker"&&c?h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"voxket-video-speaker-main",children:h.jsx(fo,{track:c,participantName:`Participant ${c.participantId}`,isPinned:!0,onClick:i,onUnpin:m})}),h.jsx("div",{className:"voxket-video-speaker-sidebar",children:d.filter(E=>E.id!==c.id).map(E=>h.jsx(fo,{track:E,participantName:`Participant ${E.participantId}`,showControls:!1,onClick:i,onPin:g},E.id))})]}):d.map(E=>h.jsx(fo,{track:E,participantName:`Participant ${E.participantId}`,isPinned:(c==null?void 0:c.id)===E.id,onClick:i,onPin:g,onUnpin:m},E.id))}),s&&f>1&&h.jsxs("div",{className:"voxket-video-pagination",children:[h.jsx("button",{className:"voxket-pagination-btn",onClick:()=>l(Math.max(0,a-1)),disabled:a===0,children:"←"}),h.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",f]}),h.jsx("button",{className:"voxket-pagination-btn",onClick:()=>l(Math.min(f-1,a+1)),disabled:a===f-1,children:"→"})]})]})}function SI(e){switch(e){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function kI({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:r,showLayoutControls:i=!0,showCameraControls:o=!0,showScreenShareControls:s=!0,className:a=""}){const l=["voxket-video-controls",a].filter(Boolean).join(" "),c=u=>{r==null||r({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return h.jsxs("div",{className:l,children:[o&&h.jsxs("div",{className:"voxket-video-controls-section",children:[h.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),h.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:[h.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"📹":"📷"}),h.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&h.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," × ",e.dimensions.height]})]}),s&&h.jsxs("div",{className:"voxket-video-controls-section",children:[h.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),h.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:[h.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"🛑":"🖥️"}),h.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),i&&h.jsxs("div",{className:"voxket-video-controls-section",children:[h.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),h.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:f})=>h.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>c(u),title:`Switch to ${f} layout`,children:[h.jsx("span",{className:"voxket-control-icon",children:d}),h.jsx("span",{className:"voxket-control-label",children:f})]},u))})]}),h.jsxs("div",{className:"voxket-video-controls-section",children:[h.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),h.jsxs("div",{className:"voxket-video-settings",children:[h.jsxs("div",{className:"voxket-setting-group",children:[h.jsx("label",{className:"voxket-setting-label",children:"Quality"}),h.jsxs("select",{className:"voxket-setting-select",children:[h.jsx("option",{value:"high",children:"High (720p)"}),h.jsx("option",{value:"medium",children:"Medium (480p)"}),h.jsx("option",{value:"low",children:"Low (240p)"})]})]}),h.jsxs("div",{className:"voxket-setting-group",children:[h.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),h.jsxs("select",{className:"voxket-setting-select",children:[h.jsx("option",{value:"30",children:"30 fps"}),h.jsx("option",{value:"15",children:"15 fps"}),h.jsx("option",{value:"10",children:"10 fps"})]})]}),h.jsxs("div",{className:"voxket-setting-group",children:[h.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),h.jsxs("select",{className:"voxket-setting-select",children:[h.jsx("option",{value:"unlimited",children:"Unlimited"}),h.jsx("option",{value:"1000",children:"1 Mbps"}),h.jsx("option",{value:"500",children:"500 Kbps"}),h.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),h.jsxs("div",{className:"voxket-video-controls-section",children:[h.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),h.jsxs("div",{className:"voxket-video-stats",children:[h.jsxs("div",{className:"voxket-stat-item",children:[h.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),h.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}×${e.dimensions.height}`:"N/A"})]}),h.jsxs("div",{className:"voxket-stat-item",children:[h.jsx("span",{className:"voxket-stat-label",children:"Source:"}),h.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),h.jsxs("div",{className:"voxket-stat-item",children:[h.jsx("span",{className:"voxket-stat-label",children:"Status:"}),h.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 Ag=({handler:e,loadData:t,data:n,client:r,addLocalMessage:i})=>{const[o,s]=P.useState(null),[a,l]=P.useState(!0),[c,u]=P.useState(!1),[d]=P.useState(Date.now()),[f,p]=P.useState("pending");P.useEffect(()=>{(async()=>{try{if(l(!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"};s(E),console.log("📋 AssignmentView: Assignment loaded from RPC data:",E)}}catch(E){console.error("📋 AssignmentView: Error loading assignment:",E),s({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{l(!1)}})()},[n,t]);const g=({message:y,assignment:E})=>{const w=y.toLowerCase().includes("declined"),C=w?"bg-red-50 border-red-200":"bg-green-50 border-green-200",k=w?"text-red-700":"text-green-700",_=w?"❌":"🎉";return h.jsxs("div",{className:`max-w-sm mx-auto ${C} border rounded-lg shadow p-3 flex flex-col items-center`,children:[h.jsx("div",{className:"text-2xl mb-2",children:_}),h.jsx("div",{className:`${k} font-semibold text-sm mb-1`,children:y}),h.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:E.title}),h.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},m=async()=>{if(!(!o||!e)){u(!0);try{const y={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",y),e.didSuccess(y),p("accepted")}catch(y){console.error("📋 AssignmentView: Error accepting assignment:",y),e.didFail({error:"Failed to accept assignment"}),p("error")}finally{u(!1)}}},v=async()=>{if(!(!o||!e)){u(!0);try{const y={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",y),e.didSuccess(y),p("declined")}catch(y){console.error("📋 AssignmentView: Error declining assignment:",y),e.didFail({error:"Failed to decline assignment"}),p("error")}finally{u(!1)}}};return a?h.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:h.jsxs("div",{className:"flex items-center justify-center py-4",children:[h.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),h.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):o?f==="accepted"||f==="declined"||f==="error"?h.jsx(g,{message:f==="accepted"?"Assignment accepted!":f==="declined"?"Assignment declined":"Assignment error occurred",assignment:o}):h.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[h.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:h.jsx("div",{className:"flex items-center justify-between",children:h.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:o.title})})}),h.jsxs("div",{className:"p-3 text-black",children:[h.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:h.jsx("p",{className:"text-xs text-black leading-snug",children:o.description})}),h.jsx("div",{className:"mb-3 text-black",children:h.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[h.jsx("span",{className:"text-xs mr-1",children:"📅"}),h.jsxs("span",{children:["Est: ",o.estimated_time_of_completion]})]})}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:m,disabled:c,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:c?h.jsxs("span",{className:"flex items-center justify-center",children:[h.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),h.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),h.jsx("button",{onClick:v,disabled:c,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"})]})]})]}):h.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:h.jsxs("div",{className:"text-center py-4",children:[h.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),h.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function CI(){const[e,t]=P.useState(null),[n,r]=P.useState([]);P.useEffect(()=>{const a=new Ti({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",l=>{console.log("RPC Method Called:",l)}),a.on("rpc.interaction.completed",l=>{console.log("RPC Interaction Completed:",l)}),()=>{a.disconnect()}},[]);const i=async()=>{if(e)try{await e.registerFrontendRPC("give_assignment",Ag,"embedded");const a=e.getRegisteredRpcMethods();r(a),console.log("✅ Assignment RPC registered successfully")}catch(a){console.error("❌ Failed to register assignment RPC:",a)}},o=async()=>{if(!e)return;const a=({handler:l,timeout:c})=>{const[u,d]=P.useState(""),f=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],p=m=>{d(m)},g=()=>{const m=f.find(v=>v.id===u);l==null||l.didSuccess({selectedProduct:u,productName:m==null?void 0:m.name,price:m==null?void 0:m.price,timestamp:new Date().toISOString()})};return h.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[h.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),h.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),h.jsx("div",{className:"space-y-3 mb-6",children:f.map(m=>h.jsx("div",{onClick:()=>p(m.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${u===m.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:h.jsxs("div",{className:"flex justify-between items-center",children:[h.jsxs("div",{children:[h.jsx("h4",{className:"font-medium",children:m.name}),h.jsx("p",{className:"text-gray-600 text-sm",children:m.price})]}),h.jsx("div",{className:`w-4 h-4 rounded-full ${u===m.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},m.id))}),h.jsxs("div",{className:"flex justify-end space-x-3",children:[h.jsx("button",{onClick:()=>l==null?void 0:l.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),h.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"})]}),c&&h.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",c," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const l=e.getRegisteredRpcMethods();r(l),console.log("✅ Product Recommendation RPC registered successfully")}catch(l){console.error("❌ Failed to register product recommendation RPC:",l)}},s=async()=>{if(!e)return;const a=({handler:l})=>{const[c,u]=P.useState(0),[d,f]=P.useState(""),p=()=>{l==null||l.didSuccess({rating:c,comment:d,timestamp:new Date().toISOString()})};return h.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[h.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),h.jsxs("div",{className:"mb-4",children:[h.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),h.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(g=>h.jsx("button",{onClick:()=>u(g),className:`text-2xl ${g<=c?"text-yellow-400":"text-gray-300"}`,children:"⭐"},g))})]}),h.jsxs("div",{className:"mb-4",children:[h.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),h.jsx("textarea",{value:d,onChange:g=>f(g.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),h.jsxs("div",{className:"flex justify-end space-x-2",children:[h.jsx("button",{onClick:()=>l==null?void 0:l.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),h.jsx("button",{onClick:p,disabled:c===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 l=e.getRegisteredRpcMethods();r(l),console.log("✅ Feedback RPC registered successfully")}catch(l){console.error("❌ Failed to register feedback RPC:",l)}};return h.jsxs("div",{className:"p-6",children:[h.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),h.jsxs("div",{className:"space-y-4 mb-6",children:[h.jsxs("div",{children:[h.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),h.jsxs("div",{className:"space-x-2",children:[h.jsx("button",{onClick:i,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),h.jsx("button",{onClick:o,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),h.jsx("button",{onClick:s,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),h.jsxs("div",{children:[h.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?h.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>h.jsx("li",{className:"text-gray-700",children:h.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):h.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),h.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[h.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),h.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[h.jsxs("li",{children:["Register RPC methods with React components using ",h.jsx("code",{children:"client.registerFrontendRPC()"})]}),h.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),h.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),h.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),h.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),h.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[h.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),h.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),h.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
143
+ `,style:{minHeight:"3rem",display:s===r?"flex":"none",alignItems:"center",justifyContent:"center"},children:h.jsx("span",{className:"italic",children:o})},s))})}const ig=N.forwardRef(({disabled:e,onStartCall:t,onStartChat:n,onStartVideo:r,prompts:i=['"Book a meeting with the marketing team"',`"What's the status of project Alpha?"`,`"Summarize yesterday's sales report"`,'"Find a good Italian restaurant nearby"','"Remind me to call John tomorrow at 10 AM"'],statusMessage:o="Agent is ready",title:s="Choose how to interact",subTitle:a="Ask me anything or give me a task to complete",theme:l="vox",modalities:c=["voice","chat","video"]},u)=>{const d=Lt(l),f=c.includes("voice"),p=c.includes("chat"),g=c.includes("video"),m=[f,p,g].filter(Boolean).length,v=l==="light"?"group-hover:text-gray-900":"group-hover:text-white";return h.jsxs("div",{className:"flex flex-col items-center h-full justify-center w-full relative px-8 py-16","aria-disabled":e,style:{background:"transparent"},children:[h.jsx("div",{className:"absolute inset-0 opacity-[0.01] pointer-events-none mix-blend-overlay",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 400 400' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulance type='fractalNoise' baseFrequency='2' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E")`,backgroundRepeat:"repeat"}}),h.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] bg-gradient-radial from-white/[0.02] to-transparent blur-3xl pointer-events-none"}),h.jsxs("div",{className:"flex flex-col items-center justify-center w-full max-w-2xl space-y-12 z-10",children:[h.jsx("div",{className:"text-center space-y-2 max-w-md",children:h.jsx("p",{className:`text-base leading-relaxed tracking-wide ${d.text.secondary}`,children:a})}),h.jsx("div",{className:"flex items-center justify-center w-full",children:f&&p&&g?h.jsxs("div",{className:"flex gap-5 items-center justify-center",children:[h.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:t,children:[h.jsx(eo,{onClick:t,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} ${v} transition-colors duration-300`,children:"Voice"})]}),h.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:n,children:[h.jsx(Qs,{onClick:n,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} ${v} transition-colors duration-300`,children:"Chat"})]}),h.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:r||t,children:[h.jsx(Js,{onClick:r||t,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} ${v} transition-colors duration-300`,children:"Video"})]})]}):m>1?h.jsxs("div",{className:"flex gap-6 items-center justify-center",children:[f&&h.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:t,children:[h.jsx(eo,{onClick:t,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} ${v} transition-colors duration-300`,children:"Voice"})]}),p&&h.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:n,children:[h.jsx(Qs,{onClick:n,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} ${v} transition-colors duration-300`,children:"Chat"})]}),g&&r&&h.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:r,children:[h.jsx(Js,{onClick:r,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} ${v} transition-colors duration-300`,children:"Video"})]})]}):h.jsx("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",children:f?h.jsxs(h.Fragment,{children:[h.jsx(eo,{onClick:t,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} ${v} transition-colors duration-300`,children:"Voice"})]}):p?h.jsxs(h.Fragment,{children:[h.jsx(Qs,{onClick:n,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} ${v} transition-colors duration-300`,children:"Chat"})]}):g&&r?h.jsxs(h.Fragment,{children:[h.jsx(Js,{onClick:r,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} ${v} transition-colors duration-300`,children:"Video"})]}):h.jsxs(h.Fragment,{children:[h.jsx(eo,{onClick:t,disabled:e,theme:l}),h.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} ${v} transition-colors duration-300`,children:"Voice"})]})})}),h.jsx("div",{className:"w-full flex justify-center",children:h.jsx(BR,{prompts:i,theme:l})})]})]})});ig.displayName="Welcome";class nc extends P.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("VoxketWidget Error:",t,n)}render(){if(this.state.hasError){if(this.props.fallback){const t=this.props.fallback;return P.createElement(t,{error:this.state.error})}return P.createElement("div",{style:{padding:"20px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"}},"VoxketWidget encountered an error. Please check the console for details.")}return this.props.children}}const og=({onClick:e,position:t="bottom-right",size:n=64,className:r="",style:i,ariaLabel:o="Open Voxket",logoScale:s=.7,isRunning:a=!1,theme:l="vox"})=>{const c={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},u=l==="light"?"#3b82f6":"#000000",d={width:n,height:n,...i},f=P.useMemo(()=>{if(typeof window>"u"||!window.matchMedia)return!1;try{return window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}},[]);return h.jsxs("div",{className:"relative",children:[a&&h.jsxs(h.Fragment,{children:[h.jsx(De.div,{className:"absolute inset-0 rounded-full pointer-events-none",style:{width:n+24,height:n+24,left:-12,top:-12,background:"linear-gradient(45deg, rgba(6,182,212,0.3), rgba(34,211,238,0.3), rgba(6,182,212,0.3))",filter:"blur(8px)"},animate:f?void 0:{scale:[1,1.1,1],opacity:[.6,.9,.6]},transition:f?void 0:{duration:2,repeat:1/0,ease:"easeInOut"}}),h.jsx(De.div,{className:"absolute inset-0 rounded-full pointer-events-none",style:{width:n+16,height:n+16,left:-8,top:-8,background:"linear-gradient(135deg, rgba(6,182,212,0.4), rgba(34,211,238,0.4))",filter:"blur(4px)"},animate:f?void 0:{scale:[1,1.05,1],opacity:[.7,1,.7]},transition:f?void 0:{duration:1.5,repeat:1/0,ease:"easeInOut",delay:.2}})]}),h.jsxs(De.button,{type:"button",onClick:e,"aria-label":o,className:`fixed z-50 rounded-full flex items-center justify-center overflow-hidden focus:outline-none focus:ring-2 focus:ring-cyan-400/60 ${c[t]} ${r}`,style:{...d,backgroundColor:u,boxShadow:a?"0 0 0 2px rgba(6,182,212,0.5), 0 0 20px rgba(6,182,212,0.4), 0 8px 32px rgba(0,0,0,0.3)":l==="light"?"0 8px 32px rgba(59, 130, 246, 0.3)":"0 8px 32px rgba(0,0,0,0.3)",border:a?"2px solid rgba(6,182,212,0.6)":"none"},initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1,...a&&!f?{boxShadow:["0 0 0 2px rgba(6,182,212,0.5), 0 0 20px rgba(6,182,212,0.4), 0 8px 32px rgba(0,0,0,0.3)","0 0 0 2px rgba(6,182,212,0.8), 0 0 30px rgba(6,182,212,0.6), 0 8px 32px rgba(0,0,0,0.3)","0 0 0 2px rgba(6,182,212,0.5), 0 0 20px rgba(6,182,212,0.4), 0 8px 32px rgba(0,0,0,0.3)"]}:{}},exit:{scale:.9,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},"data-position":t,transition:{...!f&&a?{boxShadow:{duration:2,repeat:1/0,ease:"easeInOut"}}:{}},children:[a&&h.jsxs(h.Fragment,{children:[h.jsx(De.span,{"aria-hidden":!0,className:"absolute inset-0 rounded-full pointer-events-none",style:{background:"conic-gradient(from 0deg, rgba(6,182,212,0.0) 0deg, rgba(6,182,212,1) 90deg, rgba(34,211,238,1) 180deg, rgba(6,182,212,0.0) 270deg)",WebkitMask:"radial-gradient(farthest-side, transparent calc(100% - 2px), #000 calc(100% - 2px))",mask:"radial-gradient(farthest-side, transparent calc(100% - 2px), #000 calc(100% - 2px))"},animate:f?void 0:{rotate:360},transition:f?void 0:{duration:3,repeat:1/0,ease:"linear"}}),h.jsx("span",{"aria-hidden":!0,className:"absolute inset-1 rounded-full pointer-events-none",style:{background:"radial-gradient(circle, rgba(6,182,212,0.1) 0%, transparent 70%)"}})]}),h.jsx("img",{src:"/logo.png",alt:"Voxket",className:"object-contain select-none pointer-events-none relative z-10",style:{width:`${Math.max(0,Math.min(1,s))*100}%`,height:`${Math.max(0,Math.min(1,s))*100}%`,filter:a?"brightness(1.1) contrast(1.1)":"none"},draggable:!1})]})]})};function sg({room:e,onSessionEnd:t,onSessionStart:n,enableConsoleLogging:r=!0,enableLocalStorage:i=!0,voxketSessionId:o}={}){const[s,a]=P.useState(null),[l,c]=P.useState([]),[u,d]=P.useState(null),[f,p]=P.useState([]),g=P.useCallback((E,w)=>{const C={timestamp:new Date,event:E,data:w,sessionId:s==null?void 0:s.sessionId,participantId:u==null?void 0:u.identity};if(c(k=>[...k,C]),i){const k=JSON.parse(localStorage.getItem("voxket-session-logs")||"[]");k.push(C),localStorage.setItem("voxket-session-logs",JSON.stringify(k))}return C},[s==null?void 0:s.sessionId,u==null?void 0:u.identity,r,i]);P.useEffect(()=>{if(!e)return;const E=()=>{const b=o||`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,M=new Date,I={sessionId:b,startTime:M,totalMessages:0,connectionIssues:0,participantCount:f.length,events:[]};a(I),g("SESSION_STARTED",{sessionId:b,startTime:M}),n==null||n(b)},w=()=>{if(s){const b=new Date,M=b.getTime()-s.startTime.getTime(),I={...s,endTime:b,duration:M,events:l};g("SESSION_ENDED",{sessionId:s.sessionId,duration:`${Math.round(M/1e3)}s`,totalMessages:s.totalMessages,connectionIssues:s.connectionIssues}),t==null||t(I),a(null),c([])}},C=b=>{g("CONNECTION_STATE_CHANGED",{state:b}),b===ae.ConnectionState.Reconnecting&&s&&(a(M=>M?{...M,connectionIssues:M.connectionIssues+1}:null),g("CONNECTION_ISSUE",{type:"reconnecting"}))},k=b=>{g("TRACK_PUBLISHED",{trackKind:b.kind,trackSource:b.source})},_=b=>{g("TRACK_UNPUBLISHED",{trackKind:b.kind,trackSource:b.source})},R=(b,M)=>{s&&a(I=>I?{...I,totalMessages:I.totalMessages+1}:null),g("DATA_RECEIVED",{participantId:M==null?void 0:M.identity,dataSize:b.length})},A=b=>{g("PARTICIPANT_CONNECTED",{participantId:b.identity,participantName:b.name}),p(M=>[...M,b]),s&&a(M=>M?{...M,participantCount:M.participantCount+1}:null)},O=b=>{g("PARTICIPANT_DISCONNECTED",{participantId:b.identity,participantName:b.name}),p(M=>M.filter(I=>I.identity!==b.identity))};return e.localParticipant&&d(e.localParticipant),e.on(ae.RoomEvent.Connected,E),e.on(ae.RoomEvent.Disconnected,w),e.on(ae.RoomEvent.ConnectionStateChanged,C),e.on(ae.RoomEvent.TrackPublished,k),e.on(ae.RoomEvent.TrackUnpublished,_),e.on(ae.RoomEvent.DataReceived,R),e.on(ae.RoomEvent.ParticipantConnected,A),e.on(ae.RoomEvent.ParticipantDisconnected,O),()=>{e.off(ae.RoomEvent.Connected,E),e.off(ae.RoomEvent.Disconnected,w),e.off(ae.RoomEvent.ConnectionStateChanged,C),e.off(ae.RoomEvent.TrackPublished,k),e.off(ae.RoomEvent.TrackUnpublished,_),e.off(ae.RoomEvent.DataReceived,R),e.off(ae.RoomEvent.ParticipantConnected,A),e.off(ae.RoomEvent.ParticipantDisconnected,O)}},[e,s,l,f.length,g,t,n]);const m=P.useCallback(()=>i?JSON.parse(localStorage.getItem("voxket-session-logs")||"[]"):l,[l,i]),v=P.useCallback(()=>{i&&localStorage.removeItem("voxket-session-logs"),c([])},[i]),y=P.useCallback(()=>{const E=m(),w=JSON.stringify(E,null,2),C="data:application/json;charset=utf-8,"+encodeURIComponent(w),k=`voxket-session-logs-${new Date().toISOString().split("T")[0]}.json`,_=document.createElement("a");_.setAttribute("href",C),_.setAttribute("download",k),_.click()},[m]);return{sessionMetrics:s,sessionLogs:l,logEvent:g,getSessionLogs:m,clearSessionLogs:v,exportSessionLogs:y}}class rc{constructor(){Ee(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 r=(...i)=>{this.off(t,r),n(...i)};return this.on(t,r)}off(t,n){const r=this.listeners[t];if(!r)return;const i=r.indexOf(n);i>-1&&r.splice(i,1)}removeAllListeners(t){t?delete this.listeners[t]:this.listeners={}}emit(t,...n){const r=this.listeners[t];if(!r)return;const i=[...r];for(const o of i)try{o(...n)}catch(s){console.error(`Error in event listener for ${String(t)}:`,s)}}listenerCount(t){var n;return((n=this.listeners[t])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class ag{constructor(t){Ee(this,"plugins",new Map);Ee(this,"installedPlugins",new Set);Ee(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 r=this.plugins.get(t);if(!r)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t))throw new Error(`Plugin '${t}' is already installed`);if(r.dependencies)for(const o of r.dependencies)this.installedPlugins.has(o)||await this.install(o);const i={...this.context,config:{...r.config,...n}};r.install&&await r.install(i),this.installedPlugins.add(t),this.setupPluginEvents(r,i)}async uninstall(t){var r;const n=this.plugins.get(t);if(!n)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t)){for(const[i,o]of this.plugins)if(this.installedPlugins.has(i)&&((r=o.dependencies)!=null&&r.includes(t)))throw new Error(`Cannot uninstall '${t}' because '${i}' 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",r=>{t.onSessionStart(n,r.id)}),t.onSessionEnd&&n.on("session.ended",r=>{t.onSessionEnd(n,r.id)}),t.onAgentResponse&&n.on("agent.response",r=>{t.onAgentResponse(n,r)})}}function $R(e){return e}function ic(e,t,n){return{name:e,version:"1.0.0",description:`${t} modality plugin`,install:async r=>{n.onActivate&&await n.onActivate(r)},uninstall:async r=>{n.onDeactivate&&await n.onDeactivate(r)},onAgentResponse:n.onMessage}}const VR={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)})}},zR={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,...r)=>(console.log(`[Debug] Event: ${String(n)}`,r),t(n,...r))}},UR={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 lg extends rc{constructor(n){super();Ee(this,"room",null);Ee(this,"registeredMethods",new Map);Ee(this,"activeInteractions",new Map);Ee(this,"currentInteraction",null);n&&this.setRoom(n)}setRoom(n){this.room=n}async registerFrontendRPC(n,r,i="embedded"){if(console.log(`RpcManager: Starting registration for method '${n}'`),!this.room)throw console.error(`RpcManager: Cannot register '${n}' - no room instance`),new Error("Room not initialized. Cannot register RPC method.");if(!this.room.localParticipant)throw console.error(`RpcManager: Cannot register '${n}' - no local participant`),new Error("Local participant not available for RPC registration");console.log(`RpcManager: Room state: ${this.room.state}`),console.log(`RpcManager: Local participant: ${this.room.localParticipant.identity}`),console.log(`RpcManager: Registering frontend RPC method: ${n}`);const o={methodName:n,component:r,presentationMode:i};this.registeredMethods.set(n,o);try{this.room.registerRpcMethod(n,async s=>{console.log(`RpcManager: RPC method '${n}' called by ${s.callerIdentity}`),console.log("RpcManager: Payload:",s.payload),this.emit("rpc.method.called",{methodName:n,data:s});let a;console.log(`RpcManager: Current registration for '${n}':`,o);let l=s.responseTimeout||30;try{a=JSON.parse(s.payload)}catch{a=s.payload}try{const c=await this.awaitUserInteraction(n,r,i,a,l);return JSON.stringify(c)}catch(c){throw console.error(`RpcManager: Error in RPC method '${n}':`,c),c}}),this.emit("rpc.method.registered",{methodName:n}),console.log(`RpcManager: Successfully registered RPC method: ${n}`)}catch(s){throw console.error(`RpcManager: Failed to register RPC method '${n}':`,s),s}}async awaitUserInteraction(n,r,i,o,s){return new Promise((a,l)=>{const c=`${n}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${n}, timeout: ${s} seconds`);const u={didSuccess:(f,p)=>{console.log(`RpcManager: User interaction successful for method: ${n}`,f),this.clearInteraction(c),this.currentInteraction=null;const g={success:!0,message:"User interaction completed successfully",data:f,timestamp:new Date,...p?{successView:p}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:g}),a(g)},didFail:f=>{console.log(`RpcManager: User interaction failed for method: ${n}`,f),this.clearInteraction(c);const p={success:!1,message:"User interaction failed",error:f,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:p}),a(p)},dismissView:()=>{var p;console.log(`RpcManager: User dismissed interaction for method: ${n}`),console.log("RpcManager: Current interaction before dismiss:",(p=this.currentInteraction)==null?void 0:p.methodName),this.clearInteraction(c),this.currentInteraction=null,console.log("RpcManager: Current interaction after dismiss:",this.currentInteraction);const f={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:f}),this.emit("rpc.interaction.completed",{methodName:n,response:f}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(f)},didTimeout:f=>{console.log(`RpcManager: User interaction timeout for method: ${n}`),this.clearInteraction(c),this.currentInteraction=null;const p={success:!0,message:`User interaction timed out after ${s} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...f?{timeoutView:f}:{}};this.emit("rpc.interaction.timeout",{methodName:n,response:p}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(p)}},d=setTimeout(()=>{u.didTimeout&&u.didTimeout()},s);this.activeInteractions.set(c,{resolve:f=>a(JSON.parse(f)),reject:l,timeoutId:d}),this.currentInteraction={isVisible:!0,methodName:n,component:r,presentationMode:i,timeout:s,data:o,handler:u},this.emit("rpc.interaction.started",{methodName:n,presentationMode:i}),setTimeout(async()=>{var f;if((f=this.currentInteraction)!=null&&f.handler)try{console.log(`RpcManager: Component created for method: ${n} with data:`,o)}catch(p){console.error("RpcManager: Error loading data into component:",p),u.didFail({error:"Failed to load data into component"})}},100)})}clearInteraction(n){const r=this.activeInteractions.get(n);r&&(console.log(`RpcManager: Clearing interaction: ${n}`),clearTimeout(r.timeoutId),this.activeInteractions.delete(n))}getCurrentInteraction(){return this.currentInteraction}dismissCurrentInteraction(){var n;this.currentInteraction&&(console.log(`RpcManager: Dismissing current interaction: ${this.currentInteraction.methodName}`),(n=this.currentInteraction.handler)==null||n.dismissView(),setTimeout(()=>{this.currentInteraction&&(console.log("RpcManager: Force clearing lingering interaction"),this.currentInteraction=null)},0))}getRegisteredMethods(){return Array.from(this.registeredMethods.keys())}unregisterMethod(n){this.registeredMethods.delete(n),console.log(`RpcManager: Unregistered RPC method: ${n}`)}clear(){for(const[n,r]of this.activeInteractions)clearTimeout(r.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null,console.log("RpcManager: Cleared all registrations and interactions")}}class Ye extends Error{constructor(t,n,r){super(t),this.code=n,this.details=r,this.name="VoxketError"}}class cg{constructor(t,n="User"){Ee(this,"chatMessages",[]);Ee(this,"activeTranscriptions",new Map);Ee(this,"room",null);Ee(this,"eventEmitter");Ee(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(r=>r.id===t.id)||this.chatMessages.push(t)}updateChatMessage(t){const n=this.chatMessages.findIndex(r=>r.id===t.id);n!==-1&&(this.chatMessages[n]=t)}clearChatMessages(){this.chatMessages=[],this.activeTranscriptions.clear(),console.log("🧹 ChatManager: Cleared chat messages and transcription history")}trackTranscription(t,n){this.activeTranscriptions.set(t,{messageId:n,timestamp:Date.now()})}getActiveTranscription(t){const n=Date.now(),r=this.activeTranscriptions.get(t);return r&&n-r.timestamp<1e3?r:null}async sendMessage(t,n){if(!this.room)throw new Ye("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw new Ye("No local participant","CONNECTION_FAILED");try{const r={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",r)}catch(r){throw console.error("ChatManager: Failed to send chat message:",r),new Ye("Failed to send message","NETWORK_ERROR",r)}}async sendAttachments(t,n){if(!this.room)throw new Ye("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw new Ye("No local participant","CONNECTION_FAILED");if(!t||t.length===0)throw new Ye("No files provided","INVALID_PARAMETER");const r=t.filter(i=>i.type.startsWith("image/"));if(r.length===0)throw new Ye("Only image files are allowed","INVALID_PARAMETER");r.length!==t.length&&console.warn("ChatManager: Some non-image files were filtered out");try{const i=r.map(async(o,s)=>{const l={id:`att_${Date.now()}_${s}`,content:`📎 ${o.name}`,sender:{id:"user",name:this.participantName,type:"participant"},timestamp:new Date,metadata:{...n,type:"attachment",fileName:o.name,fileSize:o.size,mimeType:o.type,uploading:!0}};this.eventEmitter.emit("chat.message.sent",l);const c=await this.room.localParticipant.sendFile(o,{mimeType:o.type,topic:"images",onProgress:d=>{const f={...l,metadata:{...l.metadata,uploadProgress:d}};this.eventEmitter.emit("chat.message.updated",f)}});try{const d=new FileReader,f=new Promise((m,v)=>{d.onload=()=>{typeof d.result=="string"?m(d.result):v(new Error("Failed to convert to base64"))},d.onerror=v});d.readAsDataURL(o);const g={type:"image",data:await f,filename:o.name,mimeType:o.type,size:o.size};await this.room.localParticipant.sendText(JSON.stringify(g),{topic:"images",destinationIdentities:[]})}catch(d){console.warn("ChatManager: Failed to send image data to agent:",d);try{const f=`I've shared an image: ${o.name}`;await this.room.localParticipant.sendText(f,{topic:"lk.chat",destinationIdentities:[]})}catch(f){console.warn("ChatManager: Failed to send image notification to agent:",f)}}const u={...l,metadata:{...l.metadata,uploading:!1,uploadProgress:1,streamId:c.id}};return this.eventEmitter.emit("chat.message.updated",u),c});await Promise.all(i)}catch(i){throw console.error("ChatManager: Failed to send attachments:",i),new Ye("Failed to send attachments","NETWORK_ERROR",i)}}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 ug{constructor(t){Ee(this,"room",null);Ee(this,"eventEmitter");Ee(this,"silencePreventionNode",null);Ee(this,"silencePreventionOscillator",null);Ee(this,"audioContext",null);this.eventEmitter=t,this.initializeAudioContext()}initializeAudioContext(){try{if(this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),console.log("🔊 MediaManager: AudioContext created:",{state:this.audioContext.state,sampleRate:this.audioContext.sampleRate})),this.audioContext.state==="suspended"){console.log("🔊 MediaManager: AudioContext suspended, will resume on user interaction");const t=async()=>{this.audioContext&&this.audioContext.state==="suspended"&&(await this.audioContext.resume(),console.log("✅ MediaManager: AudioContext resumed:",this.audioContext.state)),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})}else this.audioContext.state==="running"&&console.log("✅ MediaManager: AudioContext already running")}catch(t){console.error("MediaManager: Failed to initialize AudioContext:",t)}}async ensureAudioContextRunning(){if(this.audioContext||this.initializeAudioContext(),this.audioContext&&this.audioContext.state==="suspended"){console.log("🔊 MediaManager: Attempting to resume suspended AudioContext");try{await this.audioContext.resume(),console.log("✅ MediaManager: AudioContext resumed successfully")}catch(t){console.error("MediaManager: Failed to resume AudioContext:",t)}}}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,r;try{await this.ensureAudioContextRunning();const i=(n=this.room)==null?void 0:n.localParticipant.isMicrophoneEnabled,o=t??!i;o&&this.startSilencePrevention(),await((r=this.room)==null?void 0:r.localParticipant.setMicrophoneEnabled(o,{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0})),o?this.eventEmitter.emit("track.unmuted",{source:"microphone",enabled:!0}):(this.eventEmitter.emit("track.muted",{source:"microphone",enabled:!1}),this.stopSilencePrevention()),console.log("🎤 MediaManager: Microphone",o?"enabled":"disabled")}catch(i){throw console.error("MediaManager: Failed to toggle microphone:",i),this.stopSilencePrevention(),new Ye("Failed to toggle microphone","PERMISSION_DENIED",i)}}startSilencePrevention(){try{if(this.audioContext||(this.audioContext=new AudioContext),this.silencePreventionOscillator)return;console.log("🔇 MediaManager: Starting silence prevention"),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(),console.log("✅ MediaManager: Silence prevention started")}catch(t){console.error("❌ MediaManager: Failed to start silence prevention:",t)}}stopSilencePrevention(){try{this.silencePreventionOscillator&&(console.log("🔇 MediaManager: Stopping silence prevention"),this.silencePreventionOscillator.stop(),this.silencePreventionOscillator.disconnect(),this.silencePreventionOscillator=null),this.silencePreventionNode&&(this.silencePreventionNode.disconnect(),this.silencePreventionNode=null)}catch(t){console.error("❌ MediaManager: Failed to stop silence prevention:",t)}}async toggleCamera(t){return this.setCameraEnabled(t!==!1)}async setCameraEnabled(t){var n,r;try{const i=(n=this.room)==null?void 0:n.localParticipant.isCameraEnabled,o=t??!i;await((r=this.room)==null?void 0:r.localParticipant.setCameraEnabled(o)),o?this.eventEmitter.emit("track.unmuted",{source:"camera",enabled:!0}):this.eventEmitter.emit("track.muted",{source:"camera",enabled:!1})}catch(i){throw new Ye("Failed to toggle camera","PERMISSION_DENIED",i)}}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){throw new Ye("Failed to start screen share","PERMISSION_DENIED",n)}}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){throw new Ye("Failed to stop screen share","PERMISSION_DENIED",n)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="audioinput")}catch(t){throw new Ye("Failed to get audio input devices","DEVICE_ERROR",t)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="videoinput")}catch(t){throw new Ye("Failed to get video input devices","DEVICE_ERROR",t)}}async setAudioInputDevice(t){var n;try{if(!((n=this.room)!=null&&n.localParticipant))throw new Error("Not connected to room")}catch(r){throw new Ye("Failed to set audio input device","DEVICE_ERROR",r)}}async setVideoInputDevice(t){var n;try{if(!((n=this.room)!=null&&n.localParticipant))throw new Error("Not connected to room")}catch(r){throw new Ye("Failed to set video input device","DEVICE_ERROR",r)}}getMicrophoneTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===ae.Track.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===ae.Track.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===ae.Track.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();console.log("🔊 MediaManager.getAgentAudioTrack: Checking remote participants:",{count:t.length,participants:t.map(n=>({identity:n.identity,name:n.name,hasMicTrack:!!n.getTrackPublication(ae.Track.Source.Microphone)}))});for(const n of t){const r=n.getTrackPublication(ae.Track.Source.Microphone);if(r!=null&&r.track)return console.log("✅ MediaManager.getAgentAudioTrack: Found audio track for",n.identity),{source:ae.Track.Source.Microphone,participant:n,publication:r}}return console.log("❌ MediaManager.getAgentAudioTrack: No audio track found"),null}getAgentVideoTrack(){const t=this.getRemoteParticipants();for(const n of t){const r=n.getTrackPublication(ae.Track.Source.Camera);if(r!=null&&r.track)return{source:ae.Track.Source.Camera,participant:n,publication:r}}return null}getVideoTrackRefs(){const t=[],n=this.getLocalParticipant();if(n){const i=n.getTrackPublication(ae.Track.Source.Camera);i!=null&&i.track&&t.push({source:ae.Track.Source.Camera,participant:n,publication:i});const o=n.getTrackPublication(ae.Track.Source.ScreenShare);o!=null&&o.track&&t.push({source:ae.Track.Source.ScreenShare,participant:n,publication:o})}const r=this.getRemoteParticipants();for(const i of r){const o=i.getTrackPublication(ae.Track.Source.Camera);o!=null&&o.track&&t.push({source:ae.Track.Source.Camera,participant:i,publication:o});const s=i.getTrackPublication(ae.Track.Source.ScreenShare);s!=null&&s.track&&t.push({source:ae.Track.Source.ScreenShare,participant:i,publication:s})}return t}getCameraTrackRefs(){return this.getVideoTrackRefs().filter(t=>t.source===ae.Track.Source.Camera)}getScreenShareTrackRefs(){return this.getVideoTrackRefs().filter(t=>t.source===ae.Track.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 r=i=>!!n.canPublish&&(n.canPublishSources.length===0||n.canPublishSources.includes(i));return{camera:r(1),microphone:r(2),screenShare:r(3),data:n.canPublishData??!1}}canPublishSource(t){return this.getPublishPermissions()[t]}}class dg{constructor(t,n){Ee(this,"room",null);Ee(this,"config");Ee(this,"eventEmitter");Ee(this,"connectionState",ae.ConnectionState.Disconnected);Ee(this,"isConnected",!1);Ee(this,"currentAgentInfo",null);this.config=t,this.eventEmitter=n,this.initializeRoom()}initializeRoom(){this.room=new ae.Room({adaptiveStream:!1,stopLocalTrackOnUnpublish:!1,audioCaptureDefaults:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},publishDefaults:{stopMicTrackOnMute:!1,preConnectBuffer:!0}}),this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(ae.RoomEvent.Connected,()=>{this.connectionState=ae.ConnectionState.Connected,this.isConnected=!0,console.log("📡 ConnectionManager: Emitting connection.connected event"),this.eventEmitter.emit("connection.connected")}),this.room.on(ae.RoomEvent.Disconnected,t=>{console.log("ConnectionManager: Room disconnected, reason:",t),this.connectionState=ae.ConnectionState.Disconnected,this.isConnected=!1,t&&console.log("ConnectionManager: Disconnect reason details:",{reason:t.toString(),connectionState:this.connectionState}),this.eventEmitter.emit("connection.disconnected",t==null?void 0:t.toString())}),this.room.on(ae.RoomEvent.ConnectionStateChanged,t=>{this.connectionState=t,t===ae.ConnectionState.Connecting&&this.eventEmitter.emit("connection.connecting")}),this.room.on(ae.RoomEvent.ParticipantConnected,t=>{const n={id:t.identity,name:t.name||t.identity,isLocal:!1};this.eventEmitter.emit("participant.joined",n)}),this.room.on(ae.RoomEvent.ParticipantDisconnected,t=>{const n={id:t.identity,name:t.name||t.identity,isLocal:!1};this.eventEmitter.emit("participant.left",n)}),this.room.on(ae.RoomEvent.LocalTrackPublished,t=>{console.log("ConnectionManager: Local track published:",t.source),t.source===ae.Track.Source.ScreenShare?this.eventEmitter.emit("track.unmuted",{source:"screenShare",enabled:!0}):t.source===ae.Track.Source.Microphone&&(console.log("✅ ConnectionManager: Local MICROPHONE track RE-PUBLISHED at:",new Date().toISOString()),console.log(" Track restart complete - audio should resume"))}),this.room.on(ae.RoomEvent.LocalTrackUnpublished,t=>{console.log(" ConnectionManager: Local track unpublished:",t.source),t.source===ae.Track.Source.ScreenShare?this.eventEmitter.emit("track.muted",{source:"screenShare",enabled:!1}):t.source===ae.Track.Source.Microphone&&(console.warn("⚠️ ConnectionManager: Local MICROPHONE track UNPUBLISHED at:",new Date().toISOString()),console.log(" ⚠️ WARNING: This will cause audio disruption!"))}),this.room.on(ae.RoomEvent.LocalAudioSilenceDetected,()=>{var t,n;console.log("🔇 ConnectionManager: Local audio silence detected at:",new Date().toISOString()),console.log(" Remote participants count:",(t=this.room)==null?void 0:t.remoteParticipants.size),(n=this.room)==null||n.remoteParticipants.forEach(r=>{console.log(" Remote participant:",r.identity,{audioTracks:r.audioTrackPublications.size,hasAudio:Array.from(r.audioTrackPublications.values()).some(i=>i.track)})})}),this.room.on(ae.RoomEvent.TrackSubscribed,(t,n,r)=>{var i,o;console.log("🎵 ConnectionManager: Track subscribed:",{trackKind:t.kind,trackSource:t.source,participantIdentity:r.identity,isAgent:(i=r.identity)==null?void 0:i.startsWith("agent-")}),this.eventEmitter.emit("media.track.subscribed",{id:t.sid||n.trackSid,kind:t.kind,source:((o=t.source)==null?void 0:o.toString())||"unknown",participantId:r.identity,isEnabled:!t.isMuted,isMuted:t.isMuted})}),this.room.on(ae.RoomEvent.TrackUnsubscribed,(t,n,r)=>{var i;console.log("🔇 ConnectionManager: Track unsubscribed:",{trackKind:t.kind,participantIdentity:r.identity}),this.eventEmitter.emit("media.track.unsubscribed",{id:t.sid||n.trackSid,kind:t.kind,source:((i=t.source)==null?void 0:i.toString())||"unknown",participantId:r.identity,isEnabled:!1,isMuted:!0})}))}async fetchConnectionDetails(t,n,r,i){try{const o={agent_id:t,participant_name:n,participant_metadata:i||{user_id:""},modality:r[0],modalities:r},s=await fetch(`${this.config.baseUrl}/api/live/agent/session`,{method:"POST",headers:{accept:"application/json","X-APP-ID":this.config.appId,"X-APP-SECRET":this.config.appSecret,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){let c=`HTTP ${s.status}: Failed to fetch connection details`;try{const u=await s.json();u&&(u.error?c=`API Error: ${u.error}`:u.detail?c=`API Error: ${u.detail}`:u.message&&(c=`API Error: ${u.message}`))}catch{try{const d=await s.text();d&&(c=`API Error: ${d}`)}catch{}}throw new Error(c)}const a=await s.json();let l;return a.agent_info&&(l={id:a.agent_info.agent_info.id,name:a.agent_info.agent_info.name,capabilities:a.agent_info.capabilities,modality_supported:a.agent_info.modality_supported,session_settings:a.agent_info.session_settings||{}},this.currentAgentInfo=l),{serverUrl:a.wss_url,participantToken:a.token,voxketSessionId:a.session_id,agentInfo:l}}catch(o){console.error("ConnectionManager: fetchConnectionDetails failed:",o);const s=new Ye(`Failed to fetch connection details: ${o instanceof Error?o.message:"Unknown error"}`,"CONNECTION_FAILED",o);throw this.eventEmitter.emit("connection.error",s),s}}async connect(t,n,r,i){var o;try{this.eventEmitter.emit("connection.connecting");const s=await this.fetchConnectionDetails(t,n,r,i);return await((o=this.room)==null?void 0:o.connect(s.serverUrl,s.participantToken)),this.isConnected=!0,s}catch(s){console.error("ConnectionManager: Connection failed:",s);const a=new Ye(`Failed to connect to Voxket services: ${s instanceof Error?s.message:"Unknown error"}`,"CONNECTION_FAILED",s);throw this.eventEmitter.emit("connection.error",a),a}}async disconnect(){try{this.room&&await this.room.disconnect(),this.isConnected=!1,this.currentAgentInfo=null,this.initializeRoom(),this.eventEmitter.emit("connection.disconnected")}catch(t){console.error("ConnectionManager: Disconnect failed:",t);const n=new Ye("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===ae.ConnectionState.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 fg{constructor(t,n,r){Ee(this,"room",null);Ee(this,"eventEmitter");Ee(this,"chatManager");Ee(this,"agentManager");Ee(this,"textStreamHandlersRegistered",!1);Ee(this,"_eventEmitters",new Map);this.eventEmitter=t,this.chatManager=n,this.agentManager=r}setRoom(t){this.room=t,t&&!this.textStreamHandlersRegistered&&(console.log("📡 StreamHandlerManager: Auto-registering handlers on room set"),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 r=await t.readAll(),i={id:`msg_${Date.now()}_${n.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:r,timestamp:new Date,sender:{id:n.identity||"user",name:n.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.eventEmitter.emit("chat.message.received",i)}catch(r){console.error("StreamHandlerManager: Failed to process lk.chat message:",r)}})}catch(t){console.warn("StreamHandlerManager: lk.chat handler already registered, skipping:",t)}}registerTranscriptionHandler(){try{console.log("📡 StreamHandlerManager: Registering lk.transcription handler"),this.room.registerTextStreamHandler("lk.transcription",async(t,n)=>{var r,i;console.log("💬 StreamHandlerManager: Received lk.transcription stream from:",n.identity);try{const o=n.identity===((i=(r=this.room)==null?void 0:r.localParticipant)==null?void 0:i.identity),s=n.identity,a=this.chatManager.getActiveTranscription(s);let l,c=!0;a?(l=a.messageId,c=!1):(l=`msg_${o?"user":"agent"}_${n.identity}_${Date.now()}`,this.chatManager.trackTranscription(s,l));let u="";const d=this.agentManager.getCurrentAgentInfo(),f=(d==null?void 0:d.name)||n.identity||"AI Assistant",p=o?"participant":"agent",g=o?"User":f,m={id:l,content:"",timestamp:new Date,sender:{id:n.identity||"unknown",name:g,type:p},metadata:{topic:"lk.transcription",streaming:!0}};c&&this.eventEmitter.emit("chat.message.received",m);for await(const w of t){u+=w;const C=this.chatManager.convertMarkdownToText(u),k={...m,content:C,metadata:{...m.metadata,streaming:!0}};this.eventEmitter.emit("chat.message.updated",k)}const v=this.chatManager.convertMarkdownToText(u),y={...m,content:v,metadata:{...m.metadata,streaming:!1}};this.eventEmitter.emit("chat.message.updated",y);const E={id:l,text:v,isFinal:!0,startTime:m.timestamp.getTime(),participantId:n.identity||"agent"};this.eventEmitter.emit("transcription.received",E)}catch(o){console.error("StreamHandlerManager: Failed to process lk.transcription message:",o);try{const s=await t.readAll(),a=this.agentManager.getCurrentAgentInfo(),l=(a==null?void 0:a.name)||n.identity||"AI Assistant",c={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:s,timestamp:new Date,sender:{id:n.identity||"agent",name:l,type:"agent"},metadata:{topic:"lk.transcription"}};this.eventEmitter.emit("chat.message.received",c),console.log("💬 StreamHandlerManager: Emitted chat.message.received:",{id:c.id,sender:c.sender.name,contentLength:c.content.length,preview:c.content.substring(0,50)});const u={id:c.id,text:c.content,isFinal:!0,startTime:c.timestamp.getTime(),participantId:n.identity||"agent"};this.eventEmitter.emit("transcription.received",u),console.log("📝 StreamHandlerManager: Emitted transcription.received:",{id:u.id,textLength:u.text.length})}catch(s){console.error("StreamHandlerManager: Fallback failed for lk.transcription:",s)}}})}catch(t){console.warn("StreamHandlerManager: lk.transcription handler already registered, skipping:",t)}}registerSuggestedResponseHandler(){try{this.room.registerTextStreamHandler("suggested_response",async t=>{const n=await t.readAll();let r=[];try{r=["tes","hello how are you","algebra make me learn that","what is the meaning of life"]}catch(i){console.warn("StreamHandlerManager: Failed to parse suggested_response:",i,n)}this.eventEmitter.emit("suggested.response",r)})}catch(t){console.warn("StreamHandlerManager: suggested_response handler already registered, skipping:",t)}}registerAgentStateHandler(){try{this.room.registerTextStreamHandler("agent_state_changed",async(t,n)=>{const r=await t.readAll();let i={};try{i=typeof r=="string"?JSON.parse(r.replace(/'/g,'"')):r}catch(o){console.warn("StreamHandlerManager: Failed to parse agent_state_changed:",o,r)}this.agentManager.handleAgentStateChanged(i)})}catch(t){console.warn("StreamHandlerManager: agent_state_changed handler already registered, skipping:",t)}}registerFunctionToolsHandler(){try{this.room.registerTextStreamHandler("function_tools_executed",async(t,n)=>{var o,s,a,l;const r=await t.readAll();console.log("StreamHandlerManager: Raw function_tools_executed data (type, length, first 200 chars):",typeof r,r==null?void 0:r.length,(o=r==null?void 0:r.substring)==null?void 0:o.call(r,0,200));let i={};try{if(typeof r=="string")try{i=JSON.parse(r),console.log("StreamHandlerManager: Direct JSON parse succeeded!")}catch(c){console.warn("StreamHandlerManager: Initial JSON parse failed:",c),console.warn("First 100 chars of raw data:",r.substring(0,100));let u=r;try{console.log("StreamHandlerManager: Starting enhanced parsing..."),u=u.replace(/\bTrue\b/g,"true"),u=u.replace(/\bFalse\b/g,"false"),u=u.replace(/\bNone\b/g,"null"),u=u.replace(/,(\s*[}\]])/g,"$1"),console.log("StreamHandlerManager: After replacements (first 200 chars):",u.substring(0,200));let d="",f=!1,p="",g=0;for(;g<u.length;){const m=u[g],v=g>0?u[g-1]:"",y=g<u.length-1?u[g+1]:"";if(m==="\\"&&(y==="'"||y==='"'))if(f){d+='\\"',g+=2;continue}else{g++;continue}if(v==="\\"&&m!=="'"&&m!=='"'){d+=m,g++;continue}if((m==='"'||m==="'")&&!f&&v!=="\\"){f=!0,p=m,d+='"',g++;continue}if(m===p&&f&&v!=="\\"&&(y===":"||y===","||y==="}"||y==="]"||y===""||/\s/.test(y))){f=!1,d+='"',g++;continue}d+=m,g++}u=d,console.log("StreamHandlerManager: ✅ Quote conversion complete. Length:",u.length),console.log("StreamHandlerManager: After quote conversion (first 500 chars):",u.substring(0,500)),i=JSON.parse(u),console.log("StreamHandlerManager: ✅ Successfully parsed with enhanced logic")}catch(d){console.error("StreamHandlerManager: ❌ Enhanced parsing failed:",d==null?void 0:d.message),console.error("Error position:",(a=(s=d==null?void 0:d.message)==null?void 0:s.match(/position (\d+)/))==null?void 0:a[1]),console.error("After conversion (first 600 chars):",u==null?void 0:u.substring(0,600)),console.error("Characters around error position:",(l=d==null?void 0:d.message)!=null&&l.match(/position (\d+)/)?u==null?void 0:u.substring(Math.max(0,parseInt(d.message.match(/position (\d+)/)[1])-50),parseInt(d.message.match(/position (\d+)/)[1])+50):"N/A");try{let f=r.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null");i=new Function("return "+f)()}catch(f){throw console.error("StreamHandlerManager: All parsing methods failed:",f),c}}}else i=r}catch(c){console.warn("StreamHandlerManager: Failed to parse function_tool_executed:",c,r);let u=null;if(typeof r=="string"&&r.includes("visualization_data"))try{const d=r.match(/"arguments":\s*"({.*?})"/);if(d){const f=d[1].replace(/\\"/g,'"');u=JSON.parse(f),console.log("🛠️ StreamHandlerManager: Extracted visualization data:",u)}}catch(d){console.warn("StreamHandlerManager: Failed to extract visualization data:",d)}i={type:"function_tools_executed",function_calls:[],function_call_outputs:[],created_at:Date.now()/1e3,parseError:!0,rawData:r,extractedVisualizationData:u}}console.log("Tool executed:",i),console.log("Processing tool execution:",`${i.created_at}-${i.type}`),this.eventEmitter.emit("tool.executed",i),console.log("✅ Event emitted: tool.executed")})}catch(t){console.warn("StreamHandlerManager: function_tool_executed handler already registered, skipping:",t)}}registerImageTextStreamHandler(){try{this.room.registerTextStreamHandler("images",async(t,n)=>{try{const r=await t.readAll()}catch(r){console.error("StreamHandlerManager: Error processing images stream:",r)}})}catch(t){console.warn("StreamHandlerManager: images text handler already registered, skipping:",t)}}registerImageByteStreamHandler(){try{this.room.registerByteStreamHandler("images",async(t,n)=>{var r,i;try{const o=t.info,s={id:`img_${Date.now()}_${n.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`🖼️ ${o.name||"Image"}`,sender:{id:n.identity||"agent",name:n.identity||"Agent",type:n.identity===((i=(r=this.room)==null?void 0:r.localParticipant)==null?void 0:i.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:o.name,fileSize:o.size,mimeType:o.mimeType,streamId:o.id,downloading:!0}};this.eventEmitter.emit("chat.message.received",s),t.onProgress&&(t.onProgress=d=>{const f={...s,metadata:{...s.metadata,downloadProgress:d||0}};this.eventEmitter.emit("chat.message.updated",f)});const a=[];for await(const d of t)a.push(d);const l=new Blob(a,{type:o.mimeType||"application/octet-stream"}),c=URL.createObjectURL(l),u={...s,metadata:{...s.metadata,downloading:!1,downloadProgress:1,downloadUrl:c,blob:l}};this.eventEmitter.emit("chat.message.updated",u)}catch(o){console.error("StreamHandlerManager: Error processing image attachment:",o)}})}catch(t){console.warn("StreamHandlerManager: image byte handler already registered, skipping:",t)}}registerCommonTopicHandlers(){["error","warning","status","system","debug","info"].forEach(n=>{try{this.room.registerTextStreamHandler(n,async(r,i)=>{try{const o=await r.readAll();if(console.log(`📝 StreamHandlerManager: Received '${n}' stream:`,o),n==="error"){let s={};try{s=typeof o=="string"?JSON.parse(o):o}catch{s={message:o}}console.warn("⚠️ StreamHandlerManager: Agent error:",s),this.eventEmitter.emit("agent.error",s)}else this.eventEmitter.emit("text.stream.received",{topic:n,data:o,participantInfo:i})}catch(o){console.error(`StreamHandlerManager: Failed to process '${n}' stream:`,o)}})}catch(r){console.warn(`StreamHandlerManager: Handler for '${n}' already registered, skipping:`,r)}})}registerWildcardHandler(){try{this.room.registerTextStreamHandler("*",async(t,n)=>{var r;try{const i=await t.readAll(),o=((r=t.info)==null?void 0:r.topic)||"unknown";if(this._eventEmitters.has(o)){const s=this._eventEmitters.get(o);try{s(i),console.log(`📝 StreamHandlerManager: Processed custom topic '${o}' via event emitter`)}catch(a){console.error(`StreamHandlerManager: Error in custom handler for topic '${o}':`,a)}}else console.log(`📝 StreamHandlerManager: Received unhandled text stream for topic '${o}':`,i),this.eventEmitter.emit("text.stream.unhandled",{topic:o,data:i,participantInfo:n})}catch(i){console.error("StreamHandlerManager: Failed to process unhandled text stream:",i)}})}catch(t){console.warn("StreamHandlerManager: Generic text stream handler already registered, skipping:",t)}}registerEventEmitter(t,n){if(!this.room)throw new Error("Room not available");this._eventEmitters.set(t,n),console.log(`📝 StreamHandlerManager: Stored handler for topic '${t}' in event emitters map`);try{this.room.registerTextStreamHandler(t,async r=>{try{const i=await r.readAll();console.log(`📝 StreamHandlerManager: Direct handler called for topic '${t}'`),n(i)}catch(i){console.error(`Error processing event for topic '${t}':`,i)}}),console.log(`📝 StreamHandlerManager: Successfully registered direct handler for topic '${t}'`)}catch(r){console.warn(`StreamHandlerManager: Direct handler registration failed for topic '${t}':`,r),console.log(`📝 StreamHandlerManager: Wildcard handler will process topic '${t}' instead`)}}getRegisteredEventEmitters(){return Array.from(this._eventEmitters.keys())}hasEventEmitter(t){return this._eventEmitters.has(t)}}const hg=N.createContext(null);function lo({config:e,children:t,autoConnect:n=!1,client:r}){const[i,o]=N.useState(null),[s,a]=N.useState(!1),[l,c]=N.useState(!1),[u,d]=N.useState(null),[f,p]=N.useState(null),[g,m]=N.useState("idle"),[v,y]=N.useState(null),[E,w]=N.useState([]),[C,k]=N.useState([]),[_,R]=N.useState([]);N.useEffect(()=>{const z=r||new Ti(e);o(z);const x=A(z);return n&&!r&&O(z),()=>{x(),r||z.disconnect().catch(console.error)}},[e,n,r]);const A=z=>{const x=()=>{c(!0),d(null)},B=()=>{a(!0),c(!1),d(null)},K=()=>{a(!1),c(!1),p(null),m("idle"),w([]),k([]),R([])},S=se=>{d(se),c(!1)},Y=se=>{p(se),m(se.state)},te=se=>{m(se),f&&p({...f,state:se})},j=(se,ke)=>{p(null),m("idle"),y(ke),w([]),k([]),R([])},q=se=>{w(ke=>[...ke,se])},W=se=>{w(ke=>ke.filter(me=>me.id!==se.id))},ue=se=>{k(ke=>[...ke,se])},Q=se=>{k(ke=>[...ke,se])},ve=se=>{console.log("📝 VoxketProvider: Received transcription:",se),R(ke=>ke.find(ie=>ie.id===se.id)?(console.log("📝 VoxketProvider: Duplicate transcription detected, skipping:",se.id),ke):(console.log("📝 VoxketProvider: Adding new transcription:",se.id),[...ke,se]))},L=()=>{console.log("🧹 VoxketProvider: Clearing chat messages and transcriptions"),k([]),R([])};return z.on("connection.connecting",x),z.on("connection.connected",B),z.on("connection.disconnected",K),z.on("connection.error",S),z.on("session.created",Y),z.on("session.state.changed",te),z.on("session.ended",j),z.on("participant.joined",q),z.on("participant.left",W),z.on("chat.message.received",ue),z.on("chat.message.sent",Q),z.on("transcription.received",ve),z.on("chat.history.cleared",L),()=>{console.log("📝 VoxketProvider: Cleaning up event listeners"),z.off("connection.connecting",x),z.off("connection.connected",B),z.off("connection.disconnected",K),z.off("connection.error",S),z.off("session.created",Y),z.off("session.state.changed",te),z.off("session.ended",j),z.off("participant.joined",q),z.off("participant.left",W),z.off("chat.message.received",ue),z.off("chat.message.sent",Q),z.off("chat.history.cleared",L),z.off("transcription.received",ve)}},O=async z=>{const x=z||i;if(x)try{await x.connect()}catch(B){console.error("Failed to connect:",B)}},$={client:i,isConnected:s,isConnecting:l,connectionError:u,currentSession:f,sessionState:g,sessionMetrics:v,participants:E,chatMessages:C,transcriptions:_,connect:()=>O(),disconnect:async()=>{if(i)try{await i.disconnect()}catch(z){console.error("Failed to disconnect:",z)}},createSession:async(z,x={})=>{if(!i)throw new Error("Client not initialized");const B={agentId:z,participantName:x.participantName||"User",metadata:x.metadata,modalities:x.modalities||["voice"]};return await i.createSession(B)},endSession:async()=>i?await i.endSession():null,sendChatMessage:async z=>{if(!i)throw new Error("Client not initialized");await i.sendChatMessage(z)},setMicrophoneEnabled:async z=>{if(!i)throw new Error("Client not initialized");await i.setMicrophoneEnabled(z)},setCameraEnabled:async z=>{if(!i)throw new Error("Client not initialized");await i.setCameraEnabled(z)},startScreenShare:async()=>{if(!i)throw new Error("Client not initialized");await i.startScreenShare()},stopScreenShare:async()=>{if(!i)throw new Error("Client not initialized");await i.stopScreenShare()}};return h.jsx(hg.Provider,{value:$,children:t})}function gn(){const e=N.useContext(hg);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}const Rn=new WeakSet,ea=new WeakSet;class pg{constructor(t,n){Ee(this,"renderedComponents",new Map);Ee(this,"config");Ee(this,"voxketClient");this.config=t,this.voxketClient=n}renderUI(t={}){const n=this.resolveTarget(t.target||"body"),r=this.getTargetKey(n);if(ea.has(n)){console.warn("⚠️ UIRenderer: Target is already being processed, skipping renderUI");return}if(Rn.has(n)){console.log("✋ UIRenderer: Target already has a React root in registry, updating existing props...");const o=this.renderedComponents.get(r);if(o&&o.root){const s=this.buildWidgetProps(t);try{o.root.render(N.createElement(lo,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:N.createElement(co,s)})),console.log("✅ UIRenderer: Successfully updated existing widget with new props");return}catch(a){throw console.error("Error re-rendering existing widget:",a),new Error(`Failed to update existing widget: ${a instanceof Error?a.message:"Unknown error"}`)}}else console.warn("⚠️ Registry inconsistency detected, cleaning up"),Rn.delete(n)}let i=this.renderedComponents.get(r);if(i&&i.target===n&&Rn.has(n)){console.log("🔄 UIRenderer: Reusing existing React root for target:",r);const o=i.root,s=this.buildWidgetProps(t);try{o.render(N.createElement(lo,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:N.createElement(co,s)}))}catch(a){throw console.error("Error rendering Voxket widget:",a),new Error(`Failed to render Voxket widget: ${a instanceof Error?a.message:"Unknown error"}`)}return}ea.add(n);try{if(i){console.log("🧹 UIRenderer: Cleaning up existing component for different target");try{i.root.unmount(),this.renderedComponents.delete(r),Rn.delete(i.target),n.innerHTML=""}catch(a){console.warn("Failed to cleanup existing root:",a)}}if(Rn.has(n)){console.warn("⚠️ UIRenderer: Target already in registry, skipping root creation");return}console.log("🆕 UIRenderer: Creating new React root for target:",r);const o=Xg.createRoot(n);this.renderedComponents.set(r,{root:o,target:n}),Rn.add(n);const s=this.buildWidgetProps(t);if(!o||typeof o.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{o.render(N.createElement(lo,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:N.createElement(co,s)}))}catch(a){throw console.error("Error rendering Voxket widget:",a),new Error(`Failed to render Voxket widget: ${a instanceof Error?a.message:"Unknown error"}`)}}finally{ea.delete(n)}}removeUI(t){const n=t?this.resolveTarget(t):null;if(n){const r=this.getTargetKey(n),i=this.renderedComponents.get(r);if(i){console.log("🗑️ UIRenderer: Removing UI for target:",r),this.renderedComponents.delete(r);const o=i.target,s=()=>{var a;try{o&&o.isConnected?typeof((a=i.root)==null?void 0:a.unmount)=="function"&&(i.root.unmount(),console.log("✅ UIRenderer: UI unmounted for target:",r)):console.log("ℹ️ UIRenderer: Target element already disconnected, skipping unmount")}catch(l){console.warn("Failed to unmount React root:",l)}finally{requestAnimationFrame(()=>{try{n.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(c=>{try{c.parentNode&&c.remove()}catch(u){console.warn("Failed to remove element:",u)}})}finally{Rn.delete(n)}})}};queueMicrotask(()=>setTimeout(s,0))}else console.log("ℹ️ UIRenderer: No component found for target, cleaning registry:",r),Rn.delete(n),n.isConnected&&n.hasChildNodes()&&(n.innerHTML="");n===document.body&&n.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(s=>{if(s.classList.contains("bg-black")&&(s.classList.contains("backdrop-blur-sm")||s.classList.contains("bg-opacity-30")))try{s.remove()}catch(a){console.warn("Failed to remove fixed element:",a)}})}}removeAllUI(){for(const[t,n]of this.renderedComponents)n.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}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(r){console.warn("Failed to remove overlay:",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 r,i,o;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:((r=t.modality)==null?void 0:r.includes("chat"))!==!1,suportsVideoInput:((i=t.modality)==null?void 0:i.includes("video"))===!0,suportsScreenShare:((o=t.modality)==null?void 0:o.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 mg{constructor(t){Ee(this,"agentState","idle");Ee(this,"isAgentConnected",!1);Ee(this,"currentAgentInfo",null);Ee(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,console.log(t?"🤖 AgentManager: Agent marked as connected":"🤖 AgentManager: Agent marked as disconnected")}getCurrentAgentInfo(){return this.currentAgentInfo}setCurrentAgentInfo(t){this.currentAgentInfo=t,console.log("📝 AgentManager: Agent info updated:",t)}reset(){this.agentState="idle",this.isAgentConnected=!1,this.currentAgentInfo=null,console.log("🔄 AgentManager: Agent state reset")}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 Ti extends rc{constructor(n){super();Ee(this,"config");Ee(this,"pluginManager");Ee(this,"rpcManager");Ee(this,"chatManager");Ee(this,"mediaManager");Ee(this,"connectionManager");Ee(this,"streamHandlerManager");Ee(this,"uiRenderer");Ee(this,"agentManager");Ee(this,"currentSession",null);this.config=n,this.chatManager=new cg(this,n.participantName||"User"),this.mediaManager=new ug(this),this.agentManager=new mg(this),this.connectionManager=new dg({baseUrl:n.baseUrl,appId:n.appId,appSecret:n.appSecret},this),this.streamHandlerManager=new fg(this,this.chatManager,this.agentManager),this.uiRenderer=new pg(n,this),this.pluginManager=new ag(this),this.rpcManager=new lg,this.setupEventListeners(),this.setupRpcEventForwarding()}setupEventListeners(){this.on("connection.connected",()=>{var r,i,o,s,a,l,c;if(console.log("🔌 VoxketClient: connection.connected event fired",{hasSession:!!this.currentSession,sessionState:(r=this.currentSession)==null?void 0:r.state,sessionId:(i=this.currentSession)==null?void 0:i.id}),(s=(o=this.config).onConnected)==null||s.call(o),this.currentSession&&this.currentSession.state==="connecting"){const u=this.currentSession.state;this.currentSession.state="connected",this.emit("session.state.changed","connected",u),console.log("✅ VoxketClient: Session state changed to connected")}else console.log("⚠️ VoxketClient: Cannot update session state",{hasSession:!!this.currentSession,currentState:(a=this.currentSession)==null?void 0:a.state});const n=this.connectionManager.getRoom();if(n){this.rpcManager.setRoom(n);const u=Array.from(n.remoteParticipants.values()).find(d=>{var f;return(f=d.identity)==null?void 0:f.startsWith("agent-")});u&&(console.log("🤖 VoxketClient: Agent already in room, marking as connected",{agentIdentity:u.identity,hasAudioTrack:u.audioTrackPublications.size>0}),this.agentManager.getIsAgentConnected()||(this.agentManager.setAgentConnected(!0),this.emit("agent.connected",{identity:u.identity})))}(c=(l=this.currentSession)==null?void 0:l.activeModalities)!=null&&c.includes("voice")&&setTimeout(async()=>{try{this.mediaManager.getLocalParticipant()&&(this.mediaManager.isMicrophoneEnabled||(await this.mediaManager.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0}),console.log("🎤 VoxketClient: Microphone enabled after connection")))}catch(u){console.warn("VoxketClient: Failed to enable microphone after room connection:",u)}},100)}),this.on("connection.disconnected",n=>{var r,i,o;(i=(r=this.config).onDisconnected)==null||i.call(r,n),this.streamHandlerManager.resetHandlersFlag(),this.agentManager.reset(),this.chatManager.clearChatMessages(),n&&console.log("🔍 VoxketClient: Disconnect reason details:",{reason:n.toString(),currentSession:(o=this.currentSession)==null?void 0:o.id})}),this.on("connection.error",n=>{var r,i;(i=(r=this.config).onError)==null||i.call(r,n)}),this.on("chat.message.received",n=>{var r,i;this.chatManager.addChatMessage(n),(i=(r=this.config).onMessageReceived)==null||i.call(r,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 r,i;(i=(r=this.config).onTranscriptionReceived)==null||i.call(r,n)}),this.on("session.state.changed",n=>{var r,i;(i=(r=this.config).onSessionStateChanged)==null||i.call(r,n)}),this.on("session.created",n=>{var r,i;(i=(r=this.config).onSessionStart)==null||i.call(r,n.id)}),this.on("session.ended",(n,r)=>{var i,o;(o=(i=this.config).onSessionEnd)==null||o.call(i,r)}),this.on("participant.joined",n=>{var r,i;(i=(r=this.config).onUserJoined)==null||i.call(r,n.id)}),this.on("participant.left",n=>{var r,i;(i=(r=this.config).onUserLeft)==null||i.call(r,n.id)})}setupRpcEventForwarding(){if(!this.rpcManager){console.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,r,i,o){const s=n||this.config.agentId||"default-agent",a=r||this.config.participantName||"User",l=i||this.config.modalities||["voice"],c=o||this.config.participantMetadata,u=await this.connectionManager.connect(s,a,l,c),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 r,i;try{const o=await this.connect(n.agentId,n.participantName,n.modalities,n.participantMetadata),s={id:o.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:o.agentInfo||this.agentManager.getCurrentAgentInfo()};this.currentSession=s,this.emit("session.created",s);const a=this.connectionManager.getRoom();if(a&&a.state==="connected"&&(console.log("✅ VoxketClient: Room already connected, updating session state immediately"),this.currentSession.state="connected",this.emit("session.state.changed","connected","connecting")),(r=n.modalities)!=null&&r.includes("voice"))try{await this.mediaManager.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0}),console.log("🎤 VoxketClient: Microphone enabled successfully")}catch(l){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",l)}if((i=n.modalities)!=null&&i.includes("video"))try{await new Promise(l=>setTimeout(l,200)),await this.mediaManager.enableCamera(),console.log("🎥 VoxketClient: Camera enabled successfully")}catch(l){console.warn("VoxketClient: Failed to enable camera, but continuing with session:",l)}return s}catch(o){throw console.error("VoxketClient: Failed to create session:",o),o instanceof Ye?o:o instanceof TypeError&&o.message.includes("fetch")?new Ye("Network connection failed","CONNECTION_FAILED",o):o instanceof Error&&o.message.includes("Failed to fetch connection details")?new Ye(`API connection failed: ${o.message}`,"CONNECTION_FAILED",o):new Ye(`Failed to create session: ${o instanceof Error?o.message:"Unknown error"}`,"SESSION_NOT_FOUND",o)}}async startSession(n,r){const i={agentId:n||this.config.agentId||"default-agent",participantName:(r==null?void 0:r.participantName)||this.config.participantName||"User",modalities:(r==null?void 0:r.modalities)||this.config.modalities||["voice","chat"],metadata:r==null?void 0:r.metadata,participantMetadata:r==null?void 0:r.participantMetadata};return this.createSession(i)}async endSession(){var n,r;if(!this.currentSession)return null;try{const i={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.connectionManager.getRoom())==null?void 0:r.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,i),await this.disconnect(),i}catch(i){throw new Ye("Failed to end session","SESSION_NOT_FOUND",i)}}getCurrentSession(){return this.currentSession}getSessionMetrics(){var n,r;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.connectionManager.getRoom())==null?void 0:r.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,r){if(!this.currentSession)throw new Ye("No active session","SESSION_NOT_FOUND");return this.dismissCurrentInteraction(),this.chatManager.sendMessage(n,r)}async sendChatMessage(n,r){return this.sendMessage(n,r)}async sendAttachments(n,r){if(!this.currentSession)throw new Ye("No active session","SESSION_NOT_FOUND");return this.dismissCurrentInteraction(),this.chatManager.sendAttachments(n,r)}async sendAttachment(n,r){return this.chatManager.sendAttachment(n,r)}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,r,i="embedded"){return this.rpcManager.registerFrontendRPC(n,r,i)}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,r){return this.on(n,r)}registerEventEmitter(n,r){return this.streamHandlerManager.registerEventEmitter(n,r)}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(r){throw new Ye("Failed to start recording","RECORDING_ERROR",r)}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(r){throw new Ye("Failed to stop recording","RECORDING_ERROR",r)}}}const HR=De.create(Bm),WR=De.create(Gl),GR=De.create($m),KR=De.create(ig);function qR({theme:e,mode:t,loadingText:n}){const r=Lt(e),i=()=>{switch(t){case"voice":return n||"Connecting to voice agent...";case"chat":return n||"Starting chat session...";case"video":return n||"Connecting to video call...";default:return n||"Connecting..."}};return h.jsxs("div",{className:"flex flex-col items-center justify-center h-full w-full p-8",children:[h.jsxs("div",{className:"text-center",children:[h.jsx("h3",{className:`text-lg font-semibold mb-2 ${r.text.accent}`,children:i()}),h.jsx("p",{className:`text-sm ${r.text.muted}`,children:"Please wait a moment..."})]}),h.jsxs("div",{className:"flex space-x-1 mt-4",children:[h.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"0ms"}}),h.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"150ms"}}),h.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"300ms"}})]})]})}const YR=De.create(qR);function xf({children:e,theme:t,displayType:n="widget",onClose:r,popupPosition:i="bottom-right",onExpand:o}){const s=Lt(t);if(n==="fullscreen")return h.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:a=>{a.target===a.currentTarget&&r&&r()},children:h.jsxs("div",{className:"w-full h-full max-w-7xl max-h-[95vh] rounded-2xl relative bg-transparent flex flex-col",onClick:a=>{a.stopPropagation()},children:[r&&h.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),r()},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 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:h.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:h.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"})})}),h.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${s.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:[h.jsx("div",{className:s.cardTopGradient}),h.jsx("div",{className:s.cardPurpleBlur}),h.jsx("div",{className:s.cardPinkBlur}),h.jsx("div",{className:"relative z-10 flex flex-col h-full",children:e}),h.jsx("div",{className:s.cardPulse1}),h.jsx("div",{className:s.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(n==="popup"){const a={"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 h.jsx("div",{className:"fixed rounded-2xl inset-0 z-[9999] pointer-events-none",children:h.jsxs("div",{className:`fixed rounded-2xl ${a[i]} pointer-events-auto`,children:[r&&h.jsx("button",{onClick:r,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 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:"×"}),h.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${s.card} rounded-2xl flex flex-col relative overflow-hidden`,"data-theme":t,style:{width:"350px",height:"500px",contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0},children:[h.jsx("div",{className:s.cardTopGradient}),h.jsx("div",{className:s.cardPurpleBlur}),h.jsx("div",{className:s.cardPinkBlur}),h.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),h.jsx("div",{className:s.cardPulse1}),h.jsx("div",{className:s.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return h.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${s.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:[h.jsx("div",{className:s.cardTopGradient}),h.jsx("div",{className:s.cardPurpleBlur}),h.jsx("div",{className:s.cardPinkBlur}),h.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),h.jsx("div",{className:s.cardPulse1}),h.jsx("div",{className:s.cardPulse2,style:{animationDelay:"1s"}})]})}function ZR(e){if(typeof window>"u")return null;const{agentId:t,participantName:n,baseUrl:r,appSecret:i,appId:o,prompts:s,statusMessage:a,welcomeTitle:l,welcomeSubTitle:c,className:u,width:d,height:f,loadingText:p,suportsChatInput:g=!0,suportsVideoInput:m=!0,suportsScreenShare:v=!0,theme:y="vox",onSessionStart:E,onSessionEnd:w,enableSessionLogging:C=!0,onSessionLogsUpdate:k,onSessionMetricsUpdate:_,modalities:R=["voice"],displayType:A="widget",popupPosition:O="bottom-right",popupTriggerText:b="Open Chat",onPopupToggle:M,voxketClient:I,onDisplayTypeChange:F,participantMetadata:D,popupModalityMode:G="all"}=e,[re,X]=P.useState(!1),[$,z]=P.useState(null),[x,B]=P.useState(()=>{try{if(I)return!!I.getCurrentSession()}catch(le){console.error("Error checking existing session:",le)}return!1}),[K,S]=P.useState(!1),[Y,te]=P.useState(t||""),[j,q]=P.useState(n||"User"),[W,ue]=P.useState(()=>{try{if(I)return I.getCurrentSession()}catch(le){console.error("Error getting current session:",le)}return null}),[Q,ve]=P.useState(()=>{var le,nt,Fe;try{if(I){const T=I.getCurrentSession();if((le=T==null?void 0:T.activeModalities)!=null&&le.includes("chat"))return"chat";if((nt=T==null?void 0:T.activeModalities)!=null&&nt.includes("voice"))return"voice";if((Fe=T==null?void 0:T.activeModalities)!=null&&Fe.includes("video"))return"video"}}catch(T){console.error("Error determining current mode:",T)}return"welcome"}),[L,se]=P.useState(!1),[ke,me]=P.useState(!1),[ie,be]=P.useState(null),[Te,_e]=P.useState(!1);P.useEffect(()=>{A==="fullscreen"&&console.log("🎯 Widget: Switched to fullscreen mode")},[A]),P.useEffect(()=>{x&&!K?console.log("📊 Session started:",{currentMode:Q,sessionId:W==null?void 0:W.id}):!x&&!K&&Q==="welcome"&&console.log("📊 Returned to welcome screen")},[x,Q,K]);const ce=P.useMemo(()=>{try{if(I)return console.log("🔄 Using existing VoxketClient to preserve session state"),I;if(!o||!i||!r){const nt=`Missing required props: ${o?"":"appId "}${i?"":"appSecret "}${r?"":"baseUrl"}`;return console.error("❌ VoxketClient creation failed:",nt),z(new Error(nt)),X(!0),null}const le={appId:o,appSecret:i,baseUrl:r,agentId:Y,participantName:j||"User",modalities:R,participantMetadata:D};return console.log("🔧 Creating new VoxketClient with config:",{appId:o.substring(0,8)+"...",baseUrl:r,agentId:Y,participantName:j||"User",modalities:R}),new Ti(le)}catch(le){return console.error("❌ Failed to create VoxketClient:",le),z(le),X(!0),null}},[I,o,i,r,Y,j,R]),St=P.useMemo(()=>R,[R]),Me=P.useMemo(()=>{try{if(!ce)return console.warn("⚠️ No VoxketClient available, creating fallback room"),new ae.Room;const le=ce.getRoom();return console.log("🏠 Widget: Room reference updated:",{roomExists:!!le,roomState:le==null?void 0:le.state,sessionStarted:x,currentMode:Q}),le||new ae.Room}catch(le){return console.error("❌ Error getting room from client:",le),new ae.Room}},[ce,x,Q]);P.useEffect(()=>{if(Me){const le=()=>{console.log("🏠 Widget: Room state changed:",{state:Me.state,numParticipants:Me.numParticipants,isConnected:Me.state==="connected",sessionId:W==null?void 0:W.id})},nt=(Fe,T,H)=>{console.log("🎵 Widget: Track subscribed:",{trackKind:Fe.kind,trackSource:Fe.source,participantSid:H.sid,participantIdentity:H.identity,sessionId:W==null?void 0:W.id})};return Me.on(ae.RoomEvent.Connected,le),Me.on(ae.RoomEvent.Disconnected,le),Me.on(ae.RoomEvent.TrackSubscribed,nt),()=>{Me.off(ae.RoomEvent.Connected,le),Me.off(ae.RoomEvent.Disconnected,le),Me.off(ae.RoomEvent.TrackSubscribed,nt)}}},[Me,W==null?void 0:W.id]),P.useEffect(()=>{!K&&Q==="welcome"?console.log("🎬 Widget: Welcome screen ready"):x&&Q!=="welcome"&&console.log("🎬 Widget: Session mode active:",Q)},[Q,K,x]),P.useEffect(()=>{(Q==="voice"||Q==="video"||Q==="chat")&&!W&&!x&&!K&&ce&&!ce.connected&&(console.log("🔄 Auto-correcting: Found orphaned mode without session, returning to welcome"),ve("welcome"),S(!1))},[Q,W,x,K,ce]);const{sessionMetrics:pt,sessionLogs:mt,logEvent:en}=sg({room:Me,onSessionStart:E,onSessionEnd:w,enableConsoleLogging:C,enableLocalStorage:C,voxketSessionId:W==null?void 0:W.id});P.useEffect(()=>{k&&k(mt)},[mt,k]),P.useEffect(()=>{_&&pt&&_(pt)},[pt,_]),P.useEffect(()=>{if(!ce)return;const le=()=>{const nt=ce.connected,Fe=ce.getCurrentSession();console.log("🔗 Connection state changed:",{isConnected:nt,currentSessionId:Fe==null?void 0:Fe.id,currentMode:Q,loading:K,sessionStarted:x}),!nt&&x&&!K&&(console.log("🔴 Connection lost during active session - returning to welcome"),S(!1),B(!1),ue(null),ve("welcome")),nt&&Fe&&K&&(console.log("🟢 Connected with active session - removing loader"),S(!1),B(!0),ue(Fe))};return ce.on("connectionStateChanged",le),ce.on("sessionEnded",()=>{console.log("📞 Session ended - returning to welcome"),S(!1),B(!1),ue(null),ve("welcome")}),()=>{ce.off("connectionStateChanged",le),ce.off("sessionEnded",()=>{})}},[ce,Q,K,x]);const J=!!(!!(ce!=null&&ce.connected)&&x&&W);P.useEffect(()=>{const le=Fe=>{console.log("🔴 Widget: Room disconnected:",Fe),console.log("🔍 Widget: Current state on disconnect:",{currentMode:Q,sessionStarted:x,currentSessionId:W==null?void 0:W.id,loading:K}),S(!1),B(!1),ue(null),ve("welcome"),console.log("🏠 Widget: Automatically returning to welcome screen after disconnect")},nt=Fe=>{console.log("📹 Media devices error:",Fe)};return Me.on(ae.RoomEvent.MediaDevicesError,nt),Me.on(ae.RoomEvent.Disconnected,le),()=>{Me.off(ae.RoomEvent.Disconnected,le),Me.off(ae.RoomEvent.MediaDevicesError,nt)}},[Me,Q,x,W==null?void 0:W.id,K]);const we=async()=>{try{if(!ce){console.error("❌ VoxketClient not available"),z(new Error("VoxketClient not initialized")),X(!0);return}S(!0),ve("voice"),console.log("🎤 Starting voice session...",{agentId:Y,participantName:j}),console.log("🎤 Pre-start state:",{currentMode:"voice",sessionStarted:!1,loading:!0}),en("USER_STARTED_VOICE_SESSION",{agentId:Y,participantName:j});const le=await ce.startSession(Y,{participantName:j||"User",modalities:A==="popup"?["voice"]:["voice",...m?["video"]:[]],participantMetadata:ce.getParticipantMetadata()||D});console.log("✅ Voice session started successfully:",le.id),ue(le),B(!0),S(!1),E&&E(le.id)}catch(le){console.error("❌ Failed to start voice session:",le),S(!1),B(!1),ve("welcome")}},Ie=async()=>{try{if(!ce){console.error("❌ VoxketClient not available"),z(new Error("VoxketClient not initialized")),X(!0);return}S(!0),ve("chat"),console.log("💬 Starting chat session...",{agentId:Y,participantName:j}),en("USER_STARTED_CHAT_SESSION",{agentId:Y,participantName:j});const le=await ce.startSession(Y,{participantName:j||"User",modalities:["chat"],participantMetadata:ce.getParticipantMetadata()||D});console.log("✅ Chat session started successfully:",le.id),ue(le),B(!0),S(!1),E&&E(le.id)}catch(le){console.error("❌ Failed to start chat session:",le),S(!1),B(!1),ve("welcome")}},Ve=async()=>{try{if(!ce){console.error("❌ VoxketClient not available"),z(new Error("VoxketClient not initialized")),X(!0);return}S(!0),ve("video"),console.log("📺 Starting video session...",{agentId:Y,participantName:j}),console.log("📺 Pre-start state:",{currentMode:"video",sessionStarted:!1,loading:!0}),en("USER_STARTED_VIDEO_SESSION",{agentId:Y,participantName:j});const le=await ce.startSession(Y,{participantName:j||"User",modalities:["video","voice"],participantMetadata:ce.getParticipantMetadata()||D});console.log("✅ Video session started successfully:",le.id),ue(le),B(!0),S(!1),E&&E(le.id)}catch(le){console.error("❌ Failed to start video session:",le),S(!1),B(!1),ve("welcome")}},xt=()=>{ve("welcome"),S(!1),F&&F(e.displayType||"widget"),W&&x?(console.log("🧹 Widget: Cleaning up active session"),B(!1),ue(null),ce&&(console.log("🔌 Widget: Disconnecting client and cleaning up room"),ce.disconnect().catch(le=>{console.error("❌ Widget: Error during disconnect:",le)}))):(console.log("📝 Widget: No active session to clean up"),ce&&ce.connected&&(console.log("🔌 Widget: Force disconnecting client for fresh state"),ce.disconnect().catch(le=>{console.error("❌ Widget: Error during force disconnect:",le)}))),A==="popup"&&!L&&se(!0),console.log("✅ Widget: handleBackToWelcome completed",{newCurrentMode:"welcome",newLoading:!1,newSessionStarted:!1})},Ft=()=>{const le=!L;se(le),M&&M(le),!le&&!(W&&x)&&(ve("welcome"),B(!1),ue(null))},Vt=()=>{console.log("🔄 Closing fullscreen, switching to widget display type"),e.onDisplayTypeChange?e.onDisplayTypeChange("widget"):console.warn("⚠️ No onDisplayTypeChange callback provided")},an=()=>{if(console.log("🔄 Expand to fullscreen requested"),e.onDisplayTypeChange)e.onDisplayTypeChange("fullscreen");else{console.warn("⚠️ No onDisplayTypeChange callback provided for expand functionality");const le=document.getElementById("voice-card")||document.querySelector(".voxket-widget-container");le&&le.requestFullscreen&&le.requestFullscreen().catch(nt=>{console.warn("⚠️ Fullscreen API not supported or failed:",nt)})}};P.useEffect(()=>{var le,nt,Fe;if(I&&ce){const T=ce.getCurrentSession();ce.connected,T&&(console.log("✅ Restoring session state:",T.id),ue(T),B(!0),S(!1),(le=T.activeModalities)!=null&&le.includes("chat")?ve("chat"):(nt=T.activeModalities)!=null&&nt.includes("voice")?ve("voice"):(Fe=T.activeModalities)!=null&&Fe.includes("video")&&ve("video"))}},[I,ce]),P.useEffect(()=>()=>{!I&&ce&&ce.disconnect()},[ce,I]);let tn=Q==="video"?"w-[32rem]":"w-96",vt=Q==="video"?"h-[30rem]":"h-[25rem]",Kt={};if(d&&(d.startsWith("w-")?tn=d:(Kt.width=d,tn="")),f&&(f.startsWith("h-")?vt=f:(Kt.height=f,vt="")),A==="popup"&&!L)return console.log("🟡 Showing popup trigger button"),h.jsxs(h.Fragment,{children:[h.jsx(og,{onClick:()=>{if(J){!ie&&(W!=null&&W.activeModalities)&&(W.activeModalities.includes("chat")?be("chat"):W.activeModalities.includes("video")?be("video"):W.activeModalities.includes("voice")&&be("voice")),me(!1),se(!0),M&&M(!0);return}me(!1),se(!0),M&&M(!0)},position:O,ariaLabel:b,size:64,isRunning:J,theme:y}),ke&&G==="all"&&(()=>{const Fe={};O==="bottom-right"?(Fe.bottom=88,Fe.right=16):O==="bottom-left"?(Fe.bottom=88,Fe.left=16):O==="top-right"?(Fe.top=88,Fe.right=16):(Fe.top=88,Fe.left=16);const T="absolute w-0 h-0 border-8",H=O.startsWith("bottom")?h.jsx("div",{className:`${T} border-transparent border-t-black`,style:{bottom:-16,right:O.endsWith("right")?16:void 0,left:O.endsWith("left")?16:void 0}}):h.jsx("div",{className:`${T} border-transparent border-b-black`,style:{top:-16,right:O.endsWith("right")?16:void 0,left:O.endsWith("left")?16:void 0}});return h.jsx("div",{className:"fixed z-[51]",style:Fe,children:h.jsxs("div",{className:"relative bg-black text-white rounded-xl shadow-2xl px-3 py-3",children:[H,h.jsx("div",{className:"text-xs uppercase tracking-wide mb-2 opacity-70",children:"Choose modality"}),h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{type:"button",onClick:()=>{be("voice"),me(!1),se(!0),M&&M(!0)},className:"px-3 py-2 rounded-md bg-white/10 hover:bg-white/20 text-white text-sm",title:"Voice",children:"Voice"}),h.jsx("button",{type:"button",onClick:()=>{be("chat"),me(!1),se(!0),M&&M(!0)},className:"px-3 py-2 rounded-md bg-white/10 hover:bg-white/20 text-white text-sm",title:"Chat",children:"Chat"}),h.jsx("button",{type:"button",onClick:()=>{be("video"),me(!1),se(!0),M&&M(!0)},className:"px-3 py-2 rounded-md bg-white/10 hover:bg-white/20 text-white text-sm",title:"Video",children:"Video"})]})]})})})()]});if(re||!ce){const le=($==null?void 0:$.message)||"VoxketWidget encountered an error. Please check your configuration.";return h.jsx("div",{className:`voxket-widget-root theme-${y} flex items-center justify-center p-8 ${u||""}`,style:{width:d||"400px",height:f||"500px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"},children:h.jsxs("div",{className:"text-center",children:[h.jsx("div",{className:"text-4xl mb-4",children:"⚠️"}),h.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Widget Error"}),h.jsx("p",{className:"text-sm mb-4",children:le}),h.jsx("button",{onClick:()=>{X(!1),z(null),window.location.reload()},className:"px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"Retry"})]})})}let Ct=`voxket-widget-root theme-${y}`,Vn={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};A==="widget"?(Ct+=` flex min-h-fit ${tn} ${vt} ${u}`,Vn={...Vn,...Kt}):(Ct=`${u||""}`,Vn={});const Br=h.jsx("div",{className:"h-full w-full flex flex-col overflow-hidden relative z-10",children:h.jsxs(Tr,{mode:"wait",children:[Q==="welcome"&&!K&&h.jsx(KR,{agentId:Y,participantName:j||"",onAgentIdChange:te,onParticipantNameChange:q,onStartCall:we,onStartChat:Ie,onStartVideo:Ve,disabled:x||K,prompts:s,statusMessage:a,title:l,subTitle:c,theme:y,modalities:St,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),K&&(Q==="voice"||Q==="chat"||Q==="video")&&h.jsx(YR,{theme:y,mode:Q,loadingText:p,initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.3,ease:"easeInOut"}},`loading-${Q}`),Q==="voice"&&!K&&x&&ce&&h.jsxs(Ot.RoomContext.Provider,{value:Me,children:[h.jsx(Ot.RoomAudioRenderer,{},`audio-${(W==null?void 0:W.id)||"no-session"}`),h.jsx(Ot.StartAudio,{label:"Start Audio"},`start-audio-${(W==null?void 0:W.id)||"no-session"}`),h.jsx(HR,{loadingText:p,participantName:j||"User",sessionStarted:x,disabled:!1,theme:y,client:ce,displayType:A,onBack:A==="popup"?Ft:xt,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"voice-session")]}),Q==="chat"&&!K&&x&&ce&&h.jsx(WR,{client:ce,theme:y,displayType:A,onBack:A==="popup"?Ft:xt,onEndChat:xt,disabled:!1,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),Q==="video"&&!K&&x&&ce&&h.jsxs(Ot.RoomContext.Provider,{value:Me,children:[h.jsx(Ot.RoomAudioRenderer,{},`audio-video-${(W==null?void 0:W.id)||"no-session"}`),h.jsx(Ot.StartAudio,{label:"Start Audio"},`start-audio-video-${(W==null?void 0:W.id)||"no-session"}`),h.jsx(GR,{client:ce,theme:y,displayType:A,onBack:A==="popup"?Ft:xt,onEndCall:xt,disabled:!1,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-session")]})]})});return A==="fullscreen"||A==="popup"?h.jsx(xf,{theme:y,displayType:A,popupPosition:O,onClose:A==="fullscreen"?Vt:Ft,children:Br}):h.jsx("div",{className:Ct,style:Vn,children:h.jsx(xf,{theme:y,displayType:A,popupPosition:O,onExpand:an,children:Br})})}function co(e){return h.jsx(nc,{children:h.jsx(ZR,{...e})})}function XR({logs:e,onClear:t,onExport:n}){const[r,i]=N.useState(!1),[o,s]=N.useState(""),a=e.filter(l=>!o||l.event.toLowerCase().includes(o.toLowerCase()));return r?h.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:h.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[h.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[h.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("input",{type:"text",placeholder:"Filter events...",value:o,onChange:l=>s(l.target.value),className:"px-3 py-1 border rounded text-sm"}),h.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),h.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),h.jsx("button",{onClick:()=>i(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),h.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?h.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):h.jsx("div",{className:"space-y-2",children:a.map((l,c)=>h.jsxs("div",{className:"border rounded p-3 text-sm",children:[h.jsxs("div",{className:"flex items-center justify-between mb-1",children:[h.jsx("span",{className:"font-semibold text-blue-600",children:l.event}),h.jsx("span",{className:"text-gray-500 text-xs",children:new Date(l.timestamp).toLocaleTimeString()})]}),l.sessionId&&h.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",l.sessionId]}),l.data&&h.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:h.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(l.data,null,2)})})]},c))})})]})}):h.jsxs("button",{onClick:()=>i(!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 QR({metrics:e}){return e?h.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[h.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),h.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[h.jsxs("div",{children:[h.jsx("span",{className:"text-gray-600",children:"Session ID:"}),h.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),h.jsxs("div",{children:[h.jsx("span",{className:"text-gray-600",children:"Start Time:"}),h.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),h.jsxs("div",{children:[h.jsx("span",{className:"text-gray-600",children:"Messages:"}),h.jsx("div",{children:e.totalMessages})]}),h.jsxs("div",{children:[h.jsx("span",{className:"text-gray-600",children:"Participants:"}),h.jsx("div",{children:e.participantCount})]}),h.jsxs("div",{children:[h.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),h.jsx("div",{children:e.connectionIssues})]}),h.jsxs("div",{children:[h.jsx("span",{className:"text-gray-600",children:"Duration:"}),h.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function ir(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:r,endSession:i}=gn(),o=N.useCallback(async(a,l)=>await r(a,l),[r]),s=N.useCallback(async()=>await i(),[i]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:o,stop:s}}function gg(){const{sessionMetrics:e,currentSession:t}=gn();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 bg(){const{setMicrophoneEnabled:e,client:t}=gn(),[n,r]=N.useState(!1),[i,o]=N.useState(!1),s=N.useCallback(async()=>{if(!i){o(!0);try{const c=!n;await e(c),r(c)}catch(c){console.error("Failed to toggle microphone:",c)}finally{o(!1)}}},[n,i,e]),a=N.useCallback(async()=>{if(!(n||i)){o(!0);try{await e(!0),r(!0)}catch(c){console.error("Failed to enable microphone:",c)}finally{o(!1)}}},[n,i,e]),l=N.useCallback(async()=>{if(!(!n||i)){o(!0);try{await e(!1),r(!1)}catch(c){console.error("Failed to disable microphone:",c)}finally{o(!1)}}},[n,i,e]);return{isEnabled:n,isLoading:i,toggle:s,enable:a,disable:l}}function yg(){const{setCameraEnabled:e}=gn(),[t,n]=N.useState(!1),[r,i]=N.useState(!1),o=N.useCallback(async()=>{if(!r){i(!0);try{const l=!t;await e(l),n(l)}catch(l){console.error("Failed to toggle camera:",l)}finally{i(!1)}}},[t,r,e]),s=N.useCallback(async()=>{if(!(t||r)){i(!0);try{await e(!0),n(!0)}catch(l){console.error("Failed to enable camera:",l)}finally{i(!1)}}},[t,r,e]),a=N.useCallback(async()=>{if(!(!t||r)){i(!0);try{await e(!1),n(!1)}catch(l){console.error("Failed to disable camera:",l)}finally{i(!1)}}},[t,r,e]);return{isEnabled:t,isLoading:r,toggle:o,enable:s,disable:a}}function xg(){const{startScreenShare:e,stopScreenShare:t}=gn(),[n,r]=N.useState(!1),[i,o]=N.useState(!1),s=N.useCallback(async()=>{if(!(n||i)){o(!0);try{await e(),r(!0)}catch(c){console.error("Failed to start screen share:",c)}finally{o(!1)}}},[n,i,e]),a=N.useCallback(async()=>{if(!(!n||i)){o(!0);try{await t(),r(!1)}catch(c){console.error("Failed to stop screen share:",c)}finally{o(!1)}}},[n,i,t]),l=N.useCallback(async()=>{n?await a():await s()},[n,s,a]);return{isSharing:n,isLoading:i,start:s,stop:a,toggle:l}}function JR(){const{client:e}=gn(),[t,n]=N.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),r=N.useMemo(()=>t.tracks.find(m=>m.isLocal),[t.tracks]),i=N.useMemo(()=>t.tracks.filter(m=>!m.isLocal),[t.tracks]),o=N.useCallback(async()=>{try{r!=null&&r.isEnabled?await(e==null?void 0:e.disableCamera()):await(e==null?void 0:e.enableCamera())}catch(m){throw console.error("Failed to toggle camera:",m),m}},[e,r]),s=N.useCallback(async()=>{try{t.tracks.find(v=>v.isScreenShare)?await(e==null?void 0:e.stopScreenShare()):await(e==null?void 0:e.startScreenShare())}catch(m){throw console.error("Failed to toggle screen share:",m),m}},[e,t.tracks]),a=N.useCallback(m=>{n(v=>({...v,layout:m}))},[]),l=N.useCallback(m=>{n(v=>({...v,pinnedTrack:m}))},[]),c=N.useCallback(()=>{n(m=>({...m,pinnedTrack:void 0}))},[]),u=N.useCallback(async()=>{try{await(e==null?void 0:e.startRecording()),n(m=>({...m,isRecording:!0}))}catch(m){throw console.error("Failed to start recording:",m),m}},[e]),d=N.useCallback(async()=>{try{await(e==null?void 0:e.stopRecording()),n(m=>({...m,isRecording:!1}))}catch(m){throw console.error("Failed to stop recording:",m),m}},[e]),f=N.useCallback(m=>t.tracks.find(v=>v.id===m),[t.tracks]),p=N.useCallback(m=>t.tracks.filter(v=>v.participantId===m),[t.tracks]),g=N.useCallback(m=>m.isEnabled&&t.tracks.includes(m),[t.tracks]);return N.useEffect(()=>{if(!e)return;const m=E=>{n(w=>({...w,tracks:[...w.tracks.filter(C=>C.id!==E.id),E]}))},v=E=>{n(w=>{var C;return{...w,tracks:w.tracks.filter(k=>k.id!==E),pinnedTrack:((C=w.pinnedTrack)==null?void 0:C.id)===E?void 0:w.pinnedTrack}})},y=E=>{n(w=>({...w,tracks:w.tracks.map(C=>C.id===E.id?E:C)}))};return e.on("videoTrackAdded",m),e.on("videoTrackRemoved",v),e.on("videoTrackUpdated",y),()=>{e.off("videoTrackAdded",m),e.off("videoTrackRemoved",v),e.off("videoTrackUpdated",y)}},[e]),{tracks:t.tracks,localTrack:r,remoteTraracks:i,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:o,toggleScreenShare:s,setLayout:a,pinTrack:l,unpinTrack:c,startRecording:u,stopRecording:d,getTrackById:f,getTracksByParticipant:p,isTrackActive:g}}function Qo(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=gn(),[r,i]=N.useState(!1),o=N.useCallback(async c=>{if(!(!c.trim()||r||!n)){i(!0);try{await t(c.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{i(!1)}}},[t,r,n]),{userMessages:s,agentMessages:a,allMessages:l}=N.useMemo(()=>{const c=e.filter(d=>d.sender.type==="participant"),u=e.filter(d=>d.sender.type==="agent");return{userMessages:c,agentMessages:u,allMessages:e}},[e]);return{messages:l,userMessages:s,agentMessages:a,messageCount:l.length,isSending:r,canSend:!!n&&!r,send:o}}function eI(){const{send:e,isSending:t,canSend:n}=Qo(),[r,i]=N.useState(""),o=N.useCallback(async()=>{if(!(!r.trim()||!n))try{await e(r),i("")}catch(a){throw a}},[r,e,n]),s=N.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),o())},[o]);return{value:r,setValue:i,send:o,handleKeyPress:s,isSending:t,canSend:n&&r.trim().length>0}}function oc(){const{isConnected:e,isConnecting:t,connectionError:n,connect:r,disconnect:i}=gn(),o=N.useCallback(async()=>{if(!(e||t))try{await r()}catch(a){throw console.error("Failed to connect:",a),a}},[r,e,t]),s=N.useCallback(async()=>{if(e)try{await i()}catch(a){throw console.error("Failed to disconnect:",a),a}},[i,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:o,disconnect:s}}function vg(){const{participants:e}=gn();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const wg=N.createContext({}),Ni=()=>N.useContext(wg);function Eg({children:e,...t}){return h.jsx(wg.Provider,{value:t,children:e})}function uo({name:e,children:t,fallback:n,className:r}){return h.jsx("div",{className:`voxket-slot voxket-slot--${e} ${r||""}`,children:t||n})}function Sg(e,t={}){return Object.assign(e,t)}function kg({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:r=!0,customControls:i,className:o=""}){const s=ir(),a=bg(),l=yg(),c=xg(),u=Ni(),d=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,s.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",o].filter(Boolean).join(" ");return!s.isActive&&!r?h.jsx("div",{className:d,children:h.jsx("div",{className:"voxket-controls-inactive",children:h.jsx("p",{children:"Controls available during active session"})})}):h.jsxs("div",{className:d,children:[r&&h.jsx("div",{className:"voxket-session-actions",children:s.isActive?h.jsx("button",{onClick:s.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):h.jsx(tI,{})}),s.isActive&&h.jsxs("div",{className:"voxket-media-controls",children:[e&&h.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:[h.jsx("span",{className:"voxket-icon",children:"🎤"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&h.jsxs("button",{onClick:l.toggle,disabled:l.isLoading,className:`voxket-button voxket-button--media ${l.isEnabled?"voxket-button--active":""}`,title:l.isEnabled?"Stop camera":"Start camera",children:[h.jsx("span",{className:"voxket-icon",children:"📹"}),l.isLoading?"Loading...":l.isEnabled?"Stop Video":"Start Video"]}),n&&h.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isSharing?"voxket-button--active":""}`,title:c.isSharing?"Stop screen share":"Start screen share",children:[h.jsx("span",{className:"voxket-icon",children:"🖥️"}),c.isLoading?"Loading...":c.isSharing?"Stop Share":"Share Screen"]})]}),i&&h.jsx("div",{className:"voxket-custom-controls",children:i})]})}function tI(){ir();const[e,t]=N.useState(!1),n=async()=>{t(!0);try{console.log("Start session - agentId needed")}catch(r){console.error("Failed to start session:",r)}finally{t(!1)}};return h.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function sc({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:r=""}){const i=ir(),o=oc(),s=Ni(),a=["voxket-session-header",`voxket-session-header--${s.variant||"default"}`,`voxket-session-header--${s.size||"md"}`,r].filter(Boolean).join(" ");return h.jsxs("div",{className:a,children:[e&&h.jsxs("div",{className:"voxket-connection-status",children:[h.jsx("div",{className:`voxket-status-indicator ${o.isConnected?"connected":"disconnected"}`}),h.jsx("span",{className:"voxket-status-text",children:o.isConnecting?"Connecting...":o.isConnected?"Connected":"Disconnected"})]}),t&&i.session&&h.jsxs("div",{className:"voxket-session-info",children:[h.jsxs("div",{className:"voxket-session-id",children:["Session: ",i.session.id.slice(-8)]}),h.jsxs("div",{className:"voxket-session-state",children:["State: ",i.state]})]}),n&&i.session&&h.jsxs("div",{className:"voxket-agent-info",children:[h.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",i.session.agentId]}),h.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",i.session.activeModalities.join(", ")]})]}),o.error&&h.jsxs("div",{className:"voxket-error-message",children:["Error: ",o.error.message]})]})}function ac({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:r=""}){const i=ir(),o=Qo(),s=Ni(),a=["voxket-session-content",`voxket-session-content--${s.variant||"default"}`,`voxket-session-content--${s.size||"md"}`,r].filter(Boolean).join(" ");return i.isActive?h.jsx("div",{className:a,children:n||h.jsxs(h.Fragment,{children:[e&&h.jsxs("div",{className:"voxket-chat-container",children:[h.jsxs("div",{className:"voxket-chat-messages",children:[o.messages.map(l=>h.jsxs("div",{className:`voxket-message voxket-message--${l.sender.type}`,children:[h.jsxs("div",{className:"voxket-message-header",children:[h.jsx("span",{className:"voxket-message-sender",children:l.sender.name}),h.jsx("span",{className:"voxket-message-time",children:l.timestamp.toLocaleTimeString()})]}),h.jsx("div",{className:"voxket-message-content",children:l.content})]},l.id)),o.messages.length===0&&h.jsx("div",{className:"voxket-empty-messages",children:h.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),h.jsx(nI,{})]}),t&&h.jsx("div",{className:"voxket-transcriptions",children:h.jsx("div",{className:"voxket-transcription-placeholder",children:h.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):h.jsx("div",{className:a,children:h.jsx("div",{className:"voxket-inactive-state",children:h.jsxs("div",{className:"voxket-inactive-message",children:[h.jsx("h3",{children:"Start a conversation"}),h.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function nI(){const e=Qo(),[t,n]=N.useState(""),r=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(o){console.error("Failed to send message:",o)}},i=o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),r())};return h.jsxs("div",{className:"voxket-chat-input",children:[h.jsx("input",{type:"text",value:t,onChange:o=>n(o.target.value),onKeyPress:i,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),h.jsx("button",{onClick:r,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function lc({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:r,className:i=""}){const o=ir(),s=gg(),a=vg(),l=Ni(),c=["voxket-session-footer",`voxket-session-footer--${l.variant||"default"}`,`voxket-session-footer--${l.size||"md"}`,i].filter(Boolean).join(" ");return o.isActive?h.jsx("div",{className:c,children:r||h.jsxs(h.Fragment,{children:[n&&h.jsxs("div",{className:"voxket-session-status",children:[h.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),h.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&s.metrics&&h.jsxs("div",{className:"voxket-session-metrics",children:[h.jsxs("div",{className:"voxket-metric",children:[h.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),h.jsx("span",{className:"voxket-metric-value",children:rI(s.duration||0)})]}),h.jsxs("div",{className:"voxket-metric",children:[h.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),h.jsx("span",{className:"voxket-metric-value",children:s.metrics.messageCount})]})]}),t&&h.jsxs("div",{className:"voxket-participants-info",children:[h.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&h.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>h.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):h.jsx("div",{className:c,children:h.jsx("div",{className:"voxket-footer-inactive",children:h.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function rI(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60);return r>0?`${r}:${(n%60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}`:`${n}:${(t%60).toString().padStart(2,"0")}`}function iI({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:r,onSessionEnd:i,variant:o="default",size:s="md",theme:a,className:l="",children:c}){var p;const u=ir(),d=oc();N.useEffect(()=>{n&&e&&d.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,d.isConnected,u.isActive]),N.useEffect(()=>{var g;(g=u.session)!=null&&g.id&&r&&r(u.session.id)},[(p=u.session)==null?void 0:p.id,r]),N.useEffect(()=>()=>{u.isActive&&i&&u.stop().then(i).catch(console.error)},[]);const f=["voxket-session",`voxket-session--${o}`,`voxket-session--${s}`,u.isActive?"voxket-session--active":"voxket-session--inactive",l].filter(Boolean).join(" ");return h.jsx(Eg,{variant:o,size:s,theme:a,className:l,children:h.jsx("div",{className:f,children:c||h.jsxs(h.Fragment,{children:[h.jsx(uo,{name:"header",fallback:h.jsx(sc,{})}),h.jsx(uo,{name:"content",fallback:h.jsx(ac,{})}),h.jsx(uo,{name:"footer",fallback:h.jsx(lc,{})})]})})})}const Cg=Sg(iI,{Header:sc,Content:ac,Footer:lc,Controls:kg}),Jn={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)"}},Va={...Jn,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)"}},za={...Jn,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"}},_g=N.createContext(null),Tg=()=>{const e=N.useContext(_g);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function oI({theme:e="default",themes:t={},children:n,cssVariables:r=!0,className:i=""}){const[o,s]=N.useState(()=>{const f={default:Jn,dark:Va,enterprise:za,...t};return typeof e=="string"?f[e]||Jn:e}),[a,l]=N.useState(()=>({default:Jn,dark:Va,enterprise:za,...t})),c=f=>{if(typeof f=="string"){const p=a[f];p&&s(p)}else s(f)},u=f=>{l(p=>({...p,[f.name]:f}))};N.useEffect(()=>{if(r&&typeof document<"u"){const f=document.documentElement;Object.entries(Ng(o)).forEach(([p,g])=>{f.style.setProperty(`--voxket-${p}`,g)})}},[o,r]);const d={theme:o,setTheme:c,themes:a,registerTheme:u};return h.jsx(_g.Provider,{value:d,children:h.jsx("div",{className:`voxket-theme voxket-theme--${o.name} ${i}`,children:n})})}function Ng(e){const t={},n=(r,i="")=>{for(const[o,s]of Object.entries(r)){const a=i?`${i}-${o}`:o;typeof s=="object"&&s!==null&&!Array.isArray(s)?n(s,a):t[a]=String(s)}};return n(e),t}function sI(e=Jn,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 aI(e){var n;const{theme:t}=Tg();return((n=t.components)==null?void 0:n[e])||{}}const lI=ic("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&cI(e),t.enableVoiceActivation&&uI(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&dI(e,t)}});function cI(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 uI(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function dI(e,t){console.log("Playing audio response:",t.content)}const fI=ic("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&hI(),t.enableFileUpload&&pI(e),t.enableCustomComponents&&mI(),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"?gI(e,t):t.type==="text"&&n.enableRichText&&bI(e,t)}});function hI(e){console.log("Rich text support enabled")}function pI(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function mI(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",yI),t.set("form",xI),t.set("card",vI),t.set("chart",wI)}function gI(e,t){const{componentType:n,props:r}=t.metadata;console.log("Rendering custom component:",n,r),e.emit("chat.component.render",{type:n,props:r,timestamp:new Date})}function bI(e,t){console.log("Processing rich text message:",t.content)}function yI(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function xI(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function vI(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function wI(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function fo({track:e,participantName:t,showControls:n=!0,showName:r=!0,showMuteIndicator:i=!0,isPinned:o=!1,className:s="",onClick:a,onPin:l,onUnpin:c}){const u=N.useRef(null),[d,f]=N.useState(!1);N.useEffect(()=>{if(!u.current||!e.isEnabled)return;const v=u.current;return v.srcObject=null,()=>{v.srcObject&&(v.srcObject=null)}},[e]);const p=()=>{a==null||a(e)},g=v=>{v.stopPropagation(),o?c==null||c(e):l==null||l(e)},m=["voxket-video-tile",e.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",e.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",o?"voxket-video-tile--pinned":"",e.isEnabled?"":"voxket-video-tile--disabled",d?"voxket-video-tile--hovered":"",s].filter(Boolean).join(" ");return h.jsxs("div",{className:m,onClick:p,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[h.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&h.jsxs("div",{className:"voxket-video-placeholder",children:[h.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"🖥️":"📹"}),h.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),h.jsxs("div",{className:"voxket-video-overlay",children:[r&&t&&h.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),i&&!e.isEnabled&&h.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),n&&(d||o)&&h.jsxs("div",{className:"voxket-video-controls",children:[h.jsx("button",{className:`voxket-video-control-btn ${o?"voxket-video-control-btn--active":""}`,onClick:g,title:o?"Unpin video":"Pin video",children:"📌"}),e.isScreenShare&&h.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),e.source&&h.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&h.jsx("div",{className:"voxket-video-loading",children:h.jsx("div",{className:"voxket-spinner"})})]})}function EI({tracks:e,layout:t,className:n="",onLayoutChange:r,onTrackClick:i,maxVisibleTracks:o=9,showPagination:s=!0}){const[a,l]=N.useState(0),[c,u]=N.useState(null),d=N.useMemo(()=>{let E=[...e];t.type==="speaker"&&c&&(E=[c,...e.filter(k=>k.id!==c.id)]);const w=a*o,C=w+o;return E.slice(w,C)},[e,t,c,a,o]),f=Math.ceil(e.length/o),p=N.useMemo(()=>{const E=d.length;switch(t.type){case"grid":const w=Math.ceil(Math.sqrt(E)),C=Math.ceil(E/w);return{display:"grid",gridTemplateColumns:`repeat(${w}, 1fr)`,gridTemplateRows:`repeat(${C}, 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)},m=()=>{u(null)},v=E=>{r==null||r({...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?h.jsx("div",{className:"voxket-video-grid-empty",children:h.jsxs("div",{className:"voxket-video-grid-empty-content",children:[h.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),h.jsx("p",{children:"No video tracks available"})]})}):h.jsxs("div",{className:y,children:[h.jsxs("div",{className:"voxket-video-grid-controls",children:[h.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(E=>h.jsx("button",{className:`voxket-layout-btn ${t.type===E?"voxket-layout-btn--active":""}`,onClick:()=>v(E),title:`Switch to ${E} layout`,children:SI(E)},E))}),h.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),h.jsx("div",{className:"voxket-video-grid-content",style:p,children:t.type==="speaker"&&c?h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"voxket-video-speaker-main",children:h.jsx(fo,{track:c,participantName:`Participant ${c.participantId}`,isPinned:!0,onClick:i,onUnpin:m})}),h.jsx("div",{className:"voxket-video-speaker-sidebar",children:d.filter(E=>E.id!==c.id).map(E=>h.jsx(fo,{track:E,participantName:`Participant ${E.participantId}`,showControls:!1,onClick:i,onPin:g},E.id))})]}):d.map(E=>h.jsx(fo,{track:E,participantName:`Participant ${E.participantId}`,isPinned:(c==null?void 0:c.id)===E.id,onClick:i,onPin:g,onUnpin:m},E.id))}),s&&f>1&&h.jsxs("div",{className:"voxket-video-pagination",children:[h.jsx("button",{className:"voxket-pagination-btn",onClick:()=>l(Math.max(0,a-1)),disabled:a===0,children:"←"}),h.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",f]}),h.jsx("button",{className:"voxket-pagination-btn",onClick:()=>l(Math.min(f-1,a+1)),disabled:a===f-1,children:"→"})]})]})}function SI(e){switch(e){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function kI({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:r,showLayoutControls:i=!0,showCameraControls:o=!0,showScreenShareControls:s=!0,className:a=""}){const l=["voxket-video-controls",a].filter(Boolean).join(" "),c=u=>{r==null||r({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return h.jsxs("div",{className:l,children:[o&&h.jsxs("div",{className:"voxket-video-controls-section",children:[h.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),h.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:[h.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"📹":"📷"}),h.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&h.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," × ",e.dimensions.height]})]}),s&&h.jsxs("div",{className:"voxket-video-controls-section",children:[h.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),h.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:[h.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"🛑":"🖥️"}),h.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),i&&h.jsxs("div",{className:"voxket-video-controls-section",children:[h.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),h.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:f})=>h.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>c(u),title:`Switch to ${f} layout`,children:[h.jsx("span",{className:"voxket-control-icon",children:d}),h.jsx("span",{className:"voxket-control-label",children:f})]},u))})]}),h.jsxs("div",{className:"voxket-video-controls-section",children:[h.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),h.jsxs("div",{className:"voxket-video-settings",children:[h.jsxs("div",{className:"voxket-setting-group",children:[h.jsx("label",{className:"voxket-setting-label",children:"Quality"}),h.jsxs("select",{className:"voxket-setting-select",children:[h.jsx("option",{value:"high",children:"High (720p)"}),h.jsx("option",{value:"medium",children:"Medium (480p)"}),h.jsx("option",{value:"low",children:"Low (240p)"})]})]}),h.jsxs("div",{className:"voxket-setting-group",children:[h.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),h.jsxs("select",{className:"voxket-setting-select",children:[h.jsx("option",{value:"30",children:"30 fps"}),h.jsx("option",{value:"15",children:"15 fps"}),h.jsx("option",{value:"10",children:"10 fps"})]})]}),h.jsxs("div",{className:"voxket-setting-group",children:[h.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),h.jsxs("select",{className:"voxket-setting-select",children:[h.jsx("option",{value:"unlimited",children:"Unlimited"}),h.jsx("option",{value:"1000",children:"1 Mbps"}),h.jsx("option",{value:"500",children:"500 Kbps"}),h.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),h.jsxs("div",{className:"voxket-video-controls-section",children:[h.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),h.jsxs("div",{className:"voxket-video-stats",children:[h.jsxs("div",{className:"voxket-stat-item",children:[h.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),h.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}×${e.dimensions.height}`:"N/A"})]}),h.jsxs("div",{className:"voxket-stat-item",children:[h.jsx("span",{className:"voxket-stat-label",children:"Source:"}),h.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),h.jsxs("div",{className:"voxket-stat-item",children:[h.jsx("span",{className:"voxket-stat-label",children:"Status:"}),h.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 Ag=({handler:e,loadData:t,data:n,client:r,addLocalMessage:i})=>{const[o,s]=P.useState(null),[a,l]=P.useState(!0),[c,u]=P.useState(!1),[d]=P.useState(Date.now()),[f,p]=P.useState("pending");P.useEffect(()=>{(async()=>{try{if(l(!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"};s(E),console.log("📋 AssignmentView: Assignment loaded from RPC data:",E)}}catch(E){console.error("📋 AssignmentView: Error loading assignment:",E),s({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{l(!1)}})()},[n,t]);const g=({message:y,assignment:E})=>{const w=y.toLowerCase().includes("declined"),C=w?"bg-red-50 border-red-200":"bg-green-50 border-green-200",k=w?"text-red-700":"text-green-700",_=w?"❌":"🎉";return h.jsxs("div",{className:`max-w-sm mx-auto ${C} border rounded-lg shadow p-3 flex flex-col items-center`,children:[h.jsx("div",{className:"text-2xl mb-2",children:_}),h.jsx("div",{className:`${k} font-semibold text-sm mb-1`,children:y}),h.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:E.title}),h.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},m=async()=>{if(!(!o||!e)){u(!0);try{const y={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",y),e.didSuccess(y),p("accepted")}catch(y){console.error("📋 AssignmentView: Error accepting assignment:",y),e.didFail({error:"Failed to accept assignment"}),p("error")}finally{u(!1)}}},v=async()=>{if(!(!o||!e)){u(!0);try{const y={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",y),e.didSuccess(y),p("declined")}catch(y){console.error("📋 AssignmentView: Error declining assignment:",y),e.didFail({error:"Failed to decline assignment"}),p("error")}finally{u(!1)}}};return a?h.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:h.jsxs("div",{className:"flex items-center justify-center py-4",children:[h.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),h.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):o?f==="accepted"||f==="declined"||f==="error"?h.jsx(g,{message:f==="accepted"?"Assignment accepted!":f==="declined"?"Assignment declined":"Assignment error occurred",assignment:o}):h.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[h.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:h.jsx("div",{className:"flex items-center justify-between",children:h.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:o.title})})}),h.jsxs("div",{className:"p-3 text-black",children:[h.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:h.jsx("p",{className:"text-xs text-black leading-snug",children:o.description})}),h.jsx("div",{className:"mb-3 text-black",children:h.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[h.jsx("span",{className:"text-xs mr-1",children:"📅"}),h.jsxs("span",{children:["Est: ",o.estimated_time_of_completion]})]})}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:m,disabled:c,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:c?h.jsxs("span",{className:"flex items-center justify-center",children:[h.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),h.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),h.jsx("button",{onClick:v,disabled:c,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"})]})]})]}):h.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:h.jsxs("div",{className:"text-center py-4",children:[h.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),h.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function CI(){const[e,t]=P.useState(null),[n,r]=P.useState([]);P.useEffect(()=>{const a=new Ti({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",l=>{console.log("RPC Method Called:",l)}),a.on("rpc.interaction.completed",l=>{console.log("RPC Interaction Completed:",l)}),()=>{a.disconnect()}},[]);const i=async()=>{if(e)try{await e.registerFrontendRPC("give_assignment",Ag,"embedded");const a=e.getRegisteredRpcMethods();r(a),console.log("✅ Assignment RPC registered successfully")}catch(a){console.error("❌ Failed to register assignment RPC:",a)}},o=async()=>{if(!e)return;const a=({handler:l,timeout:c})=>{const[u,d]=P.useState(""),f=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],p=m=>{d(m)},g=()=>{const m=f.find(v=>v.id===u);l==null||l.didSuccess({selectedProduct:u,productName:m==null?void 0:m.name,price:m==null?void 0:m.price,timestamp:new Date().toISOString()})};return h.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[h.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),h.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),h.jsx("div",{className:"space-y-3 mb-6",children:f.map(m=>h.jsx("div",{onClick:()=>p(m.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${u===m.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:h.jsxs("div",{className:"flex justify-between items-center",children:[h.jsxs("div",{children:[h.jsx("h4",{className:"font-medium",children:m.name}),h.jsx("p",{className:"text-gray-600 text-sm",children:m.price})]}),h.jsx("div",{className:`w-4 h-4 rounded-full ${u===m.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},m.id))}),h.jsxs("div",{className:"flex justify-end space-x-3",children:[h.jsx("button",{onClick:()=>l==null?void 0:l.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),h.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"})]}),c&&h.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",c," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const l=e.getRegisteredRpcMethods();r(l),console.log("✅ Product Recommendation RPC registered successfully")}catch(l){console.error("❌ Failed to register product recommendation RPC:",l)}},s=async()=>{if(!e)return;const a=({handler:l})=>{const[c,u]=P.useState(0),[d,f]=P.useState(""),p=()=>{l==null||l.didSuccess({rating:c,comment:d,timestamp:new Date().toISOString()})};return h.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[h.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),h.jsxs("div",{className:"mb-4",children:[h.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),h.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(g=>h.jsx("button",{onClick:()=>u(g),className:`text-2xl ${g<=c?"text-yellow-400":"text-gray-300"}`,children:"⭐"},g))})]}),h.jsxs("div",{className:"mb-4",children:[h.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),h.jsx("textarea",{value:d,onChange:g=>f(g.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),h.jsxs("div",{className:"flex justify-end space-x-2",children:[h.jsx("button",{onClick:()=>l==null?void 0:l.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),h.jsx("button",{onClick:p,disabled:c===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 l=e.getRegisteredRpcMethods();r(l),console.log("✅ Feedback RPC registered successfully")}catch(l){console.error("❌ Failed to register feedback RPC:",l)}};return h.jsxs("div",{className:"p-6",children:[h.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),h.jsxs("div",{className:"space-y-4 mb-6",children:[h.jsxs("div",{children:[h.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),h.jsxs("div",{className:"space-x-2",children:[h.jsx("button",{onClick:i,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),h.jsx("button",{onClick:o,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),h.jsx("button",{onClick:s,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),h.jsxs("div",{children:[h.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?h.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>h.jsx("li",{className:"text-gray-700",children:h.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):h.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),h.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[h.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),h.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[h.jsxs("li",{children:["Register RPC methods with React components using ",h.jsx("code",{children:"client.registerFrontendRPC()"})]}),h.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),h.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),h.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),h.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),h.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[h.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),h.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),h.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
144
144
  const response = await participant.performRpc({
145
145
  method: 'give_assignment',
146
146
  data: JSON.stringify({