@voxket-ai/voxket-live 1.0.117 → 1.0.119

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -122,7 +122,7 @@ To suppress this warning, you need to explicitly provide the \`palette.${t}Chann
122
122
  ${n.promptSlider}
123
123
  ${i===s?"opacity-100":"opacity-0"}
124
124
  whitespace-pre-line break-words
125
- `,style:{minHeight:"2.5rem",display:i===s?"block":"none"},children:o},i))})}function K1({statusMessage:e,theme:t}){const n=De(t);return l.jsxs("div",{className:"z-10 flex items-center space-x-2 mt-2 pb-2",children:[l.jsx("div",{className:n.statusIndicator}),l.jsx("span",{className:`text-xs ${n.text.muted}`,children:e})]})}const Y1=({disabled:e,onStartCall:t,onStartChat:n,onStartVideo:s,prompts:r=['"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:i="Choose how to interact",subTitle:a="Ask me anything or give me a task to complete",theme:c="vox",modalities:d=["voice","chat","video"]})=>{const u=De(c),f=d.includes("voice"),h=d.includes("chat"),y=d.includes("video"),x=[f,h,y].filter(Boolean).length;return console.log("🎯 Welcome component debug:",{modalities:d,hasVoice:f,hasChat:h,hasVideo:y,totalButtons:x,onStartVideo:!!s}),l.jsxs("div",{className:"flex p-8 flex-col items-center h-full justify-center w-full relative","aria-disabled":e,style:{background:"transparent"},children:[l.jsxs("div",{className:"mt-1 relative flex items-center justify-center mb-8 w-full",style:{minHeight:"120px"},children:[l.jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[l.jsx("div",{className:u.pulseRings.ring1}),l.jsx("div",{className:u.pulseRings.ring2,style:{animationDelay:"0.5s"}}),l.jsx("div",{className:u.pulseRings.ring3,style:{animationDelay:"1s"}})]}),l.jsx("div",{className:"relative z-10 flex items-center justify-center",children:f&&h&&y?l.jsxs("div",{className:"flex gap-4 items-center justify-center",children:[l.jsx(Yn,{onClick:t,disabled:e,theme:c}),l.jsx(or,{onClick:n,disabled:e,theme:c}),l.jsx(ir,{onClick:s||t,disabled:e,theme:c})]}):x>1?l.jsxs("div",{className:"flex gap-6 items-center justify-center",children:[f&&l.jsx(Yn,{onClick:t,disabled:e,theme:c}),h&&l.jsx(or,{onClick:n,disabled:e,theme:c}),y&&s&&l.jsx(ir,{onClick:s,disabled:e,theme:c})]}):l.jsx("div",{className:"flex items-center justify-center",children:f?l.jsx(Yn,{onClick:t,disabled:e,theme:c}):h?l.jsx(or,{onClick:n,disabled:e,theme:c}):y&&s?l.jsx(ir,{onClick:s,disabled:e,theme:c}):l.jsx(Yn,{onClick:t,disabled:e,theme:c})})})]}),l.jsxs("div",{className:"text-center flex flex-col items-center gap-y-2 mb-6 w-full",children:[l.jsx("h3",{className:`text-xl font-semibold mb-2 ${u.text.accent}`,children:i}),l.jsx("p",{className:`text-sm leading-relaxed px-4 ${u.text.secondary}`,children:a}),x>1&&l.jsxs("div",{className:"flex gap-6 mt-4 text-xs justify-center",children:[f&&l.jsxs("div",{className:"flex flex-col items-center gap-1",children:[l.jsx(fd,{className:"w-4 h-4"}),l.jsx("span",{className:u.text.muted,children:"Voice"})]}),h&&l.jsxs("div",{className:"flex flex-col items-center gap-1",children:[l.jsx(ud,{className:"w-4 h-4"}),l.jsx("span",{className:u.text.muted,children:"Chat"})]}),y&&l.jsxs("div",{className:"flex flex-col items-center gap-1",children:[l.jsx(hd,{className:"w-4 h-4"}),l.jsx("span",{className:u.text.muted,children:"Video"})]})]})]}),l.jsx(G1,{prompts:r,theme:c}),l.jsx(K1,{statusMessage:o,theme:c})]})};function md({room:e,onSessionEnd:t,onSessionStart:n,enableConsoleLogging:s=!0,enableLocalStorage:r=!0,voxketSessionId:o}={}){const[i,a]=p.useState(null),[c,d]=p.useState([]),[u,f]=p.useState(null),[h,y]=p.useState([]),x=p.useCallback((w,T)=>{const v={timestamp:new Date,event:w,data:T,sessionId:i==null?void 0:i.sessionId,participantId:u==null?void 0:u.identity};if(d(S=>[...S,v]),r){const S=JSON.parse(localStorage.getItem("voxket-session-logs")||"[]");S.push(v),localStorage.setItem("voxket-session-logs",JSON.stringify(S))}return v},[i==null?void 0:i.sessionId,u==null?void 0:u.identity,s,r]);p.useEffect(()=>{if(!e)return;const w=()=>{const g=o||`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,D=new Date,L={sessionId:g,startTime:D,totalMessages:0,connectionIssues:0,participantCount:h.length,events:[]};a(L),x("SESSION_STARTED",{sessionId:g,startTime:D}),n==null||n(g)},T=()=>{if(i){const g=new Date,D=g.getTime()-i.startTime.getTime(),L={...i,endTime:g,duration:D,events:c};x("SESSION_ENDED",{sessionId:i.sessionId,duration:`${Math.round(D/1e3)}s`,totalMessages:i.totalMessages,connectionIssues:i.connectionIssues}),t==null||t(L),a(null),d([])}},v=g=>{x("CONNECTION_STATE_CHANGED",{state:g}),g===H.ConnectionState.Reconnecting&&i&&(a(D=>D?{...D,connectionIssues:D.connectionIssues+1}:null),x("CONNECTION_ISSUE",{type:"reconnecting"}))},S=g=>{x("TRACK_PUBLISHED",{trackKind:g.kind,trackSource:g.source})},A=g=>{x("TRACK_UNPUBLISHED",{trackKind:g.kind,trackSource:g.source})},V=(g,D)=>{i&&a(L=>L?{...L,totalMessages:L.totalMessages+1}:null),x("DATA_RECEIVED",{participantId:D==null?void 0:D.identity,dataSize:g.length})},E=g=>{x("PARTICIPANT_CONNECTED",{participantId:g.identity,participantName:g.name}),y(D=>[...D,g]),i&&a(D=>D?{...D,participantCount:D.participantCount+1}:null)},O=g=>{x("PARTICIPANT_DISCONNECTED",{participantId:g.identity,participantName:g.name}),y(D=>D.filter(L=>L.identity!==g.identity))};return e.localParticipant&&f(e.localParticipant),e.on(H.RoomEvent.Connected,w),e.on(H.RoomEvent.Disconnected,T),e.on(H.RoomEvent.ConnectionStateChanged,v),e.on(H.RoomEvent.TrackPublished,S),e.on(H.RoomEvent.TrackUnpublished,A),e.on(H.RoomEvent.DataReceived,V),e.on(H.RoomEvent.ParticipantConnected,E),e.on(H.RoomEvent.ParticipantDisconnected,O),()=>{e.off(H.RoomEvent.Connected,w),e.off(H.RoomEvent.Disconnected,T),e.off(H.RoomEvent.ConnectionStateChanged,v),e.off(H.RoomEvent.TrackPublished,S),e.off(H.RoomEvent.TrackUnpublished,A),e.off(H.RoomEvent.DataReceived,V),e.off(H.RoomEvent.ParticipantConnected,E),e.off(H.RoomEvent.ParticipantDisconnected,O)}},[e,i,c,h.length,x,t,n]);const m=p.useCallback(()=>r?JSON.parse(localStorage.getItem("voxket-session-logs")||"[]"):c,[c,r]),b=p.useCallback(()=>{r&&localStorage.removeItem("voxket-session-logs"),d([])},[r]),k=p.useCallback(()=>{const w=m(),T=JSON.stringify(w,null,2),v="data:application/json;charset=utf-8,"+encodeURIComponent(T),S=`voxket-session-logs-${new Date().toISOString().split("T")[0]}.json`,A=document.createElement("a");A.setAttribute("href",v),A.setAttribute("download",S),A.click()},[m]);return{sessionMetrics:i,sessionLogs:c,logEvent:x,getSessionLogs:m,clearSessionLogs:b,exportSessionLogs:k}}class No{constructor(){Te(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 s=(...r)=>{this.off(t,s),n(...r)};return this.on(t,s)}off(t,n){const s=this.listeners[t];if(!s)return;const r=s.indexOf(n);r>-1&&s.splice(r,1)}removeAllListeners(t){t?delete this.listeners[t]:this.listeners={}}emit(t,...n){const s=this.listeners[t];if(!s)return;const r=[...s];for(const o of r)try{o(...n)}catch(i){console.error(`Error in event listener for ${String(t)}:`,i)}}listenerCount(t){var n;return((n=this.listeners[t])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class pd{constructor(t){Te(this,"plugins",new Map);Te(this,"installedPlugins",new Set);Te(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 s=this.plugins.get(t);if(!s)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t))throw new Error(`Plugin '${t}' is already installed`);if(s.dependencies)for(const o of s.dependencies)this.installedPlugins.has(o)||await this.install(o);const r={...this.context,config:{...s.config,...n}};s.install&&await s.install(r),this.installedPlugins.add(t),this.setupPluginEvents(s,r)}async uninstall(t){var s;const n=this.plugins.get(t);if(!n)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t)){for(const[r,o]of this.plugins)if(this.installedPlugins.has(r)&&((s=o.dependencies)!=null&&s.includes(t)))throw new Error(`Cannot uninstall '${t}' because '${r}' depends on it`);n.uninstall&&await n.uninstall(this.context),this.installedPlugins.delete(t)}}isInstalled(t){return this.installedPlugins.has(t)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(t){return this.plugins.get(t)}setupPluginEvents(t,n){t.onSessionStart&&n.on("session.started",s=>{t.onSessionStart(n,s.id)}),t.onSessionEnd&&n.on("session.ended",s=>{t.onSessionEnd(n,s.id)}),t.onAgentResponse&&n.on("agent.response",s=>{t.onAgentResponse(n,s)})}}function q1(e){return e}function Ro(e,t,n){return{name:e,version:"1.0.0",description:`${t} modality plugin`,install:async s=>{n.onActivate&&await n.onActivate(s)},uninstall:async s=>{n.onDeactivate&&await n.onDeactivate(s)},onAgentResponse:n.onMessage}}const X1={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)})}},J1={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,...s)=>(console.log(`[Debug] Event: ${String(n)}`,s),t(n,...s))}},Q1={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})})}},gd=C.createContext(null);function yd({config:e,children:t,autoConnect:n=!1}){const[s,r]=C.useState(null),[o,i]=C.useState(!1),[a,c]=C.useState(!1),[d,u]=C.useState(null),[f,h]=C.useState(null),[y,x]=C.useState("idle"),[m,b]=C.useState(null),[k,w]=C.useState([]),[T,v]=C.useState([]),[S,A]=C.useState([]);C.useEffect(()=>{const M=new Dn(e);return r(M),V(M),n&&E(M),()=>{M.disconnect().catch(console.error)}},[e,n]);const V=M=>{M.on("connection.connecting",()=>{c(!0),u(null)}),M.on("connection.connected",()=>{i(!0),c(!1),u(null)}),M.on("connection.disconnected",()=>{i(!1),c(!1),h(null),x("idle"),w([]),v([]),A([])}),M.on("connection.error",J=>{u(J),c(!1)}),M.on("session.created",J=>{h(J),x(J.state)}),M.on("session.state.changed",J=>{x(J),f&&h({...f,state:J})}),M.on("session.ended",(J,P)=>{h(null),x("idle"),b(P),w([]),v([]),A([])}),M.on("participant.joined",J=>{w(P=>[...P,J])}),M.on("participant.left",J=>{w(P=>P.filter(B=>B.id!==J.id))}),M.on("chat.message.received",J=>{v(P=>[...P,J])}),M.on("chat.message.sent",J=>{v(P=>[...P,J])}),M.on("transcription.received",J=>{A(P=>[...P,J])})},E=async M=>{const J=M||s;if(J)try{await J.connect()}catch(P){console.error("Failed to connect:",P)}},Y={client:s,isConnected:o,isConnecting:a,connectionError:d,currentSession:f,sessionState:y,sessionMetrics:m,participants:k,chatMessages:T,transcriptions:S,connect:()=>E(),disconnect:async()=>{if(s)try{await s.disconnect()}catch(M){console.error("Failed to disconnect:",M)}},createSession:async(M,J={})=>{if(!s)throw new Error("Client not initialized");const P={agentId:M,participantName:J.participantName||"User",metadata:J.metadata,modalities:J.modalities||["voice"]};return await s.createSession(P)},endSession:async()=>s?await s.endSession():null,sendChatMessage:async M=>{if(!s)throw new Error("Client not initialized");await s.sendChatMessage(M)},setMicrophoneEnabled:async M=>{if(!s)throw new Error("Client not initialized");await s.setMicrophoneEnabled(M)},setCameraEnabled:async M=>{if(!s)throw new Error("Client not initialized");await s.setCameraEnabled(M)},startScreenShare:async()=>{if(!s)throw new Error("Client not initialized");await s.startScreenShare()},stopScreenShare:async()=>{if(!s)throw new Error("Client not initialized");await s.stopScreenShare()}};return l.jsx(gd.Provider,{value:Y,children:t})}function st(){const e=C.useContext(gd);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}class ex extends No{constructor(n){super();Te(this,"room",null);Te(this,"registeredMethods",new Map);Te(this,"activeInteractions",new Map);Te(this,"currentInteraction",null);n&&this.setRoom(n)}setRoom(n){this.room=n}async registerFrontendRPC(n,s,r="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:s,presentationMode:r};this.registeredMethods.set(n,o);try{this.room.registerRpcMethod(n,async i=>{console.log(`RpcManager: RPC method '${n}' called by ${i.callerIdentity}`),console.log("RpcManager: Payload:",i.payload),this.emit("rpc.method.called",{methodName:n,data:i});let a;console.log(`RpcManager: Current registration for '${n}':`,o);let c=i.responseTimeout||30;try{a=JSON.parse(i.payload)}catch{a=i.payload}try{const d=await this.awaitUserInteraction(n,s,r,a,c);return JSON.stringify(d)}catch(d){throw console.error(`RpcManager: Error in RPC method '${n}':`,d),d}}),this.emit("rpc.method.registered",{methodName:n}),console.log(`RpcManager: Successfully registered RPC method: ${n}`)}catch(i){throw console.error(`RpcManager: Failed to register RPC method '${n}':`,i),i}}async awaitUserInteraction(n,s,r,o,i){return new Promise((a,c)=>{const d=`${n}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${n}, timeout: ${i} seconds`);const u={didSuccess:(h,y)=>{console.log(`RpcManager: User interaction successful for method: ${n}`,h),this.clearInteraction(d),this.currentInteraction=null;const x={success:!0,message:"User interaction completed successfully",data:h,timestamp:new Date,...y?{successView:y}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:x}),a(x)},didFail:h=>{console.log(`RpcManager: User interaction failed for method: ${n}`,h),this.clearInteraction(d);const y={success:!1,message:"User interaction failed",error:h,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:y}),a(y)},dismissView:()=>{var y;console.log(`RpcManager: User dismissed interaction for method: ${n}`),console.log("RpcManager: Current interaction before dismiss:",(y=this.currentInteraction)==null?void 0:y.methodName),this.clearInteraction(d),this.currentInteraction=null,console.log("RpcManager: Current interaction after dismiss:",this.currentInteraction);const h={success:!0,data:{dismissed:!0,reason:"User dismissed the interaction"},message:"User interaction dismissed",timestamp:new Date};this.emit("rpc.interaction.dismissed",{methodName:n,response:h}),this.emit("rpc.interaction.completed",{methodName:n,response:h}),setTimeout(()=>{var x;((x=this.currentInteraction)==null?void 0:x.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(h)},didTimeout:h=>{console.log(`RpcManager: User interaction timeout for method: ${n}`),this.clearInteraction(d),this.currentInteraction=null;const y={success:!0,message:`User interaction timed out after ${i} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...h?{timeoutView:h}:{}};this.emit("rpc.interaction.timeout",{methodName:n,response:y}),setTimeout(()=>{var x;((x=this.currentInteraction)==null?void 0:x.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(y)}},f=setTimeout(()=>{u.didTimeout&&u.didTimeout()},i);this.activeInteractions.set(d,{resolve:h=>a(JSON.parse(h)),reject:c,timeoutId:f}),this.currentInteraction={isVisible:!0,methodName:n,component:s,presentationMode:r,timeout:i,data:o,handler:u},this.emit("rpc.interaction.started",{methodName:n,presentationMode:r}),setTimeout(async()=>{var h;if((h=this.currentInteraction)!=null&&h.handler)try{console.log(`RpcManager: Component created for method: ${n} with data:`,o)}catch(y){console.error("RpcManager: Error loading data into component:",y),u.didFail({error:"Failed to load data into component"})}},100)})}clearInteraction(n){const s=this.activeInteractions.get(n);s&&(console.log(`RpcManager: Clearing interaction: ${n}`),clearTimeout(s.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,s]of this.activeInteractions)clearTimeout(s.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null,console.log("RpcManager: Cleared all registrations and interactions")}}class ge extends Error{constructor(t,n,s){super(t),this.code=n,this.details=s,this.name="VoxketError"}}class Dn extends No{constructor(n){super();Te(this,"config");Te(this,"room",null);Te(this,"pluginManager");Te(this,"rpcManager");Te(this,"isConnected",!1);Te(this,"currentSession",null);Te(this,"connectionState",H.ConnectionState.Disconnected);Te(this,"renderedComponents",new Map);Te(this,"textStreamHandlersRegistered",!1);Te(this,"currentAgentInfo",null);Te(this,"chatMessages",[]);Te(this,"isAgentConnected",!1);Te(this,"agentState","idle");this.config=n,this.pluginManager=new pd(this),this.rpcManager=new ex,this.setupEventListeners(),this.initializeClient()}setupEventListeners(){this.on("connection.connected",()=>{var n,s;this.isConnected=!0,(s=(n=this.config).onConnected)==null||s.call(n)}),this.on("connection.disconnected",n=>{var s,r;this.isConnected=!1,(r=(s=this.config).onDisconnected)==null||r.call(s,n)}),this.on("connection.error",n=>{var s,r;(r=(s=this.config).onError)==null||r.call(s,n)}),this.on("chat.message.received",n=>{var s,r;this.addChatMessage(n),(r=(s=this.config).onMessageReceived)==null||r.call(s,n)}),this.on("chat.message.updated",n=>{this.updateChatMessage(n)}),this.on("chat.message.sent",n=>{this.addChatMessage(n)}),this.on("transcription.received",n=>{var s,r;(r=(s=this.config).onTranscriptionReceived)==null||r.call(s,n)}),this.on("session.state.changed",n=>{var s,r;(r=(s=this.config).onSessionStateChanged)==null||r.call(s,n)}),this.on("session.created",n=>{var s,r;(r=(s=this.config).onSessionStart)==null||r.call(s,n.id)}),this.on("session.ended",(n,s)=>{var r,o;(o=(r=this.config).onSessionEnd)==null||o.call(r,s)}),this.on("participant.joined",n=>{var s,r;(r=(s=this.config).onUserJoined)==null||r.call(s,n.id)}),this.on("participant.left",n=>{var s,r;(r=(s=this.config).onUserLeft)==null||r.call(s,n.id)}),this.setupRpcEventForwarding()}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))}initializeClient(){this.room=new H.Room,this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(H.RoomEvent.Connected,()=>{var n,s;this.connectionState=H.ConnectionState.Connected,this.emit("connection.connected"),this.rpcManager.setRoom(this.room),(s=(n=this.currentSession)==null?void 0:n.activeModalities)!=null&&s.includes("voice")&&setTimeout(async()=>{var r;try{(r=this.room)!=null&&r.localParticipant&&(this.room.localParticipant.isMicrophoneEnabled?this.emit("track.unmuted",{source:"microphone",enabled:!0}):(await this.room.localParticipant.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0})))}catch(o){console.warn("VoxketClient: Failed to enable microphone after room connection:",o)}},1e3),this.textStreamHandlersRegistered||this.setupTextStreamHandlers()}),this.room.on(H.RoomEvent.Disconnected,n=>{var s;console.log("🔴 VoxketClient: Room disconnected, reason:",n),this.connectionState=H.ConnectionState.Disconnected,this.textStreamHandlersRegistered=!1,this.isAgentConnected=!1,console.log("🤖 VoxketClient: Agent marked as disconnected"),n&&console.log("🔍 VoxketClient: Disconnect reason details:",{reason:n.toString(),currentSession:(s=this.currentSession)==null?void 0:s.id,agentConnected:this.isAgentConnected,connectionState:this.connectionState}),this.emit("connection.disconnected",n==null?void 0:n.toString())}),this.room.on(H.RoomEvent.ConnectionStateChanged,n=>{this.connectionState=n,n===H.ConnectionState.Connecting&&this.emit("connection.connecting")}),this.room.on(H.RoomEvent.ParticipantConnected,n=>{const s={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.joined",s)}),this.room.on(H.RoomEvent.ParticipantDisconnected,n=>{const s={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.left",s)}))}setupTextStreamHandlers(){if(!this.room)return;try{this.room.registerTextStreamHandler("lk.chat",async(s,r)=>{try{const o=await s.readAll(),i={id:`msg_${Date.now()}_${r.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:o,timestamp:new Date,sender:{id:r.identity||"user",name:r.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.emit("chat.message.received",i)}catch(o){console.error("VoxketClient: Failed to process lk.chat message:",o)}})}catch(s){console.warn("VoxketClient: lk.chat handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("lk.transcription",async(s,r)=>{var o,i;try{const a=`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`;let c="";const d=((o=this.currentAgentInfo)==null?void 0:o.name)||r.identity||"AI Assistant",u={id:a,content:"",timestamp:new Date,sender:{id:r.identity||"agent",name:d,type:"agent"},metadata:{topic:"lk.transcription",streaming:!0}};this.emit("chat.message.received",u);for await(const y of s){c+=y;const x=this.convertMarkdownToText(c),m={...u,content:x,metadata:{...u.metadata,streaming:!0}};this.emit("chat.message.updated",m)}const f=this.convertMarkdownToText(c),h={...u,content:f,metadata:{...u.metadata,streaming:!1}};this.emit("chat.message.updated",h)}catch(a){console.error("VoxketClient: Failed to process lk.transcription message:",a);try{const c=await s.readAll(),d=((i=this.currentAgentInfo)==null?void 0:i.name)||r.identity||"AI Assistant",u={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:c,timestamp:new Date,sender:{id:r.identity||"agent",name:d,type:"agent"},metadata:{topic:"lk.transcription"}};this.emit("chat.message.received",u)}catch(c){console.error("VoxketClient: Fallback failed for lk.transcription:",c)}}})}catch(s){console.warn("VoxketClient: lk.transcription handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("suggested_response",async s=>{const r=await s.readAll();let o=[];try{o=["tes","hello how are you","algebra make me learn that ","what is the meaning of life"]}catch(i){console.warn("VoxketClient: Failed to parse suggested_response:",i,r)}this.emit("suggested.response",o)})}catch(s){console.warn("VoxketClient: suggested_response handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("agent_state_changed",async(s,r)=>{const o=await s.readAll();console.log("🤖 VoxketClient: agent_state_changed stream received:",o);let i={};try{i=typeof o=="string"?JSON.parse(o.replace(/'/g,'"')):o}catch(a){console.warn("VoxketClient: Failed to parse agent_state_changed:",a,o)}this.isAgentConnected||(this.isAgentConnected=!0,console.log("🤖 VoxketClient: Agent marked as connected (first state change received)"),this.emit("agent.connected",i)),i.new_state==="speaking"?(this.setAgentState("speaking"),this.emit("agent.speaking",i)):i.new_state==="thinking"?(this.setAgentState("thinking"),this.emit("agent.thinking",i)):(i.new_state==="idle"||i.new_state==="listening")&&this.setAgentState("idle")})}catch(s){console.warn("VoxketClient: conversation_item_added handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("images",async(s,r)=>{try{const o=await s.readAll()}catch(o){console.error("VoxketClient: Error processing images stream:",o)}})}catch(s){console.warn("VoxketClient: images handler already registered, skipping:",s)}try{this.room.registerByteStreamHandler("images",async(s,r)=>{var o,i;try{const a=s.info,c={id:`img_${Date.now()}_${r.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`�️ ${a.name||"Image"}`,sender:{id:r.identity||"agent",name:r.identity||"Agent",type:r.identity===((i=(o=this.room)==null?void 0:o.localParticipant)==null?void 0:i.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:a.name,fileSize:a.size,mimeType:a.mimeType,streamId:a.id,downloading:!0}};this.emit("chat.message.received",c),s.onProgress&&(s.onProgress=y=>{const x={...c,metadata:{...c.metadata,downloadProgress:y||0}};this.emit("chat.message.updated",x)});const d=[];for await(const y of s)d.push(y);const u=new Blob(d,{type:a.mimeType||"application/octet-stream"}),f=URL.createObjectURL(u),h={...c,metadata:{...c.metadata,downloading:!1,downloadProgress:1,downloadUrl:f,blob:u}};this.emit("chat.message.updated",h)}catch(a){console.error("VoxketClient: Error processing image attachment:",a)}})}catch(s){console.warn("VoxketClient: image handler already registered, skipping:",s)}["error","warning","status","system","debug","info"].forEach(s=>{try{this.room.registerTextStreamHandler(s,async(r,o)=>{try{const i=await r.readAll();if(console.log(`📝 VoxketClient: Received '${s}' stream:`,i),s==="error"){let a={};try{a=typeof i=="string"?JSON.parse(i):i}catch{a={message:i}}console.warn("� VoxketClient: Agent error:",a),this.emit("agent.error",a)}else this.emit("text.stream.received",{topic:s,data:i,participantInfo:o})}catch(i){console.error(`VoxketClient: Failed to process '${s}' stream:`,i)}})}catch(r){console.warn(`VoxketClient: Handler for '${s}' already registered, skipping:`,r)}});try{this.room.registerTextStreamHandler("*",async(s,r)=>{var o;try{const i=await s.readAll(),a=((o=s.info)==null?void 0:o.topic)||"unknown";console.log(`📝 VoxketClient: Received unhandled text stream for topic '${a}':`,i),this.emit("text.stream.unhandled",{topic:a,data:i,participantInfo:r})}catch(i){console.error("VoxketClient: Failed to process unhandled text stream:",i)}})}catch(s){console.warn("VoxketClient: Generic text stream handler already registered, skipping:",s)}this.textStreamHandlersRegistered=!0}async fetchConnectionDetails(n,s,r){const o=n||this.config.agentId||"default-agent",i=s||this.config.participantName||"User",a=r||this.config.modalities||["voice"];try{const c={agent_id:o,participant_name:i,participant_metadata:{user_id:""},modality:a[0],modalities:a};console.log("🔗 VoxketClient: Creating session with modalities:",a);const d=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(c)});if(!d.ok){let h=`HTTP ${d.status}: Failed to fetch connection details`;try{const y=await d.json();y&&(y.error?h=`API Error: ${y.error}`:y.detail?h=`API Error: ${y.detail}`:y.message&&(h=`API Error: ${y.message}`))}catch{try{const x=await d.text();x&&(h=`API Error: ${x}`)}catch{}}throw new Error(h)}const u=await d.json();let f;return u.agent_info&&(f={id:u.agent_info.id||o,name:u.agent_info.name||"AI Assistant",avatar:u.agent_info.avatar,capabilities:u.agent_info.capabilities||["voice_interaction","text_chat"],metadata:u.agent_info.metadata||{}},this.currentAgentInfo=f),{serverUrl:u.wss_url,participantToken:u.token,voxketSessionId:u.session_id,agentInfo:f}}catch(c){console.error("VoxketClient: fetchConnectionDetails failed:",c);const d=new ge(`Failed to fetch connection details: ${c instanceof Error?c.message:"Unknown error"}`,"CONNECTION_FAILED",c);throw this.emit("connection.error",d),d}}async connect(n,s,r){var o;try{this.emit("connection.connecting");const i=await this.fetchConnectionDetails(n,s,r);return await((o=this.room)==null?void 0:o.connect(i.serverUrl,i.participantToken)),this.isConnected=!0,i}catch(i){console.error("VoxketClient: Connection failed:",i);const a=new ge(`Failed to connect to Voxket services: ${i instanceof Error?i.message:"Unknown error"}`,"CONNECTION_FAILED",i);throw this.emit("connection.error",a),a}}async disconnect(){var n;try{await((n=this.room)==null?void 0:n.disconnect()),this.isConnected=!1,this.currentSession=null,this.currentAgentInfo=null,this.textStreamHandlersRegistered=!1,this.clearChatMessages(),this.room=new H.Room,this.setupRoomEventListeners()}catch(s){const r=new ge("Failed to disconnect properly","NETWORK_ERROR",s);throw this.emit("connection.error",r),r}}async createSession(n){var s,r,o,i;try{const a=await this.connect(n.agentId,n.participantName,n.modalities),c={id:a.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:a.agentInfo||this.currentAgentInfo};if(this.currentSession=c,this.emit("session.created",c),(s=n.modalities)!=null&&s.includes("voice"))try{await new Promise(d=>setTimeout(d,500)),(r=this.room)!=null&&r.localParticipant?(await this.room.localParticipant.setMicrophoneEnabled(!0,void 0,{preConnectBuffer:!0}),this.emit("track.unmuted",{source:"microphone",enabled:!0})):console.warn("VoxketClient: No local participant found, microphone not enabled")}catch(d){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",d)}if((o=n.modalities)!=null&&o.includes("video"))try{await new Promise(d=>setTimeout(d,200)),(i=this.room)!=null&&i.localParticipant&&(console.log("🎥 VoxketClient: Attempting to enable camera for video session"),await this.room.localParticipant.setCameraEnabled(!0),this.emit("track.unmuted",{source:"camera",enabled:!0}),console.log("🎥 VoxketClient: Camera enabled successfully"))}catch(d){console.warn("VoxketClient: Failed to enable camera, but continuing with session:",d)}return setTimeout(()=>{var d;this.currentSession&&(this.currentSession.state="active",this.emit("session.state.changed","active",this.currentSession.state),this.forceAgentConnected(),console.log("🤖 VoxketClient: Session marked as active:",{sessionId:this.currentSession.id,modalities:this.currentSession.activeModalities,agentConnected:this.isAgentConnected,hasRoom:!!this.room,remoteParticipants:((d=this.room)==null?void 0:d.remoteParticipants.size)||0}))},1e3),c}catch(a){throw console.error("VoxketClient: Failed to create session:",a),a instanceof ge?a:a instanceof TypeError&&a.message.includes("fetch")?new ge("Network connection failed","CONNECTION_FAILED",a):a instanceof Error&&a.message.includes("Failed to fetch connection details")?new ge(`API connection failed: ${a.message}`,"CONNECTION_FAILED",a):new ge(`Failed to create session: ${a instanceof Error?a.message:"Unknown error"}`,"SESSION_NOT_FOUND",a)}}async startSession(n,s){const r={agentId:n||this.config.agentId||"default-agent",participantName:(s==null?void 0:s.participantName)||this.config.participantName||"User",modalities:(s==null?void 0:s.modalities)||this.config.modalities||["voice","chat"],metadata:s==null?void 0:s.metadata};return this.createSession(r)}async endSession(){var n,s;if(!this.currentSession)return null;try{const r={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((s=this.room)==null?void 0:s.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]};return this.currentSession.endedAt=new Date,this.currentSession.state="disconnected",this.emit("session.ended",this.currentSession,r),await this.disconnect(),r}catch(r){throw new ge("Failed to end session","SESSION_NOT_FOUND",r)}}getCurrentSession(){return this.currentSession}getCurrentAgentInfo(){return this.currentAgentInfo}getIsAgentConnected(){return this.isAgentConnected}forceAgentConnected(){this.isAgentConnected||(this.isAgentConnected=!0,console.log("🤖 VoxketClient: Agent manually marked as connected"),this.emit("agent.connected",{forced:!0}))}getAgentState(){return this.agentState}setAgentState(n){this.agentState!==n&&(this.agentState=n,this.emit("agent.state.changed",{state:n}))}getAgentAudioTrack(){const n=this.getRemoteParticipants();for(const s of n){const r=s.getTrackPublication(H.Track.Source.Microphone);if(r!=null&&r.track)return{source:H.Track.Source.Microphone,participant:s,publication:r}}return null}getAgentVideoTrack(){const n=this.getRemoteParticipants();for(const s of n){const r=s.getTrackPublication(H.Track.Source.Camera);if(r!=null&&r.track)return{source:H.Track.Source.Camera,participant:s,publication:r}}return null}getVideoTrackRefs(){const n=[],s=this.getLocalParticipant();if(s){const o=s.getTrackPublication(H.Track.Source.Camera);o!=null&&o.track&&n.push({source:H.Track.Source.Camera,participant:s,publication:o});const i=s.getTrackPublication(H.Track.Source.ScreenShare);i!=null&&i.track&&n.push({source:H.Track.Source.ScreenShare,participant:s,publication:i})}const r=this.getRemoteParticipants();for(const o of r){const i=o.getTrackPublication(H.Track.Source.Camera);i!=null&&i.track&&n.push({source:H.Track.Source.Camera,participant:o,publication:i});const a=o.getTrackPublication(H.Track.Source.ScreenShare);a!=null&&a.track&&n.push({source:H.Track.Source.ScreenShare,participant:o,publication:a})}return n}getCameraTrackRefs(){return this.getVideoTrackRefs().filter(n=>n.source===H.Track.Source.Camera)}getScreenShareTrackRefs(){return this.getVideoTrackRefs().filter(n=>n.source===H.Track.Source.ScreenShare)}getChatMessages(){return[...this.chatMessages]}addChatMessage(n){this.chatMessages.some(r=>r.id===n.id)||this.chatMessages.push(n)}updateChatMessage(n){const s=this.chatMessages.findIndex(r=>r.id===n.id);s!==-1&&(this.chatMessages[s]=n)}clearChatMessages(){this.chatMessages=[],this.dismissCurrentInteraction(),this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays(),this.emit("chat.history.cleared")}renderUI(n={}){var c,d,u;const s=this.resolveTarget(n.target||"body"),r=this.getTargetKey(s),o=this.renderedComponents.get(r);o&&o.target===s||this.removeUI(s);const i=(o==null?void 0:o.root)||_d.createRoot(s),a={agentId:n.agentId||this.config.agentId||"default-agent",participantName:n.participantName||this.config.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:n.className,theme:typeof n.theme=="string"?n.theme:void 0,modalities:n.modality||this.config.modalities||["voice"],suportsChatInput:((c=n.modality)==null?void 0:c.includes("chat"))!==!1,suportsVideoInput:((d=n.modality)==null?void 0:d.includes("video"))===!0,suportsScreenShare:((u=n.modality)==null?void 0:u.includes("screen_share"))===!0,autoStart:n.autoStart,displayType:n.displayType||"widget",popupPosition:n.popupPosition||"bottom-right",popupTriggerText:n.popupTriggerText||"Open Chat",width:n.width,height:n.height,onDisplayTypeChange:n.onDisplayTypeChange,prompts:n.prompts,statusMessage:n.statusMessage,welcomeTitle:n.welcomeTitle,welcomeSubTitle:n.welcomeSubTitle,loadingText:n.loadingText,voxketClient:this};if(!i||typeof i.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{i.render(C.createElement(yd,{config:this.config,autoConnect:n.autoStart||!1,children:C.createElement(xd,a)}))}catch(f){throw console.error("Error rendering Voxket widget:",f),new Error(`Failed to render Voxket widget: ${f instanceof Error?f.message:"Unknown error"}`)}this.renderedComponents.set(r,{root:i,target:s})}removeUI(n){const s=n?this.resolveTarget(n):null;if(s){const r=this.getTargetKey(s),o=this.renderedComponents.get(r);o&&(o.root.unmount(),this.renderedComponents.delete(r),s.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(a=>{try{a.remove()}catch(c){console.warn("Failed to remove element:",c)}}),s===document.body&&s.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(c=>{if(c.classList.contains("bg-black")&&c.classList.contains("backdrop-blur-sm"))try{c.remove()}catch(d){console.warn("Failed to remove fixed element:",d)}}))}}removeAllUI(){for(const[n,s]of this.renderedComponents)s.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(s=>{if(s.classList.contains("bg-black")&&(s.classList.contains("backdrop-blur-sm")||s.classList.contains("bg-opacity-30")))try{s.remove()}catch(r){console.warn("Failed to remove overlay:",r)}})}resolveTarget(n){if(typeof n=="string"){const s=document.querySelector(n);if(!s)throw new Error(`Target element not found: ${n}`);return s}return n}getTargetKey(n){return n.id?n.id:n.className?n.tagName+"_"+n.className.replace(/\s+/g,"_"):n.tagName+"_"+n.outerHTML.length%1e3}async sendMessage(n,s){var r;if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new ge("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new ge("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new ge("No local participant","CONNECTION_FAILED");this.dismissCurrentInteraction();try{const o={id:`msg_${Date.now()}`,content:n,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:s||{}},i=await((r=this.room)==null?void 0:r.localParticipant.sendText(n,{topic:"lk.chat",destinationIdentities:[]}));this.emit("chat.message.sent",o)}catch(o){throw console.error("VoxketClient: Failed to send chat message:",o),new ge("Failed to send message","NETWORK_ERROR",o)}}async sendChatMessage(n,s){return this.sendMessage(n,s)}async sendAttachments(n,s){if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new ge("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new ge("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new ge("No local participant","CONNECTION_FAILED");if(!n||n.length===0)throw new ge("No files provided","INVALID_PARAMETER");this.dismissCurrentInteraction();const r=n.filter(o=>o.type.startsWith("image/"));if(r.length===0)throw new ge("Only image files are allowed","INVALID_PARAMETER");r.length!==n.length&&console.warn("VoxketClient: Some non-image files were filtered out");try{const o=r.map(async(i,a)=>{const d={id:`att_${Date.now()}_${a}`,content:`📎 ${i.name}`,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:{...s,type:"attachment",fileName:i.name,fileSize:i.size,mimeType:i.type,uploading:!0}};this.emit("chat.message.sent",d);const u=await this.room.localParticipant.sendFile(i,{mimeType:i.type,topic:"images",onProgress:h=>{const y={...d,metadata:{...d.metadata,uploadProgress:h}};this.emit("chat.message.updated",y)}});try{const h=new FileReader,y=new Promise((b,k)=>{h.onload=()=>{typeof h.result=="string"?b(h.result):k(new Error("Failed to convert to base64"))},h.onerror=k});h.readAsDataURL(i);const m={type:"image",data:await y,filename:i.name,mimeType:i.type,size:i.size};await this.room.localParticipant.sendText(JSON.stringify(m),{topic:"images",destinationIdentities:[]})}catch(h){console.warn("VoxketClient: Failed to send image data to agent:",h);try{const y=`I've shared an image: ${i.name}`;await this.room.localParticipant.sendText(y,{topic:"lk.chat",destinationIdentities:[]})}catch(y){console.warn("VoxketClient: Failed to send image notification to agent:",y)}}const f={...d,metadata:{...d.metadata,uploading:!1,uploadProgress:1,streamId:u.id}};return this.emit("chat.message.updated",f),u});await Promise.all(o)}catch(o){throw console.error("VoxketClient: Failed to send attachments:",o),new ge("Failed to send attachments","NETWORK_ERROR",o)}}async sendAttachment(n,s){return this.sendAttachments([n],s)}toggleMicrophone(n){return this.setMicrophoneEnabled(n!==!1)}async setMicrophoneEnabled(n){var s,r;try{const o=(s=this.room)==null?void 0:s.localParticipant.isMicrophoneEnabled,i=n??!o;await((r=this.room)==null?void 0:r.localParticipant.setMicrophoneEnabled(i)),i?this.emit("track.unmuted",{source:"microphone",enabled:!0}):this.emit("track.muted",{source:"microphone",enabled:!1})}catch(o){throw console.error("VoxketClient: Failed to toggle microphone:",o),new ge("Failed to toggle microphone","PERMISSION_DENIED",o)}}toggleCamera(n){return this.setCameraEnabled(n!==!1)}async setCameraEnabled(n){var s,r;try{const o=(s=this.room)==null?void 0:s.localParticipant.isCameraEnabled,i=n??!o;await((r=this.room)==null?void 0:r.localParticipant.setCameraEnabled(i)),i?this.emit("track.unmuted",{source:"camera",enabled:!0}):this.emit("track.muted",{source:"camera",enabled:!1})}catch(o){throw console.error("VoxketClient: Failed to toggle camera:",o),new ge("Failed to toggle camera","PERMISSION_DENIED",o)}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!0))}catch(s){throw new ge("Failed to start screen share","PERMISSION_DENIED",s)}}async stopScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!1))}catch(s){throw new ge("Failed to stop screen share","PERMISSION_DENIED",s)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(s=>s.kind==="audioinput")}catch(n){throw new ge("Failed to get audio input devices","DEVICE_ERROR",n)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(s=>s.kind==="videoinput")}catch(n){throw new ge("Failed to get video input devices","DEVICE_ERROR",n)}}async setAudioInputDevice(n){var s;try{if(!((s=this.room)!=null&&s.localParticipant))throw new Error("Not connected to room")}catch(r){throw new ge("Failed to set audio input device","DEVICE_ERROR",r)}}async setVideoInputDevice(n){var s;try{if(!((s=this.room)!=null&&s.localParticipant))throw new Error("Not connected to room")}catch(r){throw new ge("Failed to set video input device","DEVICE_ERROR",r)}}getLocalParticipant(){var n;return((n=this.room)==null?void 0:n.localParticipant)??null}getRemoteParticipants(){var n;return Array.from(((n=this.room)==null?void 0:n.remoteParticipants.values())??[])}getPublishPermissions(){const n=this.getLocalParticipant();if(!n)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const s=n.permissions;if(!s)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const r=o=>!!s.canPublish&&(s.canPublishSources.length===0||s.canPublishSources.includes(o));return{camera:r(1),microphone:r(2),screenShare:r(3),data:s.canPublishData??!1}}canPublishSource(n){return this.getPublishPermissions()[n]}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===H.ConnectionState.Connected}getMicrophoneTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,s]of n.trackPublications)if(s.source===H.Track.Source.Microphone)return s.track;return null}getCameraTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,s]of n.trackPublications)if(s.source===H.Track.Source.Camera)return s.track;return null}getScreenShareTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,s]of n.trackPublications)if(s.source===H.Track.Source.ScreenShare)return s.track;return null}get isMicrophoneEnabled(){const n=this.getMicrophoneTrack();return n?!n.isMuted:!1}get isCameraEnabled(){const n=this.getCameraTrack();return n?!n.isMuted:!1}get isScreenShareEnabled(){const n=this.getScreenShareTrack();return n?!n.isMuted:!1}registerPlugin(n){this.pluginManager.register(n)}getPluginManager(){return this.pluginManager}getParticipants(){if(!this.room)return[];const n=[];return this.room.localParticipant&&n.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(s=>{n.push({id:s.identity,name:s.name||s.identity,isLocal:!1})}),n}getSessionMetrics(){var n,s;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((s=this.room)==null?void 0:s.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}updateConfig(n){this.config={...this.config,...n}}async startRecording(){var n;try{this.emit("recording.started",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(s){throw new ge("Failed to start recording","RECORDING_ERROR",s)}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(s){throw new ge("Failed to stop recording","RECORDING_ERROR",s)}}async registerFrontendRPC(n,s,r="embedded"){return this.rpcManager.registerFrontendRPC(n,s,r)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}registerEventListener(n,s){return this.on(n,s)}registerEventEmitter(n,s){if(!this.room)throw new Error("Room not available");try{this.room.registerTextStreamHandler(n,async r=>{try{const o=await r.readAll();s(o)}catch(o){console.error(`Error processing event for topic '${n}':`,o)}})}catch(r){console.warn(`VoxketClient: Handler for topic '${n}' may already be registered:`,r)}}convertMarkdownToText(n){if(!n)return"";let s=n;return s=s.replace(/\*\*(.*?)\*\*/g,"$1"),s=s.replace(/__(.*?)__/g,"$1"),s=s.replace(/\*(.*?)\*/g,"$1"),s=s.replace(/_(.*?)_/g,"$1"),s=s.replace(/~~(.*?)~~/g,"$1"),s=s.replace(/`([^`]+)`/g,"$1"),s=s.replace(/```[\s\S]*?```/g,""),s=s.replace(/^#{1,6}\s+/gm,""),s=s.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),s.trim()}}const tx=le.create(R1),nx=le.create(z1),sx=le.create(Z1),rx=le.create(Y1);function ox({onClick:e,text:t="Open Chat",position:n="bottom-right",theme:s}){const r={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},o=De(s);return l.jsx(le.button,{onClick:e,className:`voxket-popup-trigger fixed ${r[n]} z-50 px-4 py-2 rounded-full shadow-lg ${o.popupTrigger} transition-all duration-200 hover:scale-105`,initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},exit:{scale:0,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},"data-position":n,children:t})}function Ga({children:e,theme:t,displayType:n="widget",onClose:s,popupPosition:r="bottom-right",onExpand:o}){const i=De(t);if(n==="fullscreen")return l.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&&s&&s()},children:l.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:[s&&l.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),s()},className:"absolute top-4 cursor-pointer right-4 z-[10000] w-12 h-12 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 shadow-lg border border-gray-700 backdrop-blur-sm",title:"Exit Fullscreen",type:"button",children:l.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:l.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"})})}),l.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${i.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"},children:[l.jsx("div",{className:i.cardTopGradient}),l.jsx("div",{className:i.cardPurpleBlur}),l.jsx("div",{className:i.cardPinkBlur}),l.jsx("div",{className:"relative z-10 flex flex-col h-full",children:e}),l.jsx("div",{className:i.cardPulse1}),l.jsx("div",{className:i.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 l.jsx("div",{className:"fixed rounded-2xl inset-0 z-[9999] pointer-events-none",children:l.jsxs("div",{className:`fixed rounded-2xl ${a[r]} pointer-events-auto`,children:[s&&l.jsx("button",{onClick:s,className:"absolute -top-2 -right-2 z-10 w-8 h-8 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 text-sm shadow-lg border border-gray-700",children:"×"}),l.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${i.card} rounded-2xl flex flex-col relative overflow-hidden`,"data-theme":t,style:{width:"350px",height:"500px",contain:"layout style paint",overscrollBehavior:"contain"},children:[l.jsx("div",{className:i.cardTopGradient}),l.jsx("div",{className:i.cardPurpleBlur}),l.jsx("div",{className:i.cardPinkBlur}),l.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),l.jsx("div",{className:i.cardPulse1}),l.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return l.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${i.card} relative overflow-hidden`,"data-theme":t,style:{height:"100%",maxHeight:"100%",contain:"layout style paint",overscrollBehavior:"contain"},children:[l.jsx("div",{className:i.cardTopGradient}),l.jsx("div",{className:i.cardPurpleBlur}),l.jsx("div",{className:i.cardPinkBlur}),l.jsx("div",{className:"relative z-10 flex flex-col h-full",children:e}),l.jsx("div",{className:i.cardPulse1}),l.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})}function xd(e){if(typeof window>"u")return null;console.log("🎯 Widget component rendering with props:",{displayType:e.displayType,popupPosition:e.popupPosition,theme:e.theme});const{agentId:t,participantName:n,baseUrl:s,appSecret:r,appId:o,prompts:i,statusMessage:a,welcomeTitle:c,welcomeSubTitle:d,className:u,width:f,height:h,loadingText:y,suportsChatInput:x=!0,suportsVideoInput:m=!0,suportsScreenShare:b=!0,theme:k="vox",onSessionStart:w,onSessionEnd:T,enableSessionLogging:v=!0,onSessionLogsUpdate:S,onSessionMetricsUpdate:A,modalities:V=["voice"],displayType:E="widget",popupPosition:O="bottom-right",popupTriggerText:g="Open Chat",onPopupToggle:D,voxketClient:L,onDisplayTypeChange:Q}=e,[ee,ne]=p.useState(()=>L?!!L.getCurrentSession():!1),[re,Y]=p.useState(!1),[M,J]=p.useState(t||""),[P,B]=p.useState(n||"User"),[K,U]=p.useState(()=>L?L.getCurrentSession():null),[j,$]=p.useState(()=>{var de,Qe,ot;if(L){const ke=L.getCurrentSession();if((de=ke==null?void 0:ke.activeModalities)!=null&&de.includes("chat"))return"chat";if((Qe=ke==null?void 0:ke.activeModalities)!=null&&Qe.includes("voice"))return"voice";if((ot=ke==null?void 0:ke.activeModalities)!=null&&ot.includes("video"))return"video"}return"welcome"}),[W,z]=p.useState(!1);p.useEffect(()=>{console.log("🎯 Widget displayType prop changed to:",E)},[E]),p.useEffect(()=>{console.log("📊 Session state changed:",{currentMode:j,sessionStarted:ee,loading:re,currentSession:K==null?void 0:K.id,isPopupOpen:W})},[j,ee,re,K,W]);const _=p.useMemo(()=>{if(L)return console.log("🔄 Using passed VoxketClient to preserve session state"),L;console.log("🆕 Creating new VoxketClient instance");const de={appId:o,appSecret:r,baseUrl:s,agentId:M,participantName:P||"User",modalities:V};return new Dn(de)},[L,o,r,s,M,P,V]),I=V,F=p.useMemo(()=>_.getRoom()||new H.Room,[_]),oe={suportsChatInput:x,suportsVideoInput:m,suportsScreenShare:b};p.useEffect(()=>{(j==="voice"||j==="video"||j==="chat")&&!K&&!ee&&!re&&!_.connected&&(console.log("🔄 Auto-correcting: Found orphaned mode without session, returning to welcome"),$("welcome"))},[j,K,ee,re,_]);const{sessionMetrics:R,sessionLogs:X,logEvent:se}=md({room:F,onSessionStart:w,onSessionEnd:T,enableConsoleLogging:v,enableLocalStorage:v,voxketSessionId:K==null?void 0:K.id});p.useEffect(()=>{S&&S(X)},[X,S]),p.useEffect(()=>{A&&R&&A(R)},[R,A]),p.useEffect(()=>{const de=ot=>{console.log("🔴 Widget: Room disconnected:",ot),console.log("🔍 Widget: Current state on disconnect:",{currentMode:j,sessionStarted:ee,currentSessionId:K==null?void 0:K.id}),Y(!1),ne(!1),U(null),j!=="welcome"?(console.log("🔄 Widget: Setting mode to welcome after disconnect"),$("welcome")):console.log("📝 Widget: Already in welcome mode, no change needed")},Qe=ot=>{console.log("📹 Media devices error:",ot)};return F.on(H.RoomEvent.MediaDevicesError,Qe),F.on(H.RoomEvent.Disconnected,de),()=>{F.off(H.RoomEvent.Disconnected,de),F.off(H.RoomEvent.MediaDevicesError,Qe)}},[F]);const ie=async()=>{try{console.log("🎤 Starting voice session...",{agentId:M,participantName:P}),console.log("🎤 Pre-start state:",{currentMode:j,sessionStarted:ee,loading:re}),Y(!0),se("USER_STARTED_VOICE_SESSION",{agentId:M,participantName:P});const de=await _.startSession(M,{participantName:P||"User",modalities:["voice",...m?["video"]:[]]});console.log("✅ Voice session started successfully:",de.id),U(de),ne(!0),$("voice"),Y(!1),w&&w(de.id)}catch(de){console.error("❌ Failed to start voice session:",de),Y(!1),ne(!1),$("welcome")}},ae=async()=>{try{Y(!0),ne(!0),$("chat"),se("USER_STARTED_CHAT_SESSION",{agentId:M,participantName:P});const de=await _.startSession(M,{participantName:P||"User",modalities:["chat"]});U(de),Y(!1),w&&w(de.id)}catch(de){console.error("Failed to start chat session:",de),Y(!1),ne(!1),$("welcome")}},$e=async()=>{try{console.log("📺 Starting video session...",{agentId:M,participantName:P}),console.log("📺 Pre-start state:",{currentMode:j,sessionStarted:ee,loading:re}),Y(!0),se("USER_STARTED_VIDEO_SESSION",{agentId:M,participantName:P});const de=await _.startSession(M,{participantName:P||"User",modalities:["video","voice"]});console.log("✅ Video session started successfully:",de.id),U(de),ne(!0),$("video"),Y(!1),w&&w(de.id)}catch(de){console.error("❌ Failed to start video session:",de),Y(!1),ne(!1),$("welcome")}},Re=()=>{console.log("🔄 Widget: handleBackToWelcome called",{currentMode:j,sessionStarted:ee,currentSessionId:K==null?void 0:K.id,displayType:E}),$("welcome"),Q&&Q(e.displayType||"widget"),K&&ee?(console.log("🧹 Widget: Cleaning up active session"),ne(!1),U(null),_.connected?(console.log("🔌 Widget: Disconnecting client"),_.disconnect()):console.log("🔌 Widget: Client already disconnected")):console.log("📝 Widget: No active session to clean up"),E==="popup"&&!W&&z(!0),console.log("✅ Widget: handleBackToWelcome completed")},we=()=>{const de=!W;z(de),D&&D(de),!de&&!(K&&ee)&&($("welcome"),ne(!1),U(null))},Be=()=>{console.log("🔄 Closing fullscreen, switching to widget display type"),e.onDisplayTypeChange?e.onDisplayTypeChange("widget"):console.warn("⚠️ No onDisplayTypeChange callback provided")},rt=()=>{if(console.log("🔄 Expand to fullscreen requested"),e.onDisplayTypeChange)e.onDisplayTypeChange("fullscreen");else{console.warn("⚠️ No onDisplayTypeChange callback provided for expand functionality");const de=document.getElementById("voice-card")||document.querySelector(".voxket-widget-container");de&&de.requestFullscreen&&de.requestFullscreen().catch(Qe=>{console.warn("⚠️ Fullscreen API not supported or failed:",Qe)})}};p.useEffect(()=>{var de,Qe,ot;if(L&&_){console.log("🔄 Syncing widget state with existing client session state");const ke=_.getCurrentSession(),Id=_.connected;console.log("🔍 Existing session state:",{hasSession:!!ke,sessionId:ke==null?void 0:ke.id,isConnected:Id,activeModalities:ke==null?void 0:ke.activeModalities}),ke&&(console.log("✅ Restoring session state from existing client"),U(ke),ne(!0),Y(!1),(de=ke.activeModalities)!=null&&de.includes("chat")?$("chat"):(Qe=ke.activeModalities)!=null&&Qe.includes("voice")?$("voice"):(ot=ke.activeModalities)!=null&&ot.includes("video")&&$("video"))}},[L,_]),p.useEffect(()=>()=>{console.log("🧹 Cleaning up widget component"),L?console.log("🔄 Widget cleanup: preserving passed client instance"):(console.log("🧹 Widget cleanup: disconnecting self-created client"),_.disconnect())},[_,L]);let Dt="w-96",js="h-[25rem]",Ms={};if(f&&(f.startsWith("w-")?Dt=f:(Ms.width=f,Dt="")),h&&(h.startsWith("h-")?js=h:(Ms.height=h,js="")),E==="popup"&&!W)return console.log("🟡 Showing popup trigger button"),l.jsx(ox,{onClick:we,text:g,position:O,theme:k});console.log("🟢 Rendering widget content, displayType:",E,"isPopupOpen:",W,"currentMode:",j,"sessionStarted:",ee,"loading:",re);let Ps=`voxket-widget-root theme-${k}`,Fn={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};E==="widget"?(Ps+=` flex items-center justify-center min-h-fit ${Dt} ${js} ${u}`,Fn={...Fn,...Ms}):(Ps=`${u||""}`,Fn={});const Oo=l.jsx("div",{className:"h-full flex flex-col overflow-hidden relative z-10",children:l.jsxs(Yt,{mode:"wait",children:[j==="welcome"&&!re&&l.jsx(rx,{agentId:M,participantName:P||"",onAgentIdChange:J,onParticipantNameChange:B,onStartCall:ie,onStartChat:ae,onStartVideo:$e,disabled:ee||re,prompts:i,statusMessage:a,title:c,subTitle:d,theme:k,modalities:I,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),j==="voice"&&l.jsxs(Fe.RoomContext.Provider,{value:F,children:[l.jsx(Fe.RoomAudioRenderer,{}),l.jsx(Fe.StartAudio,{label:"Start Audio"}),l.jsx(tx,{loadingText:y,participantName:P||"User",capabilities:oe,sessionStarted:ee,disabled:!ee,theme:k,client:_,displayType:E,onBack:E==="popup"?we:Re,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"session-view")]}),j==="chat"&&l.jsx(nx,{client:_,theme:k,displayType:E,onBack:E==="popup"?we:Re,onEndChat:Re,disabled:!ee,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),j==="video"&&l.jsxs(Fe.RoomContext.Provider,{value:F,children:[l.jsx(Fe.RoomAudioRenderer,{}),l.jsx(Fe.StartAudio,{label:"Start Audio"}),l.jsx(sx,{client:_,theme:k,displayType:E,onBack:E==="popup"?we:Re,onEndCall:Re,disabled:!ee,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-view")]})]})});return E==="fullscreen"||E==="popup"?(console.log("📱 Rendering fullscreen/popup mode, displayType:",E),l.jsx(Ga,{theme:k,displayType:E,popupPosition:O,onClose:E==="fullscreen"?Be:we,children:Oo})):(console.log("📦 Rendering widget mode"),l.jsx("div",{className:Ps,style:Fn,children:l.jsx(Ga,{theme:k,displayType:E,popupPosition:O,onExpand:rt,children:Oo})}))}class bd 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}}function ix({logs:e,onClear:t,onExport:n}){const[s,r]=C.useState(!1),[o,i]=C.useState(""),a=e.filter(c=>!o||c.event.toLowerCase().includes(o.toLowerCase()));return s?l.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[l.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"text",placeholder:"Filter events...",value:o,onChange:c=>i(c.target.value),className:"px-3 py-1 border rounded text-sm"}),l.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),l.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),l.jsx("button",{onClick:()=>r(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),l.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?l.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):l.jsx("div",{className:"space-y-2",children:a.map((c,d)=>l.jsxs("div",{className:"border rounded p-3 text-sm",children:[l.jsxs("div",{className:"flex items-center justify-between mb-1",children:[l.jsx("span",{className:"font-semibold text-blue-600",children:c.event}),l.jsx("span",{className:"text-gray-500 text-xs",children:new Date(c.timestamp).toLocaleTimeString()})]}),c.sessionId&&l.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",c.sessionId]}),c.data&&l.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:l.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(c.data,null,2)})})]},d))})})]})}):l.jsxs("button",{onClick:()=>r(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",e.length,")"]})}function ax({metrics:e}){return e?l.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[l.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),l.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Session ID:"}),l.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Start Time:"}),l.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Messages:"}),l.jsx("div",{children:e.totalMessages})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Participants:"}),l.jsx("div",{children:e.participantCount})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),l.jsx("div",{children:e.connectionIssues})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Duration:"}),l.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function It(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:s,endSession:r}=st(),o=C.useCallback(async(a,c)=>await s(a,c),[s]),i=C.useCallback(async()=>await r(),[r]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:o,stop:i}}function vd(){const{sessionMetrics:e,currentSession:t}=st();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 wd(){const{setMicrophoneEnabled:e,client:t}=st(),[n,s]=C.useState(!1),[r,o]=C.useState(!1),i=C.useCallback(async()=>{if(!r){o(!0);try{const d=!n;await e(d),s(d)}catch(d){console.error("Failed to toggle microphone:",d)}finally{o(!1)}}},[n,r,e]),a=C.useCallback(async()=>{if(!(n||r)){o(!0);try{await e(!0),s(!0)}catch(d){console.error("Failed to enable microphone:",d)}finally{o(!1)}}},[n,r,e]),c=C.useCallback(async()=>{if(!(!n||r)){o(!0);try{await e(!1),s(!1)}catch(d){console.error("Failed to disable microphone:",d)}finally{o(!1)}}},[n,r,e]);return{isEnabled:n,isLoading:r,toggle:i,enable:a,disable:c}}function Sd(){const{setCameraEnabled:e}=st(),[t,n]=C.useState(!1),[s,r]=C.useState(!1),o=C.useCallback(async()=>{if(!s){r(!0);try{const c=!t;await e(c),n(c)}catch(c){console.error("Failed to toggle camera:",c)}finally{r(!1)}}},[t,s,e]),i=C.useCallback(async()=>{if(!(t||s)){r(!0);try{await e(!0),n(!0)}catch(c){console.error("Failed to enable camera:",c)}finally{r(!1)}}},[t,s,e]),a=C.useCallback(async()=>{if(!(!t||s)){r(!0);try{await e(!1),n(!1)}catch(c){console.error("Failed to disable camera:",c)}finally{r(!1)}}},[t,s,e]);return{isEnabled:t,isLoading:s,toggle:o,enable:i,disable:a}}function Cd(){const{startScreenShare:e,stopScreenShare:t}=st(),[n,s]=C.useState(!1),[r,o]=C.useState(!1),i=C.useCallback(async()=>{if(!(n||r)){o(!0);try{await e(),s(!0)}catch(d){console.error("Failed to start screen share:",d)}finally{o(!1)}}},[n,r,e]),a=C.useCallback(async()=>{if(!(!n||r)){o(!0);try{await t(),s(!1)}catch(d){console.error("Failed to stop screen share:",d)}finally{o(!1)}}},[n,r,t]),c=C.useCallback(async()=>{n?await a():await i()},[n,i,a]);return{isSharing:n,isLoading:r,start:i,stop:a,toggle:c}}function cx(){const{client:e}=st(),[t,n]=C.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),s=C.useMemo(()=>t.tracks.find(m=>m.isLocal),[t.tracks]),r=C.useMemo(()=>t.tracks.filter(m=>!m.isLocal),[t.tracks]),o=C.useCallback(async()=>{try{s!=null&&s.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,s]),i=C.useCallback(async()=>{try{t.tracks.find(b=>b.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=C.useCallback(m=>{n(b=>({...b,layout:m}))},[]),c=C.useCallback(m=>{n(b=>({...b,pinnedTrack:m}))},[]),d=C.useCallback(()=>{n(m=>({...m,pinnedTrack:void 0}))},[]),u=C.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]),f=C.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]),h=C.useCallback(m=>t.tracks.find(b=>b.id===m),[t.tracks]),y=C.useCallback(m=>t.tracks.filter(b=>b.participantId===m),[t.tracks]),x=C.useCallback(m=>m.isEnabled&&t.tracks.includes(m),[t.tracks]);return C.useEffect(()=>{if(!e)return;const m=w=>{n(T=>({...T,tracks:[...T.tracks.filter(v=>v.id!==w.id),w]}))},b=w=>{n(T=>{var v;return{...T,tracks:T.tracks.filter(S=>S.id!==w),pinnedTrack:((v=T.pinnedTrack)==null?void 0:v.id)===w?void 0:T.pinnedTrack}})},k=w=>{n(T=>({...T,tracks:T.tracks.map(v=>v.id===w.id?w:v)}))};return e.on("videoTrackAdded",m),e.on("videoTrackRemoved",b),e.on("videoTrackUpdated",k),()=>{e.off("videoTrackAdded",m),e.off("videoTrackRemoved",b),e.off("videoTrackUpdated",k)}},[e]),{tracks:t.tracks,localTrack:s,remoteTraracks:r,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:o,toggleScreenShare:i,setLayout:a,pinTrack:c,unpinTrack:d,startRecording:u,stopRecording:f,getTrackById:h,getTracksByParticipant:y,isTrackActive:x}}function As(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=st(),[s,r]=C.useState(!1),o=C.useCallback(async d=>{if(!(!d.trim()||s||!n)){r(!0);try{await t(d.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{r(!1)}}},[t,s,n]),{userMessages:i,agentMessages:a,allMessages:c}=C.useMemo(()=>{const d=e.filter(f=>f.sender.type==="participant"),u=e.filter(f=>f.sender.type==="agent");return{userMessages:d,agentMessages:u,allMessages:e}},[e]);return{messages:c,userMessages:i,agentMessages:a,messageCount:c.length,isSending:s,canSend:!!n&&!s,send:o}}function lx(){const{send:e,isSending:t,canSend:n}=As(),[s,r]=C.useState(""),o=C.useCallback(async()=>{if(!(!s.trim()||!n))try{await e(s),r("")}catch(a){throw a}},[s,e,n]),i=C.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),o())},[o]);return{value:s,setValue:r,send:o,handleKeyPress:i,isSending:t,canSend:n&&s.trim().length>0}}function Io(){const{isConnected:e,isConnecting:t,connectionError:n,connect:s,disconnect:r}=st(),o=C.useCallback(async()=>{if(!(e||t))try{await s()}catch(a){throw console.error("Failed to connect:",a),a}},[s,e,t]),i=C.useCallback(async()=>{if(e)try{await r()}catch(a){throw console.error("Failed to disconnect:",a),a}},[r,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:o,disconnect:i}}function kd(){const{participants:e}=st();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const Td=C.createContext({}),$n=()=>C.useContext(Td);function Ed({children:e,...t}){return l.jsx(Td.Provider,{value:t,children:e})}function ts({name:e,children:t,fallback:n,className:s}){return l.jsx("div",{className:`voxket-slot voxket-slot--${e} ${s||""}`,children:t||n})}function Ad(e,t={}){return Object.assign(e,t)}function jd({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:s=!0,customControls:r,className:o=""}){const i=It(),a=wd(),c=Sd(),d=Cd(),u=$n(),f=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,i.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",o].filter(Boolean).join(" ");return!i.isActive&&!s?l.jsx("div",{className:f,children:l.jsx("div",{className:"voxket-controls-inactive",children:l.jsx("p",{children:"Controls available during active session"})})}):l.jsxs("div",{className:f,children:[s&&l.jsx("div",{className:"voxket-session-actions",children:i.isActive?l.jsx("button",{onClick:i.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):l.jsx(dx,{})}),i.isActive&&l.jsxs("div",{className:"voxket-media-controls",children:[e&&l.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:[l.jsx("span",{className:"voxket-icon",children:"🎤"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&l.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isEnabled?"voxket-button--active":""}`,title:c.isEnabled?"Stop camera":"Start camera",children:[l.jsx("span",{className:"voxket-icon",children:"📹"}),c.isLoading?"Loading...":c.isEnabled?"Stop Video":"Start Video"]}),n&&l.jsxs("button",{onClick:d.toggle,disabled:d.isLoading,className:`voxket-button voxket-button--media ${d.isSharing?"voxket-button--active":""}`,title:d.isSharing?"Stop screen share":"Start screen share",children:[l.jsx("span",{className:"voxket-icon",children:"🖥️"}),d.isLoading?"Loading...":d.isSharing?"Stop Share":"Share Screen"]})]}),r&&l.jsx("div",{className:"voxket-custom-controls",children:r})]})}function dx(){It();const[e,t]=C.useState(!1),n=async()=>{t(!0);try{console.log("Start session - agentId needed")}catch(s){console.error("Failed to start session:",s)}finally{t(!1)}};return l.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function Do({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:s=""}){const r=It(),o=Io(),i=$n(),a=["voxket-session-header",`voxket-session-header--${i.variant||"default"}`,`voxket-session-header--${i.size||"md"}`,s].filter(Boolean).join(" ");return l.jsxs("div",{className:a,children:[e&&l.jsxs("div",{className:"voxket-connection-status",children:[l.jsx("div",{className:`voxket-status-indicator ${o.isConnected?"connected":"disconnected"}`}),l.jsx("span",{className:"voxket-status-text",children:o.isConnecting?"Connecting...":o.isConnected?"Connected":"Disconnected"})]}),t&&r.session&&l.jsxs("div",{className:"voxket-session-info",children:[l.jsxs("div",{className:"voxket-session-id",children:["Session: ",r.session.id.slice(-8)]}),l.jsxs("div",{className:"voxket-session-state",children:["State: ",r.state]})]}),n&&r.session&&l.jsxs("div",{className:"voxket-agent-info",children:[l.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",r.session.agentId]}),l.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",r.session.activeModalities.join(", ")]})]}),o.error&&l.jsxs("div",{className:"voxket-error-message",children:["Error: ",o.error.message]})]})}function $o({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:s=""}){const r=It(),o=As(),i=$n(),a=["voxket-session-content",`voxket-session-content--${i.variant||"default"}`,`voxket-session-content--${i.size||"md"}`,s].filter(Boolean).join(" ");return r.isActive?l.jsx("div",{className:a,children:n||l.jsxs(l.Fragment,{children:[e&&l.jsxs("div",{className:"voxket-chat-container",children:[l.jsxs("div",{className:"voxket-chat-messages",children:[o.messages.map(c=>l.jsxs("div",{className:`voxket-message voxket-message--${c.sender.type}`,children:[l.jsxs("div",{className:"voxket-message-header",children:[l.jsx("span",{className:"voxket-message-sender",children:c.sender.name}),l.jsx("span",{className:"voxket-message-time",children:c.timestamp.toLocaleTimeString()})]}),l.jsx("div",{className:"voxket-message-content",children:c.content})]},c.id)),o.messages.length===0&&l.jsx("div",{className:"voxket-empty-messages",children:l.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),l.jsx(ux,{})]}),t&&l.jsx("div",{className:"voxket-transcriptions",children:l.jsx("div",{className:"voxket-transcription-placeholder",children:l.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):l.jsx("div",{className:a,children:l.jsx("div",{className:"voxket-inactive-state",children:l.jsxs("div",{className:"voxket-inactive-message",children:[l.jsx("h3",{children:"Start a conversation"}),l.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function ux(){const e=As(),[t,n]=C.useState(""),s=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(o){console.error("Failed to send message:",o)}},r=o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),s())};return l.jsxs("div",{className:"voxket-chat-input",children:[l.jsx("input",{type:"text",value:t,onChange:o=>n(o.target.value),onKeyPress:r,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),l.jsx("button",{onClick:s,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function Fo({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:s,className:r=""}){const o=It(),i=vd(),a=kd(),c=$n(),d=["voxket-session-footer",`voxket-session-footer--${c.variant||"default"}`,`voxket-session-footer--${c.size||"md"}`,r].filter(Boolean).join(" ");return o.isActive?l.jsx("div",{className:d,children:s||l.jsxs(l.Fragment,{children:[n&&l.jsxs("div",{className:"voxket-session-status",children:[l.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),l.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&i.metrics&&l.jsxs("div",{className:"voxket-session-metrics",children:[l.jsxs("div",{className:"voxket-metric",children:[l.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),l.jsx("span",{className:"voxket-metric-value",children:fx(i.duration||0)})]}),l.jsxs("div",{className:"voxket-metric",children:[l.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),l.jsx("span",{className:"voxket-metric-value",children:i.metrics.messageCount})]})]}),t&&l.jsxs("div",{className:"voxket-participants-info",children:[l.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&l.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>l.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):l.jsx("div",{className:d,children:l.jsx("div",{className:"voxket-footer-inactive",children:l.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function fx(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),s=Math.floor(n/60);return s>0?`${s}:${(n%60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}`:`${n}:${(t%60).toString().padStart(2,"0")}`}function hx({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:s,onSessionEnd:r,variant:o="default",size:i="md",theme:a,className:c="",children:d}){var y;const u=It(),f=Io();C.useEffect(()=>{n&&e&&f.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,f.isConnected,u.isActive]),C.useEffect(()=>{var x;(x=u.session)!=null&&x.id&&s&&s(u.session.id)},[(y=u.session)==null?void 0:y.id,s]),C.useEffect(()=>()=>{u.isActive&&r&&u.stop().then(r).catch(console.error)},[]);const h=["voxket-session",`voxket-session--${o}`,`voxket-session--${i}`,u.isActive?"voxket-session--active":"voxket-session--inactive",c].filter(Boolean).join(" ");return l.jsx(Ed,{variant:o,size:i,theme:a,className:c,children:l.jsx("div",{className:h,children:d||l.jsxs(l.Fragment,{children:[l.jsx(ts,{name:"header",fallback:l.jsx(Do,{})}),l.jsx(ts,{name:"content",fallback:l.jsx($o,{})}),l.jsx(ts,{name:"footer",fallback:l.jsx(Fo,{})})]})})})}const Md=Ad(hx,{Header:Do,Content:$o,Footer:Fo,Controls:jd}),Nt={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)"}},Dr={...Nt,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)"}},$r={...Nt,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"}},Pd=C.createContext(null),Vd=()=>{const e=C.useContext(Pd);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function mx({theme:e="default",themes:t={},children:n,cssVariables:s=!0,className:r=""}){const[o,i]=C.useState(()=>{const h={default:Nt,dark:Dr,enterprise:$r,...t};return typeof e=="string"?h[e]||Nt:e}),[a,c]=C.useState(()=>({default:Nt,dark:Dr,enterprise:$r,...t})),d=h=>{if(typeof h=="string"){const y=a[h];y&&i(y)}else i(h)},u=h=>{c(y=>({...y,[h.name]:h}))};C.useEffect(()=>{if(s&&typeof document<"u"){const h=document.documentElement;Object.entries(Nd(o)).forEach(([y,x])=>{h.style.setProperty(`--voxket-${y}`,x)})}},[o,s]);const f={theme:o,setTheme:d,themes:a,registerTheme:u};return l.jsx(Pd.Provider,{value:f,children:l.jsx("div",{className:`voxket-theme voxket-theme--${o.name} ${r}`,children:n})})}function Nd(e){const t={},n=(s,r="")=>{for(const[o,i]of Object.entries(s)){const a=r?`${r}-${o}`:o;typeof i=="object"&&i!==null&&!Array.isArray(i)?n(i,a):t[a]=String(i)}};return n(e),t}function px(e=Nt,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 gx(e){var n;const{theme:t}=Vd();return((n=t.components)==null?void 0:n[e])||{}}const yx=Ro("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&xx(e),t.enableVoiceActivation&&bx(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&vx(e,t)}});function xx(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 bx(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function vx(e,t){console.log("Playing audio response:",t.content)}const wx=Ro("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&Sx(),t.enableFileUpload&&Cx(e),t.enableCustomComponents&&kx(),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"?Tx(e,t):t.type==="text"&&n.enableRichText&&Ex(e,t)}});function Sx(e){console.log("Rich text support enabled")}function Cx(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function kx(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",Ax),t.set("form",jx),t.set("card",Mx),t.set("chart",Px)}function Tx(e,t){const{componentType:n,props:s}=t.metadata;console.log("Rendering custom component:",n,s),e.emit("chat.component.render",{type:n,props:s,timestamp:new Date})}function Ex(e,t){console.log("Processing rich text message:",t.content)}function Ax(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function jx(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function Mx(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function Px(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function ns({track:e,participantName:t,showControls:n=!0,showName:s=!0,showMuteIndicator:r=!0,isPinned:o=!1,className:i="",onClick:a,onPin:c,onUnpin:d}){const u=C.useRef(null),[f,h]=C.useState(!1);C.useEffect(()=>{if(!u.current||!e.isEnabled)return;const b=u.current;return b.srcObject=null,()=>{b.srcObject&&(b.srcObject=null)}},[e]);const y=()=>{a==null||a(e)},x=b=>{b.stopPropagation(),o?d==null||d(e):c==null||c(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",f?"voxket-video-tile--hovered":"",i].filter(Boolean).join(" ");return l.jsxs("div",{className:m,onClick:y,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[l.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&l.jsxs("div",{className:"voxket-video-placeholder",children:[l.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"🖥️":"📹"}),l.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),l.jsxs("div",{className:"voxket-video-overlay",children:[s&&t&&l.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),r&&!e.isEnabled&&l.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),n&&(f||o)&&l.jsxs("div",{className:"voxket-video-controls",children:[l.jsx("button",{className:`voxket-video-control-btn ${o?"voxket-video-control-btn--active":""}`,onClick:x,title:o?"Unpin video":"Pin video",children:"📌"}),e.isScreenShare&&l.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),e.source&&l.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&l.jsx("div",{className:"voxket-video-loading",children:l.jsx("div",{className:"voxket-spinner"})})]})}function Vx({tracks:e,layout:t,className:n="",onLayoutChange:s,onTrackClick:r,maxVisibleTracks:o=9,showPagination:i=!0}){const[a,c]=C.useState(0),[d,u]=C.useState(null),f=C.useMemo(()=>{let w=[...e];t.type==="speaker"&&d&&(w=[d,...e.filter(S=>S.id!==d.id)]);const T=a*o,v=T+o;return w.slice(T,v)},[e,t,d,a,o]),h=Math.ceil(e.length/o),y=C.useMemo(()=>{const w=f.length;switch(t.type){case"grid":const T=Math.ceil(Math.sqrt(w)),v=Math.ceil(w/T);return{display:"grid",gridTemplateColumns:`repeat(${T}, 1fr)`,gridTemplateRows:`repeat(${v}, 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,f.length]),x=w=>{u(w)},m=()=>{u(null)},b=w=>{s==null||s({...t,type:w})},k=["voxket-video-grid",`voxket-video-grid--${t.type}`,`voxket-video-grid--${f.length}-tracks`,n].filter(Boolean).join(" ");return e.length===0?l.jsx("div",{className:"voxket-video-grid-empty",children:l.jsxs("div",{className:"voxket-video-grid-empty-content",children:[l.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),l.jsx("p",{children:"No video tracks available"})]})}):l.jsxs("div",{className:k,children:[l.jsxs("div",{className:"voxket-video-grid-controls",children:[l.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(w=>l.jsx("button",{className:`voxket-layout-btn ${t.type===w?"voxket-layout-btn--active":""}`,onClick:()=>b(w),title:`Switch to ${w} layout`,children:Nx(w)},w))}),l.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),l.jsx("div",{className:"voxket-video-grid-content",style:y,children:t.type==="speaker"&&d?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"voxket-video-speaker-main",children:l.jsx(ns,{track:d,participantName:`Participant ${d.participantId}`,isPinned:!0,onClick:r,onUnpin:m})}),l.jsx("div",{className:"voxket-video-speaker-sidebar",children:f.filter(w=>w.id!==d.id).map(w=>l.jsx(ns,{track:w,participantName:`Participant ${w.participantId}`,showControls:!1,onClick:r,onPin:x},w.id))})]}):f.map(w=>l.jsx(ns,{track:w,participantName:`Participant ${w.participantId}`,isPinned:(d==null?void 0:d.id)===w.id,onClick:r,onPin:x,onUnpin:m},w.id))}),i&&h>1&&l.jsxs("div",{className:"voxket-video-pagination",children:[l.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.max(0,a-1)),disabled:a===0,children:"←"}),l.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",h]}),l.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.min(h-1,a+1)),disabled:a===h-1,children:"→"})]})]})}function Nx(e){switch(e){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function Rx({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:s,showLayoutControls:r=!0,showCameraControls:o=!0,showScreenShareControls:i=!0,className:a=""}){const c=["voxket-video-controls",a].filter(Boolean).join(" "),d=u=>{s==null||s({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return l.jsxs("div",{className:c,children:[o&&l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),l.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:[l.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"📹":"📷"}),l.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&l.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," × ",e.dimensions.height]})]}),i&&l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),l.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:[l.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"🛑":"🖥️"}),l.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),r&&l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),l.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:f,label:h})=>l.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>d(u),title:`Switch to ${h} layout`,children:[l.jsx("span",{className:"voxket-control-icon",children:f}),l.jsx("span",{className:"voxket-control-label",children:h})]},u))})]}),l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),l.jsxs("div",{className:"voxket-video-settings",children:[l.jsxs("div",{className:"voxket-setting-group",children:[l.jsx("label",{className:"voxket-setting-label",children:"Quality"}),l.jsxs("select",{className:"voxket-setting-select",children:[l.jsx("option",{value:"high",children:"High (720p)"}),l.jsx("option",{value:"medium",children:"Medium (480p)"}),l.jsx("option",{value:"low",children:"Low (240p)"})]})]}),l.jsxs("div",{className:"voxket-setting-group",children:[l.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),l.jsxs("select",{className:"voxket-setting-select",children:[l.jsx("option",{value:"30",children:"30 fps"}),l.jsx("option",{value:"15",children:"15 fps"}),l.jsx("option",{value:"10",children:"10 fps"})]})]}),l.jsxs("div",{className:"voxket-setting-group",children:[l.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),l.jsxs("select",{className:"voxket-setting-select",children:[l.jsx("option",{value:"unlimited",children:"Unlimited"}),l.jsx("option",{value:"1000",children:"1 Mbps"}),l.jsx("option",{value:"500",children:"500 Kbps"}),l.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),l.jsxs("div",{className:"voxket-video-stats",children:[l.jsxs("div",{className:"voxket-stat-item",children:[l.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),l.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}×${e.dimensions.height}`:"N/A"})]}),l.jsxs("div",{className:"voxket-stat-item",children:[l.jsx("span",{className:"voxket-stat-label",children:"Source:"}),l.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),l.jsxs("div",{className:"voxket-stat-item",children:[l.jsx("span",{className:"voxket-stat-label",children:"Status:"}),l.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 Rd=({handler:e,loadData:t,data:n,client:s,addLocalMessage:r})=>{const[o,i]=p.useState(null),[a,c]=p.useState(!0),[d,u]=p.useState(!1),[f]=p.useState(Date.now());p.useEffect(()=>{(async()=>{try{if(c(!0),console.log("📋 AssignmentView: Loading assignment data..."),console.log("📋 AssignmentView: Received data from RPC:",n),n&&typeof n=="object"){const b={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};i(b),console.log("📋 AssignmentView: Assignment loaded from RPC data:",b)}}catch(b){console.error("📋 AssignmentView: Error loading assignment:",b),i({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{c(!1)}})()},[n,t]);const h=({message:m,assignment:b})=>{const k=m.toLowerCase().includes("declined"),w=k?"bg-red-50 border-red-200":"bg-green-50 border-green-200",T=k?"text-red-700":"text-green-700",v=k?"❌":"🎉";return l.jsxs("div",{className:`max-w-sm mx-auto ${w} border rounded-lg shadow p-3 flex flex-col items-center`,children:[l.jsx("div",{className:"text-2xl mb-2",children:v}),l.jsx("div",{className:`${T} font-semibold text-sm mb-1`,children:m}),l.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:b.title}),l.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},y=async()=>{if(!(!o||!e)){u(!0);try{const m={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",m),e.didSuccess(m,l.jsx(h,{message:"Assignment accepted!",assignment:o}))}catch(m){console.error("📋 AssignmentView: Error accepting assignment:",m),e.didFail({error:"Failed to accept assignment"})}finally{u(!1)}}},x=async()=>{if(!(!o||!e)){u(!0);try{const m={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",m),e.didSuccess(m,l.jsx(h,{message:"Assignment declined",assignment:o}))}catch(m){console.error("📋 AssignmentView: Error declining assignment:",m),e.didFail({error:"Failed to decline assignment"})}finally{u(!1)}}};return a?l.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:l.jsxs("div",{className:"flex items-center justify-center py-4",children:[l.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),l.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):o?l.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[l.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:l.jsx("div",{className:"flex items-center justify-between",children:l.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:o.title})})}),l.jsxs("div",{className:"p-3 text-black",children:[l.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:l.jsx("p",{className:"text-xs text-black leading-snug",children:o.description})}),l.jsx("div",{className:"mb-3 text-black",children:l.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[l.jsx("span",{className:"text-xs mr-1",children:"📅"}),l.jsxs("span",{children:["Est: ",o.estimated_time_of_completion]})]})}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx("button",{onClick:y,disabled:d,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:d?l.jsxs("span",{className:"flex items-center justify-center",children:[l.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),l.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),l.jsx("button",{onClick:x,disabled:d,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"})]})]})]}):l.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:l.jsxs("div",{className:"text-center py-4",children:[l.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),l.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function Ix(){const[e,t]=p.useState(null),[n,s]=p.useState([]);p.useEffect(()=>{const a=new Dn({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return t(a),a.on("rpc.method.called",c=>{console.log("RPC Method Called:",c)}),a.on("rpc.interaction.completed",c=>{console.log("RPC Interaction Completed:",c)}),()=>{a.disconnect()}},[]);const r=async()=>{if(e)try{await e.registerFrontendRPC("give_assignment",Rd,"embedded");const a=e.getRegisteredRpcMethods();s(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:c,timeout:d})=>{const[u,f]=p.useState(""),h=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],y=m=>{f(m)},x=()=>{const m=h.find(b=>b.id===u);c==null||c.didSuccess({selectedProduct:u,productName:m==null?void 0:m.name,price:m==null?void 0:m.price,timestamp:new Date().toISOString()})};return l.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[l.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),l.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),l.jsx("div",{className:"space-y-3 mb-6",children:h.map(m=>l.jsx("div",{onClick:()=>y(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:l.jsxs("div",{className:"flex justify-between items-center",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"font-medium",children:m.name}),l.jsx("p",{className:"text-gray-600 text-sm",children:m.price})]}),l.jsx("div",{className:`w-4 h-4 rounded-full ${u===m.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},m.id))}),l.jsxs("div",{className:"flex justify-end space-x-3",children:[l.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),l.jsx("button",{onClick:x,disabled:!u,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),d&&l.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",d," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const c=e.getRegisteredRpcMethods();s(c),console.log("✅ Product Recommendation RPC registered successfully")}catch(c){console.error("❌ Failed to register product recommendation RPC:",c)}},i=async()=>{if(!e)return;const a=({handler:c})=>{const[d,u]=p.useState(0),[f,h]=p.useState(""),y=()=>{c==null||c.didSuccess({rating:d,comment:f,timestamp:new Date().toISOString()})};return l.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[l.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),l.jsxs("div",{className:"mb-4",children:[l.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),l.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(x=>l.jsx("button",{onClick:()=>u(x),className:`text-2xl ${x<=d?"text-yellow-400":"text-gray-300"}`,children:"⭐"},x))})]}),l.jsxs("div",{className:"mb-4",children:[l.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),l.jsx("textarea",{value:f,onChange:x=>h(x.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),l.jsxs("div",{className:"flex justify-end space-x-2",children:[l.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),l.jsx("button",{onClick:y,disabled:d===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await e.registerFrontendRPC("collect_feedback",a,"embedded");const c=e.getRegisteredRpcMethods();s(c),console.log("✅ Feedback RPC registered successfully")}catch(c){console.error("❌ Failed to register feedback RPC:",c)}};return l.jsxs("div",{className:"p-6",children:[l.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),l.jsxs("div",{className:"space-y-4 mb-6",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),l.jsxs("div",{className:"space-x-2",children:[l.jsx("button",{onClick:r,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),l.jsx("button",{onClick:o,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),l.jsx("button",{onClick:i,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?l.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>l.jsx("li",{className:"text-gray-700",children:l.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):l.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),l.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[l.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),l.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[l.jsxs("li",{children:["Register RPC methods with React components using ",l.jsx("code",{children:"client.registerFrontendRPC()"})]}),l.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),l.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),l.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),l.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),l.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[l.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),l.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),l.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
125
+ `,style:{minHeight:"2.5rem",display:i===s?"block":"none"},children:o},i))})}function K1({statusMessage:e,theme:t}){const n=De(t);return l.jsxs("div",{className:"z-10 flex items-center space-x-2 mt-2 pb-2",children:[l.jsx("div",{className:n.statusIndicator}),l.jsx("span",{className:`text-xs ${n.text.muted}`,children:e})]})}const Y1=({disabled:e,onStartCall:t,onStartChat:n,onStartVideo:s,prompts:r=['"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:i="Choose how to interact",subTitle:a="Ask me anything or give me a task to complete",theme:c="vox",modalities:d=["voice","chat","video"]})=>{const u=De(c),f=d.includes("voice"),h=d.includes("chat"),y=d.includes("video"),x=[f,h,y].filter(Boolean).length;return console.log("🎯 Welcome component debug:",{modalities:d,hasVoice:f,hasChat:h,hasVideo:y,totalButtons:x,onStartVideo:!!s}),l.jsxs("div",{className:"flex p-8 flex-col items-center h-full justify-center w-full relative","aria-disabled":e,style:{background:"transparent"},children:[l.jsxs("div",{className:"mt-1 relative flex items-center justify-center mb-8 w-full",style:{minHeight:"120px"},children:[l.jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[l.jsx("div",{className:u.pulseRings.ring1}),l.jsx("div",{className:u.pulseRings.ring2,style:{animationDelay:"0.5s"}}),l.jsx("div",{className:u.pulseRings.ring3,style:{animationDelay:"1s"}})]}),l.jsx("div",{className:"relative z-10 flex items-center justify-center",children:f&&h&&y?l.jsxs("div",{className:"flex gap-4 items-center justify-center",children:[l.jsx(Yn,{onClick:t,disabled:e,theme:c}),l.jsx(or,{onClick:n,disabled:e,theme:c}),l.jsx(ir,{onClick:s||t,disabled:e,theme:c})]}):x>1?l.jsxs("div",{className:"flex gap-6 items-center justify-center",children:[f&&l.jsx(Yn,{onClick:t,disabled:e,theme:c}),h&&l.jsx(or,{onClick:n,disabled:e,theme:c}),y&&s&&l.jsx(ir,{onClick:s,disabled:e,theme:c})]}):l.jsx("div",{className:"flex items-center justify-center",children:f?l.jsx(Yn,{onClick:t,disabled:e,theme:c}):h?l.jsx(or,{onClick:n,disabled:e,theme:c}):y&&s?l.jsx(ir,{onClick:s,disabled:e,theme:c}):l.jsx(Yn,{onClick:t,disabled:e,theme:c})})})]}),l.jsxs("div",{className:"text-center flex flex-col items-center gap-y-2 mb-6 w-full",children:[l.jsx("h3",{className:`text-xl font-semibold mb-2 ${u.text.accent}`,children:i}),l.jsx("p",{className:`text-sm leading-relaxed px-4 ${u.text.secondary}`,children:a}),x>1&&l.jsxs("div",{className:"flex gap-6 mt-4 text-xs justify-center",children:[f&&l.jsxs("div",{className:"flex flex-col items-center gap-1",children:[l.jsx(fd,{className:"w-4 h-4"}),l.jsx("span",{className:u.text.muted,children:"Voice"})]}),h&&l.jsxs("div",{className:"flex flex-col items-center gap-1",children:[l.jsx(ud,{className:"w-4 h-4"}),l.jsx("span",{className:u.text.muted,children:"Chat"})]}),y&&l.jsxs("div",{className:"flex flex-col items-center gap-1",children:[l.jsx(hd,{className:"w-4 h-4"}),l.jsx("span",{className:u.text.muted,children:"Video"})]})]})]}),l.jsx(G1,{prompts:r,theme:c}),l.jsx(K1,{statusMessage:o,theme:c})]})};function md({room:e,onSessionEnd:t,onSessionStart:n,enableConsoleLogging:s=!0,enableLocalStorage:r=!0,voxketSessionId:o}={}){const[i,a]=p.useState(null),[c,d]=p.useState([]),[u,f]=p.useState(null),[h,y]=p.useState([]),x=p.useCallback((w,T)=>{const v={timestamp:new Date,event:w,data:T,sessionId:i==null?void 0:i.sessionId,participantId:u==null?void 0:u.identity};if(d(S=>[...S,v]),r){const S=JSON.parse(localStorage.getItem("voxket-session-logs")||"[]");S.push(v),localStorage.setItem("voxket-session-logs",JSON.stringify(S))}return v},[i==null?void 0:i.sessionId,u==null?void 0:u.identity,s,r]);p.useEffect(()=>{if(!e)return;const w=()=>{const g=o||`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,D=new Date,L={sessionId:g,startTime:D,totalMessages:0,connectionIssues:0,participantCount:h.length,events:[]};a(L),x("SESSION_STARTED",{sessionId:g,startTime:D}),n==null||n(g)},T=()=>{if(i){const g=new Date,D=g.getTime()-i.startTime.getTime(),L={...i,endTime:g,duration:D,events:c};x("SESSION_ENDED",{sessionId:i.sessionId,duration:`${Math.round(D/1e3)}s`,totalMessages:i.totalMessages,connectionIssues:i.connectionIssues}),t==null||t(L),a(null),d([])}},v=g=>{x("CONNECTION_STATE_CHANGED",{state:g}),g===H.ConnectionState.Reconnecting&&i&&(a(D=>D?{...D,connectionIssues:D.connectionIssues+1}:null),x("CONNECTION_ISSUE",{type:"reconnecting"}))},S=g=>{x("TRACK_PUBLISHED",{trackKind:g.kind,trackSource:g.source})},A=g=>{x("TRACK_UNPUBLISHED",{trackKind:g.kind,trackSource:g.source})},V=(g,D)=>{i&&a(L=>L?{...L,totalMessages:L.totalMessages+1}:null),x("DATA_RECEIVED",{participantId:D==null?void 0:D.identity,dataSize:g.length})},E=g=>{x("PARTICIPANT_CONNECTED",{participantId:g.identity,participantName:g.name}),y(D=>[...D,g]),i&&a(D=>D?{...D,participantCount:D.participantCount+1}:null)},O=g=>{x("PARTICIPANT_DISCONNECTED",{participantId:g.identity,participantName:g.name}),y(D=>D.filter(L=>L.identity!==g.identity))};return e.localParticipant&&f(e.localParticipant),e.on(H.RoomEvent.Connected,w),e.on(H.RoomEvent.Disconnected,T),e.on(H.RoomEvent.ConnectionStateChanged,v),e.on(H.RoomEvent.TrackPublished,S),e.on(H.RoomEvent.TrackUnpublished,A),e.on(H.RoomEvent.DataReceived,V),e.on(H.RoomEvent.ParticipantConnected,E),e.on(H.RoomEvent.ParticipantDisconnected,O),()=>{e.off(H.RoomEvent.Connected,w),e.off(H.RoomEvent.Disconnected,T),e.off(H.RoomEvent.ConnectionStateChanged,v),e.off(H.RoomEvent.TrackPublished,S),e.off(H.RoomEvent.TrackUnpublished,A),e.off(H.RoomEvent.DataReceived,V),e.off(H.RoomEvent.ParticipantConnected,E),e.off(H.RoomEvent.ParticipantDisconnected,O)}},[e,i,c,h.length,x,t,n]);const m=p.useCallback(()=>r?JSON.parse(localStorage.getItem("voxket-session-logs")||"[]"):c,[c,r]),b=p.useCallback(()=>{r&&localStorage.removeItem("voxket-session-logs"),d([])},[r]),k=p.useCallback(()=>{const w=m(),T=JSON.stringify(w,null,2),v="data:application/json;charset=utf-8,"+encodeURIComponent(T),S=`voxket-session-logs-${new Date().toISOString().split("T")[0]}.json`,A=document.createElement("a");A.setAttribute("href",v),A.setAttribute("download",S),A.click()},[m]);return{sessionMetrics:i,sessionLogs:c,logEvent:x,getSessionLogs:m,clearSessionLogs:b,exportSessionLogs:k}}class No{constructor(){Te(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 s=(...r)=>{this.off(t,s),n(...r)};return this.on(t,s)}off(t,n){const s=this.listeners[t];if(!s)return;const r=s.indexOf(n);r>-1&&s.splice(r,1)}removeAllListeners(t){t?delete this.listeners[t]:this.listeners={}}emit(t,...n){const s=this.listeners[t];if(!s)return;const r=[...s];for(const o of r)try{o(...n)}catch(i){console.error(`Error in event listener for ${String(t)}:`,i)}}listenerCount(t){var n;return((n=this.listeners[t])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class pd{constructor(t){Te(this,"plugins",new Map);Te(this,"installedPlugins",new Set);Te(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 s=this.plugins.get(t);if(!s)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t))throw new Error(`Plugin '${t}' is already installed`);if(s.dependencies)for(const o of s.dependencies)this.installedPlugins.has(o)||await this.install(o);const r={...this.context,config:{...s.config,...n}};s.install&&await s.install(r),this.installedPlugins.add(t),this.setupPluginEvents(s,r)}async uninstall(t){var s;const n=this.plugins.get(t);if(!n)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t)){for(const[r,o]of this.plugins)if(this.installedPlugins.has(r)&&((s=o.dependencies)!=null&&s.includes(t)))throw new Error(`Cannot uninstall '${t}' because '${r}' depends on it`);n.uninstall&&await n.uninstall(this.context),this.installedPlugins.delete(t)}}isInstalled(t){return this.installedPlugins.has(t)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(t){return this.plugins.get(t)}setupPluginEvents(t,n){t.onSessionStart&&n.on("session.started",s=>{t.onSessionStart(n,s.id)}),t.onSessionEnd&&n.on("session.ended",s=>{t.onSessionEnd(n,s.id)}),t.onAgentResponse&&n.on("agent.response",s=>{t.onAgentResponse(n,s)})}}function q1(e){return e}function Ro(e,t,n){return{name:e,version:"1.0.0",description:`${t} modality plugin`,install:async s=>{n.onActivate&&await n.onActivate(s)},uninstall:async s=>{n.onDeactivate&&await n.onDeactivate(s)},onAgentResponse:n.onMessage}}const X1={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)})}},J1={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,...s)=>(console.log(`[Debug] Event: ${String(n)}`,s),t(n,...s))}},Q1={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})})}},gd=C.createContext(null);function yd({config:e,children:t,autoConnect:n=!1}){const[s,r]=C.useState(null),[o,i]=C.useState(!1),[a,c]=C.useState(!1),[d,u]=C.useState(null),[f,h]=C.useState(null),[y,x]=C.useState("idle"),[m,b]=C.useState(null),[k,w]=C.useState([]),[T,v]=C.useState([]),[S,A]=C.useState([]);C.useEffect(()=>{const M=new Dn(e);return r(M),V(M),n&&E(M),()=>{M.disconnect().catch(console.error)}},[e,n]);const V=M=>{M.on("connection.connecting",()=>{c(!0),u(null)}),M.on("connection.connected",()=>{i(!0),c(!1),u(null)}),M.on("connection.disconnected",()=>{i(!1),c(!1),h(null),x("idle"),w([]),v([]),A([])}),M.on("connection.error",J=>{u(J),c(!1)}),M.on("session.created",J=>{h(J),x(J.state)}),M.on("session.state.changed",J=>{x(J),f&&h({...f,state:J})}),M.on("session.ended",(J,P)=>{h(null),x("idle"),b(P),w([]),v([]),A([])}),M.on("participant.joined",J=>{w(P=>[...P,J])}),M.on("participant.left",J=>{w(P=>P.filter(B=>B.id!==J.id))}),M.on("chat.message.received",J=>{v(P=>[...P,J])}),M.on("chat.message.sent",J=>{v(P=>[...P,J])}),M.on("transcription.received",J=>{A(P=>[...P,J])})},E=async M=>{const J=M||s;if(J)try{await J.connect()}catch(P){console.error("Failed to connect:",P)}},Y={client:s,isConnected:o,isConnecting:a,connectionError:d,currentSession:f,sessionState:y,sessionMetrics:m,participants:k,chatMessages:T,transcriptions:S,connect:()=>E(),disconnect:async()=>{if(s)try{await s.disconnect()}catch(M){console.error("Failed to disconnect:",M)}},createSession:async(M,J={})=>{if(!s)throw new Error("Client not initialized");const P={agentId:M,participantName:J.participantName||"User",metadata:J.metadata,modalities:J.modalities||["voice"]};return await s.createSession(P)},endSession:async()=>s?await s.endSession():null,sendChatMessage:async M=>{if(!s)throw new Error("Client not initialized");await s.sendChatMessage(M)},setMicrophoneEnabled:async M=>{if(!s)throw new Error("Client not initialized");await s.setMicrophoneEnabled(M)},setCameraEnabled:async M=>{if(!s)throw new Error("Client not initialized");await s.setCameraEnabled(M)},startScreenShare:async()=>{if(!s)throw new Error("Client not initialized");await s.startScreenShare()},stopScreenShare:async()=>{if(!s)throw new Error("Client not initialized");await s.stopScreenShare()}};return l.jsx(gd.Provider,{value:Y,children:t})}function st(){const e=C.useContext(gd);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}class ex extends No{constructor(n){super();Te(this,"room",null);Te(this,"registeredMethods",new Map);Te(this,"activeInteractions",new Map);Te(this,"currentInteraction",null);n&&this.setRoom(n)}setRoom(n){this.room=n}async registerFrontendRPC(n,s,r="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:s,presentationMode:r};this.registeredMethods.set(n,o);try{this.room.registerRpcMethod(n,async i=>{console.log(`RpcManager: RPC method '${n}' called by ${i.callerIdentity}`),console.log("RpcManager: Payload:",i.payload),this.emit("rpc.method.called",{methodName:n,data:i});let a;console.log(`RpcManager: Current registration for '${n}':`,o);let c=i.responseTimeout||30;try{a=JSON.parse(i.payload)}catch{a=i.payload}try{const d=await this.awaitUserInteraction(n,s,r,a,c);return JSON.stringify(d)}catch(d){throw console.error(`RpcManager: Error in RPC method '${n}':`,d),d}}),this.emit("rpc.method.registered",{methodName:n}),console.log(`RpcManager: Successfully registered RPC method: ${n}`)}catch(i){throw console.error(`RpcManager: Failed to register RPC method '${n}':`,i),i}}async awaitUserInteraction(n,s,r,o,i){return new Promise((a,c)=>{const d=`${n}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${n}, timeout: ${i} seconds`);const u={didSuccess:(h,y)=>{console.log(`RpcManager: User interaction successful for method: ${n}`,h),this.clearInteraction(d),this.currentInteraction=null;const x={success:!0,message:"User interaction completed successfully",data:h,timestamp:new Date,...y?{successView:y}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:x}),a(x)},didFail:h=>{console.log(`RpcManager: User interaction failed for method: ${n}`,h),this.clearInteraction(d);const y={success:!1,message:"User interaction failed",error:h,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:y}),a(y)},dismissView:()=>{var y;console.log(`RpcManager: User dismissed interaction for method: ${n}`),console.log("RpcManager: Current interaction before dismiss:",(y=this.currentInteraction)==null?void 0:y.methodName),this.clearInteraction(d),this.currentInteraction=null,console.log("RpcManager: Current interaction after dismiss:",this.currentInteraction);const h={success:!0,data:{dismissed:!0,reason:"User dismissed the interaction"},message:"User interaction dismissed",timestamp:new Date};this.emit("rpc.interaction.dismissed",{methodName:n,response:h}),this.emit("rpc.interaction.completed",{methodName:n,response:h}),setTimeout(()=>{var x;((x=this.currentInteraction)==null?void 0:x.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(h)},didTimeout:h=>{console.log(`RpcManager: User interaction timeout for method: ${n}`),this.clearInteraction(d),this.currentInteraction=null;const y={success:!0,message:`User interaction timed out after ${i} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...h?{timeoutView:h}:{}};this.emit("rpc.interaction.timeout",{methodName:n,response:y}),setTimeout(()=>{var x;((x=this.currentInteraction)==null?void 0:x.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(y)}},f=setTimeout(()=>{u.didTimeout&&u.didTimeout()},i);this.activeInteractions.set(d,{resolve:h=>a(JSON.parse(h)),reject:c,timeoutId:f}),this.currentInteraction={isVisible:!0,methodName:n,component:s,presentationMode:r,timeout:i,data:o,handler:u},this.emit("rpc.interaction.started",{methodName:n,presentationMode:r}),setTimeout(async()=>{var h;if((h=this.currentInteraction)!=null&&h.handler)try{console.log(`RpcManager: Component created for method: ${n} with data:`,o)}catch(y){console.error("RpcManager: Error loading data into component:",y),u.didFail({error:"Failed to load data into component"})}},100)})}clearInteraction(n){const s=this.activeInteractions.get(n);s&&(console.log(`RpcManager: Clearing interaction: ${n}`),clearTimeout(s.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,s]of this.activeInteractions)clearTimeout(s.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null,console.log("RpcManager: Cleared all registrations and interactions")}}class ge extends Error{constructor(t,n,s){super(t),this.code=n,this.details=s,this.name="VoxketError"}}class Dn extends No{constructor(n){super();Te(this,"config");Te(this,"room",null);Te(this,"pluginManager");Te(this,"rpcManager");Te(this,"isConnected",!1);Te(this,"currentSession",null);Te(this,"connectionState",H.ConnectionState.Disconnected);Te(this,"renderedComponents",new Map);Te(this,"textStreamHandlersRegistered",!1);Te(this,"currentAgentInfo",null);Te(this,"chatMessages",[]);Te(this,"isAgentConnected",!1);Te(this,"agentState","idle");this.config=n,this.pluginManager=new pd(this),this.rpcManager=new ex,this.setupEventListeners(),this.initializeClient()}setupEventListeners(){this.on("connection.connected",()=>{var n,s;this.isConnected=!0,(s=(n=this.config).onConnected)==null||s.call(n)}),this.on("connection.disconnected",n=>{var s,r;this.isConnected=!1,(r=(s=this.config).onDisconnected)==null||r.call(s,n)}),this.on("connection.error",n=>{var s,r;(r=(s=this.config).onError)==null||r.call(s,n)}),this.on("chat.message.received",n=>{var s,r;this.addChatMessage(n),(r=(s=this.config).onMessageReceived)==null||r.call(s,n)}),this.on("chat.message.updated",n=>{this.updateChatMessage(n)}),this.on("chat.message.sent",n=>{this.addChatMessage(n)}),this.on("transcription.received",n=>{var s,r;(r=(s=this.config).onTranscriptionReceived)==null||r.call(s,n)}),this.on("session.state.changed",n=>{var s,r;(r=(s=this.config).onSessionStateChanged)==null||r.call(s,n)}),this.on("session.created",n=>{var s,r;(r=(s=this.config).onSessionStart)==null||r.call(s,n.id)}),this.on("session.ended",(n,s)=>{var r,o;(o=(r=this.config).onSessionEnd)==null||o.call(r,s)}),this.on("participant.joined",n=>{var s,r;(r=(s=this.config).onUserJoined)==null||r.call(s,n.id)}),this.on("participant.left",n=>{var s,r;(r=(s=this.config).onUserLeft)==null||r.call(s,n.id)}),this.setupRpcEventForwarding()}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))}initializeClient(){this.room=new H.Room,this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(H.RoomEvent.Connected,()=>{var n,s;this.connectionState=H.ConnectionState.Connected,this.emit("connection.connected"),this.rpcManager.setRoom(this.room),(s=(n=this.currentSession)==null?void 0:n.activeModalities)!=null&&s.includes("voice")&&setTimeout(async()=>{var r;try{(r=this.room)!=null&&r.localParticipant&&(this.room.localParticipant.isMicrophoneEnabled?this.emit("track.unmuted",{source:"microphone",enabled:!0}):(await this.room.localParticipant.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0})))}catch(o){console.warn("VoxketClient: Failed to enable microphone after room connection:",o)}},1e3),this.textStreamHandlersRegistered||this.setupTextStreamHandlers()}),this.room.on(H.RoomEvent.Disconnected,n=>{var s;console.log("🔴 VoxketClient: Room disconnected, reason:",n),this.connectionState=H.ConnectionState.Disconnected,this.textStreamHandlersRegistered=!1,this.isAgentConnected=!1,console.log("🤖 VoxketClient: Agent marked as disconnected"),n&&console.log("🔍 VoxketClient: Disconnect reason details:",{reason:n.toString(),currentSession:(s=this.currentSession)==null?void 0:s.id,agentConnected:this.isAgentConnected,connectionState:this.connectionState}),this.emit("connection.disconnected",n==null?void 0:n.toString())}),this.room.on(H.RoomEvent.ConnectionStateChanged,n=>{this.connectionState=n,n===H.ConnectionState.Connecting&&this.emit("connection.connecting")}),this.room.on(H.RoomEvent.ParticipantConnected,n=>{const s={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.joined",s)}),this.room.on(H.RoomEvent.ParticipantDisconnected,n=>{const s={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.left",s)}))}setupTextStreamHandlers(){if(!this.room)return;try{this.room.registerTextStreamHandler("lk.chat",async(s,r)=>{try{const o=await s.readAll(),i={id:`msg_${Date.now()}_${r.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:o,timestamp:new Date,sender:{id:r.identity||"user",name:r.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.emit("chat.message.received",i)}catch(o){console.error("VoxketClient: Failed to process lk.chat message:",o)}})}catch(s){console.warn("VoxketClient: lk.chat handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("lk.transcription",async(s,r)=>{var o,i;try{const a=`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`;let c="";const d=((o=this.currentAgentInfo)==null?void 0:o.name)||r.identity||"AI Assistant",u={id:a,content:"",timestamp:new Date,sender:{id:r.identity||"agent",name:d,type:"agent"},metadata:{topic:"lk.transcription",streaming:!0}};this.emit("chat.message.received",u);for await(const y of s){c+=y;const x=this.convertMarkdownToText(c),m={...u,content:x,metadata:{...u.metadata,streaming:!0}};this.emit("chat.message.updated",m)}const f=this.convertMarkdownToText(c),h={...u,content:f,metadata:{...u.metadata,streaming:!1}};this.emit("chat.message.updated",h)}catch(a){console.error("VoxketClient: Failed to process lk.transcription message:",a);try{const c=await s.readAll(),d=((i=this.currentAgentInfo)==null?void 0:i.name)||r.identity||"AI Assistant",u={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:c,timestamp:new Date,sender:{id:r.identity||"agent",name:d,type:"agent"},metadata:{topic:"lk.transcription"}};this.emit("chat.message.received",u)}catch(c){console.error("VoxketClient: Fallback failed for lk.transcription:",c)}}})}catch(s){console.warn("VoxketClient: lk.transcription handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("suggested_response",async s=>{const r=await s.readAll();let o=[];try{o=["tes","hello how are you","algebra make me learn that ","what is the meaning of life"]}catch(i){console.warn("VoxketClient: Failed to parse suggested_response:",i,r)}this.emit("suggested.response",o)})}catch(s){console.warn("VoxketClient: suggested_response handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("agent_state_changed",async(s,r)=>{const o=await s.readAll();console.log("🤖 VoxketClient: agent_state_changed stream received:",o);let i={};try{i=typeof o=="string"?JSON.parse(o.replace(/'/g,'"')):o}catch(a){console.warn("VoxketClient: Failed to parse agent_state_changed:",a,o)}this.isAgentConnected||(this.isAgentConnected=!0,console.log("🤖 VoxketClient: Agent marked as connected (first state change received)"),this.emit("agent.connected",i)),i.new_state==="speaking"?(this.setAgentState("speaking"),this.emit("agent.speaking",i)):i.new_state==="thinking"?(this.setAgentState("thinking"),this.emit("agent.thinking",i)):(i.new_state==="idle"||i.new_state==="listening")&&this.setAgentState("idle")})}catch(s){console.warn("VoxketClient: conversation_item_added handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("images",async(s,r)=>{try{const o=await s.readAll()}catch(o){console.error("VoxketClient: Error processing images stream:",o)}})}catch(s){console.warn("VoxketClient: images handler already registered, skipping:",s)}try{this.room.registerByteStreamHandler("images",async(s,r)=>{var o,i;try{const a=s.info,c={id:`img_${Date.now()}_${r.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`�️ ${a.name||"Image"}`,sender:{id:r.identity||"agent",name:r.identity||"Agent",type:r.identity===((i=(o=this.room)==null?void 0:o.localParticipant)==null?void 0:i.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:a.name,fileSize:a.size,mimeType:a.mimeType,streamId:a.id,downloading:!0}};this.emit("chat.message.received",c),s.onProgress&&(s.onProgress=y=>{const x={...c,metadata:{...c.metadata,downloadProgress:y||0}};this.emit("chat.message.updated",x)});const d=[];for await(const y of s)d.push(y);const u=new Blob(d,{type:a.mimeType||"application/octet-stream"}),f=URL.createObjectURL(u),h={...c,metadata:{...c.metadata,downloading:!1,downloadProgress:1,downloadUrl:f,blob:u}};this.emit("chat.message.updated",h)}catch(a){console.error("VoxketClient: Error processing image attachment:",a)}})}catch(s){console.warn("VoxketClient: image handler already registered, skipping:",s)}["error","warning","status","system","debug","info"].forEach(s=>{try{this.room.registerTextStreamHandler(s,async(r,o)=>{try{const i=await r.readAll();if(console.log(`📝 VoxketClient: Received '${s}' stream:`,i),s==="error"){let a={};try{a=typeof i=="string"?JSON.parse(i):i}catch{a={message:i}}console.warn("� VoxketClient: Agent error:",a),this.emit("agent.error",a)}else this.emit("text.stream.received",{topic:s,data:i,participantInfo:o})}catch(i){console.error(`VoxketClient: Failed to process '${s}' stream:`,i)}})}catch(r){console.warn(`VoxketClient: Handler for '${s}' already registered, skipping:`,r)}});try{this.room.registerTextStreamHandler("*",async(s,r)=>{var o;try{const i=await s.readAll(),a=((o=s.info)==null?void 0:o.topic)||"unknown";console.log(`📝 VoxketClient: Received unhandled text stream for topic '${a}':`,i),this.emit("text.stream.unhandled",{topic:a,data:i,participantInfo:r})}catch(i){console.error("VoxketClient: Failed to process unhandled text stream:",i)}})}catch(s){console.warn("VoxketClient: Generic text stream handler already registered, skipping:",s)}this.textStreamHandlersRegistered=!0}async fetchConnectionDetails(n,s,r){const o=n||this.config.agentId||"default-agent",i=s||this.config.participantName||"User",a=r||this.config.modalities||["voice"];try{const c={agent_id:o,participant_name:i,participant_metadata:{user_id:""},modality:a[0],modalities:a};console.log("🔗 VoxketClient: Creating session with modalities:",a);const d=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(c)});if(!d.ok){let h=`HTTP ${d.status}: Failed to fetch connection details`;try{const y=await d.json();y&&(y.error?h=`API Error: ${y.error}`:y.detail?h=`API Error: ${y.detail}`:y.message&&(h=`API Error: ${y.message}`))}catch{try{const x=await d.text();x&&(h=`API Error: ${x}`)}catch{}}throw new Error(h)}const u=await d.json();let f;return u.agent_info&&(f={id:u.agent_info.id||o,name:u.agent_info.name||"AI Assistant",avatar:u.agent_info.avatar,capabilities:u.agent_info.capabilities||["voice_interaction","text_chat"],metadata:u.agent_info.metadata||{}},this.currentAgentInfo=f),{serverUrl:u.wss_url,participantToken:u.token,voxketSessionId:u.session_id,agentInfo:f}}catch(c){console.error("VoxketClient: fetchConnectionDetails failed:",c);const d=new ge(`Failed to fetch connection details: ${c instanceof Error?c.message:"Unknown error"}`,"CONNECTION_FAILED",c);throw this.emit("connection.error",d),d}}async connect(n,s,r){var o;try{this.emit("connection.connecting");const i=await this.fetchConnectionDetails(n,s,r);return await((o=this.room)==null?void 0:o.connect(i.serverUrl,i.participantToken)),this.isConnected=!0,i}catch(i){console.error("VoxketClient: Connection failed:",i);const a=new ge(`Failed to connect to Voxket services: ${i instanceof Error?i.message:"Unknown error"}`,"CONNECTION_FAILED",i);throw this.emit("connection.error",a),a}}async disconnect(){var n;try{await((n=this.room)==null?void 0:n.disconnect()),this.isConnected=!1,this.currentSession=null,this.currentAgentInfo=null,this.textStreamHandlersRegistered=!1,this.clearChatMessages(),this.room=new H.Room,this.setupRoomEventListeners()}catch(s){const r=new ge("Failed to disconnect properly","NETWORK_ERROR",s);throw this.emit("connection.error",r),r}}async createSession(n){var s,r,o,i;try{const a=await this.connect(n.agentId,n.participantName,n.modalities),c={id:a.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:a.agentInfo||this.currentAgentInfo};if(this.currentSession=c,this.emit("session.created",c),(s=n.modalities)!=null&&s.includes("voice"))try{await new Promise(d=>setTimeout(d,500)),(r=this.room)!=null&&r.localParticipant?(await this.room.localParticipant.setMicrophoneEnabled(!0,void 0,{preConnectBuffer:!0}),this.emit("track.unmuted",{source:"microphone",enabled:!0})):console.warn("VoxketClient: No local participant found, microphone not enabled")}catch(d){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",d)}if((o=n.modalities)!=null&&o.includes("video"))try{await new Promise(d=>setTimeout(d,200)),(i=this.room)!=null&&i.localParticipant&&(console.log("🎥 VoxketClient: Attempting to enable camera for video session"),await this.room.localParticipant.setCameraEnabled(!0),this.emit("track.unmuted",{source:"camera",enabled:!0}),console.log("🎥 VoxketClient: Camera enabled successfully"))}catch(d){console.warn("VoxketClient: Failed to enable camera, but continuing with session:",d)}return setTimeout(()=>{var d;this.currentSession&&(this.currentSession.state="active",this.emit("session.state.changed","active",this.currentSession.state),this.forceAgentConnected(),console.log("🤖 VoxketClient: Session marked as active:",{sessionId:this.currentSession.id,modalities:this.currentSession.activeModalities,agentConnected:this.isAgentConnected,hasRoom:!!this.room,remoteParticipants:((d=this.room)==null?void 0:d.remoteParticipants.size)||0}))},1e3),c}catch(a){throw console.error("VoxketClient: Failed to create session:",a),a instanceof ge?a:a instanceof TypeError&&a.message.includes("fetch")?new ge("Network connection failed","CONNECTION_FAILED",a):a instanceof Error&&a.message.includes("Failed to fetch connection details")?new ge(`API connection failed: ${a.message}`,"CONNECTION_FAILED",a):new ge(`Failed to create session: ${a instanceof Error?a.message:"Unknown error"}`,"SESSION_NOT_FOUND",a)}}async startSession(n,s){const r={agentId:n||this.config.agentId||"default-agent",participantName:(s==null?void 0:s.participantName)||this.config.participantName||"User",modalities:(s==null?void 0:s.modalities)||this.config.modalities||["voice","chat"],metadata:s==null?void 0:s.metadata};return this.createSession(r)}async endSession(){var n,s;if(!this.currentSession)return null;try{const r={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((s=this.room)==null?void 0:s.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]};return this.currentSession.endedAt=new Date,this.currentSession.state="disconnected",this.emit("session.ended",this.currentSession,r),await this.disconnect(),r}catch(r){throw new ge("Failed to end session","SESSION_NOT_FOUND",r)}}getCurrentSession(){return this.currentSession}getCurrentAgentInfo(){return this.currentAgentInfo}getIsAgentConnected(){return this.isAgentConnected}forceAgentConnected(){this.isAgentConnected||(this.isAgentConnected=!0,console.log("🤖 VoxketClient: Agent manually marked as connected"),this.emit("agent.connected",{forced:!0}))}getAgentState(){return this.agentState}setAgentState(n){this.agentState!==n&&(this.agentState=n,this.emit("agent.state.changed",{state:n}))}getAgentAudioTrack(){const n=this.getRemoteParticipants();for(const s of n){const r=s.getTrackPublication(H.Track.Source.Microphone);if(r!=null&&r.track)return{source:H.Track.Source.Microphone,participant:s,publication:r}}return null}getAgentVideoTrack(){const n=this.getRemoteParticipants();for(const s of n){const r=s.getTrackPublication(H.Track.Source.Camera);if(r!=null&&r.track)return{source:H.Track.Source.Camera,participant:s,publication:r}}return null}getVideoTrackRefs(){const n=[],s=this.getLocalParticipant();if(s){const o=s.getTrackPublication(H.Track.Source.Camera);o!=null&&o.track&&n.push({source:H.Track.Source.Camera,participant:s,publication:o});const i=s.getTrackPublication(H.Track.Source.ScreenShare);i!=null&&i.track&&n.push({source:H.Track.Source.ScreenShare,participant:s,publication:i})}const r=this.getRemoteParticipants();for(const o of r){const i=o.getTrackPublication(H.Track.Source.Camera);i!=null&&i.track&&n.push({source:H.Track.Source.Camera,participant:o,publication:i});const a=o.getTrackPublication(H.Track.Source.ScreenShare);a!=null&&a.track&&n.push({source:H.Track.Source.ScreenShare,participant:o,publication:a})}return n}getCameraTrackRefs(){return this.getVideoTrackRefs().filter(n=>n.source===H.Track.Source.Camera)}getScreenShareTrackRefs(){return this.getVideoTrackRefs().filter(n=>n.source===H.Track.Source.ScreenShare)}getChatMessages(){return[...this.chatMessages]}addChatMessage(n){this.chatMessages.some(r=>r.id===n.id)||this.chatMessages.push(n)}updateChatMessage(n){const s=this.chatMessages.findIndex(r=>r.id===n.id);s!==-1&&(this.chatMessages[s]=n)}clearChatMessages(){this.chatMessages=[],this.dismissCurrentInteraction(),this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays(),this.emit("chat.history.cleared")}renderUI(n={}){var c,d,u;const s=this.resolveTarget(n.target||"body"),r=this.getTargetKey(s),o=this.renderedComponents.get(r);o&&o.target===s||this.removeUI(s);const i=(o==null?void 0:o.root)||_d.createRoot(s),a={agentId:n.agentId||this.config.agentId||"default-agent",participantName:n.participantName||this.config.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:n.className,theme:typeof n.theme=="string"?n.theme:void 0,modalities:n.modality||this.config.modalities||["voice"],suportsChatInput:((c=n.modality)==null?void 0:c.includes("chat"))!==!1,suportsVideoInput:((d=n.modality)==null?void 0:d.includes("video"))===!0,suportsScreenShare:((u=n.modality)==null?void 0:u.includes("screen_share"))===!0,autoStart:n.autoStart,displayType:n.displayType||"widget",popupPosition:n.popupPosition||"bottom-right",popupTriggerText:n.popupTriggerText||"Open Chat",width:n.width,height:n.height,onDisplayTypeChange:n.onDisplayTypeChange,prompts:n.prompts,statusMessage:n.statusMessage,welcomeTitle:n.welcomeTitle,welcomeSubTitle:n.welcomeSubTitle,loadingText:n.loadingText,voxketClient:this};if(!i||typeof i.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{i.render(C.createElement(yd,{config:this.config,autoConnect:n.autoStart||!1,children:C.createElement(xd,a)}))}catch(f){throw console.error("Error rendering Voxket widget:",f),new Error(`Failed to render Voxket widget: ${f instanceof Error?f.message:"Unknown error"}`)}this.renderedComponents.set(r,{root:i,target:s})}removeUI(n){const s=n?this.resolveTarget(n):null;if(s){const r=this.getTargetKey(s),o=this.renderedComponents.get(r);o&&(o.root.unmount(),this.renderedComponents.delete(r),s.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(a=>{try{a.remove()}catch(c){console.warn("Failed to remove element:",c)}}),s===document.body&&s.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(c=>{if(c.classList.contains("bg-black")&&c.classList.contains("backdrop-blur-sm"))try{c.remove()}catch(d){console.warn("Failed to remove fixed element:",d)}}))}}removeAllUI(){for(const[n,s]of this.renderedComponents)s.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(s=>{if(s.classList.contains("bg-black")&&(s.classList.contains("backdrop-blur-sm")||s.classList.contains("bg-opacity-30")))try{s.remove()}catch(r){console.warn("Failed to remove overlay:",r)}})}resolveTarget(n){if(typeof n=="string"){const s=document.querySelector(n);if(!s)throw new Error(`Target element not found: ${n}`);return s}return n}getTargetKey(n){return n.id?n.id:n.className?n.tagName+"_"+n.className.replace(/\s+/g,"_"):n.tagName+"_"+n.outerHTML.length%1e3}async sendMessage(n,s){var r;if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new ge("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new ge("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new ge("No local participant","CONNECTION_FAILED");this.dismissCurrentInteraction();try{const o={id:`msg_${Date.now()}`,content:n,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:s||{}},i=await((r=this.room)==null?void 0:r.localParticipant.sendText(n,{topic:"lk.chat",destinationIdentities:[]}));this.emit("chat.message.sent",o)}catch(o){throw console.error("VoxketClient: Failed to send chat message:",o),new ge("Failed to send message","NETWORK_ERROR",o)}}async sendChatMessage(n,s){return this.sendMessage(n,s)}async sendAttachments(n,s){if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new ge("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new ge("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new ge("No local participant","CONNECTION_FAILED");if(!n||n.length===0)throw new ge("No files provided","INVALID_PARAMETER");this.dismissCurrentInteraction();const r=n.filter(o=>o.type.startsWith("image/"));if(r.length===0)throw new ge("Only image files are allowed","INVALID_PARAMETER");r.length!==n.length&&console.warn("VoxketClient: Some non-image files were filtered out");try{const o=r.map(async(i,a)=>{const d={id:`att_${Date.now()}_${a}`,content:`📎 ${i.name}`,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:{...s,type:"attachment",fileName:i.name,fileSize:i.size,mimeType:i.type,uploading:!0}};this.emit("chat.message.sent",d);const u=await this.room.localParticipant.sendFile(i,{mimeType:i.type,topic:"images",onProgress:h=>{const y={...d,metadata:{...d.metadata,uploadProgress:h}};this.emit("chat.message.updated",y)}});try{const h=new FileReader,y=new Promise((b,k)=>{h.onload=()=>{typeof h.result=="string"?b(h.result):k(new Error("Failed to convert to base64"))},h.onerror=k});h.readAsDataURL(i);const m={type:"image",data:await y,filename:i.name,mimeType:i.type,size:i.size};await this.room.localParticipant.sendText(JSON.stringify(m),{topic:"images",destinationIdentities:[]})}catch(h){console.warn("VoxketClient: Failed to send image data to agent:",h);try{const y=`I've shared an image: ${i.name}`;await this.room.localParticipant.sendText(y,{topic:"lk.chat",destinationIdentities:[]})}catch(y){console.warn("VoxketClient: Failed to send image notification to agent:",y)}}const f={...d,metadata:{...d.metadata,uploading:!1,uploadProgress:1,streamId:u.id}};return this.emit("chat.message.updated",f),u});await Promise.all(o)}catch(o){throw console.error("VoxketClient: Failed to send attachments:",o),new ge("Failed to send attachments","NETWORK_ERROR",o)}}async sendAttachment(n,s){return this.sendAttachments([n],s)}toggleMicrophone(n){return this.setMicrophoneEnabled(n!==!1)}async setMicrophoneEnabled(n){var s,r;try{const o=(s=this.room)==null?void 0:s.localParticipant.isMicrophoneEnabled,i=n??!o;await((r=this.room)==null?void 0:r.localParticipant.setMicrophoneEnabled(i)),i?this.emit("track.unmuted",{source:"microphone",enabled:!0}):this.emit("track.muted",{source:"microphone",enabled:!1})}catch(o){throw console.error("VoxketClient: Failed to toggle microphone:",o),new ge("Failed to toggle microphone","PERMISSION_DENIED",o)}}toggleCamera(n){return this.setCameraEnabled(n!==!1)}async setCameraEnabled(n){var s,r;try{const o=(s=this.room)==null?void 0:s.localParticipant.isCameraEnabled,i=n??!o;await((r=this.room)==null?void 0:r.localParticipant.setCameraEnabled(i)),i?this.emit("track.unmuted",{source:"camera",enabled:!0}):this.emit("track.muted",{source:"camera",enabled:!1})}catch(o){throw console.error("VoxketClient: Failed to toggle camera:",o),new ge("Failed to toggle camera","PERMISSION_DENIED",o)}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!0))}catch(s){throw new ge("Failed to start screen share","PERMISSION_DENIED",s)}}async stopScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!1))}catch(s){throw new ge("Failed to stop screen share","PERMISSION_DENIED",s)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(s=>s.kind==="audioinput")}catch(n){throw new ge("Failed to get audio input devices","DEVICE_ERROR",n)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(s=>s.kind==="videoinput")}catch(n){throw new ge("Failed to get video input devices","DEVICE_ERROR",n)}}async setAudioInputDevice(n){var s;try{if(!((s=this.room)!=null&&s.localParticipant))throw new Error("Not connected to room")}catch(r){throw new ge("Failed to set audio input device","DEVICE_ERROR",r)}}async setVideoInputDevice(n){var s;try{if(!((s=this.room)!=null&&s.localParticipant))throw new Error("Not connected to room")}catch(r){throw new ge("Failed to set video input device","DEVICE_ERROR",r)}}getLocalParticipant(){var n;return((n=this.room)==null?void 0:n.localParticipant)??null}getRemoteParticipants(){var n;return Array.from(((n=this.room)==null?void 0:n.remoteParticipants.values())??[])}getPublishPermissions(){const n=this.getLocalParticipant();if(!n)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const s=n.permissions;if(!s)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const r=o=>!!s.canPublish&&(s.canPublishSources.length===0||s.canPublishSources.includes(o));return{camera:r(1),microphone:r(2),screenShare:r(3),data:s.canPublishData??!1}}canPublishSource(n){return this.getPublishPermissions()[n]}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===H.ConnectionState.Connected}getMicrophoneTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,s]of n.trackPublications)if(s.source===H.Track.Source.Microphone)return s.track;return null}getCameraTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,s]of n.trackPublications)if(s.source===H.Track.Source.Camera)return s.track;return null}getScreenShareTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,s]of n.trackPublications)if(s.source===H.Track.Source.ScreenShare)return s.track;return null}get isMicrophoneEnabled(){const n=this.getMicrophoneTrack();return n?!n.isMuted:!1}get isCameraEnabled(){const n=this.getCameraTrack();return n?!n.isMuted:!1}get isScreenShareEnabled(){const n=this.getScreenShareTrack();return n?!n.isMuted:!1}registerPlugin(n){this.pluginManager.register(n)}getPluginManager(){return this.pluginManager}getParticipants(){if(!this.room)return[];const n=[];return this.room.localParticipant&&n.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(s=>{n.push({id:s.identity,name:s.name||s.identity,isLocal:!1})}),n}getSessionMetrics(){var n,s;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((s=this.room)==null?void 0:s.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}updateConfig(n){this.config={...this.config,...n}}async startRecording(){var n;try{this.emit("recording.started",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(s){throw new ge("Failed to start recording","RECORDING_ERROR",s)}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(s){throw new ge("Failed to stop recording","RECORDING_ERROR",s)}}async registerFrontendRPC(n,s,r="embedded"){return this.rpcManager.registerFrontendRPC(n,s,r)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}registerEventListener(n,s){return this.on(n,s)}registerEventEmitter(n,s){if(!this.room)throw new Error("Room not available");try{this.room.registerTextStreamHandler(n,async r=>{try{const o=await r.readAll();s(o)}catch(o){console.error(`Error processing event for topic '${n}':`,o)}})}catch(r){console.warn(`VoxketClient: Handler for topic '${n}' may already be registered:`,r)}}convertMarkdownToText(n){if(!n)return"";let s=n;return s=s.replace(/\*\*(.*?)\*\*/g,"$1"),s=s.replace(/__(.*?)__/g,"$1"),s=s.replace(/\*(.*?)\*/g,"$1"),s=s.replace(/_(.*?)_/g,"$1"),s=s.replace(/~~(.*?)~~/g,"$1"),s=s.replace(/`([^`]+)`/g,"$1"),s=s.replace(/```[\s\S]*?```/g,""),s=s.replace(/^#{1,6}\s+/gm,""),s=s.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),s.trim()}}const tx=le.create(R1),nx=le.create(z1),sx=le.create(Z1),rx=le.create(Y1);function ox({onClick:e,text:t="Open Chat",position:n="bottom-right",theme:s}){const r=De(s);return l.jsx(le.button,{onClick:e,className:`voxket-popup-trigger ${r.popupTrigger}`,initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},exit:{scale:0,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},"data-position":n,children:t})}function Ga({children:e,theme:t,displayType:n="widget",onClose:s,popupPosition:r="bottom-right",onExpand:o}){const i=De(t);if(n==="fullscreen")return l.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&&s&&s()},children:l.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:[s&&l.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),s()},className:"absolute top-4 cursor-pointer right-4 z-[10000] w-12 h-12 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 shadow-lg border border-gray-700 backdrop-blur-sm",title:"Exit Fullscreen",type:"button",children:l.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:l.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"})})}),l.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${i.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"},children:[l.jsx("div",{className:i.cardTopGradient}),l.jsx("div",{className:i.cardPurpleBlur}),l.jsx("div",{className:i.cardPinkBlur}),l.jsx("div",{className:"relative z-10 flex flex-col h-full",children:e}),l.jsx("div",{className:i.cardPulse1}),l.jsx("div",{className:i.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 l.jsx("div",{className:"fixed rounded-2xl inset-0 z-[9999] pointer-events-none",children:l.jsxs("div",{className:`fixed rounded-2xl ${a[r]} pointer-events-auto`,children:[s&&l.jsx("button",{onClick:s,className:"absolute -top-2 -right-2 z-10 w-8 h-8 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 text-sm shadow-lg border border-gray-700",children:"×"}),l.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${i.card} rounded-2xl flex flex-col relative overflow-hidden`,"data-theme":t,style:{width:"350px",height:"500px",contain:"layout style paint",overscrollBehavior:"contain"},children:[l.jsx("div",{className:i.cardTopGradient}),l.jsx("div",{className:i.cardPurpleBlur}),l.jsx("div",{className:i.cardPinkBlur}),l.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),l.jsx("div",{className:i.cardPulse1}),l.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return l.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${i.card} relative overflow-hidden`,"data-theme":t,style:{height:"100%",maxHeight:"100%",contain:"layout style paint",overscrollBehavior:"contain"},children:[l.jsx("div",{className:i.cardTopGradient}),l.jsx("div",{className:i.cardPurpleBlur}),l.jsx("div",{className:i.cardPinkBlur}),l.jsx("div",{className:"relative z-10 flex flex-col h-full",children:e}),l.jsx("div",{className:i.cardPulse1}),l.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})}function xd(e){if(typeof window>"u")return null;console.log("🎯 Widget component rendering with props:",{displayType:e.displayType,popupPosition:e.popupPosition,theme:e.theme});const{agentId:t,participantName:n,baseUrl:s,appSecret:r,appId:o,prompts:i,statusMessage:a,welcomeTitle:c,welcomeSubTitle:d,className:u,width:f,height:h,loadingText:y,suportsChatInput:x=!0,suportsVideoInput:m=!0,suportsScreenShare:b=!0,theme:k="vox",onSessionStart:w,onSessionEnd:T,enableSessionLogging:v=!0,onSessionLogsUpdate:S,onSessionMetricsUpdate:A,modalities:V=["voice"],displayType:E="widget",popupPosition:O="bottom-right",popupTriggerText:g="Open Chat",onPopupToggle:D,voxketClient:L,onDisplayTypeChange:Q}=e,[ee,ne]=p.useState(()=>L?!!L.getCurrentSession():!1),[re,Y]=p.useState(!1),[M,J]=p.useState(t||""),[P,B]=p.useState(n||"User"),[K,U]=p.useState(()=>L?L.getCurrentSession():null),[j,$]=p.useState(()=>{var de,Qe,ot;if(L){const ke=L.getCurrentSession();if((de=ke==null?void 0:ke.activeModalities)!=null&&de.includes("chat"))return"chat";if((Qe=ke==null?void 0:ke.activeModalities)!=null&&Qe.includes("voice"))return"voice";if((ot=ke==null?void 0:ke.activeModalities)!=null&&ot.includes("video"))return"video"}return"welcome"}),[W,z]=p.useState(!1);p.useEffect(()=>{console.log("🎯 Widget displayType prop changed to:",E)},[E]),p.useEffect(()=>{console.log("📊 Session state changed:",{currentMode:j,sessionStarted:ee,loading:re,currentSession:K==null?void 0:K.id,isPopupOpen:W})},[j,ee,re,K,W]);const _=p.useMemo(()=>{if(L)return console.log("🔄 Using passed VoxketClient to preserve session state"),L;console.log("🆕 Creating new VoxketClient instance");const de={appId:o,appSecret:r,baseUrl:s,agentId:M,participantName:P||"User",modalities:V};return new Dn(de)},[L,o,r,s,M,P,V]),I=V,F=p.useMemo(()=>_.getRoom()||new H.Room,[_]),oe={suportsChatInput:x,suportsVideoInput:m,suportsScreenShare:b};p.useEffect(()=>{(j==="voice"||j==="video"||j==="chat")&&!K&&!ee&&!re&&!_.connected&&(console.log("🔄 Auto-correcting: Found orphaned mode without session, returning to welcome"),$("welcome"))},[j,K,ee,re,_]);const{sessionMetrics:R,sessionLogs:X,logEvent:se}=md({room:F,onSessionStart:w,onSessionEnd:T,enableConsoleLogging:v,enableLocalStorage:v,voxketSessionId:K==null?void 0:K.id});p.useEffect(()=>{S&&S(X)},[X,S]),p.useEffect(()=>{A&&R&&A(R)},[R,A]),p.useEffect(()=>{const de=ot=>{console.log("🔴 Widget: Room disconnected:",ot),console.log("🔍 Widget: Current state on disconnect:",{currentMode:j,sessionStarted:ee,currentSessionId:K==null?void 0:K.id}),Y(!1),ne(!1),U(null),j!=="welcome"?(console.log("🔄 Widget: Setting mode to welcome after disconnect"),$("welcome")):console.log("📝 Widget: Already in welcome mode, no change needed")},Qe=ot=>{console.log("📹 Media devices error:",ot)};return F.on(H.RoomEvent.MediaDevicesError,Qe),F.on(H.RoomEvent.Disconnected,de),()=>{F.off(H.RoomEvent.Disconnected,de),F.off(H.RoomEvent.MediaDevicesError,Qe)}},[F]);const ie=async()=>{try{console.log("🎤 Starting voice session...",{agentId:M,participantName:P}),console.log("🎤 Pre-start state:",{currentMode:j,sessionStarted:ee,loading:re}),Y(!0),se("USER_STARTED_VOICE_SESSION",{agentId:M,participantName:P});const de=await _.startSession(M,{participantName:P||"User",modalities:["voice",...m?["video"]:[]]});console.log("✅ Voice session started successfully:",de.id),U(de),ne(!0),$("voice"),Y(!1),w&&w(de.id)}catch(de){console.error("❌ Failed to start voice session:",de),Y(!1),ne(!1),$("welcome")}},ae=async()=>{try{Y(!0),ne(!0),$("chat"),se("USER_STARTED_CHAT_SESSION",{agentId:M,participantName:P});const de=await _.startSession(M,{participantName:P||"User",modalities:["chat"]});U(de),Y(!1),w&&w(de.id)}catch(de){console.error("Failed to start chat session:",de),Y(!1),ne(!1),$("welcome")}},$e=async()=>{try{console.log("📺 Starting video session...",{agentId:M,participantName:P}),console.log("📺 Pre-start state:",{currentMode:j,sessionStarted:ee,loading:re}),Y(!0),se("USER_STARTED_VIDEO_SESSION",{agentId:M,participantName:P});const de=await _.startSession(M,{participantName:P||"User",modalities:["video","voice"]});console.log("✅ Video session started successfully:",de.id),U(de),ne(!0),$("video"),Y(!1),w&&w(de.id)}catch(de){console.error("❌ Failed to start video session:",de),Y(!1),ne(!1),$("welcome")}},Re=()=>{console.log("🔄 Widget: handleBackToWelcome called",{currentMode:j,sessionStarted:ee,currentSessionId:K==null?void 0:K.id,displayType:E}),$("welcome"),Q&&Q(e.displayType||"widget"),K&&ee?(console.log("🧹 Widget: Cleaning up active session"),ne(!1),U(null),_.connected?(console.log("🔌 Widget: Disconnecting client"),_.disconnect()):console.log("🔌 Widget: Client already disconnected")):console.log("📝 Widget: No active session to clean up"),E==="popup"&&!W&&z(!0),console.log("✅ Widget: handleBackToWelcome completed")},we=()=>{const de=!W;z(de),D&&D(de),!de&&!(K&&ee)&&($("welcome"),ne(!1),U(null))},Be=()=>{console.log("🔄 Closing fullscreen, switching to widget display type"),e.onDisplayTypeChange?e.onDisplayTypeChange("widget"):console.warn("⚠️ No onDisplayTypeChange callback provided")},rt=()=>{if(console.log("🔄 Expand to fullscreen requested"),e.onDisplayTypeChange)e.onDisplayTypeChange("fullscreen");else{console.warn("⚠️ No onDisplayTypeChange callback provided for expand functionality");const de=document.getElementById("voice-card")||document.querySelector(".voxket-widget-container");de&&de.requestFullscreen&&de.requestFullscreen().catch(Qe=>{console.warn("⚠️ Fullscreen API not supported or failed:",Qe)})}};p.useEffect(()=>{var de,Qe,ot;if(L&&_){console.log("🔄 Syncing widget state with existing client session state");const ke=_.getCurrentSession(),Id=_.connected;console.log("🔍 Existing session state:",{hasSession:!!ke,sessionId:ke==null?void 0:ke.id,isConnected:Id,activeModalities:ke==null?void 0:ke.activeModalities}),ke&&(console.log("✅ Restoring session state from existing client"),U(ke),ne(!0),Y(!1),(de=ke.activeModalities)!=null&&de.includes("chat")?$("chat"):(Qe=ke.activeModalities)!=null&&Qe.includes("voice")?$("voice"):(ot=ke.activeModalities)!=null&&ot.includes("video")&&$("video"))}},[L,_]),p.useEffect(()=>()=>{console.log("🧹 Cleaning up widget component"),L?console.log("🔄 Widget cleanup: preserving passed client instance"):(console.log("🧹 Widget cleanup: disconnecting self-created client"),_.disconnect())},[_,L]);let Dt="w-96",js="h-[25rem]",Ms={};if(f&&(f.startsWith("w-")?Dt=f:(Ms.width=f,Dt="")),h&&(h.startsWith("h-")?js=h:(Ms.height=h,js="")),E==="popup"&&!W)return console.log("🟡 Showing popup trigger button"),l.jsx(ox,{onClick:we,text:g,position:O,theme:k});console.log("🟢 Rendering widget content, displayType:",E,"isPopupOpen:",W,"currentMode:",j,"sessionStarted:",ee,"loading:",re);let Ps=`voxket-widget-root theme-${k}`,Fn={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};E==="widget"?(Ps+=` flex items-center justify-center min-h-fit ${Dt} ${js} ${u}`,Fn={...Fn,...Ms}):(Ps=`${u||""}`,Fn={});const Oo=l.jsx("div",{className:"h-full flex flex-col overflow-hidden relative z-10",children:l.jsxs(Yt,{mode:"wait",children:[j==="welcome"&&!re&&l.jsx(rx,{agentId:M,participantName:P||"",onAgentIdChange:J,onParticipantNameChange:B,onStartCall:ie,onStartChat:ae,onStartVideo:$e,disabled:ee||re,prompts:i,statusMessage:a,title:c,subTitle:d,theme:k,modalities:I,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),j==="voice"&&l.jsxs(Fe.RoomContext.Provider,{value:F,children:[l.jsx(Fe.RoomAudioRenderer,{}),l.jsx(Fe.StartAudio,{label:"Start Audio"}),l.jsx(tx,{loadingText:y,participantName:P||"User",capabilities:oe,sessionStarted:ee,disabled:!ee,theme:k,client:_,displayType:E,onBack:E==="popup"?we:Re,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"session-view")]}),j==="chat"&&l.jsx(nx,{client:_,theme:k,displayType:E,onBack:E==="popup"?we:Re,onEndChat:Re,disabled:!ee,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),j==="video"&&l.jsxs(Fe.RoomContext.Provider,{value:F,children:[l.jsx(Fe.RoomAudioRenderer,{}),l.jsx(Fe.StartAudio,{label:"Start Audio"}),l.jsx(sx,{client:_,theme:k,displayType:E,onBack:E==="popup"?we:Re,onEndCall:Re,disabled:!ee,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-view")]})]})});return E==="fullscreen"||E==="popup"?(console.log("📱 Rendering fullscreen/popup mode, displayType:",E),l.jsx(Ga,{theme:k,displayType:E,popupPosition:O,onClose:E==="fullscreen"?Be:we,children:Oo})):(console.log("📦 Rendering widget mode"),l.jsx("div",{className:Ps,style:Fn,children:l.jsx(Ga,{theme:k,displayType:E,popupPosition:O,onExpand:rt,children:Oo})}))}class bd 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}}function ix({logs:e,onClear:t,onExport:n}){const[s,r]=C.useState(!1),[o,i]=C.useState(""),a=e.filter(c=>!o||c.event.toLowerCase().includes(o.toLowerCase()));return s?l.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[l.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"text",placeholder:"Filter events...",value:o,onChange:c=>i(c.target.value),className:"px-3 py-1 border rounded text-sm"}),l.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),l.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),l.jsx("button",{onClick:()=>r(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),l.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?l.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):l.jsx("div",{className:"space-y-2",children:a.map((c,d)=>l.jsxs("div",{className:"border rounded p-3 text-sm",children:[l.jsxs("div",{className:"flex items-center justify-between mb-1",children:[l.jsx("span",{className:"font-semibold text-blue-600",children:c.event}),l.jsx("span",{className:"text-gray-500 text-xs",children:new Date(c.timestamp).toLocaleTimeString()})]}),c.sessionId&&l.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",c.sessionId]}),c.data&&l.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:l.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(c.data,null,2)})})]},d))})})]})}):l.jsxs("button",{onClick:()=>r(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",e.length,")"]})}function ax({metrics:e}){return e?l.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[l.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),l.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Session ID:"}),l.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Start Time:"}),l.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Messages:"}),l.jsx("div",{children:e.totalMessages})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Participants:"}),l.jsx("div",{children:e.participantCount})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),l.jsx("div",{children:e.connectionIssues})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Duration:"}),l.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function It(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:s,endSession:r}=st(),o=C.useCallback(async(a,c)=>await s(a,c),[s]),i=C.useCallback(async()=>await r(),[r]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:o,stop:i}}function vd(){const{sessionMetrics:e,currentSession:t}=st();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 wd(){const{setMicrophoneEnabled:e,client:t}=st(),[n,s]=C.useState(!1),[r,o]=C.useState(!1),i=C.useCallback(async()=>{if(!r){o(!0);try{const d=!n;await e(d),s(d)}catch(d){console.error("Failed to toggle microphone:",d)}finally{o(!1)}}},[n,r,e]),a=C.useCallback(async()=>{if(!(n||r)){o(!0);try{await e(!0),s(!0)}catch(d){console.error("Failed to enable microphone:",d)}finally{o(!1)}}},[n,r,e]),c=C.useCallback(async()=>{if(!(!n||r)){o(!0);try{await e(!1),s(!1)}catch(d){console.error("Failed to disable microphone:",d)}finally{o(!1)}}},[n,r,e]);return{isEnabled:n,isLoading:r,toggle:i,enable:a,disable:c}}function Sd(){const{setCameraEnabled:e}=st(),[t,n]=C.useState(!1),[s,r]=C.useState(!1),o=C.useCallback(async()=>{if(!s){r(!0);try{const c=!t;await e(c),n(c)}catch(c){console.error("Failed to toggle camera:",c)}finally{r(!1)}}},[t,s,e]),i=C.useCallback(async()=>{if(!(t||s)){r(!0);try{await e(!0),n(!0)}catch(c){console.error("Failed to enable camera:",c)}finally{r(!1)}}},[t,s,e]),a=C.useCallback(async()=>{if(!(!t||s)){r(!0);try{await e(!1),n(!1)}catch(c){console.error("Failed to disable camera:",c)}finally{r(!1)}}},[t,s,e]);return{isEnabled:t,isLoading:s,toggle:o,enable:i,disable:a}}function Cd(){const{startScreenShare:e,stopScreenShare:t}=st(),[n,s]=C.useState(!1),[r,o]=C.useState(!1),i=C.useCallback(async()=>{if(!(n||r)){o(!0);try{await e(),s(!0)}catch(d){console.error("Failed to start screen share:",d)}finally{o(!1)}}},[n,r,e]),a=C.useCallback(async()=>{if(!(!n||r)){o(!0);try{await t(),s(!1)}catch(d){console.error("Failed to stop screen share:",d)}finally{o(!1)}}},[n,r,t]),c=C.useCallback(async()=>{n?await a():await i()},[n,i,a]);return{isSharing:n,isLoading:r,start:i,stop:a,toggle:c}}function cx(){const{client:e}=st(),[t,n]=C.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),s=C.useMemo(()=>t.tracks.find(m=>m.isLocal),[t.tracks]),r=C.useMemo(()=>t.tracks.filter(m=>!m.isLocal),[t.tracks]),o=C.useCallback(async()=>{try{s!=null&&s.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,s]),i=C.useCallback(async()=>{try{t.tracks.find(b=>b.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=C.useCallback(m=>{n(b=>({...b,layout:m}))},[]),c=C.useCallback(m=>{n(b=>({...b,pinnedTrack:m}))},[]),d=C.useCallback(()=>{n(m=>({...m,pinnedTrack:void 0}))},[]),u=C.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]),f=C.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]),h=C.useCallback(m=>t.tracks.find(b=>b.id===m),[t.tracks]),y=C.useCallback(m=>t.tracks.filter(b=>b.participantId===m),[t.tracks]),x=C.useCallback(m=>m.isEnabled&&t.tracks.includes(m),[t.tracks]);return C.useEffect(()=>{if(!e)return;const m=w=>{n(T=>({...T,tracks:[...T.tracks.filter(v=>v.id!==w.id),w]}))},b=w=>{n(T=>{var v;return{...T,tracks:T.tracks.filter(S=>S.id!==w),pinnedTrack:((v=T.pinnedTrack)==null?void 0:v.id)===w?void 0:T.pinnedTrack}})},k=w=>{n(T=>({...T,tracks:T.tracks.map(v=>v.id===w.id?w:v)}))};return e.on("videoTrackAdded",m),e.on("videoTrackRemoved",b),e.on("videoTrackUpdated",k),()=>{e.off("videoTrackAdded",m),e.off("videoTrackRemoved",b),e.off("videoTrackUpdated",k)}},[e]),{tracks:t.tracks,localTrack:s,remoteTraracks:r,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:o,toggleScreenShare:i,setLayout:a,pinTrack:c,unpinTrack:d,startRecording:u,stopRecording:f,getTrackById:h,getTracksByParticipant:y,isTrackActive:x}}function As(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=st(),[s,r]=C.useState(!1),o=C.useCallback(async d=>{if(!(!d.trim()||s||!n)){r(!0);try{await t(d.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{r(!1)}}},[t,s,n]),{userMessages:i,agentMessages:a,allMessages:c}=C.useMemo(()=>{const d=e.filter(f=>f.sender.type==="participant"),u=e.filter(f=>f.sender.type==="agent");return{userMessages:d,agentMessages:u,allMessages:e}},[e]);return{messages:c,userMessages:i,agentMessages:a,messageCount:c.length,isSending:s,canSend:!!n&&!s,send:o}}function lx(){const{send:e,isSending:t,canSend:n}=As(),[s,r]=C.useState(""),o=C.useCallback(async()=>{if(!(!s.trim()||!n))try{await e(s),r("")}catch(a){throw a}},[s,e,n]),i=C.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),o())},[o]);return{value:s,setValue:r,send:o,handleKeyPress:i,isSending:t,canSend:n&&s.trim().length>0}}function Io(){const{isConnected:e,isConnecting:t,connectionError:n,connect:s,disconnect:r}=st(),o=C.useCallback(async()=>{if(!(e||t))try{await s()}catch(a){throw console.error("Failed to connect:",a),a}},[s,e,t]),i=C.useCallback(async()=>{if(e)try{await r()}catch(a){throw console.error("Failed to disconnect:",a),a}},[r,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:o,disconnect:i}}function kd(){const{participants:e}=st();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const Td=C.createContext({}),$n=()=>C.useContext(Td);function Ed({children:e,...t}){return l.jsx(Td.Provider,{value:t,children:e})}function ts({name:e,children:t,fallback:n,className:s}){return l.jsx("div",{className:`voxket-slot voxket-slot--${e} ${s||""}`,children:t||n})}function Ad(e,t={}){return Object.assign(e,t)}function jd({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:s=!0,customControls:r,className:o=""}){const i=It(),a=wd(),c=Sd(),d=Cd(),u=$n(),f=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,i.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",o].filter(Boolean).join(" ");return!i.isActive&&!s?l.jsx("div",{className:f,children:l.jsx("div",{className:"voxket-controls-inactive",children:l.jsx("p",{children:"Controls available during active session"})})}):l.jsxs("div",{className:f,children:[s&&l.jsx("div",{className:"voxket-session-actions",children:i.isActive?l.jsx("button",{onClick:i.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):l.jsx(dx,{})}),i.isActive&&l.jsxs("div",{className:"voxket-media-controls",children:[e&&l.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:[l.jsx("span",{className:"voxket-icon",children:"🎤"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&l.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isEnabled?"voxket-button--active":""}`,title:c.isEnabled?"Stop camera":"Start camera",children:[l.jsx("span",{className:"voxket-icon",children:"📹"}),c.isLoading?"Loading...":c.isEnabled?"Stop Video":"Start Video"]}),n&&l.jsxs("button",{onClick:d.toggle,disabled:d.isLoading,className:`voxket-button voxket-button--media ${d.isSharing?"voxket-button--active":""}`,title:d.isSharing?"Stop screen share":"Start screen share",children:[l.jsx("span",{className:"voxket-icon",children:"🖥️"}),d.isLoading?"Loading...":d.isSharing?"Stop Share":"Share Screen"]})]}),r&&l.jsx("div",{className:"voxket-custom-controls",children:r})]})}function dx(){It();const[e,t]=C.useState(!1),n=async()=>{t(!0);try{console.log("Start session - agentId needed")}catch(s){console.error("Failed to start session:",s)}finally{t(!1)}};return l.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function Do({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:s=""}){const r=It(),o=Io(),i=$n(),a=["voxket-session-header",`voxket-session-header--${i.variant||"default"}`,`voxket-session-header--${i.size||"md"}`,s].filter(Boolean).join(" ");return l.jsxs("div",{className:a,children:[e&&l.jsxs("div",{className:"voxket-connection-status",children:[l.jsx("div",{className:`voxket-status-indicator ${o.isConnected?"connected":"disconnected"}`}),l.jsx("span",{className:"voxket-status-text",children:o.isConnecting?"Connecting...":o.isConnected?"Connected":"Disconnected"})]}),t&&r.session&&l.jsxs("div",{className:"voxket-session-info",children:[l.jsxs("div",{className:"voxket-session-id",children:["Session: ",r.session.id.slice(-8)]}),l.jsxs("div",{className:"voxket-session-state",children:["State: ",r.state]})]}),n&&r.session&&l.jsxs("div",{className:"voxket-agent-info",children:[l.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",r.session.agentId]}),l.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",r.session.activeModalities.join(", ")]})]}),o.error&&l.jsxs("div",{className:"voxket-error-message",children:["Error: ",o.error.message]})]})}function $o({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:s=""}){const r=It(),o=As(),i=$n(),a=["voxket-session-content",`voxket-session-content--${i.variant||"default"}`,`voxket-session-content--${i.size||"md"}`,s].filter(Boolean).join(" ");return r.isActive?l.jsx("div",{className:a,children:n||l.jsxs(l.Fragment,{children:[e&&l.jsxs("div",{className:"voxket-chat-container",children:[l.jsxs("div",{className:"voxket-chat-messages",children:[o.messages.map(c=>l.jsxs("div",{className:`voxket-message voxket-message--${c.sender.type}`,children:[l.jsxs("div",{className:"voxket-message-header",children:[l.jsx("span",{className:"voxket-message-sender",children:c.sender.name}),l.jsx("span",{className:"voxket-message-time",children:c.timestamp.toLocaleTimeString()})]}),l.jsx("div",{className:"voxket-message-content",children:c.content})]},c.id)),o.messages.length===0&&l.jsx("div",{className:"voxket-empty-messages",children:l.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),l.jsx(ux,{})]}),t&&l.jsx("div",{className:"voxket-transcriptions",children:l.jsx("div",{className:"voxket-transcription-placeholder",children:l.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):l.jsx("div",{className:a,children:l.jsx("div",{className:"voxket-inactive-state",children:l.jsxs("div",{className:"voxket-inactive-message",children:[l.jsx("h3",{children:"Start a conversation"}),l.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function ux(){const e=As(),[t,n]=C.useState(""),s=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(o){console.error("Failed to send message:",o)}},r=o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),s())};return l.jsxs("div",{className:"voxket-chat-input",children:[l.jsx("input",{type:"text",value:t,onChange:o=>n(o.target.value),onKeyPress:r,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),l.jsx("button",{onClick:s,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function Fo({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:s,className:r=""}){const o=It(),i=vd(),a=kd(),c=$n(),d=["voxket-session-footer",`voxket-session-footer--${c.variant||"default"}`,`voxket-session-footer--${c.size||"md"}`,r].filter(Boolean).join(" ");return o.isActive?l.jsx("div",{className:d,children:s||l.jsxs(l.Fragment,{children:[n&&l.jsxs("div",{className:"voxket-session-status",children:[l.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),l.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&i.metrics&&l.jsxs("div",{className:"voxket-session-metrics",children:[l.jsxs("div",{className:"voxket-metric",children:[l.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),l.jsx("span",{className:"voxket-metric-value",children:fx(i.duration||0)})]}),l.jsxs("div",{className:"voxket-metric",children:[l.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),l.jsx("span",{className:"voxket-metric-value",children:i.metrics.messageCount})]})]}),t&&l.jsxs("div",{className:"voxket-participants-info",children:[l.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&l.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>l.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):l.jsx("div",{className:d,children:l.jsx("div",{className:"voxket-footer-inactive",children:l.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function fx(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),s=Math.floor(n/60);return s>0?`${s}:${(n%60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}`:`${n}:${(t%60).toString().padStart(2,"0")}`}function hx({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:s,onSessionEnd:r,variant:o="default",size:i="md",theme:a,className:c="",children:d}){var y;const u=It(),f=Io();C.useEffect(()=>{n&&e&&f.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,f.isConnected,u.isActive]),C.useEffect(()=>{var x;(x=u.session)!=null&&x.id&&s&&s(u.session.id)},[(y=u.session)==null?void 0:y.id,s]),C.useEffect(()=>()=>{u.isActive&&r&&u.stop().then(r).catch(console.error)},[]);const h=["voxket-session",`voxket-session--${o}`,`voxket-session--${i}`,u.isActive?"voxket-session--active":"voxket-session--inactive",c].filter(Boolean).join(" ");return l.jsx(Ed,{variant:o,size:i,theme:a,className:c,children:l.jsx("div",{className:h,children:d||l.jsxs(l.Fragment,{children:[l.jsx(ts,{name:"header",fallback:l.jsx(Do,{})}),l.jsx(ts,{name:"content",fallback:l.jsx($o,{})}),l.jsx(ts,{name:"footer",fallback:l.jsx(Fo,{})})]})})})}const Md=Ad(hx,{Header:Do,Content:$o,Footer:Fo,Controls:jd}),Nt={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)"}},Dr={...Nt,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)"}},$r={...Nt,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"}},Pd=C.createContext(null),Vd=()=>{const e=C.useContext(Pd);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function mx({theme:e="default",themes:t={},children:n,cssVariables:s=!0,className:r=""}){const[o,i]=C.useState(()=>{const h={default:Nt,dark:Dr,enterprise:$r,...t};return typeof e=="string"?h[e]||Nt:e}),[a,c]=C.useState(()=>({default:Nt,dark:Dr,enterprise:$r,...t})),d=h=>{if(typeof h=="string"){const y=a[h];y&&i(y)}else i(h)},u=h=>{c(y=>({...y,[h.name]:h}))};C.useEffect(()=>{if(s&&typeof document<"u"){const h=document.documentElement;Object.entries(Nd(o)).forEach(([y,x])=>{h.style.setProperty(`--voxket-${y}`,x)})}},[o,s]);const f={theme:o,setTheme:d,themes:a,registerTheme:u};return l.jsx(Pd.Provider,{value:f,children:l.jsx("div",{className:`voxket-theme voxket-theme--${o.name} ${r}`,children:n})})}function Nd(e){const t={},n=(s,r="")=>{for(const[o,i]of Object.entries(s)){const a=r?`${r}-${o}`:o;typeof i=="object"&&i!==null&&!Array.isArray(i)?n(i,a):t[a]=String(i)}};return n(e),t}function px(e=Nt,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 gx(e){var n;const{theme:t}=Vd();return((n=t.components)==null?void 0:n[e])||{}}const yx=Ro("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&xx(e),t.enableVoiceActivation&&bx(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&vx(e,t)}});function xx(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 bx(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function vx(e,t){console.log("Playing audio response:",t.content)}const wx=Ro("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&Sx(),t.enableFileUpload&&Cx(e),t.enableCustomComponents&&kx(),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"?Tx(e,t):t.type==="text"&&n.enableRichText&&Ex(e,t)}});function Sx(e){console.log("Rich text support enabled")}function Cx(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function kx(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",Ax),t.set("form",jx),t.set("card",Mx),t.set("chart",Px)}function Tx(e,t){const{componentType:n,props:s}=t.metadata;console.log("Rendering custom component:",n,s),e.emit("chat.component.render",{type:n,props:s,timestamp:new Date})}function Ex(e,t){console.log("Processing rich text message:",t.content)}function Ax(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function jx(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function Mx(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function Px(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function ns({track:e,participantName:t,showControls:n=!0,showName:s=!0,showMuteIndicator:r=!0,isPinned:o=!1,className:i="",onClick:a,onPin:c,onUnpin:d}){const u=C.useRef(null),[f,h]=C.useState(!1);C.useEffect(()=>{if(!u.current||!e.isEnabled)return;const b=u.current;return b.srcObject=null,()=>{b.srcObject&&(b.srcObject=null)}},[e]);const y=()=>{a==null||a(e)},x=b=>{b.stopPropagation(),o?d==null||d(e):c==null||c(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",f?"voxket-video-tile--hovered":"",i].filter(Boolean).join(" ");return l.jsxs("div",{className:m,onClick:y,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[l.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&l.jsxs("div",{className:"voxket-video-placeholder",children:[l.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"🖥️":"📹"}),l.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),l.jsxs("div",{className:"voxket-video-overlay",children:[s&&t&&l.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),r&&!e.isEnabled&&l.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),n&&(f||o)&&l.jsxs("div",{className:"voxket-video-controls",children:[l.jsx("button",{className:`voxket-video-control-btn ${o?"voxket-video-control-btn--active":""}`,onClick:x,title:o?"Unpin video":"Pin video",children:"📌"}),e.isScreenShare&&l.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),e.source&&l.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&l.jsx("div",{className:"voxket-video-loading",children:l.jsx("div",{className:"voxket-spinner"})})]})}function Vx({tracks:e,layout:t,className:n="",onLayoutChange:s,onTrackClick:r,maxVisibleTracks:o=9,showPagination:i=!0}){const[a,c]=C.useState(0),[d,u]=C.useState(null),f=C.useMemo(()=>{let w=[...e];t.type==="speaker"&&d&&(w=[d,...e.filter(S=>S.id!==d.id)]);const T=a*o,v=T+o;return w.slice(T,v)},[e,t,d,a,o]),h=Math.ceil(e.length/o),y=C.useMemo(()=>{const w=f.length;switch(t.type){case"grid":const T=Math.ceil(Math.sqrt(w)),v=Math.ceil(w/T);return{display:"grid",gridTemplateColumns:`repeat(${T}, 1fr)`,gridTemplateRows:`repeat(${v}, 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,f.length]),x=w=>{u(w)},m=()=>{u(null)},b=w=>{s==null||s({...t,type:w})},k=["voxket-video-grid",`voxket-video-grid--${t.type}`,`voxket-video-grid--${f.length}-tracks`,n].filter(Boolean).join(" ");return e.length===0?l.jsx("div",{className:"voxket-video-grid-empty",children:l.jsxs("div",{className:"voxket-video-grid-empty-content",children:[l.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),l.jsx("p",{children:"No video tracks available"})]})}):l.jsxs("div",{className:k,children:[l.jsxs("div",{className:"voxket-video-grid-controls",children:[l.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(w=>l.jsx("button",{className:`voxket-layout-btn ${t.type===w?"voxket-layout-btn--active":""}`,onClick:()=>b(w),title:`Switch to ${w} layout`,children:Nx(w)},w))}),l.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),l.jsx("div",{className:"voxket-video-grid-content",style:y,children:t.type==="speaker"&&d?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"voxket-video-speaker-main",children:l.jsx(ns,{track:d,participantName:`Participant ${d.participantId}`,isPinned:!0,onClick:r,onUnpin:m})}),l.jsx("div",{className:"voxket-video-speaker-sidebar",children:f.filter(w=>w.id!==d.id).map(w=>l.jsx(ns,{track:w,participantName:`Participant ${w.participantId}`,showControls:!1,onClick:r,onPin:x},w.id))})]}):f.map(w=>l.jsx(ns,{track:w,participantName:`Participant ${w.participantId}`,isPinned:(d==null?void 0:d.id)===w.id,onClick:r,onPin:x,onUnpin:m},w.id))}),i&&h>1&&l.jsxs("div",{className:"voxket-video-pagination",children:[l.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.max(0,a-1)),disabled:a===0,children:"←"}),l.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",h]}),l.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.min(h-1,a+1)),disabled:a===h-1,children:"→"})]})]})}function Nx(e){switch(e){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function Rx({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:s,showLayoutControls:r=!0,showCameraControls:o=!0,showScreenShareControls:i=!0,className:a=""}){const c=["voxket-video-controls",a].filter(Boolean).join(" "),d=u=>{s==null||s({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return l.jsxs("div",{className:c,children:[o&&l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),l.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:[l.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"📹":"📷"}),l.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&l.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," × ",e.dimensions.height]})]}),i&&l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),l.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:[l.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"🛑":"🖥️"}),l.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),r&&l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),l.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:f,label:h})=>l.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>d(u),title:`Switch to ${h} layout`,children:[l.jsx("span",{className:"voxket-control-icon",children:f}),l.jsx("span",{className:"voxket-control-label",children:h})]},u))})]}),l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),l.jsxs("div",{className:"voxket-video-settings",children:[l.jsxs("div",{className:"voxket-setting-group",children:[l.jsx("label",{className:"voxket-setting-label",children:"Quality"}),l.jsxs("select",{className:"voxket-setting-select",children:[l.jsx("option",{value:"high",children:"High (720p)"}),l.jsx("option",{value:"medium",children:"Medium (480p)"}),l.jsx("option",{value:"low",children:"Low (240p)"})]})]}),l.jsxs("div",{className:"voxket-setting-group",children:[l.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),l.jsxs("select",{className:"voxket-setting-select",children:[l.jsx("option",{value:"30",children:"30 fps"}),l.jsx("option",{value:"15",children:"15 fps"}),l.jsx("option",{value:"10",children:"10 fps"})]})]}),l.jsxs("div",{className:"voxket-setting-group",children:[l.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),l.jsxs("select",{className:"voxket-setting-select",children:[l.jsx("option",{value:"unlimited",children:"Unlimited"}),l.jsx("option",{value:"1000",children:"1 Mbps"}),l.jsx("option",{value:"500",children:"500 Kbps"}),l.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),l.jsxs("div",{className:"voxket-video-stats",children:[l.jsxs("div",{className:"voxket-stat-item",children:[l.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),l.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}×${e.dimensions.height}`:"N/A"})]}),l.jsxs("div",{className:"voxket-stat-item",children:[l.jsx("span",{className:"voxket-stat-label",children:"Source:"}),l.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),l.jsxs("div",{className:"voxket-stat-item",children:[l.jsx("span",{className:"voxket-stat-label",children:"Status:"}),l.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 Rd=({handler:e,loadData:t,data:n,client:s,addLocalMessage:r})=>{const[o,i]=p.useState(null),[a,c]=p.useState(!0),[d,u]=p.useState(!1),[f]=p.useState(Date.now());p.useEffect(()=>{(async()=>{try{if(c(!0),console.log("📋 AssignmentView: Loading assignment data..."),console.log("📋 AssignmentView: Received data from RPC:",n),n&&typeof n=="object"){const b={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};i(b),console.log("📋 AssignmentView: Assignment loaded from RPC data:",b)}}catch(b){console.error("📋 AssignmentView: Error loading assignment:",b),i({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{c(!1)}})()},[n,t]);const h=({message:m,assignment:b})=>{const k=m.toLowerCase().includes("declined"),w=k?"bg-red-50 border-red-200":"bg-green-50 border-green-200",T=k?"text-red-700":"text-green-700",v=k?"❌":"🎉";return l.jsxs("div",{className:`max-w-sm mx-auto ${w} border rounded-lg shadow p-3 flex flex-col items-center`,children:[l.jsx("div",{className:"text-2xl mb-2",children:v}),l.jsx("div",{className:`${T} font-semibold text-sm mb-1`,children:m}),l.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:b.title}),l.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},y=async()=>{if(!(!o||!e)){u(!0);try{const m={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",m),e.didSuccess(m,l.jsx(h,{message:"Assignment accepted!",assignment:o}))}catch(m){console.error("📋 AssignmentView: Error accepting assignment:",m),e.didFail({error:"Failed to accept assignment"})}finally{u(!1)}}},x=async()=>{if(!(!o||!e)){u(!0);try{const m={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",m),e.didSuccess(m,l.jsx(h,{message:"Assignment declined",assignment:o}))}catch(m){console.error("📋 AssignmentView: Error declining assignment:",m),e.didFail({error:"Failed to decline assignment"})}finally{u(!1)}}};return a?l.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:l.jsxs("div",{className:"flex items-center justify-center py-4",children:[l.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),l.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):o?l.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[l.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:l.jsx("div",{className:"flex items-center justify-between",children:l.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:o.title})})}),l.jsxs("div",{className:"p-3 text-black",children:[l.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:l.jsx("p",{className:"text-xs text-black leading-snug",children:o.description})}),l.jsx("div",{className:"mb-3 text-black",children:l.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[l.jsx("span",{className:"text-xs mr-1",children:"📅"}),l.jsxs("span",{children:["Est: ",o.estimated_time_of_completion]})]})}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx("button",{onClick:y,disabled:d,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:d?l.jsxs("span",{className:"flex items-center justify-center",children:[l.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),l.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),l.jsx("button",{onClick:x,disabled:d,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"})]})]})]}):l.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:l.jsxs("div",{className:"text-center py-4",children:[l.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),l.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function Ix(){const[e,t]=p.useState(null),[n,s]=p.useState([]);p.useEffect(()=>{const a=new Dn({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return t(a),a.on("rpc.method.called",c=>{console.log("RPC Method Called:",c)}),a.on("rpc.interaction.completed",c=>{console.log("RPC Interaction Completed:",c)}),()=>{a.disconnect()}},[]);const r=async()=>{if(e)try{await e.registerFrontendRPC("give_assignment",Rd,"embedded");const a=e.getRegisteredRpcMethods();s(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:c,timeout:d})=>{const[u,f]=p.useState(""),h=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],y=m=>{f(m)},x=()=>{const m=h.find(b=>b.id===u);c==null||c.didSuccess({selectedProduct:u,productName:m==null?void 0:m.name,price:m==null?void 0:m.price,timestamp:new Date().toISOString()})};return l.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[l.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),l.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),l.jsx("div",{className:"space-y-3 mb-6",children:h.map(m=>l.jsx("div",{onClick:()=>y(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:l.jsxs("div",{className:"flex justify-between items-center",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"font-medium",children:m.name}),l.jsx("p",{className:"text-gray-600 text-sm",children:m.price})]}),l.jsx("div",{className:`w-4 h-4 rounded-full ${u===m.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},m.id))}),l.jsxs("div",{className:"flex justify-end space-x-3",children:[l.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),l.jsx("button",{onClick:x,disabled:!u,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),d&&l.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",d," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const c=e.getRegisteredRpcMethods();s(c),console.log("✅ Product Recommendation RPC registered successfully")}catch(c){console.error("❌ Failed to register product recommendation RPC:",c)}},i=async()=>{if(!e)return;const a=({handler:c})=>{const[d,u]=p.useState(0),[f,h]=p.useState(""),y=()=>{c==null||c.didSuccess({rating:d,comment:f,timestamp:new Date().toISOString()})};return l.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[l.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),l.jsxs("div",{className:"mb-4",children:[l.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),l.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(x=>l.jsx("button",{onClick:()=>u(x),className:`text-2xl ${x<=d?"text-yellow-400":"text-gray-300"}`,children:"⭐"},x))})]}),l.jsxs("div",{className:"mb-4",children:[l.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),l.jsx("textarea",{value:f,onChange:x=>h(x.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),l.jsxs("div",{className:"flex justify-end space-x-2",children:[l.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),l.jsx("button",{onClick:y,disabled:d===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await e.registerFrontendRPC("collect_feedback",a,"embedded");const c=e.getRegisteredRpcMethods();s(c),console.log("✅ Feedback RPC registered successfully")}catch(c){console.error("❌ Failed to register feedback RPC:",c)}};return l.jsxs("div",{className:"p-6",children:[l.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),l.jsxs("div",{className:"space-y-4 mb-6",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),l.jsxs("div",{className:"space-x-2",children:[l.jsx("button",{onClick:r,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),l.jsx("button",{onClick:o,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),l.jsx("button",{onClick:i,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?l.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>l.jsx("li",{className:"text-gray-700",children:l.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):l.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),l.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[l.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),l.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[l.jsxs("li",{children:["Register RPC methods with React components using ",l.jsx("code",{children:"client.registerFrontendRPC()"})]}),l.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),l.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),l.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),l.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),l.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[l.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),l.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),l.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
126
126
  const response = await participant.performRpc({
127
127
  method: 'give_assignment',
128
128
  data: JSON.stringify({
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { VoxketWidgetProps } from './components/widget';
1
+ import { VoxketWidgetProps, DisplayType, PopupPosition } from './components/widget';
2
2
  import { VoxketErrorBoundary } from './components/error-boundary';
3
3
  import { ThemeType, WidgetTheme } from './styles';
4
4
  import { useSessionLogging, SessionLog, SessionMetrics } from './hooks/useSessionLogging';
@@ -24,6 +24,6 @@ export { InteractiveComponent } from './components/interactive-component';
24
24
  export { AssignmentView } from './examples/assignment-view';
25
25
  export { default as RpcExamples } from './examples/rpc-examples';
26
26
  export { agentRpcExample } from './examples/agent-rpc-example';
27
- export type { VoxketWidgetProps, ThemeType, WidgetTheme, SessionLog, SessionMetrics };
27
+ export type { VoxketWidgetProps, DisplayType, PopupPosition, ThemeType, WidgetTheme, SessionLog, SessionMetrics };
28
28
  export { useSessionLogging, SessionLogViewer, SessionMetricsComponent, VoxketErrorBoundary };
29
29
  export default VoxketWidget;
package/dist/index.js CHANGED
@@ -16753,17 +16753,12 @@ function Rb({
16753
16753
  position: n = "bottom-right",
16754
16754
  theme: r
16755
16755
  }) {
16756
- const o = {
16757
- "top-left": "top-4 left-4",
16758
- "top-right": "top-4 right-4",
16759
- "bottom-left": "bottom-4 left-4",
16760
- "bottom-right": "bottom-4 right-4"
16761
- }, s = Be(r);
16756
+ const o = Be(r);
16762
16757
  return /* @__PURE__ */ u(
16763
16758
  le.button,
16764
16759
  {
16765
16760
  onClick: e,
16766
- className: `voxket-popup-trigger fixed ${o[n]} z-50 px-4 py-2 rounded-full shadow-lg ${s.popupTrigger} transition-all duration-200 hover:scale-105`,
16761
+ className: `voxket-popup-trigger ${o.popupTrigger}`,
16767
16762
  initial: { scale: 0, opacity: 0 },
16768
16763
  animate: { scale: 1, opacity: 1 },
16769
16764
  exit: { scale: 0, opacity: 0 },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voxket-ai/voxket-live",
3
- "version": "1.0.117",
3
+ "version": "1.0.119",
4
4
  "description": "A React widget for embedding Voxket-powered audio/video/chat experiences.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",