@voxket-ai/voxket-live 1.1.13 โ 1.1.14
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 +1 -1
- package/dist/index.js +111 -99
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -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 og=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})})]})]})});og.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 sg=({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,u]=P.useState(!1),d={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},f=l==="light"?"#3b82f6":"#000000",p={width:n,height:n,...i},g=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:g?void 0:{scale:[1,1.1,1],opacity:[.6,.9,.6]},transition:g?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:g?void 0:{scale:[1,1.05,1],opacity:[.7,1,.7]},transition:g?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 ${d[t]} ${r}`,style:{...p,backgroundColor:f,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&&!g?{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:{...!g&&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:g?void 0:{rotate:360},transition:g?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%)"}})]}),c?h.jsx(ig,{className:"relative z-10",style:{fontSize:n*.5,color:"#ffffff",filter:a?"brightness(1.1) contrast(1.1)":"none"}}):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,onError:()=>u(!0)})]})]})};function ag({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 lg{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 cg 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 ug{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 dg{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 fg{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 hg{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 pg=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(pg.Provider,{value:$,children:t})}function gn(){const e=N.useContext(pg);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}const Rn=new WeakSet,ea=new WeakSet;class mg{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=Qg.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 gg{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 ug(this,n.participantName||"User"),this.mediaManager=new dg(this),this.agentManager=new gg(this),this.connectionManager=new fg({baseUrl:n.baseUrl,appId:n.appId,appSecret:n.appSecret},this),this.streamHandlerManager=new hg(this,this.chatManager,this.agentManager),this.uiRenderer=new mg(n,this),this.pluginManager=new lg(this),this.rpcManager=new cg,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(og);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}=ag({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(sg,{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 bg(){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 yg(){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 xg(){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 vg(){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 wg(){const{participants:e}=gn();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const Eg=N.createContext({}),Ni=()=>N.useContext(Eg);function Sg({children:e,...t}){return h.jsx(Eg.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 kg(e,t={}){return Object.assign(e,t)}function Cg({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:r=!0,customControls:i,className:o=""}){const s=ir(),a=yg(),l=xg(),c=vg(),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=bg(),a=wg(),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(Sg,{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 _g=kg(iI,{Header:sc,Content:ac,Footer:lc,Controls:Cg}),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"}},Tg=N.createContext(null),Ng=()=>{const e=N.useContext(Tg);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(Ag(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(Tg.Provider,{value:d,children:h.jsx("div",{className:`voxket-theme voxket-theme--${o.name} ${i}`,children:n})})}function Ag(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}=Ng();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 Mg=({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",Mg,"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 og=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})})]})]})});og.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 sg=({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,u]=P.useState(!1),d={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},f=l==="light"?"#3b82f6":"#000000",p={width:n,height:n,...i},g=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:g?void 0:{scale:[1,1.1,1],opacity:[.6,.9,.6]},transition:g?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:g?void 0:{scale:[1,1.05,1],opacity:[.7,1,.7]},transition:g?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 ${d[t]} ${r}`,style:{...p,backgroundColor:f,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&&!g?{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:{...!g&&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:g?void 0:{rotate:360},transition:g?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%)"}})]}),c?h.jsx(ig,{className:"relative z-10",style:{fontSize:n*.5,color:"#ffffff",filter:a?"brightness(1.1) contrast(1.1)":"none"}}):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,onError:()=>u(!0)})]})]})};function ag({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 lg{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 cg 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 ug{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 dg{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 fg{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 hg{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 pg=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(pg.Provider,{value:$,children:t})}function gn(){const e=N.useContext(pg);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}const Rn=new WeakSet,ea=new WeakSet;class mg{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=Qg.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 gg{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 ug(this,n.participantName||"User"),this.mediaManager=new dg(this),this.agentManager=new gg(this),this.connectionManager=new fg({baseUrl:n.baseUrl,appId:n.appId,appSecret:n.appSecret},this),this.streamHandlerManager=new hg(this,this.chatManager,this.agentManager),this.uiRenderer=new mg(n,this),this.pluginManager=new lg(this),this.rpcManager=new cg,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(og);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,width:s,height:a}){const l=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:c=>{c.target===c.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:c=>{c.stopPropagation()},children:[r&&h.jsx("button",{onClick:c=>{c.preventDefault(),c.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} ${l.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:l.cardTopGradient}),h.jsx("div",{className:l.cardPurpleBlur}),h.jsx("div",{className:l.cardPinkBlur}),h.jsx("div",{className:"relative z-10 flex flex-col h-full",children:e}),h.jsx("div",{className:l.cardPulse1}),h.jsx("div",{className:l.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(n==="popup"){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=s||"400px",d=a||"600px";return h.jsx("div",{className:"fixed rounded-2xl inset-0 z-[9999] pointer-events-none",children:h.jsxs("div",{className:`fixed rounded-2xl ${c[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} ${l.card} rounded-2xl flex flex-col relative overflow-hidden`,"data-theme":t,style:{width:u,height:d,contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0},children:[h.jsx("div",{className:l.cardTopGradient}),h.jsx("div",{className:l.cardPurpleBlur}),h.jsx("div",{className:l.cardPinkBlur}),h.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),h.jsx("div",{className:l.cardPulse1}),h.jsx("div",{className:l.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return h.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${l.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:l.cardTopGradient}),h.jsx("div",{className:l.cardPurpleBlur}),h.jsx("div",{className:l.cardPinkBlur}),h.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),h.jsx("div",{className:l.cardPulse1}),h.jsx("div",{className:l.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}=ag({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(sg,{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,width:d,height:f,children:Br}):h.jsx("div",{className:Ct,style:Vn,children:h.jsx(xf,{theme:y,displayType:A,popupPosition:O,onExpand:an,width:d,height:f,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 bg(){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 yg(){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 xg(){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 vg(){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 wg(){const{participants:e}=gn();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const Eg=N.createContext({}),Ni=()=>N.useContext(Eg);function Sg({children:e,...t}){return h.jsx(Eg.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 kg(e,t={}){return Object.assign(e,t)}function Cg({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:r=!0,customControls:i,className:o=""}){const s=ir(),a=yg(),l=xg(),c=vg(),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=bg(),a=wg(),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(Sg,{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 _g=kg(iI,{Header:sc,Content:ac,Footer:lc,Controls:Cg}),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"}},Tg=N.createContext(null),Ng=()=>{const e=N.useContext(Tg);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(Ag(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(Tg.Provider,{value:d,children:h.jsx("div",{className:`voxket-theme voxket-theme--${o.name} ${i}`,children:n})})}function Ag(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}=Ng();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 Mg=({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",Mg,"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({
|
package/dist/index.js
CHANGED
|
@@ -39661,111 +39661,119 @@ function kf({
|
|
|
39661
39661
|
displayType: n = "widget",
|
|
39662
39662
|
onClose: r,
|
|
39663
39663
|
popupPosition: i = "bottom-right",
|
|
39664
|
-
onExpand: o
|
|
39664
|
+
onExpand: o,
|
|
39665
|
+
width: s,
|
|
39666
|
+
height: a
|
|
39665
39667
|
}) {
|
|
39666
|
-
const
|
|
39667
|
-
|
|
39668
|
-
|
|
39669
|
-
|
|
39670
|
-
|
|
39671
|
-
|
|
39672
|
-
|
|
39673
|
-
|
|
39674
|
-
|
|
39675
|
-
|
|
39676
|
-
{
|
|
39677
|
-
className: "w-full h-full max-w-7xl max-h-[95vh] rounded-2xl relative bg-transparent flex flex-col",
|
|
39678
|
-
onClick: (a) => {
|
|
39679
|
-
a.stopPropagation();
|
|
39680
|
-
},
|
|
39681
|
-
children: [
|
|
39682
|
-
r && /* @__PURE__ */ g(
|
|
39683
|
-
"button",
|
|
39684
|
-
{
|
|
39685
|
-
onClick: (a) => {
|
|
39686
|
-
a.preventDefault(), a.stopPropagation(), r();
|
|
39687
|
-
},
|
|
39688
|
-
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"}`,
|
|
39689
|
-
title: "Exit Fullscreen",
|
|
39690
|
-
type: "button",
|
|
39691
|
-
children: /* @__PURE__ */ g("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: /* @__PURE__ */ g("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" }) })
|
|
39692
|
-
}
|
|
39693
|
-
),
|
|
39694
|
-
/* @__PURE__ */ N(
|
|
39695
|
-
"div",
|
|
39696
|
-
{
|
|
39697
|
-
id: "voice-card",
|
|
39698
|
-
className: `voxket-widget-root theme-${t} ${s.card} w-full h-full flex flex-col rounded-xl shadow-2xl relative overflow-hidden`,
|
|
39699
|
-
"data-theme": t,
|
|
39700
|
-
style: {
|
|
39701
|
-
minHeight: "600px",
|
|
39702
|
-
height: "100%",
|
|
39703
|
-
contain: "layout style paint",
|
|
39704
|
-
overscrollBehavior: "contain",
|
|
39705
|
-
backgroundColor: t === "midnight" ? "#161a25" : void 0
|
|
39706
|
-
},
|
|
39707
|
-
children: [
|
|
39708
|
-
/* @__PURE__ */ g("div", { className: s.cardTopGradient }),
|
|
39709
|
-
/* @__PURE__ */ g("div", { className: s.cardPurpleBlur }),
|
|
39710
|
-
/* @__PURE__ */ g("div", { className: s.cardPinkBlur }),
|
|
39711
|
-
/* @__PURE__ */ g("div", { className: "relative z-10 flex flex-col h-full", children: e }),
|
|
39712
|
-
/* @__PURE__ */ g("div", { className: s.cardPulse1 }),
|
|
39713
|
-
/* @__PURE__ */ g("div", { className: s.cardPulse2, style: { animationDelay: "1s" } })
|
|
39714
|
-
]
|
|
39715
|
-
}
|
|
39716
|
-
)
|
|
39717
|
-
]
|
|
39718
|
-
}
|
|
39719
|
-
)
|
|
39720
|
-
}
|
|
39721
|
-
) : n === "popup" ? /* @__PURE__ */ g(
|
|
39722
|
-
"div",
|
|
39723
|
-
{
|
|
39724
|
-
className: "fixed rounded-2xl inset-0 z-[9999] pointer-events-none",
|
|
39725
|
-
children: /* @__PURE__ */ N("div", { className: `fixed rounded-2xl ${{
|
|
39726
|
-
"top-left": "top-4 left-4",
|
|
39727
|
-
"top-right": "top-4 right-4",
|
|
39728
|
-
"bottom-left": "bottom-4 left-4",
|
|
39729
|
-
"bottom-right": "bottom-4 right-4"
|
|
39730
|
-
}[i]} pointer-events-auto`, children: [
|
|
39731
|
-
r && /* @__PURE__ */ g(
|
|
39732
|
-
"button",
|
|
39733
|
-
{
|
|
39734
|
-
onClick: r,
|
|
39735
|
-
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"}`,
|
|
39736
|
-
children: "ร"
|
|
39737
|
-
}
|
|
39738
|
-
),
|
|
39739
|
-
/* @__PURE__ */ N(
|
|
39668
|
+
const l = zt(t);
|
|
39669
|
+
if (n === "fullscreen")
|
|
39670
|
+
return /* @__PURE__ */ g(
|
|
39671
|
+
"div",
|
|
39672
|
+
{
|
|
39673
|
+
className: "fixed inset-0 z-[9999] bg-black/40 bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",
|
|
39674
|
+
onClick: (c) => {
|
|
39675
|
+
c.target === c.currentTarget && r && r();
|
|
39676
|
+
},
|
|
39677
|
+
children: /* @__PURE__ */ N(
|
|
39740
39678
|
"div",
|
|
39741
39679
|
{
|
|
39742
|
-
|
|
39743
|
-
|
|
39744
|
-
|
|
39745
|
-
style: {
|
|
39746
|
-
width: "350px",
|
|
39747
|
-
height: "500px",
|
|
39748
|
-
contain: "layout style paint",
|
|
39749
|
-
overscrollBehavior: "contain",
|
|
39750
|
-
backgroundColor: t === "midnight" ? "#161a25" : void 0
|
|
39680
|
+
className: "w-full h-full max-w-7xl max-h-[95vh] rounded-2xl relative bg-transparent flex flex-col",
|
|
39681
|
+
onClick: (c) => {
|
|
39682
|
+
c.stopPropagation();
|
|
39751
39683
|
},
|
|
39752
39684
|
children: [
|
|
39753
|
-
/* @__PURE__ */ g(
|
|
39754
|
-
|
|
39755
|
-
|
|
39756
|
-
|
|
39757
|
-
|
|
39758
|
-
|
|
39685
|
+
r && /* @__PURE__ */ g(
|
|
39686
|
+
"button",
|
|
39687
|
+
{
|
|
39688
|
+
onClick: (c) => {
|
|
39689
|
+
c.preventDefault(), c.stopPropagation(), r();
|
|
39690
|
+
},
|
|
39691
|
+
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"}`,
|
|
39692
|
+
title: "Exit Fullscreen",
|
|
39693
|
+
type: "button",
|
|
39694
|
+
children: /* @__PURE__ */ g("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: /* @__PURE__ */ g("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" }) })
|
|
39695
|
+
}
|
|
39696
|
+
),
|
|
39697
|
+
/* @__PURE__ */ N(
|
|
39698
|
+
"div",
|
|
39699
|
+
{
|
|
39700
|
+
id: "voice-card",
|
|
39701
|
+
className: `voxket-widget-root theme-${t} ${l.card} w-full h-full flex flex-col rounded-xl shadow-2xl relative overflow-hidden`,
|
|
39702
|
+
"data-theme": t,
|
|
39703
|
+
style: {
|
|
39704
|
+
minHeight: "600px",
|
|
39705
|
+
height: "100%",
|
|
39706
|
+
contain: "layout style paint",
|
|
39707
|
+
overscrollBehavior: "contain",
|
|
39708
|
+
backgroundColor: t === "midnight" ? "#161a25" : void 0
|
|
39709
|
+
},
|
|
39710
|
+
children: [
|
|
39711
|
+
/* @__PURE__ */ g("div", { className: l.cardTopGradient }),
|
|
39712
|
+
/* @__PURE__ */ g("div", { className: l.cardPurpleBlur }),
|
|
39713
|
+
/* @__PURE__ */ g("div", { className: l.cardPinkBlur }),
|
|
39714
|
+
/* @__PURE__ */ g("div", { className: "relative z-10 flex flex-col h-full", children: e }),
|
|
39715
|
+
/* @__PURE__ */ g("div", { className: l.cardPulse1 }),
|
|
39716
|
+
/* @__PURE__ */ g("div", { className: l.cardPulse2, style: { animationDelay: "1s" } })
|
|
39717
|
+
]
|
|
39718
|
+
}
|
|
39719
|
+
)
|
|
39759
39720
|
]
|
|
39760
39721
|
}
|
|
39761
39722
|
)
|
|
39762
|
-
|
|
39763
|
-
|
|
39764
|
-
|
|
39723
|
+
}
|
|
39724
|
+
);
|
|
39725
|
+
if (n === "popup") {
|
|
39726
|
+
const c = {
|
|
39727
|
+
"top-left": "top-4 left-4",
|
|
39728
|
+
"top-right": "top-4 right-4",
|
|
39729
|
+
"bottom-left": "bottom-4 left-4",
|
|
39730
|
+
"bottom-right": "bottom-4 right-4"
|
|
39731
|
+
}, u = s || "400px", d = a || "600px";
|
|
39732
|
+
return /* @__PURE__ */ g(
|
|
39733
|
+
"div",
|
|
39734
|
+
{
|
|
39735
|
+
className: "fixed rounded-2xl inset-0 z-[9999] pointer-events-none",
|
|
39736
|
+
children: /* @__PURE__ */ N("div", { className: `fixed rounded-2xl ${c[i]} pointer-events-auto`, children: [
|
|
39737
|
+
r && /* @__PURE__ */ g(
|
|
39738
|
+
"button",
|
|
39739
|
+
{
|
|
39740
|
+
onClick: r,
|
|
39741
|
+
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"}`,
|
|
39742
|
+
children: "ร"
|
|
39743
|
+
}
|
|
39744
|
+
),
|
|
39745
|
+
/* @__PURE__ */ N(
|
|
39746
|
+
"div",
|
|
39747
|
+
{
|
|
39748
|
+
id: "voice-card",
|
|
39749
|
+
className: `voxket-widget-root theme-${t} ${l.card} rounded-2xl flex flex-col relative overflow-hidden`,
|
|
39750
|
+
"data-theme": t,
|
|
39751
|
+
style: {
|
|
39752
|
+
width: u,
|
|
39753
|
+
height: d,
|
|
39754
|
+
contain: "layout style paint",
|
|
39755
|
+
overscrollBehavior: "contain",
|
|
39756
|
+
backgroundColor: t === "midnight" ? "#161a25" : void 0
|
|
39757
|
+
},
|
|
39758
|
+
children: [
|
|
39759
|
+
/* @__PURE__ */ g("div", { className: l.cardTopGradient }),
|
|
39760
|
+
/* @__PURE__ */ g("div", { className: l.cardPurpleBlur }),
|
|
39761
|
+
/* @__PURE__ */ g("div", { className: l.cardPinkBlur }),
|
|
39762
|
+
/* @__PURE__ */ g("div", { className: "relative z-10 flex flex-col h-full w-full", children: e }),
|
|
39763
|
+
/* @__PURE__ */ g("div", { className: l.cardPulse1 }),
|
|
39764
|
+
/* @__PURE__ */ g("div", { className: l.cardPulse2, style: { animationDelay: "1s" } })
|
|
39765
|
+
]
|
|
39766
|
+
}
|
|
39767
|
+
)
|
|
39768
|
+
] })
|
|
39769
|
+
}
|
|
39770
|
+
);
|
|
39771
|
+
}
|
|
39772
|
+
return /* @__PURE__ */ N(
|
|
39765
39773
|
"div",
|
|
39766
39774
|
{
|
|
39767
39775
|
id: "voice-card",
|
|
39768
|
-
className: `voxket-widget-root theme-${t} ${
|
|
39776
|
+
className: `voxket-widget-root theme-${t} ${l.card} relative overflow-hidden w-full h-full`,
|
|
39769
39777
|
"data-theme": t,
|
|
39770
39778
|
style: {
|
|
39771
39779
|
height: "100%",
|
|
@@ -39775,12 +39783,12 @@ function kf({
|
|
|
39775
39783
|
backgroundColor: t === "midnight" ? "#161a25" : void 0
|
|
39776
39784
|
},
|
|
39777
39785
|
children: [
|
|
39778
|
-
/* @__PURE__ */ g("div", { className:
|
|
39779
|
-
/* @__PURE__ */ g("div", { className:
|
|
39780
|
-
/* @__PURE__ */ g("div", { className:
|
|
39786
|
+
/* @__PURE__ */ g("div", { className: l.cardTopGradient }),
|
|
39787
|
+
/* @__PURE__ */ g("div", { className: l.cardPurpleBlur }),
|
|
39788
|
+
/* @__PURE__ */ g("div", { className: l.cardPinkBlur }),
|
|
39781
39789
|
/* @__PURE__ */ g("div", { className: "relative z-10 flex flex-col h-full w-full", children: e }),
|
|
39782
|
-
/* @__PURE__ */ g("div", { className:
|
|
39783
|
-
/* @__PURE__ */ g("div", { className:
|
|
39790
|
+
/* @__PURE__ */ g("div", { className: l.cardPulse1 }),
|
|
39791
|
+
/* @__PURE__ */ g("div", { className: l.cardPulse2, style: { animationDelay: "1s" } })
|
|
39784
39792
|
]
|
|
39785
39793
|
}
|
|
39786
39794
|
);
|
|
@@ -40287,6 +40295,8 @@ function TI(e) {
|
|
|
40287
40295
|
displayType: A,
|
|
40288
40296
|
popupPosition: O,
|
|
40289
40297
|
onClose: A === "fullscreen" ? Gt : Ut,
|
|
40298
|
+
width: d,
|
|
40299
|
+
height: f,
|
|
40290
40300
|
children: qr
|
|
40291
40301
|
}
|
|
40292
40302
|
) : /* @__PURE__ */ g("div", { className: Rt, style: Yn, children: /* @__PURE__ */ g(
|
|
@@ -40296,6 +40306,8 @@ function TI(e) {
|
|
|
40296
40306
|
displayType: A,
|
|
40297
40307
|
popupPosition: O,
|
|
40298
40308
|
onExpand: pn,
|
|
40309
|
+
width: d,
|
|
40310
|
+
height: f,
|
|
40299
40311
|
children: qr
|
|
40300
40312
|
}
|
|
40301
40313
|
) });
|