@voxket-ai/voxket-live 1.0.36 → 1.0.38
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/core/client.d.ts +5 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +5 -0
- package/package.json +1 -1
package/dist/core/client.d.ts
CHANGED
|
@@ -22,6 +22,11 @@ export interface RenderUIOptions {
|
|
|
22
22
|
width?: string;
|
|
23
23
|
height?: string;
|
|
24
24
|
onDisplayTypeChange?: (displayType: DisplayType) => void;
|
|
25
|
+
prompts?: string[];
|
|
26
|
+
statusMessage?: string;
|
|
27
|
+
welcomeTitle?: string;
|
|
28
|
+
welcomeSubTitle?: string;
|
|
29
|
+
loadingText?: string;
|
|
25
30
|
}
|
|
26
31
|
export interface VoxketClientConfig extends VoxketConfig {
|
|
27
32
|
agentId?: string;
|
package/dist/index.cjs
CHANGED
|
@@ -444,7 +444,7 @@ Learn more: https://react.dev/warnings/version-mismatch`))}(),typeof Map=="funct
|
|
|
444
444
|
You might need to use a local HTTP server (instead of file://): https://react.dev/link/react-devtools-faq`:""),"font-weight:bold")}Jy.createRoot=function(e,n){if(!j(e))throw Error("Target container is not a DOM element.");zv(e);var o=!1,u="",m=q0,v=uv,E=jh,D=null;return n!=null&&(n.hydrate?console.warn("hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead."):typeof n=="object"&&n!==null&&n.$$typeof===Ar&&console.error(`You passed a JSX element to createRoot. You probably meant to call root.render instead. Example usage:
|
|
445
445
|
|
|
446
446
|
let root = createRoot(domContainer);
|
|
447
|
-
root.render(<App />);`),n.unstable_strictMode===!0&&(o=!0),n.identifierPrefix!==void 0&&(u=n.identifierPrefix),n.onUncaughtError!==void 0&&(m=n.onUncaughtError),n.onCaughtError!==void 0&&(v=n.onCaughtError),n.onRecoverableError!==void 0&&(E=n.onRecoverableError),n.unstable_transitionCallbacks!==void 0&&(D=n.unstable_transitionCallbacks)),n=_g(e,1,!1,null,null,o,u,m,v,E,D,null),e[Dr]=n.current,Tg(e),new Cm(n)},Jy.hydrateRoot=function(e,n,o){if(!j(e))throw Error("Target container is not a DOM element.");zv(e),n===void 0&&console.error("Must provide initial children as second argument to hydrateRoot. Example usage: hydrateRoot(domContainer, <App />)");var u=!1,m="",v=q0,E=uv,D=jh,L=null,H=null;return o!=null&&(o.unstable_strictMode===!0&&(u=!0),o.identifierPrefix!==void 0&&(m=o.identifierPrefix),o.onUncaughtError!==void 0&&(v=o.onUncaughtError),o.onCaughtError!==void 0&&(E=o.onCaughtError),o.onRecoverableError!==void 0&&(D=o.onRecoverableError),o.unstable_transitionCallbacks!==void 0&&(L=o.unstable_transitionCallbacks),o.formState!==void 0&&(H=o.formState)),n=_g(e,1,!0,n,o??null,u,m,v,E,D,L,H),n.context=Pg(null),o=n.current,u=Ba(o),u=kn(u),m=hs(u),m.callback=null,Zi(o,m,u),o=u,n.current.lanes=o,ss(n,o),Ei(n),e[Dr]=n.current,Tg(e),new Kf(n)},Jy.version="19.1.0",typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Jy}var FC;function _Z(){if(FC)return Xb.exports;FC=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function")){if(process.env.NODE_ENV!=="production")throw new Error("^_^");try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(a){console.error(a)}}}return process.env.NODE_ENV==="production"?(t(),Xb.exports=HZ()):Xb.exports=$Z(),Xb.exports}var PZ=_Z();class E4{constructor(){Zn(this,"listeners",{})}on(a,s){return this.listeners[a]||(this.listeners[a]=[]),this.listeners[a].push(s),()=>this.off(a,s)}once(a,s){const l=(...f)=>{this.off(a,l),s(...f)};return this.on(a,l)}off(a,s){const l=this.listeners[a];if(!l)return;const f=l.indexOf(s);f>-1&&l.splice(f,1)}removeAllListeners(a){a?delete this.listeners[a]:this.listeners={}}emit(a,...s){const l=this.listeners[a];if(!l)return;const f=[...l];for(const p of f)try{p(...s)}catch(h){console.error(`Error in event listener for ${String(a)}:`,h)}}listenerCount(a){var s;return((s=this.listeners[a])==null?void 0:s.length)??0}eventNames(){return Object.keys(this.listeners)}}class Z5{constructor(a){Zn(this,"plugins",new Map);Zn(this,"installedPlugins",new Set);Zn(this,"context");this.context={client:a,emit:a.emit.bind(a),on:a.on.bind(a),config:{}}}register(a){if(this.plugins.has(a.name))throw new Error(`Plugin '${a.name}' is already registered`);if(a.dependencies){for(const s of a.dependencies)if(!this.plugins.has(s))throw new Error(`Plugin '${a.name}' depends on '${s}' which is not registered`)}this.plugins.set(a.name,a)}async install(a,s){const l=this.plugins.get(a);if(!l)throw new Error(`Plugin '${a}' is not registered`);if(this.installedPlugins.has(a))throw new Error(`Plugin '${a}' is already installed`);if(l.dependencies)for(const p of l.dependencies)this.installedPlugins.has(p)||await this.install(p);const f={...this.context,config:{...l.config,...s}};l.install&&await l.install(f),this.installedPlugins.add(a),this.setupPluginEvents(l,f)}async uninstall(a){var l;const s=this.plugins.get(a);if(!s)throw new Error(`Plugin '${a}' is not registered`);if(this.installedPlugins.has(a)){for(const[f,p]of this.plugins)if(this.installedPlugins.has(f)&&((l=p.dependencies)!=null&&l.includes(a)))throw new Error(`Cannot uninstall '${a}' because '${f}' depends on it`);s.uninstall&&await s.uninstall(this.context),this.installedPlugins.delete(a)}}isInstalled(a){return this.installedPlugins.has(a)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(a){return this.plugins.get(a)}setupPluginEvents(a,s){a.onSessionStart&&s.on("session.started",l=>{a.onSessionStart(s,l.id)}),a.onSessionEnd&&s.on("session.ended",l=>{a.onSessionEnd(s,l.id)}),a.onAgentResponse&&s.on("agent.response",l=>{a.onAgentResponse(s,l)})}}function YZ(t){return t}function C4(t,a,s){return{name:t,version:"1.0.0",description:`${a} modality plugin`,install:async l=>{s.onActivate&&await s.onActivate(l)},uninstall:async l=>{s.onDeactivate&&await s.onDeactivate(l)},onAgentResponse:s.onMessage}}const ZZ={name:"analytics",version:"1.0.0",description:"Built-in analytics tracking",install:async t=>{console.log("Analytics plugin installed"),t.on("session.started",a=>{console.log("Analytics: Session started",a.id)}),t.on("session.ended",(a,s)=>{console.log("Analytics: Session ended",a.id,s)}),t.on("chat.message.sent",a=>{console.log("Analytics: User message sent",a.content.length)})}},qZ={name:"debug",version:"1.0.0",description:"Debug logging and development tools",install:async t=>{console.log("Debug plugin installed");const a=t.emit;t.emit=(s,...l)=>(console.log(`[Debug] Event: ${String(s)}`,l),a(s,...l))}},GZ={name:"metrics",version:"1.0.0",description:"Advanced metrics collection",install:async t=>{console.log("Metrics plugin installed");const a=new Map;t.on("session.started",s=>{a.set(s.id,{startTime:Date.now(),events:[]})}),t.on("agent.response",s=>{console.log("Metrics: Agent response analyzed",{type:s.type,length:s.content.length,timestamp:s.timestamp})})}},q5=Y.createContext(null);function G5({config:t,children:a,autoConnect:s=!1}){const[l,f]=Y.useState(null),[p,h]=Y.useState(!1),[g,y]=Y.useState(!1),[x,S]=Y.useState(null),[A,C]=Y.useState(null),[R,O]=Y.useState("idle"),[V,j]=Y.useState(null),[U,z]=Y.useState([]),[B,$]=Y.useState([]),[_,I]=Y.useState([]);Y.useEffect(()=>{const Z=new U1(t);return f(Z),G(Z),s&&Q(Z),()=>{Z.disconnect().catch(console.error)}},[t,s]);const G=Z=>{Z.on("connection.connecting",()=>{y(!0),S(null)}),Z.on("connection.connected",()=>{h(!0),y(!1),S(null)}),Z.on("connection.disconnected",()=>{h(!1),y(!1),C(null),O("idle"),z([]),$([]),I([])}),Z.on("connection.error",xe=>{S(xe),y(!1)}),Z.on("session.created",xe=>{C(xe),O(xe.state)}),Z.on("session.state.changed",xe=>{O(xe),A&&C({...A,state:xe})}),Z.on("session.ended",(xe,ee)=>{C(null),O("idle"),j(ee),z([]),$([]),I([])}),Z.on("participant.joined",xe=>{z(ee=>[...ee,xe])}),Z.on("participant.left",xe=>{z(ee=>ee.filter(fe=>fe.id!==xe.id))}),Z.on("chat.message.received",xe=>{$(ee=>[...ee,xe])}),Z.on("chat.message.sent",xe=>{$(ee=>[...ee,xe])}),Z.on("transcription.received",xe=>{I(ee=>[...ee,xe])})},Q=async Z=>{const xe=Z||l;if(xe)try{await xe.connect()}catch(ee){console.error("Failed to connect:",ee)}},K={client:l,isConnected:p,isConnecting:g,connectionError:x,currentSession:A,sessionState:R,sessionMetrics:V,participants:U,chatMessages:B,transcriptions:_,connect:()=>Q(),disconnect:async()=>{if(l)try{await l.disconnect()}catch(Z){console.error("Failed to disconnect:",Z)}},createSession:async(Z,xe={})=>{if(!l)throw new Error("Client not initialized");const ee={agentId:Z,participantName:xe.participantName||"User",metadata:xe.metadata,modalities:xe.modalities||["voice"]};return await l.createSession(ee)},endSession:async()=>l?await l.endSession():null,sendChatMessage:async Z=>{if(!l)throw new Error("Client not initialized");await l.sendChatMessage(Z)},setMicrophoneEnabled:async Z=>{if(!l)throw new Error("Client not initialized");await l.setMicrophoneEnabled(Z)},setCameraEnabled:async Z=>{if(!l)throw new Error("Client not initialized");await l.setCameraEnabled(Z)},startScreenShare:async()=>{if(!l)throw new Error("Client not initialized");await l.startScreenShare()},stopScreenShare:async()=>{if(!l)throw new Error("Client not initialized");await l.stopScreenShare()}};return T.jsx(q5.Provider,{value:K,children:a})}function Gr(){const t=Y.useContext(q5);if(!t)throw new Error("useVoxket must be used within a VoxketProvider");return t}class XZ extends E4{constructor(s){super();Zn(this,"room",null);Zn(this,"registeredMethods",new Map);Zn(this,"activeInteractions",new Map);Zn(this,"currentInteraction",null);s&&this.setRoom(s)}setRoom(s){this.room=s}async registerFrontendRPC(s,l,f="embedded"){if(console.log(`RpcManager: Starting registration for method '${s}'`),!this.room)throw console.error(`RpcManager: Cannot register '${s}' - no room instance`),new Error("Room not initialized. Cannot register RPC method.");if(!this.room.localParticipant)throw console.error(`RpcManager: Cannot register '${s}' - 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: ${s}`);const p={methodName:s,component:l,presentationMode:f};this.registeredMethods.set(s,p);try{this.room.registerRpcMethod(s,async h=>{console.log(`RpcManager: RPC method '${s}' called by ${h.callerIdentity}`),console.log("RpcManager: Payload:",h.payload),this.emit("rpc.method.called",{methodName:s,data:h});let g;console.log(`RpcManager: Current registration for '${s}':`,p);let y=h.responseTimeout||30;try{g=JSON.parse(h.payload)}catch{g=h.payload}try{const x=await this.awaitUserInteraction(s,l,f,g,y);return JSON.stringify(x)}catch(x){throw console.error(`RpcManager: Error in RPC method '${s}':`,x),x}}),this.emit("rpc.method.registered",{methodName:s}),console.log(`RpcManager: Successfully registered RPC method: ${s}`)}catch(h){throw console.error(`RpcManager: Failed to register RPC method '${s}':`,h),h}}async awaitUserInteraction(s,l,f,p,h){return new Promise((g,y)=>{const x=`${s}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${s}, timeout: ${h} seconds`);const S={didSuccess:(C,R)=>{console.log(`RpcManager: User interaction successful for method: ${s}`,C),this.clearInteraction(x),this.currentInteraction=null;const O={success:!0,message:"User interaction completed successfully",data:C,timestamp:new Date,...R?{successView:R}:{}};this.emit("rpc.interaction.completed",{methodName:s,response:O}),g(O)},didFail:C=>{console.log(`RpcManager: User interaction failed for method: ${s}`,C),this.clearInteraction(x);const R={success:!1,message:"User interaction failed",error:C,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:s,response:R}),g(R)},dismissView:()=>{var R;console.log(`RpcManager: User dismissed interaction for method: ${s}`),console.log("RpcManager: Current interaction before dismiss:",(R=this.currentInteraction)==null?void 0:R.methodName),this.clearInteraction(x),this.currentInteraction=null,console.log("RpcManager: Current interaction after dismiss:",this.currentInteraction);const C={success:!0,data:{dismissed:!0,reason:"User dismissed the interaction"},message:"User interaction dismissed",timestamp:new Date};this.emit("rpc.interaction.dismissed",{methodName:s,response:C}),this.emit("rpc.interaction.completed",{methodName:s,response:C}),setTimeout(()=>{var O;((O=this.currentInteraction)==null?void 0:O.methodName)===s&&(console.log(`RpcManager: Force clearing interaction for ${s}`),this.currentInteraction=null)},0),g(C)},didTimeout:C=>{console.log(`RpcManager: User interaction timeout for method: ${s}`),this.clearInteraction(x),this.currentInteraction=null;const R={success:!0,message:`User interaction timed out after ${h} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...C?{timeoutView:C}:{}};this.emit("rpc.interaction.timeout",{methodName:s,response:R}),setTimeout(()=>{var O;((O=this.currentInteraction)==null?void 0:O.methodName)===s&&(console.log(`RpcManager: Force clearing interaction for ${s}`),this.currentInteraction=null)},0),g(R)}},A=setTimeout(()=>{S.didTimeout&&S.didTimeout()},h);this.activeInteractions.set(x,{resolve:C=>g(JSON.parse(C)),reject:y,timeoutId:A}),this.currentInteraction={isVisible:!0,methodName:s,component:l,presentationMode:f,timeout:h,data:p,handler:S},this.emit("rpc.interaction.started",{methodName:s,presentationMode:f}),setTimeout(async()=>{var C;if((C=this.currentInteraction)!=null&&C.handler)try{console.log(`RpcManager: Component created for method: ${s} with data:`,p)}catch(R){console.error("RpcManager: Error loading data into component:",R),S.didFail({error:"Failed to load data into component"})}},100)})}clearInteraction(s){const l=this.activeInteractions.get(s);l&&(console.log(`RpcManager: Clearing interaction: ${s}`),clearTimeout(l.timeoutId),this.activeInteractions.delete(s))}getCurrentInteraction(){return this.currentInteraction}dismissCurrentInteraction(){var s;this.currentInteraction&&(console.log(`RpcManager: Dismissing current interaction: ${this.currentInteraction.methodName}`),(s=this.currentInteraction.handler)==null||s.dismissView(),setTimeout(()=>{this.currentInteraction&&(console.log("RpcManager: Force clearing lingering interaction"),this.currentInteraction=null)},0))}getRegisteredMethods(){return Array.from(this.registeredMethods.keys())}unregisterMethod(s){this.registeredMethods.delete(s),console.log(`RpcManager: Unregistered RPC method: ${s}`)}clear(){for(const[s,l]of this.activeInteractions)clearTimeout(l.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null,console.log("RpcManager: Cleared all registrations and interactions")}}class $t extends Error{constructor(a,s,l){super(a),this.code=s,this.details=l,this.name="VoxketError"}}class U1 extends E4{constructor(s){super();Zn(this,"config");Zn(this,"room",null);Zn(this,"pluginManager");Zn(this,"rpcManager");Zn(this,"isConnected",!1);Zn(this,"currentSession",null);Zn(this,"connectionState",Ze.ConnectionState.Disconnected);Zn(this,"renderedComponents",new Map);Zn(this,"textStreamHandlersRegistered",!1);Zn(this,"currentAgentInfo",null);Zn(this,"chatMessages",[]);this.config=s,this.pluginManager=new Z5(this),this.rpcManager=new XZ,this.setupEventListeners(),this.initializeClient()}setupEventListeners(){this.on("connection.connected",()=>{var s,l;this.isConnected=!0,(l=(s=this.config).onConnected)==null||l.call(s)}),this.on("connection.disconnected",s=>{var l,f;this.isConnected=!1,(f=(l=this.config).onDisconnected)==null||f.call(l,s)}),this.on("connection.error",s=>{var l,f;(f=(l=this.config).onError)==null||f.call(l,s)}),this.on("chat.message.received",s=>{var l,f;this.addChatMessage(s),(f=(l=this.config).onMessageReceived)==null||f.call(l,s)}),this.on("chat.message.updated",s=>{this.updateChatMessage(s)}),this.on("chat.message.sent",s=>{this.addChatMessage(s)}),this.on("transcription.received",s=>{var l,f;(f=(l=this.config).onTranscriptionReceived)==null||f.call(l,s)}),this.on("session.state.changed",s=>{var l,f;(f=(l=this.config).onSessionStateChanged)==null||f.call(l,s)}),this.on("session.created",s=>{var l,f;(f=(l=this.config).onSessionStart)==null||f.call(l,s.id)}),this.on("session.ended",(s,l)=>{var f,p;(p=(f=this.config).onSessionEnd)==null||p.call(f,l)}),this.on("participant.joined",s=>{var l,f;(f=(l=this.config).onUserJoined)==null||f.call(l,s.id)}),this.on("participant.left",s=>{var l,f;(f=(l=this.config).onUserLeft)==null||f.call(l,s.id)}),this.setupRpcEventForwarding()}setupRpcEventForwarding(){if(!this.rpcManager){console.warn("RpcManager not initialized, skipping event forwarding setup");return}this.rpcManager.on("rpc.method.registered",s=>this.emit("rpc.method.registered",s)),this.rpcManager.on("rpc.method.called",s=>this.emit("rpc.method.called",s)),this.rpcManager.on("rpc.interaction.started",s=>this.emit("rpc.interaction.started",s)),this.rpcManager.on("rpc.interaction.completed",s=>this.emit("rpc.interaction.completed",s)),this.rpcManager.on("rpc.interaction.timeout",s=>this.emit("rpc.interaction.timeout",s)),this.rpcManager.on("rpc.interaction.dismissed",s=>this.emit("rpc.interaction.dismissed",s))}initializeClient(){this.room=new Ze.Room,this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(Ze.RoomEvent.Connected,()=>{var s,l;this.connectionState=Ze.ConnectionState.Connected,this.emit("connection.connected"),this.rpcManager.setRoom(this.room),(l=(s=this.currentSession)==null?void 0:s.activeModalities)!=null&&l.includes("voice")&&setTimeout(async()=>{var f;try{(f=this.room)!=null&&f.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(p){console.warn("VoxketClient: Failed to enable microphone after room connection:",p)}},1e3),this.textStreamHandlersRegistered||this.setupTextStreamHandlers()}),this.room.on(Ze.RoomEvent.Disconnected,s=>{this.connectionState=Ze.ConnectionState.Disconnected,this.textStreamHandlersRegistered=!1,this.emit("connection.disconnected",s==null?void 0:s.toString())}),this.room.on(Ze.RoomEvent.ConnectionStateChanged,s=>{this.connectionState=s,s===Ze.ConnectionState.Connecting&&this.emit("connection.connecting")}),this.room.on(Ze.RoomEvent.ParticipantConnected,s=>{const l={id:s.identity,name:s.name||s.identity,isLocal:!1};this.emit("participant.joined",l)}),this.room.on(Ze.RoomEvent.ParticipantDisconnected,s=>{const l={id:s.identity,name:s.name||s.identity,isLocal:!1};this.emit("participant.left",l)}))}setupTextStreamHandlers(){if(this.room){try{this.room.registerTextStreamHandler("lk.chat",async(s,l)=>{try{const f=await s.readAll(),p={id:`msg_${Date.now()}_${l.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:f,timestamp:new Date,sender:{id:l.identity||"user",name:l.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.emit("chat.message.received",p)}catch(f){console.error("VoxketClient: Failed to process lk.chat message:",f)}})}catch(s){console.warn("VoxketClient: lk.chat handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("lk.transcription",async(s,l)=>{var f,p;try{const h=`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`;let g="";const y=((f=this.currentAgentInfo)==null?void 0:f.name)||l.identity||"AI Assistant",x={id:h,content:"",timestamp:new Date,sender:{id:l.identity||"agent",name:y,type:"agent"},metadata:{topic:"lk.transcription",streaming:!0}};this.emit("chat.message.received",x);for await(const C of s){g+=C;const R=this.convertMarkdownToText(g),O={...x,content:R,metadata:{...x.metadata,streaming:!0}};this.emit("chat.message.updated",O)}const S=this.convertMarkdownToText(g),A={...x,content:S,metadata:{...x.metadata,streaming:!1}};this.emit("chat.message.updated",A)}catch(h){console.error("VoxketClient: Failed to process lk.transcription message:",h);try{const g=await s.readAll(),y=((p=this.currentAgentInfo)==null?void 0:p.name)||l.identity||"AI Assistant",x={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:g,timestamp:new Date,sender:{id:l.identity||"agent",name:y,type:"agent"},metadata:{topic:"lk.transcription"}};this.emit("chat.message.received",x)}catch(g){console.error("VoxketClient: Fallback failed for lk.transcription:",g)}}})}catch(s){console.warn("VoxketClient: lk.transcription handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("suggested_response",async s=>{const l=await s.readAll();let f=[];try{f=["tes","hello how are you","algebra make me learn that ","what is the meaning of life"]}catch(p){console.warn("VoxketClient: Failed to parse suggested_response:",p,l)}this.emit("suggested.response",f)})}catch(s){console.warn("VoxketClient: suggested_response handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("agent_state_changed",async(s,l)=>{const f=await s.readAll();let p={};try{p=typeof f=="string"?JSON.parse(f.replace(/'/g,'"')):f}catch(h){console.warn("VoxketClient: Failed to parse agent_state_changed:",h,f)}p.new_state==="speaking"?this.emit("agent.speaking",p):p.new_state==="thinking"&&this.emit("agent.thinking",p)})}catch(s){console.warn("VoxketClient: conversation_item_added handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("images",async(s,l)=>{try{const f=await s.readAll()}catch(f){console.error("VoxketClient: Error processing images stream:",f)}})}catch(s){console.warn("VoxketClient: images handler already registered, skipping:",s)}try{this.room.registerByteStreamHandler("images",async(s,l)=>{var f,p;try{const h=s.info,g={id:`img_${Date.now()}_${l.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`�️ ${h.name||"Image"}`,sender:{id:l.identity||"agent",name:l.identity||"Agent",type:l.identity===((p=(f=this.room)==null?void 0:f.localParticipant)==null?void 0:p.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:h.name,fileSize:h.size,mimeType:h.mimeType,streamId:h.id,downloading:!0}};this.emit("chat.message.received",g),s.onProgress&&(s.onProgress=C=>{const R={...g,metadata:{...g.metadata,downloadProgress:C||0}};this.emit("chat.message.updated",R)});const y=[];for await(const C of s)y.push(C);const x=new Blob(y,{type:h.mimeType||"application/octet-stream"}),S=URL.createObjectURL(x),A={...g,metadata:{...g.metadata,downloading:!1,downloadProgress:1,downloadUrl:S,blob:x}};this.emit("chat.message.updated",A)}catch(h){console.error("VoxketClient: Error processing image attachment:",h)}})}catch(s){console.warn("VoxketClient: image handler already registered, skipping:",s)}this.textStreamHandlersRegistered=!0}}async fetchConnectionDetails(s,l,f){const p=s||this.config.agentId||"default-agent",h=l||this.config.participantName||"User",g=f||this.config.modalities||["voice"];try{const y={agent_id:p,participant_name:h,participant_metadata:{user_id:""},modality:g[0]},x=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(y)});if(!x.ok){let C=`HTTP ${x.status}: Failed to fetch connection details`;try{const R=await x.json();R&&(R.error?C=`API Error: ${R.error}`:R.detail?C=`API Error: ${R.detail}`:R.message&&(C=`API Error: ${R.message}`))}catch{try{const O=await x.text();O&&(C=`API Error: ${O}`)}catch{}}throw new Error(C)}const S=await x.json();let A;return S.agent_info&&(A={id:S.agent_info.id||p,name:S.agent_info.name||"AI Assistant",avatar:S.agent_info.avatar,capabilities:S.agent_info.capabilities||["voice_interaction","text_chat"],metadata:S.agent_info.metadata||{}},this.currentAgentInfo=A),{serverUrl:S.wss_url,participantToken:S.token,voxketSessionId:S.session_id,agentInfo:A}}catch(y){console.error("VoxketClient: fetchConnectionDetails failed:",y);const x=new $t(`Failed to fetch connection details: ${y instanceof Error?y.message:"Unknown error"}`,"CONNECTION_FAILED",y);throw this.emit("connection.error",x),x}}async connect(s,l,f){var p;try{this.emit("connection.connecting");const h=await this.fetchConnectionDetails(s,l,f);return await((p=this.room)==null?void 0:p.connect(h.serverUrl,h.participantToken)),this.isConnected=!0,h}catch(h){console.error("VoxketClient: Connection failed:",h);const g=new $t(`Failed to connect to Voxket services: ${h instanceof Error?h.message:"Unknown error"}`,"CONNECTION_FAILED",h);throw this.emit("connection.error",g),g}}async disconnect(){var s;try{await((s=this.room)==null?void 0:s.disconnect()),this.isConnected=!1,this.currentSession=null,this.currentAgentInfo=null,this.textStreamHandlersRegistered=!1,this.clearChatMessages(),this.room=new Ze.Room,this.setupRoomEventListeners()}catch(l){const f=new $t("Failed to disconnect properly","NETWORK_ERROR",l);throw this.emit("connection.error",f),f}}async createSession(s){var l,f;try{const p=await this.connect(s.agentId,s.participantName,s.modalities),h={id:p.voxketSessionId,agentId:s.agentId,state:"connecting",startedAt:new Date,metadata:s.metadata||{},activeModalities:s.modalities||["voice"],agentInfo:p.agentInfo||this.currentAgentInfo};if(this.currentSession=h,this.emit("session.created",h),(l=s.modalities)!=null&&l.includes("voice"))try{await new Promise(g=>setTimeout(g,500)),(f=this.room)!=null&&f.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(g){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",g)}return setTimeout(()=>{this.currentSession&&(this.currentSession.state="active",this.emit("session.state.changed","active",this.currentSession.state))},1e3),h}catch(p){throw console.error("VoxketClient: Failed to create session:",p),p instanceof $t?p:p instanceof TypeError&&p.message.includes("fetch")?new $t("Network connection failed","CONNECTION_FAILED",p):p instanceof Error&&p.message.includes("Failed to fetch connection details")?new $t(`API connection failed: ${p.message}`,"CONNECTION_FAILED",p):new $t(`Failed to create session: ${p instanceof Error?p.message:"Unknown error"}`,"SESSION_NOT_FOUND",p)}}async startSession(s,l){const f={agentId:s||this.config.agentId||"default-agent",participantName:(l==null?void 0:l.participantName)||this.config.participantName||"User",modalities:(l==null?void 0:l.modalities)||this.config.modalities||["voice","chat"],metadata:l==null?void 0:l.metadata};return this.createSession(f)}async endSession(){var s,l;if(!this.currentSession)return null;try{const f={sessionId:this.currentSession.id,duration:Date.now()-(((s=this.currentSession.startedAt)==null?void 0:s.getTime())||0),messageCount:0,participantCount:((l=this.room)==null?void 0:l.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,f),await this.disconnect(),f}catch(f){throw new $t("Failed to end session","SESSION_NOT_FOUND",f)}}getCurrentSession(){return this.currentSession}getCurrentAgentInfo(){return this.currentAgentInfo}getChatMessages(){return[...this.chatMessages]}addChatMessage(s){this.chatMessages.some(f=>f.id===s.id)||this.chatMessages.push(s)}updateChatMessage(s){const l=this.chatMessages.findIndex(f=>f.id===s.id);l!==-1&&(this.chatMessages[l]=s)}clearChatMessages(){this.chatMessages=[],this.dismissCurrentInteraction(),this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays(),this.emit("chat.history.cleared")}renderUI(s={}){var y,x,S;const l=this.resolveTarget(s.target||"body"),f=this.getTargetKey(l),p=this.renderedComponents.get(f);p&&p.target===l||this.removeUI(l);const h=(p==null?void 0:p.root)||PZ.createRoot(l),g={agentId:s.agentId||this.config.agentId||"default-agent",participantName:s.participantName||this.config.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:s.className,theme:typeof s.theme=="string"?s.theme:void 0,modalities:s.modality||this.config.modalities||["voice"],suportsChatInput:((y=s.modality)==null?void 0:y.includes("chat"))!==!1,suportsVideoInput:((x=s.modality)==null?void 0:x.includes("video"))===!0,suportsScreenShare:((S=s.modality)==null?void 0:S.includes("screen_share"))===!0,autoStart:s.autoStart,displayType:s.displayType||"widget",popupPosition:s.popupPosition||"bottom-right",popupTriggerText:s.popupTriggerText||"Open Chat",width:s.width,height:s.height,onDisplayTypeChange:s.onDisplayTypeChange,voxketClient:this};h.render(Y.createElement(G5,{config:this.config,autoConnect:s.autoStart||!1,children:Y.createElement(X5,g)})),this.renderedComponents.set(f,{root:h,target:l})}removeUI(s){const l=s?this.resolveTarget(s):null;if(l){const f=this.getTargetKey(l),p=this.renderedComponents.get(f);p&&(p.root.unmount(),this.renderedComponents.delete(f),l.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(g=>{try{g.remove()}catch(y){console.warn("Failed to remove element:",y)}}),l===document.body&&l.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(y=>{if(y.classList.contains("bg-black")&&y.classList.contains("backdrop-blur-sm"))try{y.remove()}catch(x){console.warn("Failed to remove fixed element:",x)}}))}}removeAllUI(){for(const[s,l]of this.renderedComponents)l.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(l=>{if(l.classList.contains("bg-black")&&(l.classList.contains("backdrop-blur-sm")||l.classList.contains("bg-opacity-30")))try{l.remove()}catch(f){console.warn("Failed to remove overlay:",f)}})}resolveTarget(s){if(typeof s=="string"){const l=document.querySelector(s);if(!l)throw new Error(`Target element not found: ${s}`);return l}return s}getTargetKey(s){return s.id?s.id:s.className?s.tagName+"_"+s.className.replace(/\s+/g,"_"):s.tagName+"_"+s.outerHTML.length%1e3}async sendMessage(s,l){var f;if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new $t("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new $t("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new $t("No local participant","CONNECTION_FAILED");this.dismissCurrentInteraction();try{const p={id:`msg_${Date.now()}`,content:s,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:l||{}},h=await((f=this.room)==null?void 0:f.localParticipant.sendText(s,{topic:"lk.chat",destinationIdentities:[]}));this.emit("chat.message.sent",p)}catch(p){throw console.error("VoxketClient: Failed to send chat message:",p),new $t("Failed to send message","NETWORK_ERROR",p)}}async sendChatMessage(s,l){return this.sendMessage(s,l)}async sendAttachments(s,l){if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new $t("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new $t("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new $t("No local participant","CONNECTION_FAILED");if(!s||s.length===0)throw new $t("No files provided","INVALID_PARAMETER");this.dismissCurrentInteraction();const f=s.filter(p=>p.type.startsWith("image/"));if(f.length===0)throw new $t("Only image files are allowed","INVALID_PARAMETER");f.length!==s.length&&console.warn("VoxketClient: Some non-image files were filtered out");try{const p=f.map(async(h,g)=>{const x={id:`att_${Date.now()}_${g}`,content:`📎 ${h.name}`,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:{...l,type:"attachment",fileName:h.name,fileSize:h.size,mimeType:h.type,uploading:!0}};this.emit("chat.message.sent",x);const S=await this.room.localParticipant.sendFile(h,{mimeType:h.type,topic:"images",onProgress:C=>{const R={...x,metadata:{...x.metadata,uploadProgress:C}};this.emit("chat.message.updated",R)}});try{const C=new FileReader,R=new Promise((j,U)=>{C.onload=()=>{typeof C.result=="string"?j(C.result):U(new Error("Failed to convert to base64"))},C.onerror=U});C.readAsDataURL(h);const V={type:"image",data:await R,filename:h.name,mimeType:h.type,size:h.size};await this.room.localParticipant.sendText(JSON.stringify(V),{topic:"images",destinationIdentities:[]})}catch(C){console.warn("VoxketClient: Failed to send image data to agent:",C);try{const R=`I've shared an image: ${h.name}`;await this.room.localParticipant.sendText(R,{topic:"lk.chat",destinationIdentities:[]})}catch(R){console.warn("VoxketClient: Failed to send image notification to agent:",R)}}const A={...x,metadata:{...x.metadata,uploading:!1,uploadProgress:1,streamId:S.id}};return this.emit("chat.message.updated",A),S});await Promise.all(p)}catch(p){throw console.error("VoxketClient: Failed to send attachments:",p),new $t("Failed to send attachments","NETWORK_ERROR",p)}}async sendAttachment(s,l){return this.sendAttachments([s],l)}toggleMicrophone(s){return this.setMicrophoneEnabled(s!==!1)}async setMicrophoneEnabled(s){var l,f;try{const p=(l=this.room)==null?void 0:l.localParticipant.isMicrophoneEnabled,h=s??!p;await((f=this.room)==null?void 0:f.localParticipant.setMicrophoneEnabled(h)),h?this.emit("track.unmuted",{source:"microphone",enabled:!0}):this.emit("track.muted",{source:"microphone",enabled:!1})}catch(p){throw console.error("VoxketClient: Failed to toggle microphone:",p),new $t("Failed to toggle microphone","PERMISSION_DENIED",p)}}toggleCamera(s){return this.setCameraEnabled(s!==!1)}async setCameraEnabled(s){var l,f;try{const p=(l=this.room)==null?void 0:l.localParticipant.isCameraEnabled,h=s??!p;await((f=this.room)==null?void 0:f.localParticipant.setCameraEnabled(h)),h?this.emit("track.unmuted",{source:"camera",enabled:!0}):this.emit("track.muted",{source:"camera",enabled:!1})}catch(p){throw console.error("VoxketClient: Failed to toggle camera:",p),new $t("Failed to toggle camera","PERMISSION_DENIED",p)}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var s;try{await((s=this.room)==null?void 0:s.localParticipant.setScreenShareEnabled(!0))}catch(l){throw new $t("Failed to start screen share","PERMISSION_DENIED",l)}}async stopScreenShare(){var s;try{await((s=this.room)==null?void 0:s.localParticipant.setScreenShareEnabled(!1))}catch(l){throw new $t("Failed to stop screen share","PERMISSION_DENIED",l)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(l=>l.kind==="audioinput")}catch(s){throw new $t("Failed to get audio input devices","DEVICE_ERROR",s)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(l=>l.kind==="videoinput")}catch(s){throw new $t("Failed to get video input devices","DEVICE_ERROR",s)}}async setAudioInputDevice(s){var l;try{if(!((l=this.room)!=null&&l.localParticipant))throw new Error("Not connected to room")}catch(f){throw new $t("Failed to set audio input device","DEVICE_ERROR",f)}}async setVideoInputDevice(s){var l;try{if(!((l=this.room)!=null&&l.localParticipant))throw new Error("Not connected to room")}catch(f){throw new $t("Failed to set video input device","DEVICE_ERROR",f)}}getLocalParticipant(){var s;return((s=this.room)==null?void 0:s.localParticipant)??null}getRemoteParticipants(){var s;return Array.from(((s=this.room)==null?void 0:s.remoteParticipants.values())??[])}getPublishPermissions(){const s=this.getLocalParticipant();if(!s)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const l=s.permissions;if(!l)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const f=p=>!!l.canPublish&&(l.canPublishSources.length===0||l.canPublishSources.includes(p));return{camera:f(1),microphone:f(2),screenShare:f(3),data:l.canPublishData??!1}}canPublishSource(s){return this.getPublishPermissions()[s]}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===Ze.ConnectionState.Connected}getMicrophoneTrack(){const s=this.getLocalParticipant();if(!s)return null;for(const[,l]of s.trackPublications)if(l.source===Ze.Track.Source.Microphone)return l.track;return null}getCameraTrack(){const s=this.getLocalParticipant();if(!s)return null;for(const[,l]of s.trackPublications)if(l.source===Ze.Track.Source.Camera)return l.track;return null}getScreenShareTrack(){const s=this.getLocalParticipant();if(!s)return null;for(const[,l]of s.trackPublications)if(l.source===Ze.Track.Source.ScreenShare)return l.track;return null}get isMicrophoneEnabled(){const s=this.getMicrophoneTrack();return s?!s.isMuted:!1}get isCameraEnabled(){const s=this.getCameraTrack();return s?!s.isMuted:!1}get isScreenShareEnabled(){const s=this.getScreenShareTrack();return s?!s.isMuted:!1}registerPlugin(s){this.pluginManager.register(s)}getPluginManager(){return this.pluginManager}getParticipants(){if(!this.room)return[];const s=[];return this.room.localParticipant&&s.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(l=>{s.push({id:l.identity,name:l.name||l.identity,isLocal:!1})}),s}getSessionMetrics(){var s,l;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((s=this.currentSession.startedAt)==null?void 0:s.getTime())||0),messageCount:0,participantCount:((l=this.room)==null?void 0:l.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(s){this.config={...this.config,...s}}async startRecording(){var s;try{this.emit("recording.started",{sessionId:(s=this.currentSession)==null?void 0:s.id,timestamp:new Date})}catch(l){throw new $t("Failed to start recording","RECORDING_ERROR",l)}}async stopRecording(){var s;try{this.emit("recording.stopped",{sessionId:(s=this.currentSession)==null?void 0:s.id,timestamp:new Date})}catch(l){throw new $t("Failed to stop recording","RECORDING_ERROR",l)}}async registerFrontendRPC(s,l,f="embedded"){return this.rpcManager.registerFrontendRPC(s,l,f)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(s){this.rpcManager.unregisterMethod(s)}registerEventListener(s,l){return this.on(s,l)}registerEventEmitter(s,l){if(!this.room)throw new Error("Room not available");try{this.room.registerTextStreamHandler(s,async f=>{try{const p=await f.readAll();l(p)}catch(p){console.error(`Error processing event for topic '${s}':`,p)}})}catch(f){console.warn(`VoxketClient: Handler for topic '${s}' may already be registered:`,f)}}convertMarkdownToText(s){if(!s)return"";let l=s;return l=l.replace(/\*\*(.*?)\*\*/g,"$1"),l=l.replace(/__(.*?)__/g,"$1"),l=l.replace(/\*(.*?)\*/g,"$1"),l=l.replace(/_(.*?)_/g,"$1"),l=l.replace(/~~(.*?)~~/g,"$1"),l=l.replace(/`([^`]+)`/g,"$1"),l=l.replace(/```[\s\S]*?```/g,""),l=l.replace(/^#{1,6}\s+/gm,""),l=l.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),l.trim()}}const FZ=Vn.create(BH),IZ=Vn.create(VZ),QZ=Vn.create(jZ),KZ=Vn.create(UZ);function JZ({onClick:t,text:a="Open Chat",position:s="bottom-right",theme:l}){const f={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},p=Da(l);return T.jsx(Vn.button,{onClick:t,className:`fixed ${f[s]} z-50 px-4 py-2 rounded-full shadow-lg ${p.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},children:a})}function IC({children:t,theme:a,displayType:s="widget",onClose:l,popupPosition:f="bottom-right",onExpand:p}){const h=Da(a);if(s==="fullscreen")return T.jsx("div",{className:"fixed inset-0 z-50 bg-black bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",children:T.jsxs("div",{className:"w-full h-full max-w-6xl max-h-[90vh] rounded-2xl relative bg-transparent",children:[l&&T.jsx("button",{onClick:g=>{g.preventDefault(),g.stopPropagation(),l()},className:"absolute top-4 cursor-pointer right-4 z-[100] 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:T.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:T.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"})})}),T.jsxs("div",{id:"voice-card",className:`${h.card} w-full h-full flex flex-col rounded-xl shadow-2xl`,style:{minHeight:"600px"},children:[T.jsx("div",{className:h.cardTopGradient}),T.jsx("div",{className:h.cardPurpleBlur}),T.jsx("div",{className:h.cardPinkBlur}),T.jsx("div",{className:" flex flex-col h-full",children:t}),T.jsx("div",{className:h.cardPulse1}),T.jsx("div",{className:h.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(s==="popup"){const g={"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 T.jsx("div",{className:"fixed rounded-2xl inset-0 z-50 pointer-events-none",children:T.jsxs("div",{className:`fixed rounded-2xl ${g[f]} pointer-events-auto`,children:[l&&T.jsx("button",{onClick:l,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:"×"}),T.jsxs("div",{id:"voice-card",className:`${h.card} rounded-2xl flex flex-col`,style:{width:"300px",height:"450px"},children:[T.jsx("div",{className:h.cardPurpleBlur}),T.jsx("div",{className:h.cardPinkBlur}),T.jsx("div",{className:" flex flex-col h-full",children:t}),T.jsx("div",{className:h.cardPulse1}),T.jsx("div",{className:h.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return T.jsxs("div",{id:"voice-card",className:`${h.card}`,children:[p&&T.jsx("button",{onClick:p,className:"absolute top-4 right-4 z-20 w-10 h-10 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:"Enter Fullscreen",children:T.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:T.jsx("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})})}),T.jsx("div",{className:h.cardTopGradient}),T.jsx("div",{className:h.cardPurpleBlur}),T.jsx("div",{className:h.cardPinkBlur}),t,T.jsx("div",{className:h.cardPulse1}),T.jsx("div",{className:h.cardPulse2,style:{animationDelay:"1s"}})]})}function X5(t){if(typeof window>"u")return null;console.log("🎯 Widget component rendering with props:",{displayType:t.displayType,popupPosition:t.popupPosition,theme:t.theme});const{agentId:a,participantName:s,baseUrl:l,appSecret:f,appId:p,prompts:h,statusMessage:g,welcomeTitle:y,welcomeSubTitle:x,className:S,width:A,height:C,loadingText:R,suportsChatInput:O=!0,suportsVideoInput:V=!0,suportsScreenShare:j=!0,theme:U="vox",onSessionStart:z,onSessionEnd:B,enableSessionLogging:$=!0,onSessionLogsUpdate:_,onSessionMetricsUpdate:I,modalities:G=["voice"],displayType:Q="widget",popupPosition:se="bottom-right",popupTriggerText:ve="Open Chat",onPopupToggle:Ae,voxketClient:be,onDisplayTypeChange:$e}=t,[je,ze]=M.useState(()=>be?!!be.getCurrentSession():!1),[P,K]=M.useState(!1),[Z,xe]=M.useState(a||""),[ee,fe]=M.useState(s||"User"),[ge,ae]=M.useState(()=>be?be.getCurrentSession():null),[Ee,Ve]=M.useState(()=>{var Je,It,pa;if(be){const _t=be.getCurrentSession();if((Je=_t==null?void 0:_t.activeModalities)!=null&&Je.includes("chat"))return"chat";if((It=_t==null?void 0:_t.activeModalities)!=null&&It.includes("voice"))return"voice";if((pa=_t==null?void 0:_t.activeModalities)!=null&&pa.includes("video"))return"video"}return"welcome"}),[Me,Te]=M.useState(!1);M.useEffect(()=>{console.log("🎯 Widget displayType prop changed to:",Q)},[Q]),M.useEffect(()=>{console.log("📊 Session state changed:",{currentMode:Ee,sessionStarted:je,loading:P,currentSession:ge==null?void 0:ge.id,isPopupOpen:Me})},[Ee,je,P,ge,Me]);const Ce=M.useMemo(()=>{if(be)return console.log("🔄 Using passed VoxketClient to preserve session state"),be;console.log("🆕 Creating new VoxketClient instance");const Je={appId:p,appSecret:f,baseUrl:l,agentId:Z,participantName:ee||"User",modalities:G};return new U1(Je)},[be,p,f,l,Z,ee,G]),Oe=G,De=M.useMemo(()=>Ce.getRoom()||new Ze.Room,[Ce]),Ye={suportsChatInput:O,suportsVideoInput:V,suportsScreenShare:j},{sessionMetrics:qe,sessionLogs:st,logEvent:Nt}=P5({room:De,onSessionStart:z,onSessionEnd:B,enableConsoleLogging:$,enableLocalStorage:$,voxketSessionId:ge==null?void 0:ge.id});M.useEffect(()=>{_&&_(st)},[st,_]),M.useEffect(()=>{I&&qe&&I(qe)},[qe,I]),M.useEffect(()=>{const Je=pa=>{console.log("🔴 Room disconnected:",pa),K(!1),ze(!1),ae(null),Ve("welcome")},It=pa=>{console.log("📹 Media devices error:",pa),Lb({title:"Allow access to your microphone/camera",description:`${pa.name}: ${pa.message}`})};return De.on(Ze.RoomEvent.MediaDevicesError,It),De.on(Ze.RoomEvent.Disconnected,Je),()=>{De.off(Ze.RoomEvent.Disconnected,Je),De.off(Ze.RoomEvent.MediaDevicesError,It)}},[De]);const Xn=async()=>{try{console.log("🎤 Starting voice session...",{agentId:Z,participantName:ee}),console.log("🎤 Pre-start state:",{currentMode:Ee,sessionStarted:je,loading:P}),K(!0),ze(!0),Ve("voice"),console.log("🎤 State after mode change:",{currentMode:"voice",sessionStarted:!0,loading:!0}),Nt("USER_STARTED_VOICE_SESSION",{agentId:Z,participantName:ee});const Je=await Ce.startSession(Z,{participantName:ee||"User",modalities:["voice",...V?["video"]:[]]});console.log("✅ Voice session started successfully:",Je.id),ae(Je),K(!1),z&&z(Je.id)}catch(Je){console.error("❌ Failed to start voice session:",Je),Lb({title:"Failed to start voice session",description:Je instanceof Error?Je.message:"Unknown error occurred"}),K(!1),ze(!1),Ve("welcome")}},jn=async()=>{try{K(!0),ze(!0),Ve("chat"),Nt("USER_STARTED_CHAT_SESSION",{agentId:Z,participantName:ee});const Je=await Ce.startSession(Z,{participantName:ee||"User",modalities:["chat"]});ae(Je),K(!1),z&&z(Je.id)}catch(Je){console.error("Failed to start chat session:",Je),Lb({title:"Failed to start chat session",description:Je instanceof Error?Je.message:"Unknown error occurred"}),K(!1),ze(!1),Ve("welcome")}},ln=async()=>{try{console.log("📺 Starting video session...",{agentId:Z,participantName:ee}),console.log("📺 Pre-start state:",{currentMode:Ee,sessionStarted:je,loading:P}),K(!0),ze(!0),Ve("video"),console.log("📺 State after mode change:",{currentMode:"video",sessionStarted:!0,loading:!0}),Nt("USER_STARTED_VIDEO_SESSION",{agentId:Z,participantName:ee});const Je=await Ce.startSession(Z,{participantName:ee||"User",modalities:["video","voice"]});console.log("✅ Video session started successfully:",Je.id),ae(Je),K(!1),z&&z(Je.id)}catch(Je){console.error("❌ Failed to start video session:",Je),Lb({title:"Failed to start video session",description:Je instanceof Error?Je.message:"Unknown error occurred"}),K(!1),ze(!1),Ve("welcome")}},Ia=()=>{Ve("welcome"),$e&&$e(t.displayType||"widget"),ge&&je&&(ze(!1),ae(null),Ce.disconnect()),Q==="popup"&&!Me&&Te(!0)},Qa=()=>{const Je=!Me;Te(Je),Ae&&Ae(Je),!Je&&!(ge&&je)&&(Ve("welcome"),ze(!1),ae(null))},Yu=()=>{console.log("🔄 Closing fullscreen, switching to widget display type"),t.onDisplayTypeChange?t.onDisplayTypeChange("widget"):console.warn("⚠️ No onDisplayTypeChange callback provided")},Xr=()=>{t.onDisplayTypeChange&&t.onDisplayTypeChange("fullscreen")};M.useEffect(()=>{var Je,It,pa;if(be&&Ce){console.log("🔄 Syncing widget state with existing client session state");const _t=Ce.getCurrentSession(),a0=Ce.connected;console.log("🔍 Existing session state:",{hasSession:!!_t,sessionId:_t==null?void 0:_t.id,isConnected:a0,activeModalities:_t==null?void 0:_t.activeModalities}),_t&&(console.log("✅ Restoring session state from existing client"),ae(_t),ze(!0),K(!1),(Je=_t.activeModalities)!=null&&Je.includes("chat")?Ve("chat"):(It=_t.activeModalities)!=null&&It.includes("voice")?Ve("voice"):(pa=_t.activeModalities)!=null&&pa.includes("video")&&Ve("video"))}},[be,Ce]),M.useEffect(()=>()=>{console.log("🧹 Cleaning up widget component"),be?console.log("🔄 Widget cleanup: preserving passed client instance"):(console.log("🧹 Widget cleanup: disconnecting self-created client"),Ce.disconnect())},[Ce,be]);let Fr="w-96",ss="h-[25rem]",Zu={};if(A&&(A.startsWith("w-")?Fr=A:(Zu.width=A,Fr="")),C&&(C.startsWith("h-")?ss=C:(Zu.height=C,ss="")),Q==="popup"&&!Me)return console.log("🟡 Showing popup trigger button"),T.jsx(JZ,{onClick:Qa,text:ve,position:se,theme:U});console.log("🟢 Rendering widget content, displayType:",Q,"isPopupOpen:",Me,"currentMode:",Ee,"sessionStarted:",je,"loading:",P);let hc=`voxket-widget-root theme-${U}`,Li={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};Q==="widget"?(hc+=` flex items-center justify-center min-h-fit ${Fr} ${ss} ${S}`,Li={...Li,...Zu}):(hc=`${S||""}`,Li={});const kn=T.jsx(T.Fragment,{children:T.jsxs(zp,{mode:"wait",children:[Ee==="welcome"&&!P&&T.jsx(KZ,{agentId:Z,participantName:ee||"",onAgentIdChange:xe,onParticipantNameChange:fe,onStartCall:Xn,onStartChat:jn,onStartVideo:ln,disabled:je||P,prompts:h,statusMessage:g,title:y,subTitle:x,theme:U,modalities:Oe,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),Ee==="voice"&&T.jsxs(On.RoomContext.Provider,{value:De,children:[T.jsx(On.RoomAudioRenderer,{}),T.jsx(On.StartAudio,{label:"Start Audio"}),T.jsx(FZ,{loadingText:R,participantName:ee||"User",capabilities:Ye,sessionStarted:je,disabled:!je,theme:U,client:Ce,displayType:Q,onBack:Q==="popup"?Qa:Ia,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"session-view")]}),Ee==="chat"&&T.jsx(IZ,{client:Ce,theme:U,displayType:Q,onBack:Q==="popup"?Qa:Ia,onEndChat:Ia,disabled:!je,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),Ee==="video"&&T.jsxs(On.RoomContext.Provider,{value:De,children:[T.jsx(On.RoomAudioRenderer,{}),T.jsx(On.StartAudio,{label:"Start Audio"}),T.jsx(QZ,{client:Ce,theme:U,displayType:Q,onBack:Q==="popup"?Qa:Ia,onEndCall:Ia,disabled:!je,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-view")]})]})});return Q==="fullscreen"||Q==="popup"?(console.log("📱 Rendering fullscreen/popup mode, displayType:",Q),T.jsx(IC,{theme:U,displayType:Q,popupPosition:se,onClose:Q==="fullscreen"?Yu:Qa,children:kn})):(console.log("📦 Rendering widget mode"),T.jsx("div",{className:hc,style:Li,children:T.jsx(IC,{theme:U,displayType:Q,popupPosition:se,onExpand:Xr,children:kn})}))}function WZ({logs:t,onClear:a,onExport:s}){const[l,f]=Y.useState(!1),[p,h]=Y.useState(""),g=t.filter(y=>!p||y.event.toLowerCase().includes(p.toLowerCase()));return l?T.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:T.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[T.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[T.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",t.length,")"]}),T.jsxs("div",{className:"flex items-center gap-2",children:[T.jsx("input",{type:"text",placeholder:"Filter events...",value:p,onChange:y=>h(y.target.value),className:"px-3 py-1 border rounded text-sm"}),T.jsx("button",{onClick:a,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),T.jsx("button",{onClick:s,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),T.jsx("button",{onClick:()=>f(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),T.jsx("div",{className:"flex-1 overflow-auto p-4",children:g.length===0?T.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):T.jsx("div",{className:"space-y-2",children:g.map((y,x)=>T.jsxs("div",{className:"border rounded p-3 text-sm",children:[T.jsxs("div",{className:"flex items-center justify-between mb-1",children:[T.jsx("span",{className:"font-semibold text-blue-600",children:y.event}),T.jsx("span",{className:"text-gray-500 text-xs",children:new Date(y.timestamp).toLocaleTimeString()})]}),y.sessionId&&T.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",y.sessionId]}),y.data&&T.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:T.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(y.data,null,2)})})]},x))})})]})}):T.jsxs("button",{onClick:()=>f(!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 (",t.length,")"]})}function eq({metrics:t}){return t?T.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[T.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),T.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[T.jsxs("div",{children:[T.jsx("span",{className:"text-gray-600",children:"Session ID:"}),T.jsx("div",{className:"font-mono text-xs",children:t.sessionId})]}),T.jsxs("div",{children:[T.jsx("span",{className:"text-gray-600",children:"Start Time:"}),T.jsx("div",{children:new Date(t.startTime).toLocaleString()})]}),T.jsxs("div",{children:[T.jsx("span",{className:"text-gray-600",children:"Messages:"}),T.jsx("div",{children:t.totalMessages})]}),T.jsxs("div",{children:[T.jsx("span",{className:"text-gray-600",children:"Participants:"}),T.jsx("div",{children:t.participantCount})]}),T.jsxs("div",{children:[T.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),T.jsx("div",{children:t.connectionIssues})]}),T.jsxs("div",{children:[T.jsx("span",{className:"text-gray-600",children:"Duration:"}),T.jsxs("div",{children:[Math.round((Date.now()-new Date(t.startTime).getTime())/1e3),"s"]})]})]})]}):null}function Id(){const{currentSession:t,sessionState:a,sessionMetrics:s,createSession:l,endSession:f}=Gr(),p=Y.useCallback(async(g,y)=>await l(g,y),[l]),h=Y.useCallback(async()=>await f(),[f]);return{session:t,state:a,metrics:s,isActive:t!==null&&a!=="disconnected",isConnecting:a==="connecting",isConnected:a==="connected"||a==="active",start:p,stop:h}}function F5(){const{sessionMetrics:t,currentSession:a}=Gr();return{metrics:t,sessionId:a==null?void 0:a.id,duration:t==null?void 0:t.duration,participantCount:t==null?void 0:t.participantCount,messageCount:t==null?void 0:t.messageCount,audioQuality:t==null?void 0:t.audioQuality,networkStats:t==null?void 0:t.networkStats}}function I5(){const{setMicrophoneEnabled:t,client:a}=Gr(),[s,l]=Y.useState(!1),[f,p]=Y.useState(!1),h=Y.useCallback(async()=>{if(!f){p(!0);try{const x=!s;await t(x),l(x)}catch(x){console.error("Failed to toggle microphone:",x)}finally{p(!1)}}},[s,f,t]),g=Y.useCallback(async()=>{if(!(s||f)){p(!0);try{await t(!0),l(!0)}catch(x){console.error("Failed to enable microphone:",x)}finally{p(!1)}}},[s,f,t]),y=Y.useCallback(async()=>{if(!(!s||f)){p(!0);try{await t(!1),l(!1)}catch(x){console.error("Failed to disable microphone:",x)}finally{p(!1)}}},[s,f,t]);return{isEnabled:s,isLoading:f,toggle:h,enable:g,disable:y}}function Q5(){const{setCameraEnabled:t}=Gr(),[a,s]=Y.useState(!1),[l,f]=Y.useState(!1),p=Y.useCallback(async()=>{if(!l){f(!0);try{const y=!a;await t(y),s(y)}catch(y){console.error("Failed to toggle camera:",y)}finally{f(!1)}}},[a,l,t]),h=Y.useCallback(async()=>{if(!(a||l)){f(!0);try{await t(!0),s(!0)}catch(y){console.error("Failed to enable camera:",y)}finally{f(!1)}}},[a,l,t]),g=Y.useCallback(async()=>{if(!(!a||l)){f(!0);try{await t(!1),s(!1)}catch(y){console.error("Failed to disable camera:",y)}finally{f(!1)}}},[a,l,t]);return{isEnabled:a,isLoading:l,toggle:p,enable:h,disable:g}}function K5(){const{startScreenShare:t,stopScreenShare:a}=Gr(),[s,l]=Y.useState(!1),[f,p]=Y.useState(!1),h=Y.useCallback(async()=>{if(!(s||f)){p(!0);try{await t(),l(!0)}catch(x){console.error("Failed to start screen share:",x)}finally{p(!1)}}},[s,f,t]),g=Y.useCallback(async()=>{if(!(!s||f)){p(!0);try{await a(),l(!1)}catch(x){console.error("Failed to stop screen share:",x)}finally{p(!1)}}},[s,f,a]),y=Y.useCallback(async()=>{s?await g():await h()},[s,h,g]);return{isSharing:s,isLoading:f,start:h,stop:g,toggle:y}}function tq(){const{client:t}=Gr(),[a,s]=Y.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),l=Y.useMemo(()=>a.tracks.find(V=>V.isLocal),[a.tracks]),f=Y.useMemo(()=>a.tracks.filter(V=>!V.isLocal),[a.tracks]),p=Y.useCallback(async()=>{try{l!=null&&l.isEnabled?await(t==null?void 0:t.disableCamera()):await(t==null?void 0:t.enableCamera())}catch(V){throw console.error("Failed to toggle camera:",V),V}},[t,l]),h=Y.useCallback(async()=>{try{a.tracks.find(j=>j.isScreenShare)?await(t==null?void 0:t.stopScreenShare()):await(t==null?void 0:t.startScreenShare())}catch(V){throw console.error("Failed to toggle screen share:",V),V}},[t,a.tracks]),g=Y.useCallback(V=>{s(j=>({...j,layout:V}))},[]),y=Y.useCallback(V=>{s(j=>({...j,pinnedTrack:V}))},[]),x=Y.useCallback(()=>{s(V=>({...V,pinnedTrack:void 0}))},[]),S=Y.useCallback(async()=>{try{await(t==null?void 0:t.startRecording()),s(V=>({...V,isRecording:!0}))}catch(V){throw console.error("Failed to start recording:",V),V}},[t]),A=Y.useCallback(async()=>{try{await(t==null?void 0:t.stopRecording()),s(V=>({...V,isRecording:!1}))}catch(V){throw console.error("Failed to stop recording:",V),V}},[t]),C=Y.useCallback(V=>a.tracks.find(j=>j.id===V),[a.tracks]),R=Y.useCallback(V=>a.tracks.filter(j=>j.participantId===V),[a.tracks]),O=Y.useCallback(V=>V.isEnabled&&a.tracks.includes(V),[a.tracks]);return Y.useEffect(()=>{if(!t)return;const V=z=>{s(B=>({...B,tracks:[...B.tracks.filter($=>$.id!==z.id),z]}))},j=z=>{s(B=>{var $;return{...B,tracks:B.tracks.filter(_=>_.id!==z),pinnedTrack:(($=B.pinnedTrack)==null?void 0:$.id)===z?void 0:B.pinnedTrack}})},U=z=>{s(B=>({...B,tracks:B.tracks.map($=>$.id===z.id?z:$)}))};return t.on("videoTrackAdded",V),t.on("videoTrackRemoved",j),t.on("videoTrackUpdated",U),()=>{t.off("videoTrackAdded",V),t.off("videoTrackRemoved",j),t.off("videoTrackUpdated",U)}},[t]),{tracks:a.tracks,localTrack:l,remoteTraracks:f,pinnedTrack:a.pinnedTrack,layout:a.layout,isRecording:a.isRecording,toggleCamera:p,toggleScreenShare:h,setLayout:g,pinTrack:y,unpinTrack:x,startRecording:S,stopRecording:A,getTrackById:C,getTracksByParticipant:R,isTrackActive:O}}function $x(){const{chatMessages:t,sendChatMessage:a,currentSession:s}=Gr(),[l,f]=Y.useState(!1),p=Y.useCallback(async x=>{if(!(!x.trim()||l||!s)){f(!0);try{await a(x.trim())}catch(S){throw console.error("Failed to send chat message:",S),S}finally{f(!1)}}},[a,l,s]),{userMessages:h,agentMessages:g,allMessages:y}=Y.useMemo(()=>{const x=t.filter(A=>A.sender.type==="participant"),S=t.filter(A=>A.sender.type==="agent");return{userMessages:x,agentMessages:S,allMessages:t}},[t]);return{messages:y,userMessages:h,agentMessages:g,messageCount:y.length,isSending:l,canSend:!!s&&!l,send:p}}function nq(){const{send:t,isSending:a,canSend:s}=$x(),[l,f]=Y.useState(""),p=Y.useCallback(async()=>{if(!(!l.trim()||!s))try{await t(l),f("")}catch(g){throw g}},[l,t,s]),h=Y.useCallback(g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),p())},[p]);return{value:l,setValue:f,send:p,handleKeyPress:h,isSending:a,canSend:s&&l.trim().length>0}}function M4(){const{isConnected:t,isConnecting:a,connectionError:s,connect:l,disconnect:f}=Gr(),p=Y.useCallback(async()=>{if(!(t||a))try{await l()}catch(g){throw console.error("Failed to connect:",g),g}},[l,t,a]),h=Y.useCallback(async()=>{if(t)try{await f()}catch(g){throw console.error("Failed to disconnect:",g),g}},[f,t]);return{isConnected:t,isConnecting:a,isDisconnected:!t&&!a,error:s,hasError:!!s,connect:p,disconnect:h}}function J5(){const{participants:t}=Gr();return{participants:t,count:t.length,localParticipant:t.find(a=>a.isLocal),remoteParticipants:t.filter(a=>!a.isLocal)}}const W5=Y.createContext({}),L1=()=>Y.useContext(W5);function eV({children:t,...a}){return T.jsx(W5.Provider,{value:a,children:t})}function ox({name:t,children:a,fallback:s,className:l}){return T.jsx("div",{className:`voxket-slot voxket-slot--${t} ${l||""}`,children:a||s})}function tV(t,a={}){return Object.assign(t,a)}function nV({showMicrophoneControl:t=!0,showCameraControl:a=!0,showScreenShareControl:s=!0,showSessionActions:l=!0,customControls:f,className:p=""}){const h=Id(),g=I5(),y=Q5(),x=K5(),S=L1(),A=["voxket-session-controls",`voxket-session-controls--${S.variant||"default"}`,`voxket-session-controls--${S.size||"md"}`,h.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",p].filter(Boolean).join(" ");return!h.isActive&&!l?T.jsx("div",{className:A,children:T.jsx("div",{className:"voxket-controls-inactive",children:T.jsx("p",{children:"Controls available during active session"})})}):T.jsxs("div",{className:A,children:[l&&T.jsx("div",{className:"voxket-session-actions",children:h.isActive?T.jsx("button",{onClick:h.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):T.jsx(aq,{})}),h.isActive&&T.jsxs("div",{className:"voxket-media-controls",children:[t&&T.jsxs("button",{onClick:g.toggle,disabled:g.isLoading,className:`voxket-button voxket-button--media ${g.isEnabled?"voxket-button--active":""}`,title:g.isEnabled?"Mute microphone":"Unmute microphone",children:[T.jsx("span",{className:"voxket-icon",children:"🎤"}),g.isLoading?"Loading...":g.isEnabled?"Mute":"Unmute"]}),a&&T.jsxs("button",{onClick:y.toggle,disabled:y.isLoading,className:`voxket-button voxket-button--media ${y.isEnabled?"voxket-button--active":""}`,title:y.isEnabled?"Stop camera":"Start camera",children:[T.jsx("span",{className:"voxket-icon",children:"📹"}),y.isLoading?"Loading...":y.isEnabled?"Stop Video":"Start Video"]}),s&&T.jsxs("button",{onClick:x.toggle,disabled:x.isLoading,className:`voxket-button voxket-button--media ${x.isSharing?"voxket-button--active":""}`,title:x.isSharing?"Stop screen share":"Start screen share",children:[T.jsx("span",{className:"voxket-icon",children:"🖥️"}),x.isLoading?"Loading...":x.isSharing?"Stop Share":"Share Screen"]})]}),f&&T.jsx("div",{className:"voxket-custom-controls",children:f})]})}function aq(){Id();const[t,a]=Y.useState(!1),s=async()=>{a(!0);try{console.log("Start session - agentId needed")}catch(l){console.error("Failed to start session:",l)}finally{a(!1)}};return T.jsx("button",{onClick:s,disabled:t,className:"voxket-button voxket-button--primary",children:t?"Starting...":"Start Session"})}function R4({showConnectionStatus:t=!0,showSessionInfo:a=!0,showAgentInfo:s=!0,className:l=""}){const f=Id(),p=M4(),h=L1(),g=["voxket-session-header",`voxket-session-header--${h.variant||"default"}`,`voxket-session-header--${h.size||"md"}`,l].filter(Boolean).join(" ");return T.jsxs("div",{className:g,children:[t&&T.jsxs("div",{className:"voxket-connection-status",children:[T.jsx("div",{className:`voxket-status-indicator ${p.isConnected?"connected":"disconnected"}`}),T.jsx("span",{className:"voxket-status-text",children:p.isConnecting?"Connecting...":p.isConnected?"Connected":"Disconnected"})]}),a&&f.session&&T.jsxs("div",{className:"voxket-session-info",children:[T.jsxs("div",{className:"voxket-session-id",children:["Session: ",f.session.id.slice(-8)]}),T.jsxs("div",{className:"voxket-session-state",children:["State: ",f.state]})]}),s&&f.session&&T.jsxs("div",{className:"voxket-agent-info",children:[T.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",f.session.agentId]}),T.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",f.session.activeModalities.join(", ")]})]}),p.error&&T.jsxs("div",{className:"voxket-error-message",children:["Error: ",p.error.message]})]})}function D4({showChat:t=!0,showTranscriptions:a=!1,customContent:s,className:l=""}){const f=Id(),p=$x(),h=L1(),g=["voxket-session-content",`voxket-session-content--${h.variant||"default"}`,`voxket-session-content--${h.size||"md"}`,l].filter(Boolean).join(" ");return f.isActive?T.jsx("div",{className:g,children:s||T.jsxs(T.Fragment,{children:[t&&T.jsxs("div",{className:"voxket-chat-container",children:[T.jsxs("div",{className:"voxket-chat-messages",children:[p.messages.map(y=>T.jsxs("div",{className:`voxket-message voxket-message--${y.sender.type}`,children:[T.jsxs("div",{className:"voxket-message-header",children:[T.jsx("span",{className:"voxket-message-sender",children:y.sender.name}),T.jsx("span",{className:"voxket-message-time",children:y.timestamp.toLocaleTimeString()})]}),T.jsx("div",{className:"voxket-message-content",children:y.content})]},y.id)),p.messages.length===0&&T.jsx("div",{className:"voxket-empty-messages",children:T.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),T.jsx(iq,{})]}),a&&T.jsx("div",{className:"voxket-transcriptions",children:T.jsx("div",{className:"voxket-transcription-placeholder",children:T.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):T.jsx("div",{className:g,children:T.jsx("div",{className:"voxket-inactive-state",children:T.jsxs("div",{className:"voxket-inactive-message",children:[T.jsx("h3",{children:"Start a conversation"}),T.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function iq(){const t=$x(),[a,s]=Y.useState(""),l=async()=>{if(!(!a.trim()||!t.canSend))try{await t.send(a),s("")}catch(p){console.error("Failed to send message:",p)}},f=p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),l())};return T.jsxs("div",{className:"voxket-chat-input",children:[T.jsx("input",{type:"text",value:a,onChange:p=>s(p.target.value),onKeyPress:f,placeholder:"Type your message...",disabled:!t.canSend,className:"voxket-input"}),T.jsx("button",{onClick:l,disabled:!t.canSend||!a.trim(),className:"voxket-send-button",children:t.isSending?"Sending...":"Send"})]})}function V4({showMetrics:t=!0,showParticipants:a=!0,showStatus:s=!0,customFooter:l,className:f=""}){const p=Id(),h=F5(),g=J5(),y=L1(),x=["voxket-session-footer",`voxket-session-footer--${y.variant||"default"}`,`voxket-session-footer--${y.size||"md"}`,f].filter(Boolean).join(" ");return p.isActive?T.jsx("div",{className:x,children:l||T.jsxs(T.Fragment,{children:[s&&T.jsxs("div",{className:"voxket-session-status",children:[T.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),T.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),t&&h.metrics&&T.jsxs("div",{className:"voxket-session-metrics",children:[T.jsxs("div",{className:"voxket-metric",children:[T.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),T.jsx("span",{className:"voxket-metric-value",children:sq(h.duration||0)})]}),T.jsxs("div",{className:"voxket-metric",children:[T.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),T.jsx("span",{className:"voxket-metric-value",children:h.metrics.messageCount})]})]}),a&&T.jsxs("div",{className:"voxket-participants-info",children:[T.jsxs("span",{className:"voxket-participants-count",children:[g.count," participant",g.count!==1?"s":""]}),g.remoteParticipants.length>0&&T.jsx("div",{className:"voxket-participant-list",children:g.remoteParticipants.map(S=>T.jsx("span",{className:"voxket-participant-name",children:S.name},S.id))})]})]})}):T.jsx("div",{className:x,children:T.jsx("div",{className:"voxket-footer-inactive",children:T.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function sq(t){const a=Math.floor(t/1e3),s=Math.floor(a/60),l=Math.floor(s/60);return l>0?`${l}:${(s%60).toString().padStart(2,"0")}:${(a%60).toString().padStart(2,"0")}`:`${s}:${(a%60).toString().padStart(2,"0")}`}function oq({agentId:t,sessionConfig:a,autoStart:s=!1,onSessionStart:l,onSessionEnd:f,variant:p="default",size:h="md",theme:g,className:y="",children:x}){var R;const S=Id(),A=M4();Y.useEffect(()=>{s&&t&&A.isConnected&&!S.isActive&&S.start(t,a).catch(console.error)},[s,t,A.isConnected,S.isActive]),Y.useEffect(()=>{var O;(O=S.session)!=null&&O.id&&l&&l(S.session.id)},[(R=S.session)==null?void 0:R.id,l]),Y.useEffect(()=>()=>{S.isActive&&f&&S.stop().then(f).catch(console.error)},[]);const C=["voxket-session",`voxket-session--${p}`,`voxket-session--${h}`,S.isActive?"voxket-session--active":"voxket-session--inactive",y].filter(Boolean).join(" ");return T.jsx(eV,{variant:p,size:h,theme:g,className:y,children:T.jsx("div",{className:C,children:x||T.jsxs(T.Fragment,{children:[T.jsx(ox,{name:"header",fallback:T.jsx(R4,{})}),T.jsx(ox,{name:"content",fallback:T.jsx(D4,{})}),T.jsx(ox,{name:"footer",fallback:T.jsx(V4,{})})]})})})}const aV=tV(oq,{Header:R4,Content:D4,Footer:V4,Controls:nV}),Zd={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)"}},Iw={...Zd,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)"}},Qw={...Zd,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"}},iV=Y.createContext(null),sV=()=>{const t=Y.useContext(iV);if(!t)throw new Error("useTheme must be used within a ThemeProvider");return t};function rq({theme:t="default",themes:a={},children:s,cssVariables:l=!0,className:f=""}){const[p,h]=Y.useState(()=>{const C={default:Zd,dark:Iw,enterprise:Qw,...a};return typeof t=="string"?C[t]||Zd:t}),[g,y]=Y.useState(()=>({default:Zd,dark:Iw,enterprise:Qw,...a})),x=C=>{if(typeof C=="string"){const R=g[C];R&&h(R)}else h(C)},S=C=>{y(R=>({...R,[C.name]:C}))};Y.useEffect(()=>{if(l&&typeof document<"u"){const C=document.documentElement;Object.entries(oV(p)).forEach(([R,O])=>{C.style.setProperty(`--voxket-${R}`,O)})}},[p,l]);const A={theme:p,setTheme:x,themes:g,registerTheme:S};return T.jsx(iV.Provider,{value:A,children:T.jsx("div",{className:`voxket-theme voxket-theme--${p.name} ${f}`,children:s})})}function oV(t){const a={},s=(l,f="")=>{for(const[p,h]of Object.entries(l)){const g=f?`${f}-${p}`:p;typeof h=="object"&&h!==null&&!Array.isArray(h)?s(h,g):a[g]=String(h)}};return s(t),a}function lq(t=Zd,a){return{...t,...a,colors:{...t.colors,...a.colors},typography:{...t.typography,...a.typography},spacing:{...t.spacing,...a.spacing},borderRadius:{...t.borderRadius,...a.borderRadius},shadows:{...t.shadows,...a.shadows}}}function cq(t){var s;const{theme:a}=sV();return((s=a.components)==null?void 0:s[t])||{}}const uq=C4("voice-modality","voice",{onActivate:async t=>{const a=t.config;a.enableTranscription&&fq(t),a.enableVoiceActivation&&dq(t,a),console.log("Voice modality activated",a)},onDeactivate:async t=>{console.log("Voice modality deactivated")},onMessage:async(t,a)=>{a.type==="audio"&&hq(t,a)}});function fq(t,a){t.on("participant.speaking.started",s=>{console.log("Transcription: Started for",s.name)}),t.on("participant.speaking.stopped",s=>{console.log("Transcription: Stopped for",s.name)})}function dq(t,a){const s=a.silenceThreshold||-50;console.log("Voice activation setup with threshold:",s)}function hq(t,a){console.log("Playing audio response:",a.content)}const mq=C4("chat-modality","chat",{onActivate:async t=>{const a=t.config;a.enableRichText&&pq(),a.enableFileUpload&&gq(t),a.enableCustomComponents&&yq(),console.log("Chat modality activated",a)},onDeactivate:async t=>{console.log("Chat modality deactivated")},onMessage:async(t,a)=>{const s=t.config;a.type==="ui_component"?vq(t,a):a.type==="text"&&s.enableRichText&&bq(t,a)}});function pq(t){console.log("Rich text support enabled")}function gq(t){console.log("File upload enabled"),t.on("chat.file.uploaded",a=>{console.log("File uploaded:",a.name)})}function yq(t){console.log("Custom components enabled");const a=new Map;a.set("quick-actions",xq),a.set("form",Sq),a.set("card",wq),a.set("chart",Tq)}function vq(t,a){const{componentType:s,props:l}=a.metadata;console.log("Rendering custom component:",s,l),t.emit("chat.component.render",{type:s,props:l,timestamp:new Date})}function bq(t,a){console.log("Processing rich text message:",a.content)}function xq(t){return{type:"quick-actions",actions:t.actions||[],layout:t.layout||"horizontal"}}function Sq(t){return{type:"form",fields:t.fields||[],submitAction:t.submitAction,validation:t.validation}}function wq(t){return{type:"card",title:t.title,content:t.content,actions:t.actions,variant:t.variant||"default"}}function Tq(t){return{type:"chart",chartType:t.chartType||"line",data:t.data,options:t.options}}function rx({track:t,participantName:a,showControls:s=!0,showName:l=!0,showMuteIndicator:f=!0,isPinned:p=!1,className:h="",onClick:g,onPin:y,onUnpin:x}){const S=Y.useRef(null),[A,C]=Y.useState(!1);Y.useEffect(()=>{if(!S.current||!t.isEnabled)return;const j=S.current;return j.srcObject=null,()=>{j.srcObject&&(j.srcObject=null)}},[t]);const R=()=>{g==null||g(t)},O=j=>{j.stopPropagation(),p?x==null||x(t):y==null||y(t)},V=["voxket-video-tile",t.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",t.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",p?"voxket-video-tile--pinned":"",t.isEnabled?"":"voxket-video-tile--disabled",A?"voxket-video-tile--hovered":"",h].filter(Boolean).join(" ");return T.jsxs("div",{className:V,onClick:R,onMouseEnter:()=>C(!0),onMouseLeave:()=>C(!1),style:{aspectRatio:t.dimensions?`${t.dimensions.width} / ${t.dimensions.height}`:"16 / 9"},children:[T.jsx("video",{ref:S,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:t.isLocal}),!t.isEnabled&&T.jsxs("div",{className:"voxket-video-placeholder",children:[T.jsx("div",{className:"voxket-video-placeholder-icon",children:t.isScreenShare?"🖥️":"📹"}),T.jsx("p",{className:"voxket-video-placeholder-text",children:t.isScreenShare?"Screen sharing paused":"Camera off"})]}),T.jsxs("div",{className:"voxket-video-overlay",children:[l&&a&&T.jsxs("div",{className:"voxket-video-name",children:[a,t.isLocal&&" (You)"]}),f&&!t.isEnabled&&T.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),s&&(A||p)&&T.jsxs("div",{className:"voxket-video-controls",children:[T.jsx("button",{className:`voxket-video-control-btn ${p?"voxket-video-control-btn--active":""}`,onClick:O,title:p?"Unpin video":"Pin video",children:"📌"}),t.isScreenShare&&T.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),t.source&&T.jsx("div",{className:"voxket-video-source",children:t.source})]})]}),!t.isEnabled&&T.jsx("div",{className:"voxket-video-loading",children:T.jsx("div",{className:"voxket-spinner"})})]})}function Aq({tracks:t,layout:a,className:s="",onLayoutChange:l,onTrackClick:f,maxVisibleTracks:p=9,showPagination:h=!0}){const[g,y]=Y.useState(0),[x,S]=Y.useState(null),A=Y.useMemo(()=>{let z=[...t];a.type==="speaker"&&x&&(z=[x,...t.filter(_=>_.id!==x.id)]);const B=g*p,$=B+p;return z.slice(B,$)},[t,a,x,g,p]),C=Math.ceil(t.length/p),R=Y.useMemo(()=>{const z=A.length;switch(a.type){case"grid":const B=Math.ceil(Math.sqrt(z)),$=Math.ceil(z/B);return{display:"grid",gridTemplateColumns:`repeat(${B}, 1fr)`,gridTemplateRows:`repeat(${$}, 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{}}},[a.type,A.length]),O=z=>{S(z)},V=()=>{S(null)},j=z=>{l==null||l({...a,type:z})},U=["voxket-video-grid",`voxket-video-grid--${a.type}`,`voxket-video-grid--${A.length}-tracks`,s].filter(Boolean).join(" ");return t.length===0?T.jsx("div",{className:"voxket-video-grid-empty",children:T.jsxs("div",{className:"voxket-video-grid-empty-content",children:[T.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),T.jsx("p",{children:"No video tracks available"})]})}):T.jsxs("div",{className:U,children:[T.jsxs("div",{className:"voxket-video-grid-controls",children:[T.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(z=>T.jsx("button",{className:`voxket-layout-btn ${a.type===z?"voxket-layout-btn--active":""}`,onClick:()=>j(z),title:`Switch to ${z} layout`,children:Eq(z)},z))}),T.jsxs("div",{className:"voxket-video-count",children:[t.length," participant",t.length!==1?"s":""]})]}),T.jsx("div",{className:"voxket-video-grid-content",style:R,children:a.type==="speaker"&&x?T.jsxs(T.Fragment,{children:[T.jsx("div",{className:"voxket-video-speaker-main",children:T.jsx(rx,{track:x,participantName:`Participant ${x.participantId}`,isPinned:!0,onClick:f,onUnpin:V})}),T.jsx("div",{className:"voxket-video-speaker-sidebar",children:A.filter(z=>z.id!==x.id).map(z=>T.jsx(rx,{track:z,participantName:`Participant ${z.participantId}`,showControls:!1,onClick:f,onPin:O},z.id))})]}):A.map(z=>T.jsx(rx,{track:z,participantName:`Participant ${z.participantId}`,isPinned:(x==null?void 0:x.id)===z.id,onClick:f,onPin:O,onUnpin:V},z.id))}),h&&C>1&&T.jsxs("div",{className:"voxket-video-pagination",children:[T.jsx("button",{className:"voxket-pagination-btn",onClick:()=>y(Math.max(0,g-1)),disabled:g===0,children:"←"}),T.jsxs("span",{className:"voxket-pagination-info",children:["Page ",g+1," of ",C]}),T.jsx("button",{className:"voxket-pagination-btn",onClick:()=>y(Math.min(C-1,g+1)),disabled:g===C-1,children:"→"})]})]})}function Eq(t){switch(t){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function Cq({localTrack:t,onToggleCamera:a,onToggleScreenShare:s,onLayoutChange:l,showLayoutControls:f=!0,showCameraControls:p=!0,showScreenShareControls:h=!0,className:g=""}){const y=["voxket-video-controls",g].filter(Boolean).join(" "),x=S=>{l==null||l({type:S,showLocalVideo:!0,aspectRatio:"16:9"})};return T.jsxs("div",{className:y,children:[p&&T.jsxs("div",{className:"voxket-video-controls-section",children:[T.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),T.jsxs("button",{className:`voxket-control-btn ${t!=null&&t.isEnabled?"voxket-control-btn--active":""}`,onClick:a,title:t!=null&&t.isEnabled?"Turn off camera":"Turn on camera",children:[T.jsx("span",{className:"voxket-control-icon",children:t!=null&&t.isEnabled?"📹":"📷"}),T.jsx("span",{className:"voxket-control-label",children:t!=null&&t.isEnabled?"Camera On":"Camera Off"})]}),(t==null?void 0:t.dimensions)&&T.jsxs("div",{className:"voxket-video-info",children:[t.dimensions.width," × ",t.dimensions.height]})]}),h&&T.jsxs("div",{className:"voxket-video-controls-section",children:[T.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),T.jsxs("button",{className:`voxket-control-btn ${t!=null&&t.isScreenShare?"voxket-control-btn--active":""}`,onClick:s,title:t!=null&&t.isScreenShare?"Stop screen sharing":"Start screen sharing",children:[T.jsx("span",{className:"voxket-control-icon",children:t!=null&&t.isScreenShare?"🛑":"🖥️"}),T.jsx("span",{className:"voxket-control-label",children:t!=null&&t.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),f&&T.jsxs("div",{className:"voxket-video-controls-section",children:[T.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),T.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:S,icon:A,label:C})=>T.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>x(S),title:`Switch to ${C} layout`,children:[T.jsx("span",{className:"voxket-control-icon",children:A}),T.jsx("span",{className:"voxket-control-label",children:C})]},S))})]}),T.jsxs("div",{className:"voxket-video-controls-section",children:[T.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),T.jsxs("div",{className:"voxket-video-settings",children:[T.jsxs("div",{className:"voxket-setting-group",children:[T.jsx("label",{className:"voxket-setting-label",children:"Quality"}),T.jsxs("select",{className:"voxket-setting-select",children:[T.jsx("option",{value:"high",children:"High (720p)"}),T.jsx("option",{value:"medium",children:"Medium (480p)"}),T.jsx("option",{value:"low",children:"Low (240p)"})]})]}),T.jsxs("div",{className:"voxket-setting-group",children:[T.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),T.jsxs("select",{className:"voxket-setting-select",children:[T.jsx("option",{value:"30",children:"30 fps"}),T.jsx("option",{value:"15",children:"15 fps"}),T.jsx("option",{value:"10",children:"10 fps"})]})]}),T.jsxs("div",{className:"voxket-setting-group",children:[T.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),T.jsxs("select",{className:"voxket-setting-select",children:[T.jsx("option",{value:"unlimited",children:"Unlimited"}),T.jsx("option",{value:"1000",children:"1 Mbps"}),T.jsx("option",{value:"500",children:"500 Kbps"}),T.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),T.jsxs("div",{className:"voxket-video-controls-section",children:[T.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),T.jsxs("div",{className:"voxket-video-stats",children:[T.jsxs("div",{className:"voxket-stat-item",children:[T.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),T.jsx("span",{className:"voxket-stat-value",children:t!=null&&t.dimensions?`${t.dimensions.width}×${t.dimensions.height}`:"N/A"})]}),T.jsxs("div",{className:"voxket-stat-item",children:[T.jsx("span",{className:"voxket-stat-label",children:"Source:"}),T.jsx("span",{className:"voxket-stat-value",children:(t==null?void 0:t.source)||"None"})]}),T.jsxs("div",{className:"voxket-stat-item",children:[T.jsx("span",{className:"voxket-stat-label",children:"Status:"}),T.jsx("span",{className:`voxket-stat-value ${t!=null&&t.isEnabled?"voxket-stat-value--active":"voxket-stat-value--inactive"}`,children:t!=null&&t.isEnabled?"Active":"Inactive"})]})]})]})]})}const rV=({handler:t,loadData:a,data:s,client:l,addLocalMessage:f})=>{const[p,h]=M.useState(null),[g,y]=M.useState(!0),[x,S]=M.useState(!1),[A]=M.useState(Date.now());M.useEffect(()=>{(async()=>{try{if(y(!0),console.log("📋 AssignmentView: Loading assignment data..."),console.log("📋 AssignmentView: Received data from RPC:",s),s&&typeof s=="object"){const j={title:s.title||"Untitled Assignment",description:s.description||"No description provided",estimated_time_of_completion:s.estimated_time_of_completion||"Unknown"};h(j),console.log("📋 AssignmentView: Assignment loaded from RPC data:",j)}}catch(j){console.error("📋 AssignmentView: Error loading assignment:",j),h({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{y(!1)}})()},[s,a]);const C=({message:V,assignment:j})=>{const U=V.toLowerCase().includes("declined"),z=U?"bg-red-50 border-red-200":"bg-green-50 border-green-200",B=U?"text-red-700":"text-green-700",$=U?"❌":"🎉";return T.jsxs("div",{className:`max-w-sm mx-auto ${z} border rounded-lg shadow p-3 flex flex-col items-center`,children:[T.jsx("div",{className:"text-2xl mb-2",children:$}),T.jsx("div",{className:`${B} font-semibold text-sm mb-1`,children:V}),T.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:j.title}),T.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},R=async()=>{if(!(!p||!t)){S(!0);try{const V={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",V),t.didSuccess(V,T.jsx(C,{message:"Assignment accepted!",assignment:p}))}catch(V){console.error("📋 AssignmentView: Error accepting assignment:",V),t.didFail({error:"Failed to accept assignment"})}finally{S(!1)}}},O=async()=>{if(!(!p||!t)){S(!0);try{const V={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",V),t.didSuccess(V,T.jsx(C,{message:"Assignment declined",assignment:p}))}catch(V){console.error("📋 AssignmentView: Error declining assignment:",V),t.didFail({error:"Failed to decline assignment"})}finally{S(!1)}}};return g?T.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:T.jsxs("div",{className:"flex items-center justify-center py-4",children:[T.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),T.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):p?T.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[T.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:T.jsx("div",{className:"flex items-center justify-between",children:T.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:p.title})})}),T.jsxs("div",{className:"p-3",children:[T.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:T.jsx("p",{className:"text-xs text-gray-700 leading-snug",children:p.description})}),T.jsx("div",{className:"mb-3",children:T.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[T.jsx("span",{className:"text-xs mr-1",children:"📅"}),T.jsxs("span",{children:["Est: ",p.estimated_time_of_completion]})]})}),T.jsxs("div",{className:"flex gap-2",children:[T.jsx("button",{onClick:R,disabled:x,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:x?T.jsxs("span",{className:"flex items-center justify-center",children:[T.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),T.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),T.jsx("button",{onClick:O,disabled:x,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"})]})]})]}):T.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:T.jsxs("div",{className:"text-center py-4",children:[T.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),T.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function Mq(){const[t,a]=M.useState(null),[s,l]=M.useState([]);M.useEffect(()=>{const g=new U1({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return a(g),g.on("rpc.method.called",y=>{console.log("RPC Method Called:",y)}),g.on("rpc.interaction.completed",y=>{console.log("RPC Interaction Completed:",y)}),()=>{g.disconnect()}},[]);const f=async()=>{if(t)try{await t.registerFrontendRPC("give_assignment",rV,"embedded");const g=t.getRegisteredRpcMethods();l(g),console.log("✅ Assignment RPC registered successfully")}catch(g){console.error("❌ Failed to register assignment RPC:",g)}},p=async()=>{if(!t)return;const g=({handler:y,timeout:x})=>{const[S,A]=M.useState(""),C=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],R=V=>{A(V)},O=()=>{const V=C.find(j=>j.id===S);y==null||y.didSuccess({selectedProduct:S,productName:V==null?void 0:V.name,price:V==null?void 0:V.price,timestamp:new Date().toISOString()})};return T.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[T.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),T.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),T.jsx("div",{className:"space-y-3 mb-6",children:C.map(V=>T.jsx("div",{onClick:()=>R(V.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${S===V.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:T.jsxs("div",{className:"flex justify-between items-center",children:[T.jsxs("div",{children:[T.jsx("h4",{className:"font-medium",children:V.name}),T.jsx("p",{className:"text-gray-600 text-sm",children:V.price})]}),T.jsx("div",{className:`w-4 h-4 rounded-full ${S===V.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},V.id))}),T.jsxs("div",{className:"flex justify-end space-x-3",children:[T.jsx("button",{onClick:()=>y==null?void 0:y.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),T.jsx("button",{onClick:O,disabled:!S,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),x&&T.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",x," seconds"]})]})};try{await t.registerFrontendRPC("recommend_product",g,"modal");const y=t.getRegisteredRpcMethods();l(y),console.log("✅ Product Recommendation RPC registered successfully")}catch(y){console.error("❌ Failed to register product recommendation RPC:",y)}},h=async()=>{if(!t)return;const g=({handler:y})=>{const[x,S]=M.useState(0),[A,C]=M.useState(""),R=()=>{y==null||y.didSuccess({rating:x,comment:A,timestamp:new Date().toISOString()})};return T.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[T.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),T.jsxs("div",{className:"mb-4",children:[T.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),T.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(O=>T.jsx("button",{onClick:()=>S(O),className:`text-2xl ${O<=x?"text-yellow-400":"text-gray-300"}`,children:"⭐"},O))})]}),T.jsxs("div",{className:"mb-4",children:[T.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),T.jsx("textarea",{value:A,onChange:O=>C(O.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),T.jsxs("div",{className:"flex justify-end space-x-2",children:[T.jsx("button",{onClick:()=>y==null?void 0:y.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),T.jsx("button",{onClick:R,disabled:x===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 t.registerFrontendRPC("collect_feedback",g,"embedded");const y=t.getRegisteredRpcMethods();l(y),console.log("✅ Feedback RPC registered successfully")}catch(y){console.error("❌ Failed to register feedback RPC:",y)}};return T.jsxs("div",{className:"p-6",children:[T.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),T.jsxs("div",{className:"space-y-4 mb-6",children:[T.jsxs("div",{children:[T.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),T.jsxs("div",{className:"space-x-2",children:[T.jsx("button",{onClick:f,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),T.jsx("button",{onClick:p,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),T.jsx("button",{onClick:h,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),T.jsxs("div",{children:[T.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),s.length>0?T.jsx("ul",{className:"list-disc list-inside space-y-1",children:s.map(g=>T.jsx("li",{className:"text-gray-700",children:T.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:g})},g))}):T.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),T.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[T.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),T.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[T.jsxs("li",{children:["Register RPC methods with React components using ",T.jsx("code",{children:"client.registerFrontendRPC()"})]}),T.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),T.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),T.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),T.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),T.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[T.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),T.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),T.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
|
|
447
|
+
root.render(<App />);`),n.unstable_strictMode===!0&&(o=!0),n.identifierPrefix!==void 0&&(u=n.identifierPrefix),n.onUncaughtError!==void 0&&(m=n.onUncaughtError),n.onCaughtError!==void 0&&(v=n.onCaughtError),n.onRecoverableError!==void 0&&(E=n.onRecoverableError),n.unstable_transitionCallbacks!==void 0&&(D=n.unstable_transitionCallbacks)),n=_g(e,1,!1,null,null,o,u,m,v,E,D,null),e[Dr]=n.current,Tg(e),new Cm(n)},Jy.hydrateRoot=function(e,n,o){if(!j(e))throw Error("Target container is not a DOM element.");zv(e),n===void 0&&console.error("Must provide initial children as second argument to hydrateRoot. Example usage: hydrateRoot(domContainer, <App />)");var u=!1,m="",v=q0,E=uv,D=jh,L=null,H=null;return o!=null&&(o.unstable_strictMode===!0&&(u=!0),o.identifierPrefix!==void 0&&(m=o.identifierPrefix),o.onUncaughtError!==void 0&&(v=o.onUncaughtError),o.onCaughtError!==void 0&&(E=o.onCaughtError),o.onRecoverableError!==void 0&&(D=o.onRecoverableError),o.unstable_transitionCallbacks!==void 0&&(L=o.unstable_transitionCallbacks),o.formState!==void 0&&(H=o.formState)),n=_g(e,1,!0,n,o??null,u,m,v,E,D,L,H),n.context=Pg(null),o=n.current,u=Ba(o),u=kn(u),m=hs(u),m.callback=null,Zi(o,m,u),o=u,n.current.lanes=o,ss(n,o),Ei(n),e[Dr]=n.current,Tg(e),new Kf(n)},Jy.version="19.1.0",typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Jy}var FC;function _Z(){if(FC)return Xb.exports;FC=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function")){if(process.env.NODE_ENV!=="production")throw new Error("^_^");try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(a){console.error(a)}}}return process.env.NODE_ENV==="production"?(t(),Xb.exports=HZ()):Xb.exports=$Z(),Xb.exports}var PZ=_Z();class E4{constructor(){Zn(this,"listeners",{})}on(a,s){return this.listeners[a]||(this.listeners[a]=[]),this.listeners[a].push(s),()=>this.off(a,s)}once(a,s){const l=(...f)=>{this.off(a,l),s(...f)};return this.on(a,l)}off(a,s){const l=this.listeners[a];if(!l)return;const f=l.indexOf(s);f>-1&&l.splice(f,1)}removeAllListeners(a){a?delete this.listeners[a]:this.listeners={}}emit(a,...s){const l=this.listeners[a];if(!l)return;const f=[...l];for(const p of f)try{p(...s)}catch(h){console.error(`Error in event listener for ${String(a)}:`,h)}}listenerCount(a){var s;return((s=this.listeners[a])==null?void 0:s.length)??0}eventNames(){return Object.keys(this.listeners)}}class Z5{constructor(a){Zn(this,"plugins",new Map);Zn(this,"installedPlugins",new Set);Zn(this,"context");this.context={client:a,emit:a.emit.bind(a),on:a.on.bind(a),config:{}}}register(a){if(this.plugins.has(a.name))throw new Error(`Plugin '${a.name}' is already registered`);if(a.dependencies){for(const s of a.dependencies)if(!this.plugins.has(s))throw new Error(`Plugin '${a.name}' depends on '${s}' which is not registered`)}this.plugins.set(a.name,a)}async install(a,s){const l=this.plugins.get(a);if(!l)throw new Error(`Plugin '${a}' is not registered`);if(this.installedPlugins.has(a))throw new Error(`Plugin '${a}' is already installed`);if(l.dependencies)for(const p of l.dependencies)this.installedPlugins.has(p)||await this.install(p);const f={...this.context,config:{...l.config,...s}};l.install&&await l.install(f),this.installedPlugins.add(a),this.setupPluginEvents(l,f)}async uninstall(a){var l;const s=this.plugins.get(a);if(!s)throw new Error(`Plugin '${a}' is not registered`);if(this.installedPlugins.has(a)){for(const[f,p]of this.plugins)if(this.installedPlugins.has(f)&&((l=p.dependencies)!=null&&l.includes(a)))throw new Error(`Cannot uninstall '${a}' because '${f}' depends on it`);s.uninstall&&await s.uninstall(this.context),this.installedPlugins.delete(a)}}isInstalled(a){return this.installedPlugins.has(a)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(a){return this.plugins.get(a)}setupPluginEvents(a,s){a.onSessionStart&&s.on("session.started",l=>{a.onSessionStart(s,l.id)}),a.onSessionEnd&&s.on("session.ended",l=>{a.onSessionEnd(s,l.id)}),a.onAgentResponse&&s.on("agent.response",l=>{a.onAgentResponse(s,l)})}}function YZ(t){return t}function C4(t,a,s){return{name:t,version:"1.0.0",description:`${a} modality plugin`,install:async l=>{s.onActivate&&await s.onActivate(l)},uninstall:async l=>{s.onDeactivate&&await s.onDeactivate(l)},onAgentResponse:s.onMessage}}const ZZ={name:"analytics",version:"1.0.0",description:"Built-in analytics tracking",install:async t=>{console.log("Analytics plugin installed"),t.on("session.started",a=>{console.log("Analytics: Session started",a.id)}),t.on("session.ended",(a,s)=>{console.log("Analytics: Session ended",a.id,s)}),t.on("chat.message.sent",a=>{console.log("Analytics: User message sent",a.content.length)})}},qZ={name:"debug",version:"1.0.0",description:"Debug logging and development tools",install:async t=>{console.log("Debug plugin installed");const a=t.emit;t.emit=(s,...l)=>(console.log(`[Debug] Event: ${String(s)}`,l),a(s,...l))}},GZ={name:"metrics",version:"1.0.0",description:"Advanced metrics collection",install:async t=>{console.log("Metrics plugin installed");const a=new Map;t.on("session.started",s=>{a.set(s.id,{startTime:Date.now(),events:[]})}),t.on("agent.response",s=>{console.log("Metrics: Agent response analyzed",{type:s.type,length:s.content.length,timestamp:s.timestamp})})}},q5=Y.createContext(null);function G5({config:t,children:a,autoConnect:s=!1}){const[l,f]=Y.useState(null),[p,h]=Y.useState(!1),[g,y]=Y.useState(!1),[x,S]=Y.useState(null),[A,C]=Y.useState(null),[R,O]=Y.useState("idle"),[V,j]=Y.useState(null),[U,z]=Y.useState([]),[B,$]=Y.useState([]),[_,I]=Y.useState([]);Y.useEffect(()=>{const Z=new U1(t);return f(Z),G(Z),s&&Q(Z),()=>{Z.disconnect().catch(console.error)}},[t,s]);const G=Z=>{Z.on("connection.connecting",()=>{y(!0),S(null)}),Z.on("connection.connected",()=>{h(!0),y(!1),S(null)}),Z.on("connection.disconnected",()=>{h(!1),y(!1),C(null),O("idle"),z([]),$([]),I([])}),Z.on("connection.error",xe=>{S(xe),y(!1)}),Z.on("session.created",xe=>{C(xe),O(xe.state)}),Z.on("session.state.changed",xe=>{O(xe),A&&C({...A,state:xe})}),Z.on("session.ended",(xe,ee)=>{C(null),O("idle"),j(ee),z([]),$([]),I([])}),Z.on("participant.joined",xe=>{z(ee=>[...ee,xe])}),Z.on("participant.left",xe=>{z(ee=>ee.filter(fe=>fe.id!==xe.id))}),Z.on("chat.message.received",xe=>{$(ee=>[...ee,xe])}),Z.on("chat.message.sent",xe=>{$(ee=>[...ee,xe])}),Z.on("transcription.received",xe=>{I(ee=>[...ee,xe])})},Q=async Z=>{const xe=Z||l;if(xe)try{await xe.connect()}catch(ee){console.error("Failed to connect:",ee)}},K={client:l,isConnected:p,isConnecting:g,connectionError:x,currentSession:A,sessionState:R,sessionMetrics:V,participants:U,chatMessages:B,transcriptions:_,connect:()=>Q(),disconnect:async()=>{if(l)try{await l.disconnect()}catch(Z){console.error("Failed to disconnect:",Z)}},createSession:async(Z,xe={})=>{if(!l)throw new Error("Client not initialized");const ee={agentId:Z,participantName:xe.participantName||"User",metadata:xe.metadata,modalities:xe.modalities||["voice"]};return await l.createSession(ee)},endSession:async()=>l?await l.endSession():null,sendChatMessage:async Z=>{if(!l)throw new Error("Client not initialized");await l.sendChatMessage(Z)},setMicrophoneEnabled:async Z=>{if(!l)throw new Error("Client not initialized");await l.setMicrophoneEnabled(Z)},setCameraEnabled:async Z=>{if(!l)throw new Error("Client not initialized");await l.setCameraEnabled(Z)},startScreenShare:async()=>{if(!l)throw new Error("Client not initialized");await l.startScreenShare()},stopScreenShare:async()=>{if(!l)throw new Error("Client not initialized");await l.stopScreenShare()}};return T.jsx(q5.Provider,{value:K,children:a})}function Gr(){const t=Y.useContext(q5);if(!t)throw new Error("useVoxket must be used within a VoxketProvider");return t}class XZ extends E4{constructor(s){super();Zn(this,"room",null);Zn(this,"registeredMethods",new Map);Zn(this,"activeInteractions",new Map);Zn(this,"currentInteraction",null);s&&this.setRoom(s)}setRoom(s){this.room=s}async registerFrontendRPC(s,l,f="embedded"){if(console.log(`RpcManager: Starting registration for method '${s}'`),!this.room)throw console.error(`RpcManager: Cannot register '${s}' - no room instance`),new Error("Room not initialized. Cannot register RPC method.");if(!this.room.localParticipant)throw console.error(`RpcManager: Cannot register '${s}' - 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: ${s}`);const p={methodName:s,component:l,presentationMode:f};this.registeredMethods.set(s,p);try{this.room.registerRpcMethod(s,async h=>{console.log(`RpcManager: RPC method '${s}' called by ${h.callerIdentity}`),console.log("RpcManager: Payload:",h.payload),this.emit("rpc.method.called",{methodName:s,data:h});let g;console.log(`RpcManager: Current registration for '${s}':`,p);let y=h.responseTimeout||30;try{g=JSON.parse(h.payload)}catch{g=h.payload}try{const x=await this.awaitUserInteraction(s,l,f,g,y);return JSON.stringify(x)}catch(x){throw console.error(`RpcManager: Error in RPC method '${s}':`,x),x}}),this.emit("rpc.method.registered",{methodName:s}),console.log(`RpcManager: Successfully registered RPC method: ${s}`)}catch(h){throw console.error(`RpcManager: Failed to register RPC method '${s}':`,h),h}}async awaitUserInteraction(s,l,f,p,h){return new Promise((g,y)=>{const x=`${s}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${s}, timeout: ${h} seconds`);const S={didSuccess:(C,R)=>{console.log(`RpcManager: User interaction successful for method: ${s}`,C),this.clearInteraction(x),this.currentInteraction=null;const O={success:!0,message:"User interaction completed successfully",data:C,timestamp:new Date,...R?{successView:R}:{}};this.emit("rpc.interaction.completed",{methodName:s,response:O}),g(O)},didFail:C=>{console.log(`RpcManager: User interaction failed for method: ${s}`,C),this.clearInteraction(x);const R={success:!1,message:"User interaction failed",error:C,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:s,response:R}),g(R)},dismissView:()=>{var R;console.log(`RpcManager: User dismissed interaction for method: ${s}`),console.log("RpcManager: Current interaction before dismiss:",(R=this.currentInteraction)==null?void 0:R.methodName),this.clearInteraction(x),this.currentInteraction=null,console.log("RpcManager: Current interaction after dismiss:",this.currentInteraction);const C={success:!0,data:{dismissed:!0,reason:"User dismissed the interaction"},message:"User interaction dismissed",timestamp:new Date};this.emit("rpc.interaction.dismissed",{methodName:s,response:C}),this.emit("rpc.interaction.completed",{methodName:s,response:C}),setTimeout(()=>{var O;((O=this.currentInteraction)==null?void 0:O.methodName)===s&&(console.log(`RpcManager: Force clearing interaction for ${s}`),this.currentInteraction=null)},0),g(C)},didTimeout:C=>{console.log(`RpcManager: User interaction timeout for method: ${s}`),this.clearInteraction(x),this.currentInteraction=null;const R={success:!0,message:`User interaction timed out after ${h} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...C?{timeoutView:C}:{}};this.emit("rpc.interaction.timeout",{methodName:s,response:R}),setTimeout(()=>{var O;((O=this.currentInteraction)==null?void 0:O.methodName)===s&&(console.log(`RpcManager: Force clearing interaction for ${s}`),this.currentInteraction=null)},0),g(R)}},A=setTimeout(()=>{S.didTimeout&&S.didTimeout()},h);this.activeInteractions.set(x,{resolve:C=>g(JSON.parse(C)),reject:y,timeoutId:A}),this.currentInteraction={isVisible:!0,methodName:s,component:l,presentationMode:f,timeout:h,data:p,handler:S},this.emit("rpc.interaction.started",{methodName:s,presentationMode:f}),setTimeout(async()=>{var C;if((C=this.currentInteraction)!=null&&C.handler)try{console.log(`RpcManager: Component created for method: ${s} with data:`,p)}catch(R){console.error("RpcManager: Error loading data into component:",R),S.didFail({error:"Failed to load data into component"})}},100)})}clearInteraction(s){const l=this.activeInteractions.get(s);l&&(console.log(`RpcManager: Clearing interaction: ${s}`),clearTimeout(l.timeoutId),this.activeInteractions.delete(s))}getCurrentInteraction(){return this.currentInteraction}dismissCurrentInteraction(){var s;this.currentInteraction&&(console.log(`RpcManager: Dismissing current interaction: ${this.currentInteraction.methodName}`),(s=this.currentInteraction.handler)==null||s.dismissView(),setTimeout(()=>{this.currentInteraction&&(console.log("RpcManager: Force clearing lingering interaction"),this.currentInteraction=null)},0))}getRegisteredMethods(){return Array.from(this.registeredMethods.keys())}unregisterMethod(s){this.registeredMethods.delete(s),console.log(`RpcManager: Unregistered RPC method: ${s}`)}clear(){for(const[s,l]of this.activeInteractions)clearTimeout(l.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null,console.log("RpcManager: Cleared all registrations and interactions")}}class $t extends Error{constructor(a,s,l){super(a),this.code=s,this.details=l,this.name="VoxketError"}}class U1 extends E4{constructor(s){super();Zn(this,"config");Zn(this,"room",null);Zn(this,"pluginManager");Zn(this,"rpcManager");Zn(this,"isConnected",!1);Zn(this,"currentSession",null);Zn(this,"connectionState",Ze.ConnectionState.Disconnected);Zn(this,"renderedComponents",new Map);Zn(this,"textStreamHandlersRegistered",!1);Zn(this,"currentAgentInfo",null);Zn(this,"chatMessages",[]);this.config=s,this.pluginManager=new Z5(this),this.rpcManager=new XZ,this.setupEventListeners(),this.initializeClient()}setupEventListeners(){this.on("connection.connected",()=>{var s,l;this.isConnected=!0,(l=(s=this.config).onConnected)==null||l.call(s)}),this.on("connection.disconnected",s=>{var l,f;this.isConnected=!1,(f=(l=this.config).onDisconnected)==null||f.call(l,s)}),this.on("connection.error",s=>{var l,f;(f=(l=this.config).onError)==null||f.call(l,s)}),this.on("chat.message.received",s=>{var l,f;this.addChatMessage(s),(f=(l=this.config).onMessageReceived)==null||f.call(l,s)}),this.on("chat.message.updated",s=>{this.updateChatMessage(s)}),this.on("chat.message.sent",s=>{this.addChatMessage(s)}),this.on("transcription.received",s=>{var l,f;(f=(l=this.config).onTranscriptionReceived)==null||f.call(l,s)}),this.on("session.state.changed",s=>{var l,f;(f=(l=this.config).onSessionStateChanged)==null||f.call(l,s)}),this.on("session.created",s=>{var l,f;(f=(l=this.config).onSessionStart)==null||f.call(l,s.id)}),this.on("session.ended",(s,l)=>{var f,p;(p=(f=this.config).onSessionEnd)==null||p.call(f,l)}),this.on("participant.joined",s=>{var l,f;(f=(l=this.config).onUserJoined)==null||f.call(l,s.id)}),this.on("participant.left",s=>{var l,f;(f=(l=this.config).onUserLeft)==null||f.call(l,s.id)}),this.setupRpcEventForwarding()}setupRpcEventForwarding(){if(!this.rpcManager){console.warn("RpcManager not initialized, skipping event forwarding setup");return}this.rpcManager.on("rpc.method.registered",s=>this.emit("rpc.method.registered",s)),this.rpcManager.on("rpc.method.called",s=>this.emit("rpc.method.called",s)),this.rpcManager.on("rpc.interaction.started",s=>this.emit("rpc.interaction.started",s)),this.rpcManager.on("rpc.interaction.completed",s=>this.emit("rpc.interaction.completed",s)),this.rpcManager.on("rpc.interaction.timeout",s=>this.emit("rpc.interaction.timeout",s)),this.rpcManager.on("rpc.interaction.dismissed",s=>this.emit("rpc.interaction.dismissed",s))}initializeClient(){this.room=new Ze.Room,this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(Ze.RoomEvent.Connected,()=>{var s,l;this.connectionState=Ze.ConnectionState.Connected,this.emit("connection.connected"),this.rpcManager.setRoom(this.room),(l=(s=this.currentSession)==null?void 0:s.activeModalities)!=null&&l.includes("voice")&&setTimeout(async()=>{var f;try{(f=this.room)!=null&&f.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(p){console.warn("VoxketClient: Failed to enable microphone after room connection:",p)}},1e3),this.textStreamHandlersRegistered||this.setupTextStreamHandlers()}),this.room.on(Ze.RoomEvent.Disconnected,s=>{this.connectionState=Ze.ConnectionState.Disconnected,this.textStreamHandlersRegistered=!1,this.emit("connection.disconnected",s==null?void 0:s.toString())}),this.room.on(Ze.RoomEvent.ConnectionStateChanged,s=>{this.connectionState=s,s===Ze.ConnectionState.Connecting&&this.emit("connection.connecting")}),this.room.on(Ze.RoomEvent.ParticipantConnected,s=>{const l={id:s.identity,name:s.name||s.identity,isLocal:!1};this.emit("participant.joined",l)}),this.room.on(Ze.RoomEvent.ParticipantDisconnected,s=>{const l={id:s.identity,name:s.name||s.identity,isLocal:!1};this.emit("participant.left",l)}))}setupTextStreamHandlers(){if(this.room){try{this.room.registerTextStreamHandler("lk.chat",async(s,l)=>{try{const f=await s.readAll(),p={id:`msg_${Date.now()}_${l.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:f,timestamp:new Date,sender:{id:l.identity||"user",name:l.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.emit("chat.message.received",p)}catch(f){console.error("VoxketClient: Failed to process lk.chat message:",f)}})}catch(s){console.warn("VoxketClient: lk.chat handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("lk.transcription",async(s,l)=>{var f,p;try{const h=`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`;let g="";const y=((f=this.currentAgentInfo)==null?void 0:f.name)||l.identity||"AI Assistant",x={id:h,content:"",timestamp:new Date,sender:{id:l.identity||"agent",name:y,type:"agent"},metadata:{topic:"lk.transcription",streaming:!0}};this.emit("chat.message.received",x);for await(const C of s){g+=C;const R=this.convertMarkdownToText(g),O={...x,content:R,metadata:{...x.metadata,streaming:!0}};this.emit("chat.message.updated",O)}const S=this.convertMarkdownToText(g),A={...x,content:S,metadata:{...x.metadata,streaming:!1}};this.emit("chat.message.updated",A)}catch(h){console.error("VoxketClient: Failed to process lk.transcription message:",h);try{const g=await s.readAll(),y=((p=this.currentAgentInfo)==null?void 0:p.name)||l.identity||"AI Assistant",x={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:g,timestamp:new Date,sender:{id:l.identity||"agent",name:y,type:"agent"},metadata:{topic:"lk.transcription"}};this.emit("chat.message.received",x)}catch(g){console.error("VoxketClient: Fallback failed for lk.transcription:",g)}}})}catch(s){console.warn("VoxketClient: lk.transcription handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("suggested_response",async s=>{const l=await s.readAll();let f=[];try{f=["tes","hello how are you","algebra make me learn that ","what is the meaning of life"]}catch(p){console.warn("VoxketClient: Failed to parse suggested_response:",p,l)}this.emit("suggested.response",f)})}catch(s){console.warn("VoxketClient: suggested_response handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("agent_state_changed",async(s,l)=>{const f=await s.readAll();let p={};try{p=typeof f=="string"?JSON.parse(f.replace(/'/g,'"')):f}catch(h){console.warn("VoxketClient: Failed to parse agent_state_changed:",h,f)}p.new_state==="speaking"?this.emit("agent.speaking",p):p.new_state==="thinking"&&this.emit("agent.thinking",p)})}catch(s){console.warn("VoxketClient: conversation_item_added handler already registered, skipping:",s)}try{this.room.registerTextStreamHandler("images",async(s,l)=>{try{const f=await s.readAll()}catch(f){console.error("VoxketClient: Error processing images stream:",f)}})}catch(s){console.warn("VoxketClient: images handler already registered, skipping:",s)}try{this.room.registerByteStreamHandler("images",async(s,l)=>{var f,p;try{const h=s.info,g={id:`img_${Date.now()}_${l.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`�️ ${h.name||"Image"}`,sender:{id:l.identity||"agent",name:l.identity||"Agent",type:l.identity===((p=(f=this.room)==null?void 0:f.localParticipant)==null?void 0:p.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:h.name,fileSize:h.size,mimeType:h.mimeType,streamId:h.id,downloading:!0}};this.emit("chat.message.received",g),s.onProgress&&(s.onProgress=C=>{const R={...g,metadata:{...g.metadata,downloadProgress:C||0}};this.emit("chat.message.updated",R)});const y=[];for await(const C of s)y.push(C);const x=new Blob(y,{type:h.mimeType||"application/octet-stream"}),S=URL.createObjectURL(x),A={...g,metadata:{...g.metadata,downloading:!1,downloadProgress:1,downloadUrl:S,blob:x}};this.emit("chat.message.updated",A)}catch(h){console.error("VoxketClient: Error processing image attachment:",h)}})}catch(s){console.warn("VoxketClient: image handler already registered, skipping:",s)}this.textStreamHandlersRegistered=!0}}async fetchConnectionDetails(s,l,f){const p=s||this.config.agentId||"default-agent",h=l||this.config.participantName||"User",g=f||this.config.modalities||["voice"];try{const y={agent_id:p,participant_name:h,participant_metadata:{user_id:""},modality:g[0]},x=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(y)});if(!x.ok){let C=`HTTP ${x.status}: Failed to fetch connection details`;try{const R=await x.json();R&&(R.error?C=`API Error: ${R.error}`:R.detail?C=`API Error: ${R.detail}`:R.message&&(C=`API Error: ${R.message}`))}catch{try{const O=await x.text();O&&(C=`API Error: ${O}`)}catch{}}throw new Error(C)}const S=await x.json();let A;return S.agent_info&&(A={id:S.agent_info.id||p,name:S.agent_info.name||"AI Assistant",avatar:S.agent_info.avatar,capabilities:S.agent_info.capabilities||["voice_interaction","text_chat"],metadata:S.agent_info.metadata||{}},this.currentAgentInfo=A),{serverUrl:S.wss_url,participantToken:S.token,voxketSessionId:S.session_id,agentInfo:A}}catch(y){console.error("VoxketClient: fetchConnectionDetails failed:",y);const x=new $t(`Failed to fetch connection details: ${y instanceof Error?y.message:"Unknown error"}`,"CONNECTION_FAILED",y);throw this.emit("connection.error",x),x}}async connect(s,l,f){var p;try{this.emit("connection.connecting");const h=await this.fetchConnectionDetails(s,l,f);return await((p=this.room)==null?void 0:p.connect(h.serverUrl,h.participantToken)),this.isConnected=!0,h}catch(h){console.error("VoxketClient: Connection failed:",h);const g=new $t(`Failed to connect to Voxket services: ${h instanceof Error?h.message:"Unknown error"}`,"CONNECTION_FAILED",h);throw this.emit("connection.error",g),g}}async disconnect(){var s;try{await((s=this.room)==null?void 0:s.disconnect()),this.isConnected=!1,this.currentSession=null,this.currentAgentInfo=null,this.textStreamHandlersRegistered=!1,this.clearChatMessages(),this.room=new Ze.Room,this.setupRoomEventListeners()}catch(l){const f=new $t("Failed to disconnect properly","NETWORK_ERROR",l);throw this.emit("connection.error",f),f}}async createSession(s){var l,f;try{const p=await this.connect(s.agentId,s.participantName,s.modalities),h={id:p.voxketSessionId,agentId:s.agentId,state:"connecting",startedAt:new Date,metadata:s.metadata||{},activeModalities:s.modalities||["voice"],agentInfo:p.agentInfo||this.currentAgentInfo};if(this.currentSession=h,this.emit("session.created",h),(l=s.modalities)!=null&&l.includes("voice"))try{await new Promise(g=>setTimeout(g,500)),(f=this.room)!=null&&f.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(g){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",g)}return setTimeout(()=>{this.currentSession&&(this.currentSession.state="active",this.emit("session.state.changed","active",this.currentSession.state))},1e3),h}catch(p){throw console.error("VoxketClient: Failed to create session:",p),p instanceof $t?p:p instanceof TypeError&&p.message.includes("fetch")?new $t("Network connection failed","CONNECTION_FAILED",p):p instanceof Error&&p.message.includes("Failed to fetch connection details")?new $t(`API connection failed: ${p.message}`,"CONNECTION_FAILED",p):new $t(`Failed to create session: ${p instanceof Error?p.message:"Unknown error"}`,"SESSION_NOT_FOUND",p)}}async startSession(s,l){const f={agentId:s||this.config.agentId||"default-agent",participantName:(l==null?void 0:l.participantName)||this.config.participantName||"User",modalities:(l==null?void 0:l.modalities)||this.config.modalities||["voice","chat"],metadata:l==null?void 0:l.metadata};return this.createSession(f)}async endSession(){var s,l;if(!this.currentSession)return null;try{const f={sessionId:this.currentSession.id,duration:Date.now()-(((s=this.currentSession.startedAt)==null?void 0:s.getTime())||0),messageCount:0,participantCount:((l=this.room)==null?void 0:l.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,f),await this.disconnect(),f}catch(f){throw new $t("Failed to end session","SESSION_NOT_FOUND",f)}}getCurrentSession(){return this.currentSession}getCurrentAgentInfo(){return this.currentAgentInfo}getChatMessages(){return[...this.chatMessages]}addChatMessage(s){this.chatMessages.some(f=>f.id===s.id)||this.chatMessages.push(s)}updateChatMessage(s){const l=this.chatMessages.findIndex(f=>f.id===s.id);l!==-1&&(this.chatMessages[l]=s)}clearChatMessages(){this.chatMessages=[],this.dismissCurrentInteraction(),this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays(),this.emit("chat.history.cleared")}renderUI(s={}){var y,x,S;const l=this.resolveTarget(s.target||"body"),f=this.getTargetKey(l),p=this.renderedComponents.get(f);p&&p.target===l||this.removeUI(l);const h=(p==null?void 0:p.root)||PZ.createRoot(l),g={agentId:s.agentId||this.config.agentId||"default-agent",participantName:s.participantName||this.config.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:s.className,theme:typeof s.theme=="string"?s.theme:void 0,modalities:s.modality||this.config.modalities||["voice"],suportsChatInput:((y=s.modality)==null?void 0:y.includes("chat"))!==!1,suportsVideoInput:((x=s.modality)==null?void 0:x.includes("video"))===!0,suportsScreenShare:((S=s.modality)==null?void 0:S.includes("screen_share"))===!0,autoStart:s.autoStart,displayType:s.displayType||"widget",popupPosition:s.popupPosition||"bottom-right",popupTriggerText:s.popupTriggerText||"Open Chat",width:s.width,height:s.height,onDisplayTypeChange:s.onDisplayTypeChange,prompts:s.prompts,statusMessage:s.statusMessage,welcomeTitle:s.welcomeTitle,welcomeSubTitle:s.welcomeSubTitle,loadingText:s.loadingText,voxketClient:this};h.render(Y.createElement(G5,{config:this.config,autoConnect:s.autoStart||!1,children:Y.createElement(X5,g)})),this.renderedComponents.set(f,{root:h,target:l})}removeUI(s){const l=s?this.resolveTarget(s):null;if(l){const f=this.getTargetKey(l),p=this.renderedComponents.get(f);p&&(p.root.unmount(),this.renderedComponents.delete(f),l.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(g=>{try{g.remove()}catch(y){console.warn("Failed to remove element:",y)}}),l===document.body&&l.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(y=>{if(y.classList.contains("bg-black")&&y.classList.contains("backdrop-blur-sm"))try{y.remove()}catch(x){console.warn("Failed to remove fixed element:",x)}}))}}removeAllUI(){for(const[s,l]of this.renderedComponents)l.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(l=>{if(l.classList.contains("bg-black")&&(l.classList.contains("backdrop-blur-sm")||l.classList.contains("bg-opacity-30")))try{l.remove()}catch(f){console.warn("Failed to remove overlay:",f)}})}resolveTarget(s){if(typeof s=="string"){const l=document.querySelector(s);if(!l)throw new Error(`Target element not found: ${s}`);return l}return s}getTargetKey(s){return s.id?s.id:s.className?s.tagName+"_"+s.className.replace(/\s+/g,"_"):s.tagName+"_"+s.outerHTML.length%1e3}async sendMessage(s,l){var f;if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new $t("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new $t("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new $t("No local participant","CONNECTION_FAILED");this.dismissCurrentInteraction();try{const p={id:`msg_${Date.now()}`,content:s,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:l||{}},h=await((f=this.room)==null?void 0:f.localParticipant.sendText(s,{topic:"lk.chat",destinationIdentities:[]}));this.emit("chat.message.sent",p)}catch(p){throw console.error("VoxketClient: Failed to send chat message:",p),new $t("Failed to send message","NETWORK_ERROR",p)}}async sendChatMessage(s,l){return this.sendMessage(s,l)}async sendAttachments(s,l){if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new $t("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new $t("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new $t("No local participant","CONNECTION_FAILED");if(!s||s.length===0)throw new $t("No files provided","INVALID_PARAMETER");this.dismissCurrentInteraction();const f=s.filter(p=>p.type.startsWith("image/"));if(f.length===0)throw new $t("Only image files are allowed","INVALID_PARAMETER");f.length!==s.length&&console.warn("VoxketClient: Some non-image files were filtered out");try{const p=f.map(async(h,g)=>{const x={id:`att_${Date.now()}_${g}`,content:`📎 ${h.name}`,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:{...l,type:"attachment",fileName:h.name,fileSize:h.size,mimeType:h.type,uploading:!0}};this.emit("chat.message.sent",x);const S=await this.room.localParticipant.sendFile(h,{mimeType:h.type,topic:"images",onProgress:C=>{const R={...x,metadata:{...x.metadata,uploadProgress:C}};this.emit("chat.message.updated",R)}});try{const C=new FileReader,R=new Promise((j,U)=>{C.onload=()=>{typeof C.result=="string"?j(C.result):U(new Error("Failed to convert to base64"))},C.onerror=U});C.readAsDataURL(h);const V={type:"image",data:await R,filename:h.name,mimeType:h.type,size:h.size};await this.room.localParticipant.sendText(JSON.stringify(V),{topic:"images",destinationIdentities:[]})}catch(C){console.warn("VoxketClient: Failed to send image data to agent:",C);try{const R=`I've shared an image: ${h.name}`;await this.room.localParticipant.sendText(R,{topic:"lk.chat",destinationIdentities:[]})}catch(R){console.warn("VoxketClient: Failed to send image notification to agent:",R)}}const A={...x,metadata:{...x.metadata,uploading:!1,uploadProgress:1,streamId:S.id}};return this.emit("chat.message.updated",A),S});await Promise.all(p)}catch(p){throw console.error("VoxketClient: Failed to send attachments:",p),new $t("Failed to send attachments","NETWORK_ERROR",p)}}async sendAttachment(s,l){return this.sendAttachments([s],l)}toggleMicrophone(s){return this.setMicrophoneEnabled(s!==!1)}async setMicrophoneEnabled(s){var l,f;try{const p=(l=this.room)==null?void 0:l.localParticipant.isMicrophoneEnabled,h=s??!p;await((f=this.room)==null?void 0:f.localParticipant.setMicrophoneEnabled(h)),h?this.emit("track.unmuted",{source:"microphone",enabled:!0}):this.emit("track.muted",{source:"microphone",enabled:!1})}catch(p){throw console.error("VoxketClient: Failed to toggle microphone:",p),new $t("Failed to toggle microphone","PERMISSION_DENIED",p)}}toggleCamera(s){return this.setCameraEnabled(s!==!1)}async setCameraEnabled(s){var l,f;try{const p=(l=this.room)==null?void 0:l.localParticipant.isCameraEnabled,h=s??!p;await((f=this.room)==null?void 0:f.localParticipant.setCameraEnabled(h)),h?this.emit("track.unmuted",{source:"camera",enabled:!0}):this.emit("track.muted",{source:"camera",enabled:!1})}catch(p){throw console.error("VoxketClient: Failed to toggle camera:",p),new $t("Failed to toggle camera","PERMISSION_DENIED",p)}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var s;try{await((s=this.room)==null?void 0:s.localParticipant.setScreenShareEnabled(!0))}catch(l){throw new $t("Failed to start screen share","PERMISSION_DENIED",l)}}async stopScreenShare(){var s;try{await((s=this.room)==null?void 0:s.localParticipant.setScreenShareEnabled(!1))}catch(l){throw new $t("Failed to stop screen share","PERMISSION_DENIED",l)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(l=>l.kind==="audioinput")}catch(s){throw new $t("Failed to get audio input devices","DEVICE_ERROR",s)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(l=>l.kind==="videoinput")}catch(s){throw new $t("Failed to get video input devices","DEVICE_ERROR",s)}}async setAudioInputDevice(s){var l;try{if(!((l=this.room)!=null&&l.localParticipant))throw new Error("Not connected to room")}catch(f){throw new $t("Failed to set audio input device","DEVICE_ERROR",f)}}async setVideoInputDevice(s){var l;try{if(!((l=this.room)!=null&&l.localParticipant))throw new Error("Not connected to room")}catch(f){throw new $t("Failed to set video input device","DEVICE_ERROR",f)}}getLocalParticipant(){var s;return((s=this.room)==null?void 0:s.localParticipant)??null}getRemoteParticipants(){var s;return Array.from(((s=this.room)==null?void 0:s.remoteParticipants.values())??[])}getPublishPermissions(){const s=this.getLocalParticipant();if(!s)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const l=s.permissions;if(!l)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const f=p=>!!l.canPublish&&(l.canPublishSources.length===0||l.canPublishSources.includes(p));return{camera:f(1),microphone:f(2),screenShare:f(3),data:l.canPublishData??!1}}canPublishSource(s){return this.getPublishPermissions()[s]}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===Ze.ConnectionState.Connected}getMicrophoneTrack(){const s=this.getLocalParticipant();if(!s)return null;for(const[,l]of s.trackPublications)if(l.source===Ze.Track.Source.Microphone)return l.track;return null}getCameraTrack(){const s=this.getLocalParticipant();if(!s)return null;for(const[,l]of s.trackPublications)if(l.source===Ze.Track.Source.Camera)return l.track;return null}getScreenShareTrack(){const s=this.getLocalParticipant();if(!s)return null;for(const[,l]of s.trackPublications)if(l.source===Ze.Track.Source.ScreenShare)return l.track;return null}get isMicrophoneEnabled(){const s=this.getMicrophoneTrack();return s?!s.isMuted:!1}get isCameraEnabled(){const s=this.getCameraTrack();return s?!s.isMuted:!1}get isScreenShareEnabled(){const s=this.getScreenShareTrack();return s?!s.isMuted:!1}registerPlugin(s){this.pluginManager.register(s)}getPluginManager(){return this.pluginManager}getParticipants(){if(!this.room)return[];const s=[];return this.room.localParticipant&&s.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(l=>{s.push({id:l.identity,name:l.name||l.identity,isLocal:!1})}),s}getSessionMetrics(){var s,l;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((s=this.currentSession.startedAt)==null?void 0:s.getTime())||0),messageCount:0,participantCount:((l=this.room)==null?void 0:l.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(s){this.config={...this.config,...s}}async startRecording(){var s;try{this.emit("recording.started",{sessionId:(s=this.currentSession)==null?void 0:s.id,timestamp:new Date})}catch(l){throw new $t("Failed to start recording","RECORDING_ERROR",l)}}async stopRecording(){var s;try{this.emit("recording.stopped",{sessionId:(s=this.currentSession)==null?void 0:s.id,timestamp:new Date})}catch(l){throw new $t("Failed to stop recording","RECORDING_ERROR",l)}}async registerFrontendRPC(s,l,f="embedded"){return this.rpcManager.registerFrontendRPC(s,l,f)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(s){this.rpcManager.unregisterMethod(s)}registerEventListener(s,l){return this.on(s,l)}registerEventEmitter(s,l){if(!this.room)throw new Error("Room not available");try{this.room.registerTextStreamHandler(s,async f=>{try{const p=await f.readAll();l(p)}catch(p){console.error(`Error processing event for topic '${s}':`,p)}})}catch(f){console.warn(`VoxketClient: Handler for topic '${s}' may already be registered:`,f)}}convertMarkdownToText(s){if(!s)return"";let l=s;return l=l.replace(/\*\*(.*?)\*\*/g,"$1"),l=l.replace(/__(.*?)__/g,"$1"),l=l.replace(/\*(.*?)\*/g,"$1"),l=l.replace(/_(.*?)_/g,"$1"),l=l.replace(/~~(.*?)~~/g,"$1"),l=l.replace(/`([^`]+)`/g,"$1"),l=l.replace(/```[\s\S]*?```/g,""),l=l.replace(/^#{1,6}\s+/gm,""),l=l.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),l.trim()}}const FZ=Vn.create(BH),IZ=Vn.create(VZ),QZ=Vn.create(jZ),KZ=Vn.create(UZ);function JZ({onClick:t,text:a="Open Chat",position:s="bottom-right",theme:l}){const f={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},p=Da(l);return T.jsx(Vn.button,{onClick:t,className:`fixed ${f[s]} z-50 px-4 py-2 rounded-full shadow-lg ${p.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},children:a})}function IC({children:t,theme:a,displayType:s="widget",onClose:l,popupPosition:f="bottom-right",onExpand:p}){const h=Da(a);if(s==="fullscreen")return T.jsx("div",{className:"fixed inset-0 z-50 bg-black bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",children:T.jsxs("div",{className:"w-full h-full max-w-6xl max-h-[90vh] rounded-2xl relative bg-transparent",children:[l&&T.jsx("button",{onClick:g=>{g.preventDefault(),g.stopPropagation(),l()},className:"absolute top-4 cursor-pointer right-4 z-[100] 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:T.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:T.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"})})}),T.jsxs("div",{id:"voice-card",className:`${h.card} w-full h-full flex flex-col rounded-xl shadow-2xl`,style:{minHeight:"600px"},children:[T.jsx("div",{className:h.cardTopGradient}),T.jsx("div",{className:h.cardPurpleBlur}),T.jsx("div",{className:h.cardPinkBlur}),T.jsx("div",{className:" flex flex-col h-full",children:t}),T.jsx("div",{className:h.cardPulse1}),T.jsx("div",{className:h.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(s==="popup"){const g={"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 T.jsx("div",{className:"fixed rounded-2xl inset-0 z-50 pointer-events-none",children:T.jsxs("div",{className:`fixed rounded-2xl ${g[f]} pointer-events-auto`,children:[l&&T.jsx("button",{onClick:l,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:"×"}),T.jsxs("div",{id:"voice-card",className:`${h.card} rounded-2xl flex flex-col`,style:{width:"300px",height:"450px"},children:[T.jsx("div",{className:h.cardPurpleBlur}),T.jsx("div",{className:h.cardPinkBlur}),T.jsx("div",{className:" flex flex-col h-full",children:t}),T.jsx("div",{className:h.cardPulse1}),T.jsx("div",{className:h.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return T.jsxs("div",{id:"voice-card",className:`${h.card}`,children:[p&&T.jsx("button",{onClick:p,className:"absolute top-4 right-4 z-20 w-10 h-10 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:"Enter Fullscreen",children:T.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:T.jsx("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})})}),T.jsx("div",{className:h.cardTopGradient}),T.jsx("div",{className:h.cardPurpleBlur}),T.jsx("div",{className:h.cardPinkBlur}),t,T.jsx("div",{className:h.cardPulse1}),T.jsx("div",{className:h.cardPulse2,style:{animationDelay:"1s"}})]})}function X5(t){if(typeof window>"u")return null;console.log("🎯 Widget component rendering with props:",{displayType:t.displayType,popupPosition:t.popupPosition,theme:t.theme});const{agentId:a,participantName:s,baseUrl:l,appSecret:f,appId:p,prompts:h,statusMessage:g,welcomeTitle:y,welcomeSubTitle:x,className:S,width:A,height:C,loadingText:R,suportsChatInput:O=!0,suportsVideoInput:V=!0,suportsScreenShare:j=!0,theme:U="vox",onSessionStart:z,onSessionEnd:B,enableSessionLogging:$=!0,onSessionLogsUpdate:_,onSessionMetricsUpdate:I,modalities:G=["voice"],displayType:Q="widget",popupPosition:se="bottom-right",popupTriggerText:ve="Open Chat",onPopupToggle:Ae,voxketClient:be,onDisplayTypeChange:$e}=t,[je,ze]=M.useState(()=>be?!!be.getCurrentSession():!1),[P,K]=M.useState(!1),[Z,xe]=M.useState(a||""),[ee,fe]=M.useState(s||"User"),[ge,ae]=M.useState(()=>be?be.getCurrentSession():null),[Ee,Ve]=M.useState(()=>{var Je,It,pa;if(be){const _t=be.getCurrentSession();if((Je=_t==null?void 0:_t.activeModalities)!=null&&Je.includes("chat"))return"chat";if((It=_t==null?void 0:_t.activeModalities)!=null&&It.includes("voice"))return"voice";if((pa=_t==null?void 0:_t.activeModalities)!=null&&pa.includes("video"))return"video"}return"welcome"}),[Me,Te]=M.useState(!1);M.useEffect(()=>{console.log("🎯 Widget displayType prop changed to:",Q)},[Q]),M.useEffect(()=>{console.log("📊 Session state changed:",{currentMode:Ee,sessionStarted:je,loading:P,currentSession:ge==null?void 0:ge.id,isPopupOpen:Me})},[Ee,je,P,ge,Me]);const Ce=M.useMemo(()=>{if(be)return console.log("🔄 Using passed VoxketClient to preserve session state"),be;console.log("🆕 Creating new VoxketClient instance");const Je={appId:p,appSecret:f,baseUrl:l,agentId:Z,participantName:ee||"User",modalities:G};return new U1(Je)},[be,p,f,l,Z,ee,G]),Oe=G,De=M.useMemo(()=>Ce.getRoom()||new Ze.Room,[Ce]),Ye={suportsChatInput:O,suportsVideoInput:V,suportsScreenShare:j},{sessionMetrics:qe,sessionLogs:st,logEvent:Nt}=P5({room:De,onSessionStart:z,onSessionEnd:B,enableConsoleLogging:$,enableLocalStorage:$,voxketSessionId:ge==null?void 0:ge.id});M.useEffect(()=>{_&&_(st)},[st,_]),M.useEffect(()=>{I&&qe&&I(qe)},[qe,I]),M.useEffect(()=>{const Je=pa=>{console.log("🔴 Room disconnected:",pa),K(!1),ze(!1),ae(null),Ve("welcome")},It=pa=>{console.log("📹 Media devices error:",pa),Lb({title:"Allow access to your microphone/camera",description:`${pa.name}: ${pa.message}`})};return De.on(Ze.RoomEvent.MediaDevicesError,It),De.on(Ze.RoomEvent.Disconnected,Je),()=>{De.off(Ze.RoomEvent.Disconnected,Je),De.off(Ze.RoomEvent.MediaDevicesError,It)}},[De]);const Xn=async()=>{try{console.log("🎤 Starting voice session...",{agentId:Z,participantName:ee}),console.log("🎤 Pre-start state:",{currentMode:Ee,sessionStarted:je,loading:P}),K(!0),ze(!0),Ve("voice"),console.log("🎤 State after mode change:",{currentMode:"voice",sessionStarted:!0,loading:!0}),Nt("USER_STARTED_VOICE_SESSION",{agentId:Z,participantName:ee});const Je=await Ce.startSession(Z,{participantName:ee||"User",modalities:["voice",...V?["video"]:[]]});console.log("✅ Voice session started successfully:",Je.id),ae(Je),K(!1),z&&z(Je.id)}catch(Je){console.error("❌ Failed to start voice session:",Je),Lb({title:"Failed to start voice session",description:Je instanceof Error?Je.message:"Unknown error occurred"}),K(!1),ze(!1),Ve("welcome")}},jn=async()=>{try{K(!0),ze(!0),Ve("chat"),Nt("USER_STARTED_CHAT_SESSION",{agentId:Z,participantName:ee});const Je=await Ce.startSession(Z,{participantName:ee||"User",modalities:["chat"]});ae(Je),K(!1),z&&z(Je.id)}catch(Je){console.error("Failed to start chat session:",Je),Lb({title:"Failed to start chat session",description:Je instanceof Error?Je.message:"Unknown error occurred"}),K(!1),ze(!1),Ve("welcome")}},ln=async()=>{try{console.log("📺 Starting video session...",{agentId:Z,participantName:ee}),console.log("📺 Pre-start state:",{currentMode:Ee,sessionStarted:je,loading:P}),K(!0),ze(!0),Ve("video"),console.log("📺 State after mode change:",{currentMode:"video",sessionStarted:!0,loading:!0}),Nt("USER_STARTED_VIDEO_SESSION",{agentId:Z,participantName:ee});const Je=await Ce.startSession(Z,{participantName:ee||"User",modalities:["video","voice"]});console.log("✅ Video session started successfully:",Je.id),ae(Je),K(!1),z&&z(Je.id)}catch(Je){console.error("❌ Failed to start video session:",Je),Lb({title:"Failed to start video session",description:Je instanceof Error?Je.message:"Unknown error occurred"}),K(!1),ze(!1),Ve("welcome")}},Ia=()=>{Ve("welcome"),$e&&$e(t.displayType||"widget"),ge&&je&&(ze(!1),ae(null),Ce.disconnect()),Q==="popup"&&!Me&&Te(!0)},Qa=()=>{const Je=!Me;Te(Je),Ae&&Ae(Je),!Je&&!(ge&&je)&&(Ve("welcome"),ze(!1),ae(null))},Yu=()=>{console.log("🔄 Closing fullscreen, switching to widget display type"),t.onDisplayTypeChange?t.onDisplayTypeChange("widget"):console.warn("⚠️ No onDisplayTypeChange callback provided")},Xr=()=>{t.onDisplayTypeChange&&t.onDisplayTypeChange("fullscreen")};M.useEffect(()=>{var Je,It,pa;if(be&&Ce){console.log("🔄 Syncing widget state with existing client session state");const _t=Ce.getCurrentSession(),a0=Ce.connected;console.log("🔍 Existing session state:",{hasSession:!!_t,sessionId:_t==null?void 0:_t.id,isConnected:a0,activeModalities:_t==null?void 0:_t.activeModalities}),_t&&(console.log("✅ Restoring session state from existing client"),ae(_t),ze(!0),K(!1),(Je=_t.activeModalities)!=null&&Je.includes("chat")?Ve("chat"):(It=_t.activeModalities)!=null&&It.includes("voice")?Ve("voice"):(pa=_t.activeModalities)!=null&&pa.includes("video")&&Ve("video"))}},[be,Ce]),M.useEffect(()=>()=>{console.log("🧹 Cleaning up widget component"),be?console.log("🔄 Widget cleanup: preserving passed client instance"):(console.log("🧹 Widget cleanup: disconnecting self-created client"),Ce.disconnect())},[Ce,be]);let Fr="w-96",ss="h-[25rem]",Zu={};if(A&&(A.startsWith("w-")?Fr=A:(Zu.width=A,Fr="")),C&&(C.startsWith("h-")?ss=C:(Zu.height=C,ss="")),Q==="popup"&&!Me)return console.log("🟡 Showing popup trigger button"),T.jsx(JZ,{onClick:Qa,text:ve,position:se,theme:U});console.log("🟢 Rendering widget content, displayType:",Q,"isPopupOpen:",Me,"currentMode:",Ee,"sessionStarted:",je,"loading:",P);let hc=`voxket-widget-root theme-${U}`,Li={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};Q==="widget"?(hc+=` flex items-center justify-center min-h-fit ${Fr} ${ss} ${S}`,Li={...Li,...Zu}):(hc=`${S||""}`,Li={});const kn=T.jsx(T.Fragment,{children:T.jsxs(zp,{mode:"wait",children:[Ee==="welcome"&&!P&&T.jsx(KZ,{agentId:Z,participantName:ee||"",onAgentIdChange:xe,onParticipantNameChange:fe,onStartCall:Xn,onStartChat:jn,onStartVideo:ln,disabled:je||P,prompts:h,statusMessage:g,title:y,subTitle:x,theme:U,modalities:Oe,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),Ee==="voice"&&T.jsxs(On.RoomContext.Provider,{value:De,children:[T.jsx(On.RoomAudioRenderer,{}),T.jsx(On.StartAudio,{label:"Start Audio"}),T.jsx(FZ,{loadingText:R,participantName:ee||"User",capabilities:Ye,sessionStarted:je,disabled:!je,theme:U,client:Ce,displayType:Q,onBack:Q==="popup"?Qa:Ia,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"session-view")]}),Ee==="chat"&&T.jsx(IZ,{client:Ce,theme:U,displayType:Q,onBack:Q==="popup"?Qa:Ia,onEndChat:Ia,disabled:!je,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),Ee==="video"&&T.jsxs(On.RoomContext.Provider,{value:De,children:[T.jsx(On.RoomAudioRenderer,{}),T.jsx(On.StartAudio,{label:"Start Audio"}),T.jsx(QZ,{client:Ce,theme:U,displayType:Q,onBack:Q==="popup"?Qa:Ia,onEndCall:Ia,disabled:!je,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-view")]})]})});return Q==="fullscreen"||Q==="popup"?(console.log("📱 Rendering fullscreen/popup mode, displayType:",Q),T.jsx(IC,{theme:U,displayType:Q,popupPosition:se,onClose:Q==="fullscreen"?Yu:Qa,children:kn})):(console.log("📦 Rendering widget mode"),T.jsx("div",{className:hc,style:Li,children:T.jsx(IC,{theme:U,displayType:Q,popupPosition:se,onExpand:Xr,children:kn})}))}function WZ({logs:t,onClear:a,onExport:s}){const[l,f]=Y.useState(!1),[p,h]=Y.useState(""),g=t.filter(y=>!p||y.event.toLowerCase().includes(p.toLowerCase()));return l?T.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:T.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[T.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[T.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",t.length,")"]}),T.jsxs("div",{className:"flex items-center gap-2",children:[T.jsx("input",{type:"text",placeholder:"Filter events...",value:p,onChange:y=>h(y.target.value),className:"px-3 py-1 border rounded text-sm"}),T.jsx("button",{onClick:a,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),T.jsx("button",{onClick:s,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),T.jsx("button",{onClick:()=>f(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),T.jsx("div",{className:"flex-1 overflow-auto p-4",children:g.length===0?T.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):T.jsx("div",{className:"space-y-2",children:g.map((y,x)=>T.jsxs("div",{className:"border rounded p-3 text-sm",children:[T.jsxs("div",{className:"flex items-center justify-between mb-1",children:[T.jsx("span",{className:"font-semibold text-blue-600",children:y.event}),T.jsx("span",{className:"text-gray-500 text-xs",children:new Date(y.timestamp).toLocaleTimeString()})]}),y.sessionId&&T.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",y.sessionId]}),y.data&&T.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:T.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(y.data,null,2)})})]},x))})})]})}):T.jsxs("button",{onClick:()=>f(!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 (",t.length,")"]})}function eq({metrics:t}){return t?T.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[T.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),T.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[T.jsxs("div",{children:[T.jsx("span",{className:"text-gray-600",children:"Session ID:"}),T.jsx("div",{className:"font-mono text-xs",children:t.sessionId})]}),T.jsxs("div",{children:[T.jsx("span",{className:"text-gray-600",children:"Start Time:"}),T.jsx("div",{children:new Date(t.startTime).toLocaleString()})]}),T.jsxs("div",{children:[T.jsx("span",{className:"text-gray-600",children:"Messages:"}),T.jsx("div",{children:t.totalMessages})]}),T.jsxs("div",{children:[T.jsx("span",{className:"text-gray-600",children:"Participants:"}),T.jsx("div",{children:t.participantCount})]}),T.jsxs("div",{children:[T.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),T.jsx("div",{children:t.connectionIssues})]}),T.jsxs("div",{children:[T.jsx("span",{className:"text-gray-600",children:"Duration:"}),T.jsxs("div",{children:[Math.round((Date.now()-new Date(t.startTime).getTime())/1e3),"s"]})]})]})]}):null}function Id(){const{currentSession:t,sessionState:a,sessionMetrics:s,createSession:l,endSession:f}=Gr(),p=Y.useCallback(async(g,y)=>await l(g,y),[l]),h=Y.useCallback(async()=>await f(),[f]);return{session:t,state:a,metrics:s,isActive:t!==null&&a!=="disconnected",isConnecting:a==="connecting",isConnected:a==="connected"||a==="active",start:p,stop:h}}function F5(){const{sessionMetrics:t,currentSession:a}=Gr();return{metrics:t,sessionId:a==null?void 0:a.id,duration:t==null?void 0:t.duration,participantCount:t==null?void 0:t.participantCount,messageCount:t==null?void 0:t.messageCount,audioQuality:t==null?void 0:t.audioQuality,networkStats:t==null?void 0:t.networkStats}}function I5(){const{setMicrophoneEnabled:t,client:a}=Gr(),[s,l]=Y.useState(!1),[f,p]=Y.useState(!1),h=Y.useCallback(async()=>{if(!f){p(!0);try{const x=!s;await t(x),l(x)}catch(x){console.error("Failed to toggle microphone:",x)}finally{p(!1)}}},[s,f,t]),g=Y.useCallback(async()=>{if(!(s||f)){p(!0);try{await t(!0),l(!0)}catch(x){console.error("Failed to enable microphone:",x)}finally{p(!1)}}},[s,f,t]),y=Y.useCallback(async()=>{if(!(!s||f)){p(!0);try{await t(!1),l(!1)}catch(x){console.error("Failed to disable microphone:",x)}finally{p(!1)}}},[s,f,t]);return{isEnabled:s,isLoading:f,toggle:h,enable:g,disable:y}}function Q5(){const{setCameraEnabled:t}=Gr(),[a,s]=Y.useState(!1),[l,f]=Y.useState(!1),p=Y.useCallback(async()=>{if(!l){f(!0);try{const y=!a;await t(y),s(y)}catch(y){console.error("Failed to toggle camera:",y)}finally{f(!1)}}},[a,l,t]),h=Y.useCallback(async()=>{if(!(a||l)){f(!0);try{await t(!0),s(!0)}catch(y){console.error("Failed to enable camera:",y)}finally{f(!1)}}},[a,l,t]),g=Y.useCallback(async()=>{if(!(!a||l)){f(!0);try{await t(!1),s(!1)}catch(y){console.error("Failed to disable camera:",y)}finally{f(!1)}}},[a,l,t]);return{isEnabled:a,isLoading:l,toggle:p,enable:h,disable:g}}function K5(){const{startScreenShare:t,stopScreenShare:a}=Gr(),[s,l]=Y.useState(!1),[f,p]=Y.useState(!1),h=Y.useCallback(async()=>{if(!(s||f)){p(!0);try{await t(),l(!0)}catch(x){console.error("Failed to start screen share:",x)}finally{p(!1)}}},[s,f,t]),g=Y.useCallback(async()=>{if(!(!s||f)){p(!0);try{await a(),l(!1)}catch(x){console.error("Failed to stop screen share:",x)}finally{p(!1)}}},[s,f,a]),y=Y.useCallback(async()=>{s?await g():await h()},[s,h,g]);return{isSharing:s,isLoading:f,start:h,stop:g,toggle:y}}function tq(){const{client:t}=Gr(),[a,s]=Y.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),l=Y.useMemo(()=>a.tracks.find(V=>V.isLocal),[a.tracks]),f=Y.useMemo(()=>a.tracks.filter(V=>!V.isLocal),[a.tracks]),p=Y.useCallback(async()=>{try{l!=null&&l.isEnabled?await(t==null?void 0:t.disableCamera()):await(t==null?void 0:t.enableCamera())}catch(V){throw console.error("Failed to toggle camera:",V),V}},[t,l]),h=Y.useCallback(async()=>{try{a.tracks.find(j=>j.isScreenShare)?await(t==null?void 0:t.stopScreenShare()):await(t==null?void 0:t.startScreenShare())}catch(V){throw console.error("Failed to toggle screen share:",V),V}},[t,a.tracks]),g=Y.useCallback(V=>{s(j=>({...j,layout:V}))},[]),y=Y.useCallback(V=>{s(j=>({...j,pinnedTrack:V}))},[]),x=Y.useCallback(()=>{s(V=>({...V,pinnedTrack:void 0}))},[]),S=Y.useCallback(async()=>{try{await(t==null?void 0:t.startRecording()),s(V=>({...V,isRecording:!0}))}catch(V){throw console.error("Failed to start recording:",V),V}},[t]),A=Y.useCallback(async()=>{try{await(t==null?void 0:t.stopRecording()),s(V=>({...V,isRecording:!1}))}catch(V){throw console.error("Failed to stop recording:",V),V}},[t]),C=Y.useCallback(V=>a.tracks.find(j=>j.id===V),[a.tracks]),R=Y.useCallback(V=>a.tracks.filter(j=>j.participantId===V),[a.tracks]),O=Y.useCallback(V=>V.isEnabled&&a.tracks.includes(V),[a.tracks]);return Y.useEffect(()=>{if(!t)return;const V=z=>{s(B=>({...B,tracks:[...B.tracks.filter($=>$.id!==z.id),z]}))},j=z=>{s(B=>{var $;return{...B,tracks:B.tracks.filter(_=>_.id!==z),pinnedTrack:(($=B.pinnedTrack)==null?void 0:$.id)===z?void 0:B.pinnedTrack}})},U=z=>{s(B=>({...B,tracks:B.tracks.map($=>$.id===z.id?z:$)}))};return t.on("videoTrackAdded",V),t.on("videoTrackRemoved",j),t.on("videoTrackUpdated",U),()=>{t.off("videoTrackAdded",V),t.off("videoTrackRemoved",j),t.off("videoTrackUpdated",U)}},[t]),{tracks:a.tracks,localTrack:l,remoteTraracks:f,pinnedTrack:a.pinnedTrack,layout:a.layout,isRecording:a.isRecording,toggleCamera:p,toggleScreenShare:h,setLayout:g,pinTrack:y,unpinTrack:x,startRecording:S,stopRecording:A,getTrackById:C,getTracksByParticipant:R,isTrackActive:O}}function $x(){const{chatMessages:t,sendChatMessage:a,currentSession:s}=Gr(),[l,f]=Y.useState(!1),p=Y.useCallback(async x=>{if(!(!x.trim()||l||!s)){f(!0);try{await a(x.trim())}catch(S){throw console.error("Failed to send chat message:",S),S}finally{f(!1)}}},[a,l,s]),{userMessages:h,agentMessages:g,allMessages:y}=Y.useMemo(()=>{const x=t.filter(A=>A.sender.type==="participant"),S=t.filter(A=>A.sender.type==="agent");return{userMessages:x,agentMessages:S,allMessages:t}},[t]);return{messages:y,userMessages:h,agentMessages:g,messageCount:y.length,isSending:l,canSend:!!s&&!l,send:p}}function nq(){const{send:t,isSending:a,canSend:s}=$x(),[l,f]=Y.useState(""),p=Y.useCallback(async()=>{if(!(!l.trim()||!s))try{await t(l),f("")}catch(g){throw g}},[l,t,s]),h=Y.useCallback(g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),p())},[p]);return{value:l,setValue:f,send:p,handleKeyPress:h,isSending:a,canSend:s&&l.trim().length>0}}function M4(){const{isConnected:t,isConnecting:a,connectionError:s,connect:l,disconnect:f}=Gr(),p=Y.useCallback(async()=>{if(!(t||a))try{await l()}catch(g){throw console.error("Failed to connect:",g),g}},[l,t,a]),h=Y.useCallback(async()=>{if(t)try{await f()}catch(g){throw console.error("Failed to disconnect:",g),g}},[f,t]);return{isConnected:t,isConnecting:a,isDisconnected:!t&&!a,error:s,hasError:!!s,connect:p,disconnect:h}}function J5(){const{participants:t}=Gr();return{participants:t,count:t.length,localParticipant:t.find(a=>a.isLocal),remoteParticipants:t.filter(a=>!a.isLocal)}}const W5=Y.createContext({}),L1=()=>Y.useContext(W5);function eV({children:t,...a}){return T.jsx(W5.Provider,{value:a,children:t})}function ox({name:t,children:a,fallback:s,className:l}){return T.jsx("div",{className:`voxket-slot voxket-slot--${t} ${l||""}`,children:a||s})}function tV(t,a={}){return Object.assign(t,a)}function nV({showMicrophoneControl:t=!0,showCameraControl:a=!0,showScreenShareControl:s=!0,showSessionActions:l=!0,customControls:f,className:p=""}){const h=Id(),g=I5(),y=Q5(),x=K5(),S=L1(),A=["voxket-session-controls",`voxket-session-controls--${S.variant||"default"}`,`voxket-session-controls--${S.size||"md"}`,h.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",p].filter(Boolean).join(" ");return!h.isActive&&!l?T.jsx("div",{className:A,children:T.jsx("div",{className:"voxket-controls-inactive",children:T.jsx("p",{children:"Controls available during active session"})})}):T.jsxs("div",{className:A,children:[l&&T.jsx("div",{className:"voxket-session-actions",children:h.isActive?T.jsx("button",{onClick:h.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):T.jsx(aq,{})}),h.isActive&&T.jsxs("div",{className:"voxket-media-controls",children:[t&&T.jsxs("button",{onClick:g.toggle,disabled:g.isLoading,className:`voxket-button voxket-button--media ${g.isEnabled?"voxket-button--active":""}`,title:g.isEnabled?"Mute microphone":"Unmute microphone",children:[T.jsx("span",{className:"voxket-icon",children:"🎤"}),g.isLoading?"Loading...":g.isEnabled?"Mute":"Unmute"]}),a&&T.jsxs("button",{onClick:y.toggle,disabled:y.isLoading,className:`voxket-button voxket-button--media ${y.isEnabled?"voxket-button--active":""}`,title:y.isEnabled?"Stop camera":"Start camera",children:[T.jsx("span",{className:"voxket-icon",children:"📹"}),y.isLoading?"Loading...":y.isEnabled?"Stop Video":"Start Video"]}),s&&T.jsxs("button",{onClick:x.toggle,disabled:x.isLoading,className:`voxket-button voxket-button--media ${x.isSharing?"voxket-button--active":""}`,title:x.isSharing?"Stop screen share":"Start screen share",children:[T.jsx("span",{className:"voxket-icon",children:"🖥️"}),x.isLoading?"Loading...":x.isSharing?"Stop Share":"Share Screen"]})]}),f&&T.jsx("div",{className:"voxket-custom-controls",children:f})]})}function aq(){Id();const[t,a]=Y.useState(!1),s=async()=>{a(!0);try{console.log("Start session - agentId needed")}catch(l){console.error("Failed to start session:",l)}finally{a(!1)}};return T.jsx("button",{onClick:s,disabled:t,className:"voxket-button voxket-button--primary",children:t?"Starting...":"Start Session"})}function R4({showConnectionStatus:t=!0,showSessionInfo:a=!0,showAgentInfo:s=!0,className:l=""}){const f=Id(),p=M4(),h=L1(),g=["voxket-session-header",`voxket-session-header--${h.variant||"default"}`,`voxket-session-header--${h.size||"md"}`,l].filter(Boolean).join(" ");return T.jsxs("div",{className:g,children:[t&&T.jsxs("div",{className:"voxket-connection-status",children:[T.jsx("div",{className:`voxket-status-indicator ${p.isConnected?"connected":"disconnected"}`}),T.jsx("span",{className:"voxket-status-text",children:p.isConnecting?"Connecting...":p.isConnected?"Connected":"Disconnected"})]}),a&&f.session&&T.jsxs("div",{className:"voxket-session-info",children:[T.jsxs("div",{className:"voxket-session-id",children:["Session: ",f.session.id.slice(-8)]}),T.jsxs("div",{className:"voxket-session-state",children:["State: ",f.state]})]}),s&&f.session&&T.jsxs("div",{className:"voxket-agent-info",children:[T.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",f.session.agentId]}),T.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",f.session.activeModalities.join(", ")]})]}),p.error&&T.jsxs("div",{className:"voxket-error-message",children:["Error: ",p.error.message]})]})}function D4({showChat:t=!0,showTranscriptions:a=!1,customContent:s,className:l=""}){const f=Id(),p=$x(),h=L1(),g=["voxket-session-content",`voxket-session-content--${h.variant||"default"}`,`voxket-session-content--${h.size||"md"}`,l].filter(Boolean).join(" ");return f.isActive?T.jsx("div",{className:g,children:s||T.jsxs(T.Fragment,{children:[t&&T.jsxs("div",{className:"voxket-chat-container",children:[T.jsxs("div",{className:"voxket-chat-messages",children:[p.messages.map(y=>T.jsxs("div",{className:`voxket-message voxket-message--${y.sender.type}`,children:[T.jsxs("div",{className:"voxket-message-header",children:[T.jsx("span",{className:"voxket-message-sender",children:y.sender.name}),T.jsx("span",{className:"voxket-message-time",children:y.timestamp.toLocaleTimeString()})]}),T.jsx("div",{className:"voxket-message-content",children:y.content})]},y.id)),p.messages.length===0&&T.jsx("div",{className:"voxket-empty-messages",children:T.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),T.jsx(iq,{})]}),a&&T.jsx("div",{className:"voxket-transcriptions",children:T.jsx("div",{className:"voxket-transcription-placeholder",children:T.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):T.jsx("div",{className:g,children:T.jsx("div",{className:"voxket-inactive-state",children:T.jsxs("div",{className:"voxket-inactive-message",children:[T.jsx("h3",{children:"Start a conversation"}),T.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function iq(){const t=$x(),[a,s]=Y.useState(""),l=async()=>{if(!(!a.trim()||!t.canSend))try{await t.send(a),s("")}catch(p){console.error("Failed to send message:",p)}},f=p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),l())};return T.jsxs("div",{className:"voxket-chat-input",children:[T.jsx("input",{type:"text",value:a,onChange:p=>s(p.target.value),onKeyPress:f,placeholder:"Type your message...",disabled:!t.canSend,className:"voxket-input"}),T.jsx("button",{onClick:l,disabled:!t.canSend||!a.trim(),className:"voxket-send-button",children:t.isSending?"Sending...":"Send"})]})}function V4({showMetrics:t=!0,showParticipants:a=!0,showStatus:s=!0,customFooter:l,className:f=""}){const p=Id(),h=F5(),g=J5(),y=L1(),x=["voxket-session-footer",`voxket-session-footer--${y.variant||"default"}`,`voxket-session-footer--${y.size||"md"}`,f].filter(Boolean).join(" ");return p.isActive?T.jsx("div",{className:x,children:l||T.jsxs(T.Fragment,{children:[s&&T.jsxs("div",{className:"voxket-session-status",children:[T.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),T.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),t&&h.metrics&&T.jsxs("div",{className:"voxket-session-metrics",children:[T.jsxs("div",{className:"voxket-metric",children:[T.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),T.jsx("span",{className:"voxket-metric-value",children:sq(h.duration||0)})]}),T.jsxs("div",{className:"voxket-metric",children:[T.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),T.jsx("span",{className:"voxket-metric-value",children:h.metrics.messageCount})]})]}),a&&T.jsxs("div",{className:"voxket-participants-info",children:[T.jsxs("span",{className:"voxket-participants-count",children:[g.count," participant",g.count!==1?"s":""]}),g.remoteParticipants.length>0&&T.jsx("div",{className:"voxket-participant-list",children:g.remoteParticipants.map(S=>T.jsx("span",{className:"voxket-participant-name",children:S.name},S.id))})]})]})}):T.jsx("div",{className:x,children:T.jsx("div",{className:"voxket-footer-inactive",children:T.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function sq(t){const a=Math.floor(t/1e3),s=Math.floor(a/60),l=Math.floor(s/60);return l>0?`${l}:${(s%60).toString().padStart(2,"0")}:${(a%60).toString().padStart(2,"0")}`:`${s}:${(a%60).toString().padStart(2,"0")}`}function oq({agentId:t,sessionConfig:a,autoStart:s=!1,onSessionStart:l,onSessionEnd:f,variant:p="default",size:h="md",theme:g,className:y="",children:x}){var R;const S=Id(),A=M4();Y.useEffect(()=>{s&&t&&A.isConnected&&!S.isActive&&S.start(t,a).catch(console.error)},[s,t,A.isConnected,S.isActive]),Y.useEffect(()=>{var O;(O=S.session)!=null&&O.id&&l&&l(S.session.id)},[(R=S.session)==null?void 0:R.id,l]),Y.useEffect(()=>()=>{S.isActive&&f&&S.stop().then(f).catch(console.error)},[]);const C=["voxket-session",`voxket-session--${p}`,`voxket-session--${h}`,S.isActive?"voxket-session--active":"voxket-session--inactive",y].filter(Boolean).join(" ");return T.jsx(eV,{variant:p,size:h,theme:g,className:y,children:T.jsx("div",{className:C,children:x||T.jsxs(T.Fragment,{children:[T.jsx(ox,{name:"header",fallback:T.jsx(R4,{})}),T.jsx(ox,{name:"content",fallback:T.jsx(D4,{})}),T.jsx(ox,{name:"footer",fallback:T.jsx(V4,{})})]})})})}const aV=tV(oq,{Header:R4,Content:D4,Footer:V4,Controls:nV}),Zd={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)"}},Iw={...Zd,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)"}},Qw={...Zd,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"}},iV=Y.createContext(null),sV=()=>{const t=Y.useContext(iV);if(!t)throw new Error("useTheme must be used within a ThemeProvider");return t};function rq({theme:t="default",themes:a={},children:s,cssVariables:l=!0,className:f=""}){const[p,h]=Y.useState(()=>{const C={default:Zd,dark:Iw,enterprise:Qw,...a};return typeof t=="string"?C[t]||Zd:t}),[g,y]=Y.useState(()=>({default:Zd,dark:Iw,enterprise:Qw,...a})),x=C=>{if(typeof C=="string"){const R=g[C];R&&h(R)}else h(C)},S=C=>{y(R=>({...R,[C.name]:C}))};Y.useEffect(()=>{if(l&&typeof document<"u"){const C=document.documentElement;Object.entries(oV(p)).forEach(([R,O])=>{C.style.setProperty(`--voxket-${R}`,O)})}},[p,l]);const A={theme:p,setTheme:x,themes:g,registerTheme:S};return T.jsx(iV.Provider,{value:A,children:T.jsx("div",{className:`voxket-theme voxket-theme--${p.name} ${f}`,children:s})})}function oV(t){const a={},s=(l,f="")=>{for(const[p,h]of Object.entries(l)){const g=f?`${f}-${p}`:p;typeof h=="object"&&h!==null&&!Array.isArray(h)?s(h,g):a[g]=String(h)}};return s(t),a}function lq(t=Zd,a){return{...t,...a,colors:{...t.colors,...a.colors},typography:{...t.typography,...a.typography},spacing:{...t.spacing,...a.spacing},borderRadius:{...t.borderRadius,...a.borderRadius},shadows:{...t.shadows,...a.shadows}}}function cq(t){var s;const{theme:a}=sV();return((s=a.components)==null?void 0:s[t])||{}}const uq=C4("voice-modality","voice",{onActivate:async t=>{const a=t.config;a.enableTranscription&&fq(t),a.enableVoiceActivation&&dq(t,a),console.log("Voice modality activated",a)},onDeactivate:async t=>{console.log("Voice modality deactivated")},onMessage:async(t,a)=>{a.type==="audio"&&hq(t,a)}});function fq(t,a){t.on("participant.speaking.started",s=>{console.log("Transcription: Started for",s.name)}),t.on("participant.speaking.stopped",s=>{console.log("Transcription: Stopped for",s.name)})}function dq(t,a){const s=a.silenceThreshold||-50;console.log("Voice activation setup with threshold:",s)}function hq(t,a){console.log("Playing audio response:",a.content)}const mq=C4("chat-modality","chat",{onActivate:async t=>{const a=t.config;a.enableRichText&&pq(),a.enableFileUpload&&gq(t),a.enableCustomComponents&&yq(),console.log("Chat modality activated",a)},onDeactivate:async t=>{console.log("Chat modality deactivated")},onMessage:async(t,a)=>{const s=t.config;a.type==="ui_component"?vq(t,a):a.type==="text"&&s.enableRichText&&bq(t,a)}});function pq(t){console.log("Rich text support enabled")}function gq(t){console.log("File upload enabled"),t.on("chat.file.uploaded",a=>{console.log("File uploaded:",a.name)})}function yq(t){console.log("Custom components enabled");const a=new Map;a.set("quick-actions",xq),a.set("form",Sq),a.set("card",wq),a.set("chart",Tq)}function vq(t,a){const{componentType:s,props:l}=a.metadata;console.log("Rendering custom component:",s,l),t.emit("chat.component.render",{type:s,props:l,timestamp:new Date})}function bq(t,a){console.log("Processing rich text message:",a.content)}function xq(t){return{type:"quick-actions",actions:t.actions||[],layout:t.layout||"horizontal"}}function Sq(t){return{type:"form",fields:t.fields||[],submitAction:t.submitAction,validation:t.validation}}function wq(t){return{type:"card",title:t.title,content:t.content,actions:t.actions,variant:t.variant||"default"}}function Tq(t){return{type:"chart",chartType:t.chartType||"line",data:t.data,options:t.options}}function rx({track:t,participantName:a,showControls:s=!0,showName:l=!0,showMuteIndicator:f=!0,isPinned:p=!1,className:h="",onClick:g,onPin:y,onUnpin:x}){const S=Y.useRef(null),[A,C]=Y.useState(!1);Y.useEffect(()=>{if(!S.current||!t.isEnabled)return;const j=S.current;return j.srcObject=null,()=>{j.srcObject&&(j.srcObject=null)}},[t]);const R=()=>{g==null||g(t)},O=j=>{j.stopPropagation(),p?x==null||x(t):y==null||y(t)},V=["voxket-video-tile",t.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",t.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",p?"voxket-video-tile--pinned":"",t.isEnabled?"":"voxket-video-tile--disabled",A?"voxket-video-tile--hovered":"",h].filter(Boolean).join(" ");return T.jsxs("div",{className:V,onClick:R,onMouseEnter:()=>C(!0),onMouseLeave:()=>C(!1),style:{aspectRatio:t.dimensions?`${t.dimensions.width} / ${t.dimensions.height}`:"16 / 9"},children:[T.jsx("video",{ref:S,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:t.isLocal}),!t.isEnabled&&T.jsxs("div",{className:"voxket-video-placeholder",children:[T.jsx("div",{className:"voxket-video-placeholder-icon",children:t.isScreenShare?"🖥️":"📹"}),T.jsx("p",{className:"voxket-video-placeholder-text",children:t.isScreenShare?"Screen sharing paused":"Camera off"})]}),T.jsxs("div",{className:"voxket-video-overlay",children:[l&&a&&T.jsxs("div",{className:"voxket-video-name",children:[a,t.isLocal&&" (You)"]}),f&&!t.isEnabled&&T.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),s&&(A||p)&&T.jsxs("div",{className:"voxket-video-controls",children:[T.jsx("button",{className:`voxket-video-control-btn ${p?"voxket-video-control-btn--active":""}`,onClick:O,title:p?"Unpin video":"Pin video",children:"📌"}),t.isScreenShare&&T.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),t.source&&T.jsx("div",{className:"voxket-video-source",children:t.source})]})]}),!t.isEnabled&&T.jsx("div",{className:"voxket-video-loading",children:T.jsx("div",{className:"voxket-spinner"})})]})}function Aq({tracks:t,layout:a,className:s="",onLayoutChange:l,onTrackClick:f,maxVisibleTracks:p=9,showPagination:h=!0}){const[g,y]=Y.useState(0),[x,S]=Y.useState(null),A=Y.useMemo(()=>{let z=[...t];a.type==="speaker"&&x&&(z=[x,...t.filter(_=>_.id!==x.id)]);const B=g*p,$=B+p;return z.slice(B,$)},[t,a,x,g,p]),C=Math.ceil(t.length/p),R=Y.useMemo(()=>{const z=A.length;switch(a.type){case"grid":const B=Math.ceil(Math.sqrt(z)),$=Math.ceil(z/B);return{display:"grid",gridTemplateColumns:`repeat(${B}, 1fr)`,gridTemplateRows:`repeat(${$}, 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{}}},[a.type,A.length]),O=z=>{S(z)},V=()=>{S(null)},j=z=>{l==null||l({...a,type:z})},U=["voxket-video-grid",`voxket-video-grid--${a.type}`,`voxket-video-grid--${A.length}-tracks`,s].filter(Boolean).join(" ");return t.length===0?T.jsx("div",{className:"voxket-video-grid-empty",children:T.jsxs("div",{className:"voxket-video-grid-empty-content",children:[T.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),T.jsx("p",{children:"No video tracks available"})]})}):T.jsxs("div",{className:U,children:[T.jsxs("div",{className:"voxket-video-grid-controls",children:[T.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(z=>T.jsx("button",{className:`voxket-layout-btn ${a.type===z?"voxket-layout-btn--active":""}`,onClick:()=>j(z),title:`Switch to ${z} layout`,children:Eq(z)},z))}),T.jsxs("div",{className:"voxket-video-count",children:[t.length," participant",t.length!==1?"s":""]})]}),T.jsx("div",{className:"voxket-video-grid-content",style:R,children:a.type==="speaker"&&x?T.jsxs(T.Fragment,{children:[T.jsx("div",{className:"voxket-video-speaker-main",children:T.jsx(rx,{track:x,participantName:`Participant ${x.participantId}`,isPinned:!0,onClick:f,onUnpin:V})}),T.jsx("div",{className:"voxket-video-speaker-sidebar",children:A.filter(z=>z.id!==x.id).map(z=>T.jsx(rx,{track:z,participantName:`Participant ${z.participantId}`,showControls:!1,onClick:f,onPin:O},z.id))})]}):A.map(z=>T.jsx(rx,{track:z,participantName:`Participant ${z.participantId}`,isPinned:(x==null?void 0:x.id)===z.id,onClick:f,onPin:O,onUnpin:V},z.id))}),h&&C>1&&T.jsxs("div",{className:"voxket-video-pagination",children:[T.jsx("button",{className:"voxket-pagination-btn",onClick:()=>y(Math.max(0,g-1)),disabled:g===0,children:"←"}),T.jsxs("span",{className:"voxket-pagination-info",children:["Page ",g+1," of ",C]}),T.jsx("button",{className:"voxket-pagination-btn",onClick:()=>y(Math.min(C-1,g+1)),disabled:g===C-1,children:"→"})]})]})}function Eq(t){switch(t){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function Cq({localTrack:t,onToggleCamera:a,onToggleScreenShare:s,onLayoutChange:l,showLayoutControls:f=!0,showCameraControls:p=!0,showScreenShareControls:h=!0,className:g=""}){const y=["voxket-video-controls",g].filter(Boolean).join(" "),x=S=>{l==null||l({type:S,showLocalVideo:!0,aspectRatio:"16:9"})};return T.jsxs("div",{className:y,children:[p&&T.jsxs("div",{className:"voxket-video-controls-section",children:[T.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),T.jsxs("button",{className:`voxket-control-btn ${t!=null&&t.isEnabled?"voxket-control-btn--active":""}`,onClick:a,title:t!=null&&t.isEnabled?"Turn off camera":"Turn on camera",children:[T.jsx("span",{className:"voxket-control-icon",children:t!=null&&t.isEnabled?"📹":"📷"}),T.jsx("span",{className:"voxket-control-label",children:t!=null&&t.isEnabled?"Camera On":"Camera Off"})]}),(t==null?void 0:t.dimensions)&&T.jsxs("div",{className:"voxket-video-info",children:[t.dimensions.width," × ",t.dimensions.height]})]}),h&&T.jsxs("div",{className:"voxket-video-controls-section",children:[T.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),T.jsxs("button",{className:`voxket-control-btn ${t!=null&&t.isScreenShare?"voxket-control-btn--active":""}`,onClick:s,title:t!=null&&t.isScreenShare?"Stop screen sharing":"Start screen sharing",children:[T.jsx("span",{className:"voxket-control-icon",children:t!=null&&t.isScreenShare?"🛑":"🖥️"}),T.jsx("span",{className:"voxket-control-label",children:t!=null&&t.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),f&&T.jsxs("div",{className:"voxket-video-controls-section",children:[T.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),T.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:S,icon:A,label:C})=>T.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>x(S),title:`Switch to ${C} layout`,children:[T.jsx("span",{className:"voxket-control-icon",children:A}),T.jsx("span",{className:"voxket-control-label",children:C})]},S))})]}),T.jsxs("div",{className:"voxket-video-controls-section",children:[T.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),T.jsxs("div",{className:"voxket-video-settings",children:[T.jsxs("div",{className:"voxket-setting-group",children:[T.jsx("label",{className:"voxket-setting-label",children:"Quality"}),T.jsxs("select",{className:"voxket-setting-select",children:[T.jsx("option",{value:"high",children:"High (720p)"}),T.jsx("option",{value:"medium",children:"Medium (480p)"}),T.jsx("option",{value:"low",children:"Low (240p)"})]})]}),T.jsxs("div",{className:"voxket-setting-group",children:[T.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),T.jsxs("select",{className:"voxket-setting-select",children:[T.jsx("option",{value:"30",children:"30 fps"}),T.jsx("option",{value:"15",children:"15 fps"}),T.jsx("option",{value:"10",children:"10 fps"})]})]}),T.jsxs("div",{className:"voxket-setting-group",children:[T.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),T.jsxs("select",{className:"voxket-setting-select",children:[T.jsx("option",{value:"unlimited",children:"Unlimited"}),T.jsx("option",{value:"1000",children:"1 Mbps"}),T.jsx("option",{value:"500",children:"500 Kbps"}),T.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),T.jsxs("div",{className:"voxket-video-controls-section",children:[T.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),T.jsxs("div",{className:"voxket-video-stats",children:[T.jsxs("div",{className:"voxket-stat-item",children:[T.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),T.jsx("span",{className:"voxket-stat-value",children:t!=null&&t.dimensions?`${t.dimensions.width}×${t.dimensions.height}`:"N/A"})]}),T.jsxs("div",{className:"voxket-stat-item",children:[T.jsx("span",{className:"voxket-stat-label",children:"Source:"}),T.jsx("span",{className:"voxket-stat-value",children:(t==null?void 0:t.source)||"None"})]}),T.jsxs("div",{className:"voxket-stat-item",children:[T.jsx("span",{className:"voxket-stat-label",children:"Status:"}),T.jsx("span",{className:`voxket-stat-value ${t!=null&&t.isEnabled?"voxket-stat-value--active":"voxket-stat-value--inactive"}`,children:t!=null&&t.isEnabled?"Active":"Inactive"})]})]})]})]})}const rV=({handler:t,loadData:a,data:s,client:l,addLocalMessage:f})=>{const[p,h]=M.useState(null),[g,y]=M.useState(!0),[x,S]=M.useState(!1),[A]=M.useState(Date.now());M.useEffect(()=>{(async()=>{try{if(y(!0),console.log("📋 AssignmentView: Loading assignment data..."),console.log("📋 AssignmentView: Received data from RPC:",s),s&&typeof s=="object"){const j={title:s.title||"Untitled Assignment",description:s.description||"No description provided",estimated_time_of_completion:s.estimated_time_of_completion||"Unknown"};h(j),console.log("📋 AssignmentView: Assignment loaded from RPC data:",j)}}catch(j){console.error("📋 AssignmentView: Error loading assignment:",j),h({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{y(!1)}})()},[s,a]);const C=({message:V,assignment:j})=>{const U=V.toLowerCase().includes("declined"),z=U?"bg-red-50 border-red-200":"bg-green-50 border-green-200",B=U?"text-red-700":"text-green-700",$=U?"❌":"🎉";return T.jsxs("div",{className:`max-w-sm mx-auto ${z} border rounded-lg shadow p-3 flex flex-col items-center`,children:[T.jsx("div",{className:"text-2xl mb-2",children:$}),T.jsx("div",{className:`${B} font-semibold text-sm mb-1`,children:V}),T.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:j.title}),T.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},R=async()=>{if(!(!p||!t)){S(!0);try{const V={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",V),t.didSuccess(V,T.jsx(C,{message:"Assignment accepted!",assignment:p}))}catch(V){console.error("📋 AssignmentView: Error accepting assignment:",V),t.didFail({error:"Failed to accept assignment"})}finally{S(!1)}}},O=async()=>{if(!(!p||!t)){S(!0);try{const V={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",V),t.didSuccess(V,T.jsx(C,{message:"Assignment declined",assignment:p}))}catch(V){console.error("📋 AssignmentView: Error declining assignment:",V),t.didFail({error:"Failed to decline assignment"})}finally{S(!1)}}};return g?T.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:T.jsxs("div",{className:"flex items-center justify-center py-4",children:[T.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),T.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):p?T.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[T.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:T.jsx("div",{className:"flex items-center justify-between",children:T.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:p.title})})}),T.jsxs("div",{className:"p-3",children:[T.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:T.jsx("p",{className:"text-xs text-gray-700 leading-snug",children:p.description})}),T.jsx("div",{className:"mb-3",children:T.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[T.jsx("span",{className:"text-xs mr-1",children:"📅"}),T.jsxs("span",{children:["Est: ",p.estimated_time_of_completion]})]})}),T.jsxs("div",{className:"flex gap-2",children:[T.jsx("button",{onClick:R,disabled:x,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:x?T.jsxs("span",{className:"flex items-center justify-center",children:[T.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),T.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),T.jsx("button",{onClick:O,disabled:x,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"})]})]})]}):T.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:T.jsxs("div",{className:"text-center py-4",children:[T.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),T.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function Mq(){const[t,a]=M.useState(null),[s,l]=M.useState([]);M.useEffect(()=>{const g=new U1({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return a(g),g.on("rpc.method.called",y=>{console.log("RPC Method Called:",y)}),g.on("rpc.interaction.completed",y=>{console.log("RPC Interaction Completed:",y)}),()=>{g.disconnect()}},[]);const f=async()=>{if(t)try{await t.registerFrontendRPC("give_assignment",rV,"embedded");const g=t.getRegisteredRpcMethods();l(g),console.log("✅ Assignment RPC registered successfully")}catch(g){console.error("❌ Failed to register assignment RPC:",g)}},p=async()=>{if(!t)return;const g=({handler:y,timeout:x})=>{const[S,A]=M.useState(""),C=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],R=V=>{A(V)},O=()=>{const V=C.find(j=>j.id===S);y==null||y.didSuccess({selectedProduct:S,productName:V==null?void 0:V.name,price:V==null?void 0:V.price,timestamp:new Date().toISOString()})};return T.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[T.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),T.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),T.jsx("div",{className:"space-y-3 mb-6",children:C.map(V=>T.jsx("div",{onClick:()=>R(V.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${S===V.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:T.jsxs("div",{className:"flex justify-between items-center",children:[T.jsxs("div",{children:[T.jsx("h4",{className:"font-medium",children:V.name}),T.jsx("p",{className:"text-gray-600 text-sm",children:V.price})]}),T.jsx("div",{className:`w-4 h-4 rounded-full ${S===V.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},V.id))}),T.jsxs("div",{className:"flex justify-end space-x-3",children:[T.jsx("button",{onClick:()=>y==null?void 0:y.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),T.jsx("button",{onClick:O,disabled:!S,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),x&&T.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",x," seconds"]})]})};try{await t.registerFrontendRPC("recommend_product",g,"modal");const y=t.getRegisteredRpcMethods();l(y),console.log("✅ Product Recommendation RPC registered successfully")}catch(y){console.error("❌ Failed to register product recommendation RPC:",y)}},h=async()=>{if(!t)return;const g=({handler:y})=>{const[x,S]=M.useState(0),[A,C]=M.useState(""),R=()=>{y==null||y.didSuccess({rating:x,comment:A,timestamp:new Date().toISOString()})};return T.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[T.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),T.jsxs("div",{className:"mb-4",children:[T.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),T.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(O=>T.jsx("button",{onClick:()=>S(O),className:`text-2xl ${O<=x?"text-yellow-400":"text-gray-300"}`,children:"⭐"},O))})]}),T.jsxs("div",{className:"mb-4",children:[T.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),T.jsx("textarea",{value:A,onChange:O=>C(O.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),T.jsxs("div",{className:"flex justify-end space-x-2",children:[T.jsx("button",{onClick:()=>y==null?void 0:y.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),T.jsx("button",{onClick:R,disabled:x===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 t.registerFrontendRPC("collect_feedback",g,"embedded");const y=t.getRegisteredRpcMethods();l(y),console.log("✅ Feedback RPC registered successfully")}catch(y){console.error("❌ Failed to register feedback RPC:",y)}};return T.jsxs("div",{className:"p-6",children:[T.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),T.jsxs("div",{className:"space-y-4 mb-6",children:[T.jsxs("div",{children:[T.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),T.jsxs("div",{className:"space-x-2",children:[T.jsx("button",{onClick:f,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),T.jsx("button",{onClick:p,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),T.jsx("button",{onClick:h,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),T.jsxs("div",{children:[T.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),s.length>0?T.jsx("ul",{className:"list-disc list-inside space-y-1",children:s.map(g=>T.jsx("li",{className:"text-gray-700",children:T.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:g})},g))}):T.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),T.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[T.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),T.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[T.jsxs("li",{children:["Register RPC methods with React components using ",T.jsx("code",{children:"client.registerFrontendRPC()"})]}),T.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),T.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),T.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),T.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),T.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[T.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),T.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),T.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
|
|
448
448
|
const response = await participant.performRpc({
|
|
449
449
|
method: 'give_assignment',
|
|
450
450
|
data: JSON.stringify({
|
package/dist/index.js
CHANGED
|
@@ -46409,6 +46409,11 @@ class U4 extends lN {
|
|
|
46409
46409
|
width: s.width,
|
|
46410
46410
|
height: s.height,
|
|
46411
46411
|
onDisplayTypeChange: s.onDisplayTypeChange,
|
|
46412
|
+
prompts: s.prompts,
|
|
46413
|
+
statusMessage: s.statusMessage,
|
|
46414
|
+
welcomeTitle: s.welcomeTitle,
|
|
46415
|
+
welcomeSubTitle: s.welcomeSubTitle,
|
|
46416
|
+
loadingText: s.loadingText,
|
|
46412
46417
|
voxketClient: this
|
|
46413
46418
|
// Pass the current client instance to preserve session state
|
|
46414
46419
|
};
|
package/package.json
CHANGED