@voxket-ai/voxket-live 1.0.70 → 1.0.72
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -177,7 +177,7 @@ To suppress this warning, you need to explicitly provide the \`palette.${t}Chann
|
|
|
177
177
|
${n.promptSlider}
|
|
178
178
|
${i===r?"opacity-100":"opacity-0"}
|
|
179
179
|
whitespace-pre-line break-words
|
|
180
|
-
`,style:{minHeight:"2.5rem",display:i===r?"block":"none"},children:o},i))})}function Z8({statusMessage:e,theme:t}){const n=Ie(t);return d.jsxs("div",{className:"z-10 flex items-center space-x-2 mt-2 pb-2",children:[d.jsx("div",{className:n.statusIndicator}),d.jsx("span",{className:`text-xs ${n.text.muted}`,children:e})]})}const K8=({disabled:e,onStartCall:t,onStartChat:n,onStartVideo:r,prompts:s=['"Book a meeting with the marketing team"',`"What's the status of project Alpha?"`,`"Summarize yesterday's sales report"`,'"Find a good Italian restaurant nearby"','"Remind me to call John tomorrow at 10 AM"'],statusMessage:o="Agent is ready",title:i="Choose how to interact",subTitle:a="Ask me anything or give me a task to complete",theme:c="vox",modalities:l=["voice","chat","video"]})=>{const u=Ie(c),f=l.includes("voice"),h=l.includes("chat"),g=l.includes("video"),y=[f,h,g].filter(Boolean).length;return console.log("🎯 Welcome component debug:",{modalities:l,hasVoice:f,hasChat:h,hasVideo:g,totalButtons:y,onStartVideo:!!r}),d.jsxs("div",{inert:e,className:"flex p-8 flex-col items-center h-full justify-center w-full",children:[d.jsxs("div",{className:"mt-1 relative flex items-center justify-center mb-8 w-full",style:{minHeight:"120px"},children:[d.jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[d.jsx("div",{className:u.pulseRings.ring1}),d.jsx("div",{className:u.pulseRings.ring2,style:{animationDelay:"0.5s"}}),d.jsx("div",{className:u.pulseRings.ring3,style:{animationDelay:"1s"}})]}),d.jsx("div",{className:"relative z-10 flex items-center justify-center",children:f&&h&&g?d.jsxs("div",{className:"flex gap-4 items-center justify-center",children:[d.jsx(zr,{onClick:t,disabled:e,theme:c}),d.jsx(jo,{onClick:n,disabled:e,theme:c}),d.jsx(Po,{onClick:r||t,disabled:e,theme:c})]}):y>1?d.jsxs("div",{className:"flex gap-6 items-center justify-center",children:[f&&d.jsx(zr,{onClick:t,disabled:e,theme:c}),h&&d.jsx(jo,{onClick:n,disabled:e,theme:c}),g&&r&&d.jsx(Po,{onClick:r,disabled:e,theme:c})]}):d.jsx("div",{className:"flex items-center justify-center",children:f?d.jsx(zr,{onClick:t,disabled:e,theme:c}):h?d.jsx(jo,{onClick:n,disabled:e,theme:c}):g&&r?d.jsx(Po,{onClick:r,disabled:e,theme:c}):d.jsx(zr,{onClick:t,disabled:e,theme:c})})})]}),d.jsxs("div",{className:"text-center flex flex-col items-center gap-y-2 mb-6 w-full",children:[d.jsx("h3",{className:`text-xl font-semibold mb-2 ${u.text.accent}`,children:i}),d.jsx("p",{className:`text-sm leading-relaxed px-4 ${u.text.secondary}`,children:a}),y>1&&d.jsxs("div",{className:"flex gap-6 mt-4 text-xs justify-center",children:[f&&d.jsxs("div",{className:"flex flex-col items-center gap-1",children:[d.jsx(Gh,{className:"w-4 h-4"}),d.jsx("span",{className:u.text.muted,children:"Voice"})]}),h&&d.jsxs("div",{className:"flex flex-col items-center gap-1",children:[d.jsx(Kh,{className:"w-4 h-4"}),d.jsx("span",{className:u.text.muted,children:"Chat"})]}),g&&d.jsxs("div",{className:"flex flex-col items-center gap-1",children:[d.jsx(Yh,{className:"w-4 h-4"}),d.jsx("span",{className:u.text.muted,children:"Video"})]})]})]}),d.jsx(W8,{prompts:s,theme:c}),d.jsx(Z8,{statusMessage:o,theme:c})]})};function qh({room:e,onSessionEnd:t,onSessionStart:n,enableConsoleLogging:r=!0,enableLocalStorage:s=!0,voxketSessionId:o}={}){const[i,a]=m.useState(null),[c,l]=m.useState([]),[u,f]=m.useState(null),[h,g]=m.useState([]),y=m.useCallback((v,S)=>{const C={timestamp:new Date,event:v,data:S,sessionId:i==null?void 0:i.sessionId,participantId:u==null?void 0:u.identity};if(l(E=>[...E,C]),s){const E=JSON.parse(localStorage.getItem("voxket-session-logs")||"[]");E.push(C),localStorage.setItem("voxket-session-logs",JSON.stringify(E))}return C},[i==null?void 0:i.sessionId,u==null?void 0:u.identity,r,s]);m.useEffect(()=>{if(!e)return;const v=()=>{const b=o||`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,I=new Date,L={sessionId:b,startTime:I,totalMessages:0,connectionIssues:0,participantCount:h.length,events:[]};a(L),y("SESSION_STARTED",{sessionId:b,startTime:I}),n==null||n(b)},S=()=>{if(i){const b=new Date,I=b.getTime()-i.startTime.getTime(),L={...i,endTime:b,duration:I,events:c};y("SESSION_ENDED",{sessionId:i.sessionId,duration:`${Math.round(I/1e3)}s`,totalMessages:i.totalMessages,connectionIssues:i.connectionIssues}),t==null||t(L),a(null),l([])}},C=b=>{y("CONNECTION_STATE_CHANGED",{state:b}),b===te.ConnectionState.Reconnecting&&i&&(a(I=>I?{...I,connectionIssues:I.connectionIssues+1}:null),y("CONNECTION_ISSUE",{type:"reconnecting"}))},E=b=>{y("TRACK_PUBLISHED",{trackKind:b.kind,trackSource:b.source})},T=b=>{y("TRACK_UNPUBLISHED",{trackKind:b.kind,trackSource:b.source})},k=(b,I)=>{i&&a(L=>L?{...L,totalMessages:L.totalMessages+1}:null),y("DATA_RECEIVED",{participantId:I==null?void 0:I.identity,dataSize:b.length})},j=b=>{y("PARTICIPANT_CONNECTED",{participantId:b.identity,participantName:b.name}),g(I=>[...I,b]),i&&a(I=>I?{...I,participantCount:I.participantCount+1}:null)},$=b=>{y("PARTICIPANT_DISCONNECTED",{participantId:b.identity,participantName:b.name}),g(I=>I.filter(L=>L.identity!==b.identity))};return e.localParticipant&&f(e.localParticipant),e.on(te.RoomEvent.Connected,v),e.on(te.RoomEvent.Disconnected,S),e.on(te.RoomEvent.ConnectionStateChanged,C),e.on(te.RoomEvent.TrackPublished,E),e.on(te.RoomEvent.TrackUnpublished,T),e.on(te.RoomEvent.DataReceived,k),e.on(te.RoomEvent.ParticipantConnected,j),e.on(te.RoomEvent.ParticipantDisconnected,$),()=>{e.off(te.RoomEvent.Connected,v),e.off(te.RoomEvent.Disconnected,S),e.off(te.RoomEvent.ConnectionStateChanged,C),e.off(te.RoomEvent.TrackPublished,E),e.off(te.RoomEvent.TrackUnpublished,T),e.off(te.RoomEvent.DataReceived,k),e.off(te.RoomEvent.ParticipantConnected,j),e.off(te.RoomEvent.ParticipantDisconnected,$)}},[e,i,c,h.length,y,t,n]);const p=m.useCallback(()=>s?JSON.parse(localStorage.getItem("voxket-session-logs")||"[]"):c,[c,s]),x=m.useCallback(()=>{s&&localStorage.removeItem("voxket-session-logs"),l([])},[s]),w=m.useCallback(()=>{const v=p(),S=JSON.stringify(v,null,2),C="data:application/json;charset=utf-8,"+encodeURIComponent(S),E=`voxket-session-logs-${new Date().toISOString().split("T")[0]}.json`,T=document.createElement("a");T.setAttribute("href",C),T.setAttribute("download",E),T.click()},[p]);return{sessionMetrics:i,sessionLogs:c,logEvent:y,getSessionLogs:p,clearSessionLogs:x,exportSessionLogs:w}}class ja{constructor(){Te(this,"listeners",{})}on(t,n){return this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(n),()=>this.off(t,n)}once(t,n){const r=(...s)=>{this.off(t,r),n(...s)};return this.on(t,r)}off(t,n){const r=this.listeners[t];if(!r)return;const s=r.indexOf(n);s>-1&&r.splice(s,1)}removeAllListeners(t){t?delete this.listeners[t]:this.listeners={}}emit(t,...n){const r=this.listeners[t];if(!r)return;const s=[...r];for(const o of s)try{o(...n)}catch(i){console.error(`Error in event listener for ${String(t)}:`,i)}}listenerCount(t){var n;return((n=this.listeners[t])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class Xh{constructor(t){Te(this,"plugins",new Map);Te(this,"installedPlugins",new Set);Te(this,"context");this.context={client:t,emit:t.emit.bind(t),on:t.on.bind(t),config:{}}}register(t){if(this.plugins.has(t.name))throw new Error(`Plugin '${t.name}' is already registered`);if(t.dependencies){for(const n of t.dependencies)if(!this.plugins.has(n))throw new Error(`Plugin '${t.name}' depends on '${n}' which is not registered`)}this.plugins.set(t.name,t)}async install(t,n){const r=this.plugins.get(t);if(!r)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t))throw new Error(`Plugin '${t}' is already installed`);if(r.dependencies)for(const o of r.dependencies)this.installedPlugins.has(o)||await this.install(o);const s={...this.context,config:{...r.config,...n}};r.install&&await r.install(s),this.installedPlugins.add(t),this.setupPluginEvents(r,s)}async uninstall(t){var r;const n=this.plugins.get(t);if(!n)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t)){for(const[s,o]of this.plugins)if(this.installedPlugins.has(s)&&((r=o.dependencies)!=null&&r.includes(t)))throw new Error(`Cannot uninstall '${t}' because '${s}' depends on it`);n.uninstall&&await n.uninstall(this.context),this.installedPlugins.delete(t)}}isInstalled(t){return this.installedPlugins.has(t)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(t){return this.plugins.get(t)}setupPluginEvents(t,n){t.onSessionStart&&n.on("session.started",r=>{t.onSessionStart(n,r.id)}),t.onSessionEnd&&n.on("session.ended",r=>{t.onSessionEnd(n,r.id)}),t.onAgentResponse&&n.on("agent.response",r=>{t.onAgentResponse(n,r)})}}function G8(e){return e}function Pa(e,t,n){return{name:e,version:"1.0.0",description:`${t} modality plugin`,install:async r=>{n.onActivate&&await n.onActivate(r)},uninstall:async r=>{n.onDeactivate&&await n.onDeactivate(r)},onAgentResponse:n.onMessage}}const Y8={name:"analytics",version:"1.0.0",description:"Built-in analytics tracking",install:async e=>{console.log("Analytics plugin installed"),e.on("session.started",t=>{console.log("Analytics: Session started",t.id)}),e.on("session.ended",(t,n)=>{console.log("Analytics: Session ended",t.id,n)}),e.on("chat.message.sent",t=>{console.log("Analytics: User message sent",t.content.length)})}},q8={name:"debug",version:"1.0.0",description:"Debug logging and development tools",install:async e=>{console.log("Debug plugin installed");const t=e.emit;e.emit=(n,...r)=>(console.log(`[Debug] Event: ${String(n)}`,r),t(n,...r))}},X8={name:"metrics",version:"1.0.0",description:"Advanced metrics collection",install:async e=>{console.log("Metrics plugin installed");const t=new Map;e.on("session.started",n=>{t.set(n.id,{startTime:Date.now(),events:[]})}),e.on("agent.response",n=>{console.log("Metrics: Agent response analyzed",{type:n.type,length:n.content.length,timestamp:n.timestamp})})}},Jh=A.createContext(null);function Qh({config:e,children:t,autoConnect:n=!1}){const[r,s]=A.useState(null),[o,i]=A.useState(!1),[a,c]=A.useState(!1),[l,u]=A.useState(null),[f,h]=A.useState(null),[g,y]=A.useState("idle"),[p,x]=A.useState(null),[w,v]=A.useState([]),[S,C]=A.useState([]),[E,T]=A.useState([]);A.useEffect(()=>{const P=new Ar(e);return s(P),k(P),n&&j(P),()=>{P.disconnect().catch(console.error)}},[e,n]);const k=P=>{P.on("connection.connecting",()=>{c(!0),u(null)}),P.on("connection.connected",()=>{i(!0),c(!1),u(null)}),P.on("connection.disconnected",()=>{i(!1),c(!1),h(null),y("idle"),v([]),C([]),T([])}),P.on("connection.error",Y=>{u(Y),c(!1)}),P.on("session.created",Y=>{h(Y),y(Y.state)}),P.on("session.state.changed",Y=>{y(Y),f&&h({...f,state:Y})}),P.on("session.ended",(Y,R)=>{h(null),y("idle"),x(R),v([]),C([]),T([])}),P.on("participant.joined",Y=>{v(R=>[...R,Y])}),P.on("participant.left",Y=>{v(R=>R.filter(V=>V.id!==Y.id))}),P.on("chat.message.received",Y=>{C(R=>[...R,Y])}),P.on("chat.message.sent",Y=>{C(R=>[...R,Y])}),P.on("transcription.received",Y=>{T(R=>[...R,Y])})},j=async P=>{const Y=P||r;if(Y)try{await Y.connect()}catch(R){console.error("Failed to connect:",R)}},z={client:r,isConnected:o,isConnecting:a,connectionError:l,currentSession:f,sessionState:g,sessionMetrics:p,participants:w,chatMessages:S,transcriptions:E,connect:()=>j(),disconnect:async()=>{if(r)try{await r.disconnect()}catch(P){console.error("Failed to disconnect:",P)}},createSession:async(P,Y={})=>{if(!r)throw new Error("Client not initialized");const R={agentId:P,participantName:Y.participantName||"User",metadata:Y.metadata,modalities:Y.modalities||["voice"]};return await r.createSession(R)},endSession:async()=>r?await r.endSession():null,sendChatMessage:async P=>{if(!r)throw new Error("Client not initialized");await r.sendChatMessage(P)},setMicrophoneEnabled:async P=>{if(!r)throw new Error("Client not initialized");await r.setMicrophoneEnabled(P)},setCameraEnabled:async P=>{if(!r)throw new Error("Client not initialized");await r.setCameraEnabled(P)},startScreenShare:async()=>{if(!r)throw new Error("Client not initialized");await r.startScreenShare()},stopScreenShare:async()=>{if(!r)throw new Error("Client not initialized");await r.stopScreenShare()}};return d.jsx(Jh.Provider,{value:z,children:t})}function bt(){const e=A.useContext(Jh);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}class J8 extends ja{constructor(n){super();Te(this,"room",null);Te(this,"registeredMethods",new Map);Te(this,"activeInteractions",new Map);Te(this,"currentInteraction",null);n&&this.setRoom(n)}setRoom(n){this.room=n}async registerFrontendRPC(n,r,s="embedded"){if(console.log(`RpcManager: Starting registration for method '${n}'`),!this.room)throw console.error(`RpcManager: Cannot register '${n}' - no room instance`),new Error("Room not initialized. Cannot register RPC method.");if(!this.room.localParticipant)throw console.error(`RpcManager: Cannot register '${n}' - no local participant`),new Error("Local participant not available for RPC registration");console.log(`RpcManager: Room state: ${this.room.state}`),console.log(`RpcManager: Local participant: ${this.room.localParticipant.identity}`),console.log(`RpcManager: Registering frontend RPC method: ${n}`);const o={methodName:n,component:r,presentationMode:s};this.registeredMethods.set(n,o);try{this.room.registerRpcMethod(n,async i=>{console.log(`RpcManager: RPC method '${n}' called by ${i.callerIdentity}`),console.log("RpcManager: Payload:",i.payload),this.emit("rpc.method.called",{methodName:n,data:i});let a;console.log(`RpcManager: Current registration for '${n}':`,o);let c=i.responseTimeout||30;try{a=JSON.parse(i.payload)}catch{a=i.payload}try{const l=await this.awaitUserInteraction(n,r,s,a,c);return JSON.stringify(l)}catch(l){throw console.error(`RpcManager: Error in RPC method '${n}':`,l),l}}),this.emit("rpc.method.registered",{methodName:n}),console.log(`RpcManager: Successfully registered RPC method: ${n}`)}catch(i){throw console.error(`RpcManager: Failed to register RPC method '${n}':`,i),i}}async awaitUserInteraction(n,r,s,o,i){return new Promise((a,c)=>{const l=`${n}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${n}, timeout: ${i} seconds`);const u={didSuccess:(h,g)=>{console.log(`RpcManager: User interaction successful for method: ${n}`,h),this.clearInteraction(l),this.currentInteraction=null;const y={success:!0,message:"User interaction completed successfully",data:h,timestamp:new Date,...g?{successView:g}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:y}),a(y)},didFail:h=>{console.log(`RpcManager: User interaction failed for method: ${n}`,h),this.clearInteraction(l);const g={success:!1,message:"User interaction failed",error:h,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:g}),a(g)},dismissView:()=>{var g;console.log(`RpcManager: User dismissed interaction for method: ${n}`),console.log("RpcManager: Current interaction before dismiss:",(g=this.currentInteraction)==null?void 0:g.methodName),this.clearInteraction(l),this.currentInteraction=null,console.log("RpcManager: Current interaction after dismiss:",this.currentInteraction);const h={success:!0,data:{dismissed:!0,reason:"User dismissed the interaction"},message:"User interaction dismissed",timestamp:new Date};this.emit("rpc.interaction.dismissed",{methodName:n,response:h}),this.emit("rpc.interaction.completed",{methodName:n,response:h}),setTimeout(()=>{var y;((y=this.currentInteraction)==null?void 0:y.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(h)},didTimeout:h=>{console.log(`RpcManager: User interaction timeout for method: ${n}`),this.clearInteraction(l),this.currentInteraction=null;const g={success:!0,message:`User interaction timed out after ${i} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...h?{timeoutView:h}:{}};this.emit("rpc.interaction.timeout",{methodName:n,response:g}),setTimeout(()=>{var y;((y=this.currentInteraction)==null?void 0:y.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(g)}},f=setTimeout(()=>{u.didTimeout&&u.didTimeout()},i);this.activeInteractions.set(l,{resolve:h=>a(JSON.parse(h)),reject:c,timeoutId:f}),this.currentInteraction={isVisible:!0,methodName:n,component:r,presentationMode:s,timeout:i,data:o,handler:u},this.emit("rpc.interaction.started",{methodName:n,presentationMode:s}),setTimeout(async()=>{var h;if((h=this.currentInteraction)!=null&&h.handler)try{console.log(`RpcManager: Component created for method: ${n} with data:`,o)}catch(g){console.error("RpcManager: Error loading data into component:",g),u.didFail({error:"Failed to load data into component"})}},100)})}clearInteraction(n){const r=this.activeInteractions.get(n);r&&(console.log(`RpcManager: Clearing interaction: ${n}`),clearTimeout(r.timeoutId),this.activeInteractions.delete(n))}getCurrentInteraction(){return this.currentInteraction}dismissCurrentInteraction(){var n;this.currentInteraction&&(console.log(`RpcManager: Dismissing current interaction: ${this.currentInteraction.methodName}`),(n=this.currentInteraction.handler)==null||n.dismissView(),setTimeout(()=>{this.currentInteraction&&(console.log("RpcManager: Force clearing lingering interaction"),this.currentInteraction=null)},0))}getRegisteredMethods(){return Array.from(this.registeredMethods.keys())}unregisterMethod(n){this.registeredMethods.delete(n),console.log(`RpcManager: Unregistered RPC method: ${n}`)}clear(){for(const[n,r]of this.activeInteractions)clearTimeout(r.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null,console.log("RpcManager: Cleared all registrations and interactions")}}class ue extends Error{constructor(t,n,r){super(t),this.code=n,this.details=r,this.name="VoxketError"}}function Q8(e){if(!Ws.createRoot||typeof Ws.createRoot!="function")throw new Error("createRoot is not available. Make sure React 18+ and react-dom/client are properly installed and accessible.");try{const t=Ws.createRoot(e);if(!t)throw new Error("createRoot returned null or undefined");return{render:n=>{if(!t||typeof t.render!="function")throw new Error("React root render method is not available");try{t.render(n)}catch(r){throw console.error("Error rendering React element:",r),r}},unmount:()=>{try{t&&typeof t.unmount=="function"&&t.unmount()}catch(n){console.warn("Error unmounting React root:",n);try{e.innerHTML=""}catch(r){console.warn("Error clearing container:",r)}}}}}catch(t){throw console.error("Error creating React root:",t),new Error(`Failed to create React root: ${t instanceof Error?t.message:"Unknown error"}`)}}class Ar extends ja{constructor(n){super();Te(this,"config");Te(this,"room",null);Te(this,"pluginManager");Te(this,"rpcManager");Te(this,"isConnected",!1);Te(this,"currentSession",null);Te(this,"connectionState",te.ConnectionState.Disconnected);Te(this,"renderedComponents",new Map);Te(this,"textStreamHandlersRegistered",!1);Te(this,"currentAgentInfo",null);Te(this,"chatMessages",[]);this.config=n,this.pluginManager=new Xh(this),this.rpcManager=new J8,this.setupEventListeners(),this.initializeClient()}setupEventListeners(){this.on("connection.connected",()=>{var n,r;this.isConnected=!0,(r=(n=this.config).onConnected)==null||r.call(n)}),this.on("connection.disconnected",n=>{var r,s;this.isConnected=!1,(s=(r=this.config).onDisconnected)==null||s.call(r,n)}),this.on("connection.error",n=>{var r,s;(s=(r=this.config).onError)==null||s.call(r,n)}),this.on("chat.message.received",n=>{var r,s;this.addChatMessage(n),(s=(r=this.config).onMessageReceived)==null||s.call(r,n)}),this.on("chat.message.updated",n=>{this.updateChatMessage(n)}),this.on("chat.message.sent",n=>{this.addChatMessage(n)}),this.on("transcription.received",n=>{var r,s;(s=(r=this.config).onTranscriptionReceived)==null||s.call(r,n)}),this.on("session.state.changed",n=>{var r,s;(s=(r=this.config).onSessionStateChanged)==null||s.call(r,n)}),this.on("session.created",n=>{var r,s;(s=(r=this.config).onSessionStart)==null||s.call(r,n.id)}),this.on("session.ended",(n,r)=>{var s,o;(o=(s=this.config).onSessionEnd)==null||o.call(s,r)}),this.on("participant.joined",n=>{var r,s;(s=(r=this.config).onUserJoined)==null||s.call(r,n.id)}),this.on("participant.left",n=>{var r,s;(s=(r=this.config).onUserLeft)==null||s.call(r,n.id)}),this.setupRpcEventForwarding()}setupRpcEventForwarding(){if(!this.rpcManager){console.warn("RpcManager not initialized, skipping event forwarding setup");return}this.rpcManager.on("rpc.method.registered",n=>this.emit("rpc.method.registered",n)),this.rpcManager.on("rpc.method.called",n=>this.emit("rpc.method.called",n)),this.rpcManager.on("rpc.interaction.started",n=>this.emit("rpc.interaction.started",n)),this.rpcManager.on("rpc.interaction.completed",n=>this.emit("rpc.interaction.completed",n)),this.rpcManager.on("rpc.interaction.timeout",n=>this.emit("rpc.interaction.timeout",n)),this.rpcManager.on("rpc.interaction.dismissed",n=>this.emit("rpc.interaction.dismissed",n))}initializeClient(){this.room=new te.Room,this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(te.RoomEvent.Connected,()=>{var n,r;this.connectionState=te.ConnectionState.Connected,this.emit("connection.connected"),this.rpcManager.setRoom(this.room),(r=(n=this.currentSession)==null?void 0:n.activeModalities)!=null&&r.includes("voice")&&setTimeout(async()=>{var s;try{(s=this.room)!=null&&s.localParticipant&&(this.room.localParticipant.isMicrophoneEnabled?this.emit("track.unmuted",{source:"microphone",enabled:!0}):(await this.room.localParticipant.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0})))}catch(o){console.warn("VoxketClient: Failed to enable microphone after room connection:",o)}},1e3),this.textStreamHandlersRegistered||this.setupTextStreamHandlers()}),this.room.on(te.RoomEvent.Disconnected,n=>{this.connectionState=te.ConnectionState.Disconnected,this.textStreamHandlersRegistered=!1,this.emit("connection.disconnected",n==null?void 0:n.toString())}),this.room.on(te.RoomEvent.ConnectionStateChanged,n=>{this.connectionState=n,n===te.ConnectionState.Connecting&&this.emit("connection.connecting")}),this.room.on(te.RoomEvent.ParticipantConnected,n=>{const r={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.joined",r)}),this.room.on(te.RoomEvent.ParticipantDisconnected,n=>{const r={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.left",r)}))}setupTextStreamHandlers(){if(this.room){try{this.room.registerTextStreamHandler("lk.chat",async(n,r)=>{try{const s=await n.readAll(),o={id:`msg_${Date.now()}_${r.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:s,timestamp:new Date,sender:{id:r.identity||"user",name:r.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.emit("chat.message.received",o)}catch(s){console.error("VoxketClient: Failed to process lk.chat message:",s)}})}catch(n){console.warn("VoxketClient: lk.chat handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("lk.transcription",async(n,r)=>{var s,o;try{const i=`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`;let a="";const c=((s=this.currentAgentInfo)==null?void 0:s.name)||r.identity||"AI Assistant",l={id:i,content:"",timestamp:new Date,sender:{id:r.identity||"agent",name:c,type:"agent"},metadata:{topic:"lk.transcription",streaming:!0}};this.emit("chat.message.received",l);for await(const h of n){a+=h;const g=this.convertMarkdownToText(a),y={...l,content:g,metadata:{...l.metadata,streaming:!0}};this.emit("chat.message.updated",y)}const u=this.convertMarkdownToText(a),f={...l,content:u,metadata:{...l.metadata,streaming:!1}};this.emit("chat.message.updated",f)}catch(i){console.error("VoxketClient: Failed to process lk.transcription message:",i);try{const a=await n.readAll(),c=((o=this.currentAgentInfo)==null?void 0:o.name)||r.identity||"AI Assistant",l={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:a,timestamp:new Date,sender:{id:r.identity||"agent",name:c,type:"agent"},metadata:{topic:"lk.transcription"}};this.emit("chat.message.received",l)}catch(a){console.error("VoxketClient: Fallback failed for lk.transcription:",a)}}})}catch(n){console.warn("VoxketClient: lk.transcription handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("suggested_response",async n=>{const r=await n.readAll();let s=[];try{s=["tes","hello how are you","algebra make me learn that ","what is the meaning of life"]}catch(o){console.warn("VoxketClient: Failed to parse suggested_response:",o,r)}this.emit("suggested.response",s)})}catch(n){console.warn("VoxketClient: suggested_response handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("agent_state_changed",async(n,r)=>{const s=await n.readAll();let o={};try{o=typeof s=="string"?JSON.parse(s.replace(/'/g,'"')):s}catch(i){console.warn("VoxketClient: Failed to parse agent_state_changed:",i,s)}o.new_state==="speaking"?this.emit("agent.speaking",o):o.new_state==="thinking"&&this.emit("agent.thinking",o)})}catch(n){console.warn("VoxketClient: conversation_item_added handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("images",async(n,r)=>{try{const s=await n.readAll()}catch(s){console.error("VoxketClient: Error processing images stream:",s)}})}catch(n){console.warn("VoxketClient: images handler already registered, skipping:",n)}try{this.room.registerByteStreamHandler("images",async(n,r)=>{var s,o;try{const i=n.info,a={id:`img_${Date.now()}_${r.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`�️ ${i.name||"Image"}`,sender:{id:r.identity||"agent",name:r.identity||"Agent",type:r.identity===((o=(s=this.room)==null?void 0:s.localParticipant)==null?void 0:o.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:i.name,fileSize:i.size,mimeType:i.mimeType,streamId:i.id,downloading:!0}};this.emit("chat.message.received",a),n.onProgress&&(n.onProgress=h=>{const g={...a,metadata:{...a.metadata,downloadProgress:h||0}};this.emit("chat.message.updated",g)});const c=[];for await(const h of n)c.push(h);const l=new Blob(c,{type:i.mimeType||"application/octet-stream"}),u=URL.createObjectURL(l),f={...a,metadata:{...a.metadata,downloading:!1,downloadProgress:1,downloadUrl:u,blob:l}};this.emit("chat.message.updated",f)}catch(i){console.error("VoxketClient: Error processing image attachment:",i)}})}catch(n){console.warn("VoxketClient: image handler already registered, skipping:",n)}this.textStreamHandlersRegistered=!0}}async fetchConnectionDetails(n,r,s){const o=n||this.config.agentId||"default-agent",i=r||this.config.participantName||"User",a=s||this.config.modalities||["voice"];try{const c={agent_id:o,participant_name:i,participant_metadata:{user_id:""},modality:a[0]},l=await fetch(`${this.config.baseUrl}/api/live/agent/session`,{method:"POST",headers:{accept:"application/json","X-APP-ID":this.config.appId,"X-APP-SECRET":this.config.appSecret,"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){let h=`HTTP ${l.status}: Failed to fetch connection details`;try{const g=await l.json();g&&(g.error?h=`API Error: ${g.error}`:g.detail?h=`API Error: ${g.detail}`:g.message&&(h=`API Error: ${g.message}`))}catch{try{const y=await l.text();y&&(h=`API Error: ${y}`)}catch{}}throw new Error(h)}const u=await l.json();let f;return u.agent_info&&(f={id:u.agent_info.id||o,name:u.agent_info.name||"AI Assistant",avatar:u.agent_info.avatar,capabilities:u.agent_info.capabilities||["voice_interaction","text_chat"],metadata:u.agent_info.metadata||{}},this.currentAgentInfo=f),{serverUrl:u.wss_url,participantToken:u.token,voxketSessionId:u.session_id,agentInfo:f}}catch(c){console.error("VoxketClient: fetchConnectionDetails failed:",c);const l=new ue(`Failed to fetch connection details: ${c instanceof Error?c.message:"Unknown error"}`,"CONNECTION_FAILED",c);throw this.emit("connection.error",l),l}}async connect(n,r,s){var o;try{this.emit("connection.connecting");const i=await this.fetchConnectionDetails(n,r,s);return await((o=this.room)==null?void 0:o.connect(i.serverUrl,i.participantToken)),this.isConnected=!0,i}catch(i){console.error("VoxketClient: Connection failed:",i);const a=new ue(`Failed to connect to Voxket services: ${i instanceof Error?i.message:"Unknown error"}`,"CONNECTION_FAILED",i);throw this.emit("connection.error",a),a}}async disconnect(){var n;try{await((n=this.room)==null?void 0:n.disconnect()),this.isConnected=!1,this.currentSession=null,this.currentAgentInfo=null,this.textStreamHandlersRegistered=!1,this.clearChatMessages(),this.room=new te.Room,this.setupRoomEventListeners()}catch(r){const s=new ue("Failed to disconnect properly","NETWORK_ERROR",r);throw this.emit("connection.error",s),s}}async createSession(n){var r,s;try{const o=await this.connect(n.agentId,n.participantName,n.modalities),i={id:o.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:o.agentInfo||this.currentAgentInfo};if(this.currentSession=i,this.emit("session.created",i),(r=n.modalities)!=null&&r.includes("voice"))try{await new Promise(a=>setTimeout(a,500)),(s=this.room)!=null&&s.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(a){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",a)}return setTimeout(()=>{this.currentSession&&(this.currentSession.state="active",this.emit("session.state.changed","active",this.currentSession.state))},1e3),i}catch(o){throw console.error("VoxketClient: Failed to create session:",o),o instanceof ue?o:o instanceof TypeError&&o.message.includes("fetch")?new ue("Network connection failed","CONNECTION_FAILED",o):o instanceof Error&&o.message.includes("Failed to fetch connection details")?new ue(`API connection failed: ${o.message}`,"CONNECTION_FAILED",o):new ue(`Failed to create session: ${o instanceof Error?o.message:"Unknown error"}`,"SESSION_NOT_FOUND",o)}}async startSession(n,r){const s={agentId:n||this.config.agentId||"default-agent",participantName:(r==null?void 0:r.participantName)||this.config.participantName||"User",modalities:(r==null?void 0:r.modalities)||this.config.modalities||["voice","chat"],metadata:r==null?void 0:r.metadata};return this.createSession(s)}async endSession(){var n,r;if(!this.currentSession)return null;try{const s={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.room)==null?void 0:r.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]};return this.currentSession.endedAt=new Date,this.currentSession.state="disconnected",this.emit("session.ended",this.currentSession,s),await this.disconnect(),s}catch(s){throw new ue("Failed to end session","SESSION_NOT_FOUND",s)}}getCurrentSession(){return this.currentSession}getCurrentAgentInfo(){return this.currentAgentInfo}getChatMessages(){return[...this.chatMessages]}addChatMessage(n){this.chatMessages.some(s=>s.id===n.id)||this.chatMessages.push(n)}updateChatMessage(n){const r=this.chatMessages.findIndex(s=>s.id===n.id);r!==-1&&(this.chatMessages[r]=n)}clearChatMessages(){this.chatMessages=[],this.dismissCurrentInteraction(),this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays(),this.emit("chat.history.cleared")}renderUI(n={}){var c,l,u;const r=this.resolveTarget(n.target||"body"),s=this.getTargetKey(r),o=this.renderedComponents.get(s);o&&o.target===r||this.removeUI(r);const i=(o==null?void 0:o.root)||Q8(r),a={agentId:n.agentId||this.config.agentId||"default-agent",participantName:n.participantName||this.config.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:n.className,theme:typeof n.theme=="string"?n.theme:void 0,modalities:n.modality||this.config.modalities||["voice"],suportsChatInput:((c=n.modality)==null?void 0:c.includes("chat"))!==!1,suportsVideoInput:((l=n.modality)==null?void 0:l.includes("video"))===!0,suportsScreenShare:((u=n.modality)==null?void 0:u.includes("screen_share"))===!0,autoStart:n.autoStart,displayType:n.displayType||"widget",popupPosition:n.popupPosition||"bottom-right",popupTriggerText:n.popupTriggerText||"Open Chat",width:n.width,height:n.height,onDisplayTypeChange:n.onDisplayTypeChange,prompts:n.prompts,statusMessage:n.statusMessage,welcomeTitle:n.welcomeTitle,welcomeSubTitle:n.welcomeSubTitle,loadingText:n.loadingText,voxketClient:this};if(!i||typeof i.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{i.render(m.createElement(Qh,{config:this.config,autoConnect:n.autoStart||!1,children:m.createElement(em,a)}))}catch(f){throw console.error("Error rendering Voxket widget:",f),new Error(`Failed to render Voxket widget: ${f instanceof Error?f.message:"Unknown error"}`)}this.renderedComponents.set(s,{root:i,target:r})}removeUI(n){const r=n?this.resolveTarget(n):null;if(r){const s=this.getTargetKey(r),o=this.renderedComponents.get(s);if(o){try{o.root&&typeof o.root.unmount=="function"&&o.root.unmount()}catch(a){console.warn("Error unmounting React component:",a);try{r&&(r.innerHTML="")}catch(c){console.warn("Error during manual cleanup:",c)}}this.renderedComponents.delete(s),r.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(a=>{try{a.remove()}catch(c){console.warn("Failed to remove element:",c)}}),r===document.body&&r.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(c=>{if(c.classList.contains("bg-black")&&c.classList.contains("backdrop-blur-sm"))try{c.remove()}catch(l){console.warn("Failed to remove fixed element:",l)}})}}}removeAllUI(){var n,r;for(const[s,o]of this.renderedComponents)(r=(n=o.root).unmount)==null||r.call(n);this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(r=>{if(r.classList.contains("bg-black")&&(r.classList.contains("backdrop-blur-sm")||r.classList.contains("bg-opacity-30")))try{r.remove()}catch(s){console.warn("Failed to remove overlay:",s)}})}resolveTarget(n){if(typeof n=="string"){const r=document.querySelector(n);if(!r)throw new Error(`Target element not found: ${n}`);return r}return n}getTargetKey(n){return n.id?n.id:n.className?n.tagName+"_"+n.className.replace(/\s+/g,"_"):n.tagName+"_"+n.outerHTML.length%1e3}async sendMessage(n,r){var s;if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new ue("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new ue("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new ue("No local participant","CONNECTION_FAILED");this.dismissCurrentInteraction();try{const o={id:`msg_${Date.now()}`,content:n,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:r||{}},i=await((s=this.room)==null?void 0:s.localParticipant.sendText(n,{topic:"lk.chat",destinationIdentities:[]}));this.emit("chat.message.sent",o)}catch(o){throw console.error("VoxketClient: Failed to send chat message:",o),new ue("Failed to send message","NETWORK_ERROR",o)}}async sendChatMessage(n,r){return this.sendMessage(n,r)}async sendAttachments(n,r){if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new ue("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new ue("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new ue("No local participant","CONNECTION_FAILED");if(!n||n.length===0)throw new ue("No files provided","INVALID_PARAMETER");this.dismissCurrentInteraction();const s=n.filter(o=>o.type.startsWith("image/"));if(s.length===0)throw new ue("Only image files are allowed","INVALID_PARAMETER");s.length!==n.length&&console.warn("VoxketClient: Some non-image files were filtered out");try{const o=s.map(async(i,a)=>{const l={id:`att_${Date.now()}_${a}`,content:`📎 ${i.name}`,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:{...r,type:"attachment",fileName:i.name,fileSize:i.size,mimeType:i.type,uploading:!0}};this.emit("chat.message.sent",l);const u=await this.room.localParticipant.sendFile(i,{mimeType:i.type,topic:"images",onProgress:h=>{const g={...l,metadata:{...l.metadata,uploadProgress:h}};this.emit("chat.message.updated",g)}});try{const h=new FileReader,g=new Promise((x,w)=>{h.onload=()=>{typeof h.result=="string"?x(h.result):w(new Error("Failed to convert to base64"))},h.onerror=w});h.readAsDataURL(i);const p={type:"image",data:await g,filename:i.name,mimeType:i.type,size:i.size};await this.room.localParticipant.sendText(JSON.stringify(p),{topic:"images",destinationIdentities:[]})}catch(h){console.warn("VoxketClient: Failed to send image data to agent:",h);try{const g=`I've shared an image: ${i.name}`;await this.room.localParticipant.sendText(g,{topic:"lk.chat",destinationIdentities:[]})}catch(g){console.warn("VoxketClient: Failed to send image notification to agent:",g)}}const f={...l,metadata:{...l.metadata,uploading:!1,uploadProgress:1,streamId:u.id}};return this.emit("chat.message.updated",f),u});await Promise.all(o)}catch(o){throw console.error("VoxketClient: Failed to send attachments:",o),new ue("Failed to send attachments","NETWORK_ERROR",o)}}async sendAttachment(n,r){return this.sendAttachments([n],r)}toggleMicrophone(n){return this.setMicrophoneEnabled(n!==!1)}async setMicrophoneEnabled(n){var r,s;try{const o=(r=this.room)==null?void 0:r.localParticipant.isMicrophoneEnabled,i=n??!o;await((s=this.room)==null?void 0:s.localParticipant.setMicrophoneEnabled(i)),i?this.emit("track.unmuted",{source:"microphone",enabled:!0}):this.emit("track.muted",{source:"microphone",enabled:!1})}catch(o){throw console.error("VoxketClient: Failed to toggle microphone:",o),new ue("Failed to toggle microphone","PERMISSION_DENIED",o)}}toggleCamera(n){return this.setCameraEnabled(n!==!1)}async setCameraEnabled(n){var r,s;try{const o=(r=this.room)==null?void 0:r.localParticipant.isCameraEnabled,i=n??!o;await((s=this.room)==null?void 0:s.localParticipant.setCameraEnabled(i)),i?this.emit("track.unmuted",{source:"camera",enabled:!0}):this.emit("track.muted",{source:"camera",enabled:!1})}catch(o){throw console.error("VoxketClient: Failed to toggle camera:",o),new ue("Failed to toggle camera","PERMISSION_DENIED",o)}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!0))}catch(r){throw new ue("Failed to start screen share","PERMISSION_DENIED",r)}}async stopScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!1))}catch(r){throw new ue("Failed to stop screen share","PERMISSION_DENIED",r)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="audioinput")}catch(n){throw new ue("Failed to get audio input devices","DEVICE_ERROR",n)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch(n){throw new ue("Failed to get video input devices","DEVICE_ERROR",n)}}async setAudioInputDevice(n){var r;try{if(!((r=this.room)!=null&&r.localParticipant))throw new Error("Not connected to room")}catch(s){throw new ue("Failed to set audio input device","DEVICE_ERROR",s)}}async setVideoInputDevice(n){var r;try{if(!((r=this.room)!=null&&r.localParticipant))throw new Error("Not connected to room")}catch(s){throw new ue("Failed to set video input device","DEVICE_ERROR",s)}}getLocalParticipant(){var n;return((n=this.room)==null?void 0:n.localParticipant)??null}getRemoteParticipants(){var n;return Array.from(((n=this.room)==null?void 0:n.remoteParticipants.values())??[])}getPublishPermissions(){const n=this.getLocalParticipant();if(!n)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const r=n.permissions;if(!r)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const s=o=>!!r.canPublish&&(r.canPublishSources.length===0||r.canPublishSources.includes(o));return{camera:s(1),microphone:s(2),screenShare:s(3),data:r.canPublishData??!1}}canPublishSource(n){return this.getPublishPermissions()[n]}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===te.ConnectionState.Connected}getMicrophoneTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,r]of n.trackPublications)if(r.source===te.Track.Source.Microphone)return r.track;return null}getCameraTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,r]of n.trackPublications)if(r.source===te.Track.Source.Camera)return r.track;return null}getScreenShareTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,r]of n.trackPublications)if(r.source===te.Track.Source.ScreenShare)return r.track;return null}get isMicrophoneEnabled(){const n=this.getMicrophoneTrack();return n?!n.isMuted:!1}get isCameraEnabled(){const n=this.getCameraTrack();return n?!n.isMuted:!1}get isScreenShareEnabled(){const n=this.getScreenShareTrack();return n?!n.isMuted:!1}registerPlugin(n){this.pluginManager.register(n)}getPluginManager(){return this.pluginManager}getParticipants(){if(!this.room)return[];const n=[];return this.room.localParticipant&&n.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(r=>{n.push({id:r.identity,name:r.name||r.identity,isLocal:!1})}),n}getSessionMetrics(){var n,r;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.room)==null?void 0:r.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]}:null}updateConfig(n){this.config={...this.config,...n}}async startRecording(){var n;try{this.emit("recording.started",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(r){throw new ue("Failed to start recording","RECORDING_ERROR",r)}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(r){throw new ue("Failed to stop recording","RECORDING_ERROR",r)}}async registerFrontendRPC(n,r,s="embedded"){return this.rpcManager.registerFrontendRPC(n,r,s)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}registerEventListener(n,r){return this.on(n,r)}registerEventEmitter(n,r){if(!this.room)throw new Error("Room not available");try{this.room.registerTextStreamHandler(n,async s=>{try{const o=await s.readAll();r(o)}catch(o){console.error(`Error processing event for topic '${n}':`,o)}})}catch(s){console.warn(`VoxketClient: Handler for topic '${n}' may already be registered:`,s)}}convertMarkdownToText(n){if(!n)return"";let r=n;return r=r.replace(/\*\*(.*?)\*\*/g,"$1"),r=r.replace(/__(.*?)__/g,"$1"),r=r.replace(/\*(.*?)\*/g,"$1"),r=r.replace(/_(.*?)_/g,"$1"),r=r.replace(/~~(.*?)~~/g,"$1"),r=r.replace(/`([^`]+)`/g,"$1"),r=r.replace(/```[\s\S]*?```/g,""),r=r.replace(/^#{1,6}\s+/gm,""),r=r.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),r.trim()}}const e6=ae.create(N8),t6=ae.create(B8),n6=ae.create(U8),r6=ae.create(K8);function s6({onClick:e,text:t="Open Chat",position:n="bottom-right",theme:r}){const s={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},o=Ie(r);return d.jsx(ae.button,{onClick:e,className:`fixed ${s[n]} z-50 px-4 py-2 rounded-full shadow-lg ${o.popupTrigger} transition-all duration-200 hover:scale-105`,initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},exit:{scale:0,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},children:t})}function ad({children:e,theme:t,displayType:n="widget",onClose:r,popupPosition:s="bottom-right",onExpand:o}){const i=Ie(t);if(n==="fullscreen")return d.jsx("div",{className:"fixed inset-0 z-50 bg-black bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",children:d.jsxs("div",{className:"w-full h-full max-w-6xl max-h-[90vh] rounded-2xl relative bg-transparent",children:[r&&d.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),r()},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:d.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:d.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"})})}),d.jsxs("div",{id:"voice-card",className:`${i.card} w-full h-full flex flex-col rounded-xl shadow-2xl`,style:{minHeight:"600px"},children:[d.jsx("div",{className:i.cardTopGradient}),d.jsx("div",{className:i.cardPurpleBlur}),d.jsx("div",{className:i.cardPinkBlur}),d.jsx("div",{className:" flex flex-col h-full",children:e}),d.jsx("div",{className:i.cardPulse1}),d.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(n==="popup"){const a={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"};return d.jsx("div",{className:"fixed rounded-2xl inset-0 z-50 pointer-events-none",children:d.jsxs("div",{className:`fixed rounded-2xl ${a[s]} pointer-events-auto`,children:[r&&d.jsx("button",{onClick:r,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:"×"}),d.jsxs("div",{id:"voice-card",className:`${i.card} rounded-2xl flex flex-col`,style:{width:"300px",height:"450px"},children:[d.jsx("div",{className:i.cardPurpleBlur}),d.jsx("div",{className:i.cardPinkBlur}),d.jsx("div",{className:" flex flex-col h-full",children:e}),d.jsx("div",{className:i.cardPulse1}),d.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return d.jsxs("div",{id:"voice-card",className:`${i.card}`,children:[o&&d.jsx("button",{onClick:o,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:d.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:d.jsx("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})})}),d.jsx("div",{className:i.cardTopGradient}),d.jsx("div",{className:i.cardPurpleBlur}),d.jsx("div",{className:i.cardPinkBlur}),e,d.jsx("div",{className:i.cardPulse1}),d.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})}function em(e){if(typeof window>"u")return null;console.log("🎯 Widget component rendering with props:",{displayType:e.displayType,popupPosition:e.popupPosition,theme:e.theme});const{agentId:t,participantName:n,baseUrl:r,appSecret:s,appId:o,prompts:i,statusMessage:a,welcomeTitle:c,welcomeSubTitle:l,className:u,width:f,height:h,loadingText:g,suportsChatInput:y=!0,suportsVideoInput:p=!0,suportsScreenShare:x=!0,theme:w="vox",onSessionStart:v,onSessionEnd:S,enableSessionLogging:C=!0,onSessionLogsUpdate:E,onSessionMetricsUpdate:T,modalities:k=["voice"],displayType:j="widget",popupPosition:$="bottom-right",popupTriggerText:b="Open Chat",onPopupToggle:I,voxketClient:L,onDisplayTypeChange:Z}=e,[K,q]=m.useState(()=>L?!!L.getCurrentSession():!1),[G,z]=m.useState(!1),[P,Y]=m.useState(t||""),[R,V]=m.useState(n||"User"),[W,M]=m.useState(()=>L?L.getCurrentSession():null),[_,H]=m.useState(()=>{var ie,Mt,et;if(L){const be=L.getCurrentSession();if((ie=be==null?void 0:be.activeModalities)!=null&&ie.includes("chat"))return"chat";if((Mt=be==null?void 0:be.activeModalities)!=null&&Mt.includes("voice"))return"voice";if((et=be==null?void 0:be.activeModalities)!=null&&et.includes("video"))return"video"}return"welcome"}),[B,N]=m.useState(!1);m.useEffect(()=>{console.log("🎯 Widget displayType prop changed to:",j)},[j]),m.useEffect(()=>{console.log("📊 Session state changed:",{currentMode:_,sessionStarted:K,loading:G,currentSession:W==null?void 0:W.id,isPopupOpen:B})},[_,K,G,W,B]);const F=m.useMemo(()=>{if(L)return console.log("🔄 Using passed VoxketClient to preserve session state"),L;console.log("🆕 Creating new VoxketClient instance");const ie={appId:o,appSecret:s,baseUrl:r,agentId:P,participantName:R||"User",modalities:k};return new Ar(ie)},[L,o,s,r,P,R,k]),U=k,O=m.useMemo(()=>F.getRoom()||new te.Room,[F]),J={suportsChatInput:y,suportsVideoInput:p,suportsScreenShare:x},{sessionMetrics:X,sessionLogs:se,logEvent:me}=qh({room:O,onSessionStart:v,onSessionEnd:S,enableConsoleLogging:C,enableLocalStorage:C,voxketSessionId:W==null?void 0:W.id});m.useEffect(()=>{E&&E(se)},[se,E]),m.useEffect(()=>{T&&X&&T(X)},[X,T]),m.useEffect(()=>{const ie=et=>{console.log("🔴 Room disconnected:",et),z(!1),q(!1),M(null),H("welcome")},Mt=et=>{console.log("📹 Media devices error:",et),Dr({title:"Allow access to your microphone/camera",description:`${et.name}: ${et.message}`})};return O.on(te.RoomEvent.MediaDevicesError,Mt),O.on(te.RoomEvent.Disconnected,ie),()=>{O.off(te.RoomEvent.Disconnected,ie),O.off(te.RoomEvent.MediaDevicesError,Mt)}},[O]);const $e=async()=>{try{console.log("🎤 Starting voice session...",{agentId:P,participantName:R}),console.log("🎤 Pre-start state:",{currentMode:_,sessionStarted:K,loading:G}),z(!0),q(!0),H("voice"),console.log("🎤 State after mode change:",{currentMode:"voice",sessionStarted:!0,loading:!0}),me("USER_STARTED_VOICE_SESSION",{agentId:P,participantName:R});const ie=await F.startSession(P,{participantName:R||"User",modalities:["voice",...p?["video"]:[]]});console.log("✅ Voice session started successfully:",ie.id),M(ie),z(!1),v&&v(ie.id)}catch(ie){console.error("❌ Failed to start voice session:",ie),Dr({title:"Failed to start voice session",description:ie instanceof Error?ie.message:"Unknown error occurred"}),z(!1),q(!1),H("welcome")}},at=async()=>{try{z(!0),q(!0),H("chat"),me("USER_STARTED_CHAT_SESSION",{agentId:P,participantName:R});const ie=await F.startSession(P,{participantName:R||"User",modalities:["chat"]});M(ie),z(!1),v&&v(ie.id)}catch(ie){console.error("Failed to start chat session:",ie),Dr({title:"Failed to start chat session",description:ie instanceof Error?ie.message:"Unknown error occurred"}),z(!1),q(!1),H("welcome")}},Ut=async()=>{try{console.log("📺 Starting video session...",{agentId:P,participantName:R}),console.log("📺 Pre-start state:",{currentMode:_,sessionStarted:K,loading:G}),z(!0),q(!0),H("video"),console.log("📺 State after mode change:",{currentMode:"video",sessionStarted:!0,loading:!0}),me("USER_STARTED_VIDEO_SESSION",{agentId:P,participantName:R});const ie=await F.startSession(P,{participantName:R||"User",modalities:["video","voice"]});console.log("✅ Video session started successfully:",ie.id),M(ie),z(!1),v&&v(ie.id)}catch(ie){console.error("❌ Failed to start video session:",ie),Dr({title:"Failed to start video session",description:ie instanceof Error?ie.message:"Unknown error occurred"}),z(!1),q(!1),H("welcome")}},Wt=()=>{H("welcome"),Z&&Z(e.displayType||"widget"),W&&K&&(q(!1),M(null),F.disconnect()),j==="popup"&&!B&&N(!0)},ct=()=>{const ie=!B;N(ie),I&&I(ie),!ie&&!(W&&K)&&(H("welcome"),q(!1),M(null))},ym=()=>{console.log("🔄 Closing fullscreen, switching to widget display type"),e.onDisplayTypeChange?e.onDisplayTypeChange("widget"):console.warn("⚠️ No onDisplayTypeChange callback provided")},xm=()=>{e.onDisplayTypeChange&&e.onDisplayTypeChange("fullscreen")};m.useEffect(()=>{var ie,Mt,et;if(L&&F){console.log("🔄 Syncing widget state with existing client session state");const be=F.getCurrentSession(),bm=F.connected;console.log("🔍 Existing session state:",{hasSession:!!be,sessionId:be==null?void 0:be.id,isConnected:bm,activeModalities:be==null?void 0:be.activeModalities}),be&&(console.log("✅ Restoring session state from existing client"),M(be),q(!0),z(!1),(ie=be.activeModalities)!=null&&ie.includes("chat")?H("chat"):(Mt=be.activeModalities)!=null&&Mt.includes("voice")?H("voice"):(et=be.activeModalities)!=null&&et.includes("video")&&H("video"))}},[L,F]),m.useEffect(()=>()=>{console.log("🧹 Cleaning up widget component"),L?console.log("🔄 Widget cleanup: preserving passed client instance"):(console.log("🧹 Widget cleanup: disconnecting self-created client"),F.disconnect())},[F,L]);let Bs="w-96",Hs="h-[25rem]",zs={};if(f&&(f.startsWith("w-")?Bs=f:(zs.width=f,Bs="")),h&&(h.startsWith("h-")?Hs=h:(zs.height=h,Hs="")),j==="popup"&&!B)return console.log("🟡 Showing popup trigger button"),d.jsx(s6,{onClick:ct,text:b,position:$,theme:w});console.log("🟢 Rendering widget content, displayType:",j,"isPopupOpen:",B,"currentMode:",_,"sessionStarted:",K,"loading:",G);let Us=`voxket-widget-root theme-${w}`,jr={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};j==="widget"?(Us+=` flex items-center justify-center min-h-fit ${Bs} ${Hs} ${u}`,jr={...jr,...zs}):(Us=`${u||""}`,jr={});const Ia=d.jsx(d.Fragment,{children:d.jsxs(Cn,{mode:"wait",children:[_==="welcome"&&!G&&d.jsx(r6,{agentId:P,participantName:R||"",onAgentIdChange:Y,onParticipantNameChange:V,onStartCall:$e,onStartChat:at,onStartVideo:Ut,disabled:K||G,prompts:i,statusMessage:a,title:c,subTitle:l,theme:w,modalities:U,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),_==="voice"&&d.jsxs(Ee.RoomContext.Provider,{value:O,children:[d.jsx(Ee.RoomAudioRenderer,{}),d.jsx(Ee.StartAudio,{label:"Start Audio"}),d.jsx(e6,{loadingText:g,participantName:R||"User",capabilities:J,sessionStarted:K,disabled:!K,theme:w,client:F,displayType:j,onBack:j==="popup"?ct:Wt,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"session-view")]}),_==="chat"&&d.jsx(t6,{client:F,theme:w,displayType:j,onBack:j==="popup"?ct:Wt,onEndChat:Wt,disabled:!K,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),_==="video"&&d.jsxs(Ee.RoomContext.Provider,{value:O,children:[d.jsx(Ee.RoomAudioRenderer,{}),d.jsx(Ee.StartAudio,{label:"Start Audio"}),d.jsx(n6,{client:F,theme:w,displayType:j,onBack:j==="popup"?ct:Wt,onEndCall:Wt,disabled:!K,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-view")]})]})});return j==="fullscreen"||j==="popup"?(console.log("📱 Rendering fullscreen/popup mode, displayType:",j),d.jsx(ad,{theme:w,displayType:j,popupPosition:$,onClose:j==="fullscreen"?ym:ct,children:Ia})):(console.log("📦 Rendering widget mode"),d.jsx("div",{className:Us,style:jr,children:d.jsx(ad,{theme:w,displayType:j,popupPosition:$,onExpand:xm,children:Ia})}))}class tm extends m.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("VoxketWidget Error:",t,n)}render(){if(this.state.hasError){if(this.props.fallback){const t=this.props.fallback;return m.createElement(t,{error:this.state.error})}return m.createElement("div",{style:{padding:"20px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"}},"VoxketWidget encountered an error. Please check the console for details.")}return this.props.children}}function o6({logs:e,onClear:t,onExport:n}){const[r,s]=A.useState(!1),[o,i]=A.useState(""),a=e.filter(c=>!o||c.event.toLowerCase().includes(o.toLowerCase()));return r?d.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:d.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[d.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[d.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"text",placeholder:"Filter events...",value:o,onChange:c=>i(c.target.value),className:"px-3 py-1 border rounded text-sm"}),d.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),d.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),d.jsx("button",{onClick:()=>s(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),d.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?d.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):d.jsx("div",{className:"space-y-2",children:a.map((c,l)=>d.jsxs("div",{className:"border rounded p-3 text-sm",children:[d.jsxs("div",{className:"flex items-center justify-between mb-1",children:[d.jsx("span",{className:"font-semibold text-blue-600",children:c.event}),d.jsx("span",{className:"text-gray-500 text-xs",children:new Date(c.timestamp).toLocaleTimeString()})]}),c.sessionId&&d.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",c.sessionId]}),c.data&&d.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:d.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(c.data,null,2)})})]},l))})})]})}):d.jsxs("button",{onClick:()=>s(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",e.length,")"]})}function i6({metrics:e}){return e?d.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[d.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),d.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[d.jsxs("div",{children:[d.jsx("span",{className:"text-gray-600",children:"Session ID:"}),d.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),d.jsxs("div",{children:[d.jsx("span",{className:"text-gray-600",children:"Start Time:"}),d.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),d.jsxs("div",{children:[d.jsx("span",{className:"text-gray-600",children:"Messages:"}),d.jsx("div",{children:e.totalMessages})]}),d.jsxs("div",{children:[d.jsx("span",{className:"text-gray-600",children:"Participants:"}),d.jsx("div",{children:e.participantCount})]}),d.jsxs("div",{children:[d.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),d.jsx("div",{children:e.connectionIssues})]}),d.jsxs("div",{children:[d.jsx("span",{className:"text-gray-600",children:"Duration:"}),d.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function cn(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:r,endSession:s}=bt(),o=A.useCallback(async(a,c)=>await r(a,c),[r]),i=A.useCallback(async()=>await s(),[s]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:o,stop:i}}function nm(){const{sessionMetrics:e,currentSession:t}=bt();return{metrics:e,sessionId:t==null?void 0:t.id,duration:e==null?void 0:e.duration,participantCount:e==null?void 0:e.participantCount,messageCount:e==null?void 0:e.messageCount,audioQuality:e==null?void 0:e.audioQuality,networkStats:e==null?void 0:e.networkStats}}function rm(){const{setMicrophoneEnabled:e,client:t}=bt(),[n,r]=A.useState(!1),[s,o]=A.useState(!1),i=A.useCallback(async()=>{if(!s){o(!0);try{const l=!n;await e(l),r(l)}catch(l){console.error("Failed to toggle microphone:",l)}finally{o(!1)}}},[n,s,e]),a=A.useCallback(async()=>{if(!(n||s)){o(!0);try{await e(!0),r(!0)}catch(l){console.error("Failed to enable microphone:",l)}finally{o(!1)}}},[n,s,e]),c=A.useCallback(async()=>{if(!(!n||s)){o(!0);try{await e(!1),r(!1)}catch(l){console.error("Failed to disable microphone:",l)}finally{o(!1)}}},[n,s,e]);return{isEnabled:n,isLoading:s,toggle:i,enable:a,disable:c}}function sm(){const{setCameraEnabled:e}=bt(),[t,n]=A.useState(!1),[r,s]=A.useState(!1),o=A.useCallback(async()=>{if(!r){s(!0);try{const c=!t;await e(c),n(c)}catch(c){console.error("Failed to toggle camera:",c)}finally{s(!1)}}},[t,r,e]),i=A.useCallback(async()=>{if(!(t||r)){s(!0);try{await e(!0),n(!0)}catch(c){console.error("Failed to enable camera:",c)}finally{s(!1)}}},[t,r,e]),a=A.useCallback(async()=>{if(!(!t||r)){s(!0);try{await e(!1),n(!1)}catch(c){console.error("Failed to disable camera:",c)}finally{s(!1)}}},[t,r,e]);return{isEnabled:t,isLoading:r,toggle:o,enable:i,disable:a}}function om(){const{startScreenShare:e,stopScreenShare:t}=bt(),[n,r]=A.useState(!1),[s,o]=A.useState(!1),i=A.useCallback(async()=>{if(!(n||s)){o(!0);try{await e(),r(!0)}catch(l){console.error("Failed to start screen share:",l)}finally{o(!1)}}},[n,s,e]),a=A.useCallback(async()=>{if(!(!n||s)){o(!0);try{await t(),r(!1)}catch(l){console.error("Failed to stop screen share:",l)}finally{o(!1)}}},[n,s,t]),c=A.useCallback(async()=>{n?await a():await i()},[n,i,a]);return{isSharing:n,isLoading:s,start:i,stop:a,toggle:c}}function a6(){const{client:e}=bt(),[t,n]=A.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),r=A.useMemo(()=>t.tracks.find(p=>p.isLocal),[t.tracks]),s=A.useMemo(()=>t.tracks.filter(p=>!p.isLocal),[t.tracks]),o=A.useCallback(async()=>{try{r!=null&&r.isEnabled?await(e==null?void 0:e.disableCamera()):await(e==null?void 0:e.enableCamera())}catch(p){throw console.error("Failed to toggle camera:",p),p}},[e,r]),i=A.useCallback(async()=>{try{t.tracks.find(x=>x.isScreenShare)?await(e==null?void 0:e.stopScreenShare()):await(e==null?void 0:e.startScreenShare())}catch(p){throw console.error("Failed to toggle screen share:",p),p}},[e,t.tracks]),a=A.useCallback(p=>{n(x=>({...x,layout:p}))},[]),c=A.useCallback(p=>{n(x=>({...x,pinnedTrack:p}))},[]),l=A.useCallback(()=>{n(p=>({...p,pinnedTrack:void 0}))},[]),u=A.useCallback(async()=>{try{await(e==null?void 0:e.startRecording()),n(p=>({...p,isRecording:!0}))}catch(p){throw console.error("Failed to start recording:",p),p}},[e]),f=A.useCallback(async()=>{try{await(e==null?void 0:e.stopRecording()),n(p=>({...p,isRecording:!1}))}catch(p){throw console.error("Failed to stop recording:",p),p}},[e]),h=A.useCallback(p=>t.tracks.find(x=>x.id===p),[t.tracks]),g=A.useCallback(p=>t.tracks.filter(x=>x.participantId===p),[t.tracks]),y=A.useCallback(p=>p.isEnabled&&t.tracks.includes(p),[t.tracks]);return A.useEffect(()=>{if(!e)return;const p=v=>{n(S=>({...S,tracks:[...S.tracks.filter(C=>C.id!==v.id),v]}))},x=v=>{n(S=>{var C;return{...S,tracks:S.tracks.filter(E=>E.id!==v),pinnedTrack:((C=S.pinnedTrack)==null?void 0:C.id)===v?void 0:S.pinnedTrack}})},w=v=>{n(S=>({...S,tracks:S.tracks.map(C=>C.id===v.id?v:C)}))};return e.on("videoTrackAdded",p),e.on("videoTrackRemoved",x),e.on("videoTrackUpdated",w),()=>{e.off("videoTrackAdded",p),e.off("videoTrackRemoved",x),e.off("videoTrackUpdated",w)}},[e]),{tracks:t.tracks,localTrack:r,remoteTraracks:s,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:o,toggleScreenShare:i,setLayout:a,pinTrack:c,unpinTrack:l,startRecording:u,stopRecording:f,getTrackById:h,getTracksByParticipant:g,isTrackActive:y}}function _s(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=bt(),[r,s]=A.useState(!1),o=A.useCallback(async l=>{if(!(!l.trim()||r||!n)){s(!0);try{await t(l.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{s(!1)}}},[t,r,n]),{userMessages:i,agentMessages:a,allMessages:c}=A.useMemo(()=>{const l=e.filter(f=>f.sender.type==="participant"),u=e.filter(f=>f.sender.type==="agent");return{userMessages:l,agentMessages:u,allMessages:e}},[e]);return{messages:c,userMessages:i,agentMessages:a,messageCount:c.length,isSending:r,canSend:!!n&&!r,send:o}}function c6(){const{send:e,isSending:t,canSend:n}=_s(),[r,s]=A.useState(""),o=A.useCallback(async()=>{if(!(!r.trim()||!n))try{await e(r),s("")}catch(a){throw a}},[r,e,n]),i=A.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),o())},[o]);return{value:r,setValue:s,send:o,handleKeyPress:i,isSending:t,canSend:n&&r.trim().length>0}}function Ma(){const{isConnected:e,isConnecting:t,connectionError:n,connect:r,disconnect:s}=bt(),o=A.useCallback(async()=>{if(!(e||t))try{await r()}catch(a){throw console.error("Failed to connect:",a),a}},[r,e,t]),i=A.useCallback(async()=>{if(e)try{await s()}catch(a){throw console.error("Failed to disconnect:",a),a}},[s,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:o,disconnect:i}}function im(){const{participants:e}=bt();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const am=A.createContext({}),Tr=()=>A.useContext(am);function cm({children:e,...t}){return d.jsx(am.Provider,{value:t,children:e})}function Qr({name:e,children:t,fallback:n,className:r}){return d.jsx("div",{className:`voxket-slot voxket-slot--${e} ${r||""}`,children:t||n})}function lm(e,t={}){return Object.assign(e,t)}function dm({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:r=!0,customControls:s,className:o=""}){const i=cn(),a=rm(),c=sm(),l=om(),u=Tr(),f=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,i.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",o].filter(Boolean).join(" ");return!i.isActive&&!r?d.jsx("div",{className:f,children:d.jsx("div",{className:"voxket-controls-inactive",children:d.jsx("p",{children:"Controls available during active session"})})}):d.jsxs("div",{className:f,children:[r&&d.jsx("div",{className:"voxket-session-actions",children:i.isActive?d.jsx("button",{onClick:i.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):d.jsx(l6,{})}),i.isActive&&d.jsxs("div",{className:"voxket-media-controls",children:[e&&d.jsxs("button",{onClick:a.toggle,disabled:a.isLoading,className:`voxket-button voxket-button--media ${a.isEnabled?"voxket-button--active":""}`,title:a.isEnabled?"Mute microphone":"Unmute microphone",children:[d.jsx("span",{className:"voxket-icon",children:"🎤"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&d.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isEnabled?"voxket-button--active":""}`,title:c.isEnabled?"Stop camera":"Start camera",children:[d.jsx("span",{className:"voxket-icon",children:"📹"}),c.isLoading?"Loading...":c.isEnabled?"Stop Video":"Start Video"]}),n&&d.jsxs("button",{onClick:l.toggle,disabled:l.isLoading,className:`voxket-button voxket-button--media ${l.isSharing?"voxket-button--active":""}`,title:l.isSharing?"Stop screen share":"Start screen share",children:[d.jsx("span",{className:"voxket-icon",children:"🖥️"}),l.isLoading?"Loading...":l.isSharing?"Stop Share":"Share Screen"]})]}),s&&d.jsx("div",{className:"voxket-custom-controls",children:s})]})}function l6(){cn();const[e,t]=A.useState(!1),n=async()=>{t(!0);try{console.log("Start session - agentId needed")}catch(r){console.error("Failed to start session:",r)}finally{t(!1)}};return d.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function Na({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:r=""}){const s=cn(),o=Ma(),i=Tr(),a=["voxket-session-header",`voxket-session-header--${i.variant||"default"}`,`voxket-session-header--${i.size||"md"}`,r].filter(Boolean).join(" ");return d.jsxs("div",{className:a,children:[e&&d.jsxs("div",{className:"voxket-connection-status",children:[d.jsx("div",{className:`voxket-status-indicator ${o.isConnected?"connected":"disconnected"}`}),d.jsx("span",{className:"voxket-status-text",children:o.isConnecting?"Connecting...":o.isConnected?"Connected":"Disconnected"})]}),t&&s.session&&d.jsxs("div",{className:"voxket-session-info",children:[d.jsxs("div",{className:"voxket-session-id",children:["Session: ",s.session.id.slice(-8)]}),d.jsxs("div",{className:"voxket-session-state",children:["State: ",s.state]})]}),n&&s.session&&d.jsxs("div",{className:"voxket-agent-info",children:[d.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",s.session.agentId]}),d.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",s.session.activeModalities.join(", ")]})]}),o.error&&d.jsxs("div",{className:"voxket-error-message",children:["Error: ",o.error.message]})]})}function Ra({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:r=""}){const s=cn(),o=_s(),i=Tr(),a=["voxket-session-content",`voxket-session-content--${i.variant||"default"}`,`voxket-session-content--${i.size||"md"}`,r].filter(Boolean).join(" ");return s.isActive?d.jsx("div",{className:a,children:n||d.jsxs(d.Fragment,{children:[e&&d.jsxs("div",{className:"voxket-chat-container",children:[d.jsxs("div",{className:"voxket-chat-messages",children:[o.messages.map(c=>d.jsxs("div",{className:`voxket-message voxket-message--${c.sender.type}`,children:[d.jsxs("div",{className:"voxket-message-header",children:[d.jsx("span",{className:"voxket-message-sender",children:c.sender.name}),d.jsx("span",{className:"voxket-message-time",children:c.timestamp.toLocaleTimeString()})]}),d.jsx("div",{className:"voxket-message-content",children:c.content})]},c.id)),o.messages.length===0&&d.jsx("div",{className:"voxket-empty-messages",children:d.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),d.jsx(d6,{})]}),t&&d.jsx("div",{className:"voxket-transcriptions",children:d.jsx("div",{className:"voxket-transcription-placeholder",children:d.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):d.jsx("div",{className:a,children:d.jsx("div",{className:"voxket-inactive-state",children:d.jsxs("div",{className:"voxket-inactive-message",children:[d.jsx("h3",{children:"Start a conversation"}),d.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function d6(){const e=_s(),[t,n]=A.useState(""),r=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(o){console.error("Failed to send message:",o)}},s=o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),r())};return d.jsxs("div",{className:"voxket-chat-input",children:[d.jsx("input",{type:"text",value:t,onChange:o=>n(o.target.value),onKeyPress:s,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),d.jsx("button",{onClick:r,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function Va({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:r,className:s=""}){const o=cn(),i=nm(),a=im(),c=Tr(),l=["voxket-session-footer",`voxket-session-footer--${c.variant||"default"}`,`voxket-session-footer--${c.size||"md"}`,s].filter(Boolean).join(" ");return o.isActive?d.jsx("div",{className:l,children:r||d.jsxs(d.Fragment,{children:[n&&d.jsxs("div",{className:"voxket-session-status",children:[d.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),d.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&i.metrics&&d.jsxs("div",{className:"voxket-session-metrics",children:[d.jsxs("div",{className:"voxket-metric",children:[d.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),d.jsx("span",{className:"voxket-metric-value",children:u6(i.duration||0)})]}),d.jsxs("div",{className:"voxket-metric",children:[d.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),d.jsx("span",{className:"voxket-metric-value",children:i.metrics.messageCount})]})]}),t&&d.jsxs("div",{className:"voxket-participants-info",children:[d.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&d.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>d.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):d.jsx("div",{className:l,children:d.jsx("div",{className:"voxket-footer-inactive",children:d.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function u6(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60);return r>0?`${r}:${(n%60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}`:`${n}:${(t%60).toString().padStart(2,"0")}`}function f6({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:r,onSessionEnd:s,variant:o="default",size:i="md",theme:a,className:c="",children:l}){var g;const u=cn(),f=Ma();A.useEffect(()=>{n&&e&&f.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,f.isConnected,u.isActive]),A.useEffect(()=>{var y;(y=u.session)!=null&&y.id&&r&&r(u.session.id)},[(g=u.session)==null?void 0:g.id,r]),A.useEffect(()=>()=>{u.isActive&&s&&u.stop().then(s).catch(console.error)},[]);const h=["voxket-session",`voxket-session--${o}`,`voxket-session--${i}`,u.isActive?"voxket-session--active":"voxket-session--inactive",c].filter(Boolean).join(" ");return d.jsx(cm,{variant:o,size:i,theme:a,className:c,children:d.jsx("div",{className:h,children:l||d.jsxs(d.Fragment,{children:[d.jsx(Qr,{name:"header",fallback:d.jsx(Na,{})}),d.jsx(Qr,{name:"content",fallback:d.jsx(Ra,{})}),d.jsx(Qr,{name:"footer",fallback:d.jsx(Va,{})})]})})})}const um=lm(f6,{Header:Na,Content:Ra,Footer:Va,Controls:dm}),tn={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)"}},bi={...tn,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)"}},vi={...tn,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"}},fm=A.createContext(null),hm=()=>{const e=A.useContext(fm);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function h6({theme:e="default",themes:t={},children:n,cssVariables:r=!0,className:s=""}){const[o,i]=A.useState(()=>{const h={default:tn,dark:bi,enterprise:vi,...t};return typeof e=="string"?h[e]||tn:e}),[a,c]=A.useState(()=>({default:tn,dark:bi,enterprise:vi,...t})),l=h=>{if(typeof h=="string"){const g=a[h];g&&i(g)}else i(h)},u=h=>{c(g=>({...g,[h.name]:h}))};A.useEffect(()=>{if(r&&typeof document<"u"){const h=document.documentElement;Object.entries(mm(o)).forEach(([g,y])=>{h.style.setProperty(`--voxket-${g}`,y)})}},[o,r]);const f={theme:o,setTheme:l,themes:a,registerTheme:u};return d.jsx(fm.Provider,{value:f,children:d.jsx("div",{className:`voxket-theme voxket-theme--${o.name} ${s}`,children:n})})}function mm(e){const t={},n=(r,s="")=>{for(const[o,i]of Object.entries(r)){const a=s?`${s}-${o}`:o;typeof i=="object"&&i!==null&&!Array.isArray(i)?n(i,a):t[a]=String(i)}};return n(e),t}function m6(e=tn,t){return{...e,...t,colors:{...e.colors,...t.colors},typography:{...e.typography,...t.typography},spacing:{...e.spacing,...t.spacing},borderRadius:{...e.borderRadius,...t.borderRadius},shadows:{...e.shadows,...t.shadows}}}function p6(e){var n;const{theme:t}=hm();return((n=t.components)==null?void 0:n[e])||{}}const g6=Pa("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&y6(e),t.enableVoiceActivation&&x6(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&b6(e,t)}});function y6(e,t){e.on("participant.speaking.started",n=>{console.log("Transcription: Started for",n.name)}),e.on("participant.speaking.stopped",n=>{console.log("Transcription: Stopped for",n.name)})}function x6(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function b6(e,t){console.log("Playing audio response:",t.content)}const v6=Pa("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&w6(),t.enableFileUpload&&S6(e),t.enableCustomComponents&&C6(),console.log("Chat modality activated",t)},onDeactivate:async e=>{console.log("Chat modality deactivated")},onMessage:async(e,t)=>{const n=e.config;t.type==="ui_component"?k6(e,t):t.type==="text"&&n.enableRichText&&E6(e,t)}});function w6(e){console.log("Rich text support enabled")}function S6(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function C6(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",A6),t.set("form",T6),t.set("card",j6),t.set("chart",P6)}function k6(e,t){const{componentType:n,props:r}=t.metadata;console.log("Rendering custom component:",n,r),e.emit("chat.component.render",{type:n,props:r,timestamp:new Date})}function E6(e,t){console.log("Processing rich text message:",t.content)}function A6(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function T6(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function j6(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function P6(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function es({track:e,participantName:t,showControls:n=!0,showName:r=!0,showMuteIndicator:s=!0,isPinned:o=!1,className:i="",onClick:a,onPin:c,onUnpin:l}){const u=A.useRef(null),[f,h]=A.useState(!1);A.useEffect(()=>{if(!u.current||!e.isEnabled)return;const x=u.current;return x.srcObject=null,()=>{x.srcObject&&(x.srcObject=null)}},[e]);const g=()=>{a==null||a(e)},y=x=>{x.stopPropagation(),o?l==null||l(e):c==null||c(e)},p=["voxket-video-tile",e.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",e.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",o?"voxket-video-tile--pinned":"",e.isEnabled?"":"voxket-video-tile--disabled",f?"voxket-video-tile--hovered":"",i].filter(Boolean).join(" ");return d.jsxs("div",{className:p,onClick:g,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[d.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&d.jsxs("div",{className:"voxket-video-placeholder",children:[d.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"🖥️":"📹"}),d.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),d.jsxs("div",{className:"voxket-video-overlay",children:[r&&t&&d.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),s&&!e.isEnabled&&d.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),n&&(f||o)&&d.jsxs("div",{className:"voxket-video-controls",children:[d.jsx("button",{className:`voxket-video-control-btn ${o?"voxket-video-control-btn--active":""}`,onClick:y,title:o?"Unpin video":"Pin video",children:"📌"}),e.isScreenShare&&d.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),e.source&&d.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&d.jsx("div",{className:"voxket-video-loading",children:d.jsx("div",{className:"voxket-spinner"})})]})}function M6({tracks:e,layout:t,className:n="",onLayoutChange:r,onTrackClick:s,maxVisibleTracks:o=9,showPagination:i=!0}){const[a,c]=A.useState(0),[l,u]=A.useState(null),f=A.useMemo(()=>{let v=[...e];t.type==="speaker"&&l&&(v=[l,...e.filter(E=>E.id!==l.id)]);const S=a*o,C=S+o;return v.slice(S,C)},[e,t,l,a,o]),h=Math.ceil(e.length/o),g=A.useMemo(()=>{const v=f.length;switch(t.type){case"grid":const S=Math.ceil(Math.sqrt(v)),C=Math.ceil(v/S);return{display:"grid",gridTemplateColumns:`repeat(${S}, 1fr)`,gridTemplateRows:`repeat(${C}, 1fr)`,gap:"8px"};case"speaker":return{display:"flex",flexDirection:"column",gap:"8px"};case"sidebar":return{display:"flex",gap:"8px"};case"gallery":return{display:"flex",flexWrap:"wrap",gap:"8px",justifyContent:"center"};default:return{}}},[t.type,f.length]),y=v=>{u(v)},p=()=>{u(null)},x=v=>{r==null||r({...t,type:v})},w=["voxket-video-grid",`voxket-video-grid--${t.type}`,`voxket-video-grid--${f.length}-tracks`,n].filter(Boolean).join(" ");return e.length===0?d.jsx("div",{className:"voxket-video-grid-empty",children:d.jsxs("div",{className:"voxket-video-grid-empty-content",children:[d.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),d.jsx("p",{children:"No video tracks available"})]})}):d.jsxs("div",{className:w,children:[d.jsxs("div",{className:"voxket-video-grid-controls",children:[d.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(v=>d.jsx("button",{className:`voxket-layout-btn ${t.type===v?"voxket-layout-btn--active":""}`,onClick:()=>x(v),title:`Switch to ${v} layout`,children:N6(v)},v))}),d.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),d.jsx("div",{className:"voxket-video-grid-content",style:g,children:t.type==="speaker"&&l?d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"voxket-video-speaker-main",children:d.jsx(es,{track:l,participantName:`Participant ${l.participantId}`,isPinned:!0,onClick:s,onUnpin:p})}),d.jsx("div",{className:"voxket-video-speaker-sidebar",children:f.filter(v=>v.id!==l.id).map(v=>d.jsx(es,{track:v,participantName:`Participant ${v.participantId}`,showControls:!1,onClick:s,onPin:y},v.id))})]}):f.map(v=>d.jsx(es,{track:v,participantName:`Participant ${v.participantId}`,isPinned:(l==null?void 0:l.id)===v.id,onClick:s,onPin:y,onUnpin:p},v.id))}),i&&h>1&&d.jsxs("div",{className:"voxket-video-pagination",children:[d.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.max(0,a-1)),disabled:a===0,children:"←"}),d.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",h]}),d.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.min(h-1,a+1)),disabled:a===h-1,children:"→"})]})]})}function N6(e){switch(e){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function R6({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:r,showLayoutControls:s=!0,showCameraControls:o=!0,showScreenShareControls:i=!0,className:a=""}){const c=["voxket-video-controls",a].filter(Boolean).join(" "),l=u=>{r==null||r({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return d.jsxs("div",{className:c,children:[o&&d.jsxs("div",{className:"voxket-video-controls-section",children:[d.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),d.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isEnabled?"voxket-control-btn--active":""}`,onClick:t,title:e!=null&&e.isEnabled?"Turn off camera":"Turn on camera",children:[d.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"📹":"📷"}),d.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&d.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," × ",e.dimensions.height]})]}),i&&d.jsxs("div",{className:"voxket-video-controls-section",children:[d.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),d.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isScreenShare?"voxket-control-btn--active":""}`,onClick:n,title:e!=null&&e.isScreenShare?"Stop screen sharing":"Start screen sharing",children:[d.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"🛑":"🖥️"}),d.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),s&&d.jsxs("div",{className:"voxket-video-controls-section",children:[d.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),d.jsx("div",{className:"voxket-layout-buttons",children:[{type:"grid",icon:"⊞",label:"Grid"},{type:"speaker",icon:"🎤",label:"Speaker"},{type:"sidebar",icon:"⫸",label:"Sidebar"},{type:"gallery",icon:"⊡",label:"Gallery"}].map(({type:u,icon:f,label:h})=>d.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>l(u),title:`Switch to ${h} layout`,children:[d.jsx("span",{className:"voxket-control-icon",children:f}),d.jsx("span",{className:"voxket-control-label",children:h})]},u))})]}),d.jsxs("div",{className:"voxket-video-controls-section",children:[d.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),d.jsxs("div",{className:"voxket-video-settings",children:[d.jsxs("div",{className:"voxket-setting-group",children:[d.jsx("label",{className:"voxket-setting-label",children:"Quality"}),d.jsxs("select",{className:"voxket-setting-select",children:[d.jsx("option",{value:"high",children:"High (720p)"}),d.jsx("option",{value:"medium",children:"Medium (480p)"}),d.jsx("option",{value:"low",children:"Low (240p)"})]})]}),d.jsxs("div",{className:"voxket-setting-group",children:[d.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),d.jsxs("select",{className:"voxket-setting-select",children:[d.jsx("option",{value:"30",children:"30 fps"}),d.jsx("option",{value:"15",children:"15 fps"}),d.jsx("option",{value:"10",children:"10 fps"})]})]}),d.jsxs("div",{className:"voxket-setting-group",children:[d.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),d.jsxs("select",{className:"voxket-setting-select",children:[d.jsx("option",{value:"unlimited",children:"Unlimited"}),d.jsx("option",{value:"1000",children:"1 Mbps"}),d.jsx("option",{value:"500",children:"500 Kbps"}),d.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),d.jsxs("div",{className:"voxket-video-controls-section",children:[d.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),d.jsxs("div",{className:"voxket-video-stats",children:[d.jsxs("div",{className:"voxket-stat-item",children:[d.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),d.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}×${e.dimensions.height}`:"N/A"})]}),d.jsxs("div",{className:"voxket-stat-item",children:[d.jsx("span",{className:"voxket-stat-label",children:"Source:"}),d.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),d.jsxs("div",{className:"voxket-stat-item",children:[d.jsx("span",{className:"voxket-stat-label",children:"Status:"}),d.jsx("span",{className:`voxket-stat-value ${e!=null&&e.isEnabled?"voxket-stat-value--active":"voxket-stat-value--inactive"}`,children:e!=null&&e.isEnabled?"Active":"Inactive"})]})]})]})]})}const pm=({handler:e,loadData:t,data:n,client:r,addLocalMessage:s})=>{const[o,i]=m.useState(null),[a,c]=m.useState(!0),[l,u]=m.useState(!1),[f]=m.useState(Date.now());m.useEffect(()=>{(async()=>{try{if(c(!0),console.log("📋 AssignmentView: Loading assignment data..."),console.log("📋 AssignmentView: Received data from RPC:",n),n&&typeof n=="object"){const x={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};i(x),console.log("📋 AssignmentView: Assignment loaded from RPC data:",x)}}catch(x){console.error("📋 AssignmentView: Error loading assignment:",x),i({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{c(!1)}})()},[n,t]);const h=({message:p,assignment:x})=>{const w=p.toLowerCase().includes("declined"),v=w?"bg-red-50 border-red-200":"bg-green-50 border-green-200",S=w?"text-red-700":"text-green-700",C=w?"❌":"🎉";return d.jsxs("div",{className:`max-w-sm mx-auto ${v} border rounded-lg shadow p-3 flex flex-col items-center`,children:[d.jsx("div",{className:"text-2xl mb-2",children:C}),d.jsx("div",{className:`${S} font-semibold text-sm mb-1`,children:p}),d.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:x.title}),d.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},g=async()=>{if(!(!o||!e)){u(!0);try{const p={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",p),e.didSuccess(p,d.jsx(h,{message:"Assignment accepted!",assignment:o}))}catch(p){console.error("📋 AssignmentView: Error accepting assignment:",p),e.didFail({error:"Failed to accept assignment"})}finally{u(!1)}}},y=async()=>{if(!(!o||!e)){u(!0);try{const p={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",p),e.didSuccess(p,d.jsx(h,{message:"Assignment declined",assignment:o}))}catch(p){console.error("📋 AssignmentView: Error declining assignment:",p),e.didFail({error:"Failed to decline assignment"})}finally{u(!1)}}};return a?d.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:d.jsxs("div",{className:"flex items-center justify-center py-4",children:[d.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),d.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):o?d.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[d.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:d.jsx("div",{className:"flex items-center justify-between",children:d.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:o.title})})}),d.jsxs("div",{className:"p-3",children:[d.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:d.jsx("p",{className:"text-xs text-gray-700 leading-snug",children:o.description})}),d.jsx("div",{className:"mb-3",children:d.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[d.jsx("span",{className:"text-xs mr-1",children:"📅"}),d.jsxs("span",{children:["Est: ",o.estimated_time_of_completion]})]})}),d.jsxs("div",{className:"flex gap-2",children:[d.jsx("button",{onClick:g,disabled:l,className:"flex-1 bg-green-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:l?d.jsxs("span",{className:"flex items-center justify-center",children:[d.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),d.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),d.jsx("button",{onClick:y,disabled:l,className:"flex-1 bg-red-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Decline"})]})]})]}):d.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:d.jsxs("div",{className:"text-center py-4",children:[d.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),d.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function V6(){const[e,t]=m.useState(null),[n,r]=m.useState([]);m.useEffect(()=>{const a=new Ar({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return t(a),a.on("rpc.method.called",c=>{console.log("RPC Method Called:",c)}),a.on("rpc.interaction.completed",c=>{console.log("RPC Interaction Completed:",c)}),()=>{a.disconnect()}},[]);const s=async()=>{if(e)try{await e.registerFrontendRPC("give_assignment",pm,"embedded");const a=e.getRegisteredRpcMethods();r(a),console.log("✅ Assignment RPC registered successfully")}catch(a){console.error("❌ Failed to register assignment RPC:",a)}},o=async()=>{if(!e)return;const a=({handler:c,timeout:l})=>{const[u,f]=m.useState(""),h=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],g=p=>{f(p)},y=()=>{const p=h.find(x=>x.id===u);c==null||c.didSuccess({selectedProduct:u,productName:p==null?void 0:p.name,price:p==null?void 0:p.price,timestamp:new Date().toISOString()})};return d.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[d.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),d.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),d.jsx("div",{className:"space-y-3 mb-6",children:h.map(p=>d.jsx("div",{onClick:()=>g(p.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${u===p.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:d.jsxs("div",{className:"flex justify-between items-center",children:[d.jsxs("div",{children:[d.jsx("h4",{className:"font-medium",children:p.name}),d.jsx("p",{className:"text-gray-600 text-sm",children:p.price})]}),d.jsx("div",{className:`w-4 h-4 rounded-full ${u===p.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},p.id))}),d.jsxs("div",{className:"flex justify-end space-x-3",children:[d.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),d.jsx("button",{onClick:y,disabled:!u,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),l&&d.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",l," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const c=e.getRegisteredRpcMethods();r(c),console.log("✅ Product Recommendation RPC registered successfully")}catch(c){console.error("❌ Failed to register product recommendation RPC:",c)}},i=async()=>{if(!e)return;const a=({handler:c})=>{const[l,u]=m.useState(0),[f,h]=m.useState(""),g=()=>{c==null||c.didSuccess({rating:l,comment:f,timestamp:new Date().toISOString()})};return d.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[d.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),d.jsxs("div",{className:"mb-4",children:[d.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),d.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(y=>d.jsx("button",{onClick:()=>u(y),className:`text-2xl ${y<=l?"text-yellow-400":"text-gray-300"}`,children:"⭐"},y))})]}),d.jsxs("div",{className:"mb-4",children:[d.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),d.jsx("textarea",{value:f,onChange:y=>h(y.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),d.jsxs("div",{className:"flex justify-end space-x-2",children:[d.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),d.jsx("button",{onClick:g,disabled:l===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await e.registerFrontendRPC("collect_feedback",a,"embedded");const c=e.getRegisteredRpcMethods();r(c),console.log("✅ Feedback RPC registered successfully")}catch(c){console.error("❌ Failed to register feedback RPC:",c)}};return d.jsxs("div",{className:"p-6",children:[d.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),d.jsxs("div",{className:"space-y-4 mb-6",children:[d.jsxs("div",{children:[d.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),d.jsxs("div",{className:"space-x-2",children:[d.jsx("button",{onClick:s,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),d.jsx("button",{onClick:o,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),d.jsx("button",{onClick:i,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),d.jsxs("div",{children:[d.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?d.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>d.jsx("li",{className:"text-gray-700",children:d.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):d.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),d.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[d.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),d.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[d.jsxs("li",{children:["Register RPC methods with React components using ",d.jsx("code",{children:"client.registerFrontendRPC()"})]}),d.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),d.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),d.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),d.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),d.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[d.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),d.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),d.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
|
|
180
|
+
`,style:{minHeight:"2.5rem",display:i===r?"block":"none"},children:o},i))})}function Z8({statusMessage:e,theme:t}){const n=Ie(t);return d.jsxs("div",{className:"z-10 flex items-center space-x-2 mt-2 pb-2",children:[d.jsx("div",{className:n.statusIndicator}),d.jsx("span",{className:`text-xs ${n.text.muted}`,children:e})]})}const K8=({disabled:e,onStartCall:t,onStartChat:n,onStartVideo:r,prompts:s=['"Book a meeting with the marketing team"',`"What's the status of project Alpha?"`,`"Summarize yesterday's sales report"`,'"Find a good Italian restaurant nearby"','"Remind me to call John tomorrow at 10 AM"'],statusMessage:o="Agent is ready",title:i="Choose how to interact",subTitle:a="Ask me anything or give me a task to complete",theme:c="vox",modalities:l=["voice","chat","video"]})=>{const u=Ie(c),f=l.includes("voice"),h=l.includes("chat"),g=l.includes("video"),y=[f,h,g].filter(Boolean).length;return console.log("🎯 Welcome component debug:",{modalities:l,hasVoice:f,hasChat:h,hasVideo:g,totalButtons:y,onStartVideo:!!r}),d.jsxs("div",{inert:e,className:"flex p-8 flex-col items-center h-full justify-center w-full",children:[d.jsxs("div",{className:"mt-1 relative flex items-center justify-center mb-8 w-full",style:{minHeight:"120px"},children:[d.jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[d.jsx("div",{className:u.pulseRings.ring1}),d.jsx("div",{className:u.pulseRings.ring2,style:{animationDelay:"0.5s"}}),d.jsx("div",{className:u.pulseRings.ring3,style:{animationDelay:"1s"}})]}),d.jsx("div",{className:"relative z-10 flex items-center justify-center",children:f&&h&&g?d.jsxs("div",{className:"flex gap-4 items-center justify-center",children:[d.jsx(zr,{onClick:t,disabled:e,theme:c}),d.jsx(jo,{onClick:n,disabled:e,theme:c}),d.jsx(Po,{onClick:r||t,disabled:e,theme:c})]}):y>1?d.jsxs("div",{className:"flex gap-6 items-center justify-center",children:[f&&d.jsx(zr,{onClick:t,disabled:e,theme:c}),h&&d.jsx(jo,{onClick:n,disabled:e,theme:c}),g&&r&&d.jsx(Po,{onClick:r,disabled:e,theme:c})]}):d.jsx("div",{className:"flex items-center justify-center",children:f?d.jsx(zr,{onClick:t,disabled:e,theme:c}):h?d.jsx(jo,{onClick:n,disabled:e,theme:c}):g&&r?d.jsx(Po,{onClick:r,disabled:e,theme:c}):d.jsx(zr,{onClick:t,disabled:e,theme:c})})})]}),d.jsxs("div",{className:"text-center flex flex-col items-center gap-y-2 mb-6 w-full",children:[d.jsx("h3",{className:`text-xl font-semibold mb-2 ${u.text.accent}`,children:i}),d.jsx("p",{className:`text-sm leading-relaxed px-4 ${u.text.secondary}`,children:a}),y>1&&d.jsxs("div",{className:"flex gap-6 mt-4 text-xs justify-center",children:[f&&d.jsxs("div",{className:"flex flex-col items-center gap-1",children:[d.jsx(Gh,{className:"w-4 h-4"}),d.jsx("span",{className:u.text.muted,children:"Voice"})]}),h&&d.jsxs("div",{className:"flex flex-col items-center gap-1",children:[d.jsx(Kh,{className:"w-4 h-4"}),d.jsx("span",{className:u.text.muted,children:"Chat"})]}),g&&d.jsxs("div",{className:"flex flex-col items-center gap-1",children:[d.jsx(Yh,{className:"w-4 h-4"}),d.jsx("span",{className:u.text.muted,children:"Video"})]})]})]}),d.jsx(W8,{prompts:s,theme:c}),d.jsx(Z8,{statusMessage:o,theme:c})]})};function qh({room:e,onSessionEnd:t,onSessionStart:n,enableConsoleLogging:r=!0,enableLocalStorage:s=!0,voxketSessionId:o}={}){const[i,a]=m.useState(null),[c,l]=m.useState([]),[u,f]=m.useState(null),[h,g]=m.useState([]),y=m.useCallback((v,S)=>{const C={timestamp:new Date,event:v,data:S,sessionId:i==null?void 0:i.sessionId,participantId:u==null?void 0:u.identity};if(l(E=>[...E,C]),s){const E=JSON.parse(localStorage.getItem("voxket-session-logs")||"[]");E.push(C),localStorage.setItem("voxket-session-logs",JSON.stringify(E))}return C},[i==null?void 0:i.sessionId,u==null?void 0:u.identity,r,s]);m.useEffect(()=>{if(!e)return;const v=()=>{const b=o||`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,I=new Date,L={sessionId:b,startTime:I,totalMessages:0,connectionIssues:0,participantCount:h.length,events:[]};a(L),y("SESSION_STARTED",{sessionId:b,startTime:I}),n==null||n(b)},S=()=>{if(i){const b=new Date,I=b.getTime()-i.startTime.getTime(),L={...i,endTime:b,duration:I,events:c};y("SESSION_ENDED",{sessionId:i.sessionId,duration:`${Math.round(I/1e3)}s`,totalMessages:i.totalMessages,connectionIssues:i.connectionIssues}),t==null||t(L),a(null),l([])}},C=b=>{y("CONNECTION_STATE_CHANGED",{state:b}),b===te.ConnectionState.Reconnecting&&i&&(a(I=>I?{...I,connectionIssues:I.connectionIssues+1}:null),y("CONNECTION_ISSUE",{type:"reconnecting"}))},E=b=>{y("TRACK_PUBLISHED",{trackKind:b.kind,trackSource:b.source})},T=b=>{y("TRACK_UNPUBLISHED",{trackKind:b.kind,trackSource:b.source})},k=(b,I)=>{i&&a(L=>L?{...L,totalMessages:L.totalMessages+1}:null),y("DATA_RECEIVED",{participantId:I==null?void 0:I.identity,dataSize:b.length})},j=b=>{y("PARTICIPANT_CONNECTED",{participantId:b.identity,participantName:b.name}),g(I=>[...I,b]),i&&a(I=>I?{...I,participantCount:I.participantCount+1}:null)},$=b=>{y("PARTICIPANT_DISCONNECTED",{participantId:b.identity,participantName:b.name}),g(I=>I.filter(L=>L.identity!==b.identity))};return e.localParticipant&&f(e.localParticipant),e.on(te.RoomEvent.Connected,v),e.on(te.RoomEvent.Disconnected,S),e.on(te.RoomEvent.ConnectionStateChanged,C),e.on(te.RoomEvent.TrackPublished,E),e.on(te.RoomEvent.TrackUnpublished,T),e.on(te.RoomEvent.DataReceived,k),e.on(te.RoomEvent.ParticipantConnected,j),e.on(te.RoomEvent.ParticipantDisconnected,$),()=>{e.off(te.RoomEvent.Connected,v),e.off(te.RoomEvent.Disconnected,S),e.off(te.RoomEvent.ConnectionStateChanged,C),e.off(te.RoomEvent.TrackPublished,E),e.off(te.RoomEvent.TrackUnpublished,T),e.off(te.RoomEvent.DataReceived,k),e.off(te.RoomEvent.ParticipantConnected,j),e.off(te.RoomEvent.ParticipantDisconnected,$)}},[e,i,c,h.length,y,t,n]);const p=m.useCallback(()=>s?JSON.parse(localStorage.getItem("voxket-session-logs")||"[]"):c,[c,s]),x=m.useCallback(()=>{s&&localStorage.removeItem("voxket-session-logs"),l([])},[s]),w=m.useCallback(()=>{const v=p(),S=JSON.stringify(v,null,2),C="data:application/json;charset=utf-8,"+encodeURIComponent(S),E=`voxket-session-logs-${new Date().toISOString().split("T")[0]}.json`,T=document.createElement("a");T.setAttribute("href",C),T.setAttribute("download",E),T.click()},[p]);return{sessionMetrics:i,sessionLogs:c,logEvent:y,getSessionLogs:p,clearSessionLogs:x,exportSessionLogs:w}}class ja{constructor(){Te(this,"listeners",{})}on(t,n){return this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(n),()=>this.off(t,n)}once(t,n){const r=(...s)=>{this.off(t,r),n(...s)};return this.on(t,r)}off(t,n){const r=this.listeners[t];if(!r)return;const s=r.indexOf(n);s>-1&&r.splice(s,1)}removeAllListeners(t){t?delete this.listeners[t]:this.listeners={}}emit(t,...n){const r=this.listeners[t];if(!r)return;const s=[...r];for(const o of s)try{o(...n)}catch(i){console.error(`Error in event listener for ${String(t)}:`,i)}}listenerCount(t){var n;return((n=this.listeners[t])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class Xh{constructor(t){Te(this,"plugins",new Map);Te(this,"installedPlugins",new Set);Te(this,"context");this.context={client:t,emit:t.emit.bind(t),on:t.on.bind(t),config:{}}}register(t){if(this.plugins.has(t.name))throw new Error(`Plugin '${t.name}' is already registered`);if(t.dependencies){for(const n of t.dependencies)if(!this.plugins.has(n))throw new Error(`Plugin '${t.name}' depends on '${n}' which is not registered`)}this.plugins.set(t.name,t)}async install(t,n){const r=this.plugins.get(t);if(!r)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t))throw new Error(`Plugin '${t}' is already installed`);if(r.dependencies)for(const o of r.dependencies)this.installedPlugins.has(o)||await this.install(o);const s={...this.context,config:{...r.config,...n}};r.install&&await r.install(s),this.installedPlugins.add(t),this.setupPluginEvents(r,s)}async uninstall(t){var r;const n=this.plugins.get(t);if(!n)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t)){for(const[s,o]of this.plugins)if(this.installedPlugins.has(s)&&((r=o.dependencies)!=null&&r.includes(t)))throw new Error(`Cannot uninstall '${t}' because '${s}' depends on it`);n.uninstall&&await n.uninstall(this.context),this.installedPlugins.delete(t)}}isInstalled(t){return this.installedPlugins.has(t)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(t){return this.plugins.get(t)}setupPluginEvents(t,n){t.onSessionStart&&n.on("session.started",r=>{t.onSessionStart(n,r.id)}),t.onSessionEnd&&n.on("session.ended",r=>{t.onSessionEnd(n,r.id)}),t.onAgentResponse&&n.on("agent.response",r=>{t.onAgentResponse(n,r)})}}function G8(e){return e}function Pa(e,t,n){return{name:e,version:"1.0.0",description:`${t} modality plugin`,install:async r=>{n.onActivate&&await n.onActivate(r)},uninstall:async r=>{n.onDeactivate&&await n.onDeactivate(r)},onAgentResponse:n.onMessage}}const Y8={name:"analytics",version:"1.0.0",description:"Built-in analytics tracking",install:async e=>{console.log("Analytics plugin installed"),e.on("session.started",t=>{console.log("Analytics: Session started",t.id)}),e.on("session.ended",(t,n)=>{console.log("Analytics: Session ended",t.id,n)}),e.on("chat.message.sent",t=>{console.log("Analytics: User message sent",t.content.length)})}},q8={name:"debug",version:"1.0.0",description:"Debug logging and development tools",install:async e=>{console.log("Debug plugin installed");const t=e.emit;e.emit=(n,...r)=>(console.log(`[Debug] Event: ${String(n)}`,r),t(n,...r))}},X8={name:"metrics",version:"1.0.0",description:"Advanced metrics collection",install:async e=>{console.log("Metrics plugin installed");const t=new Map;e.on("session.started",n=>{t.set(n.id,{startTime:Date.now(),events:[]})}),e.on("agent.response",n=>{console.log("Metrics: Agent response analyzed",{type:n.type,length:n.content.length,timestamp:n.timestamp})})}},Jh=A.createContext(null);function Qh({config:e,children:t,autoConnect:n=!1}){const[r,s]=A.useState(null),[o,i]=A.useState(!1),[a,c]=A.useState(!1),[l,u]=A.useState(null),[f,h]=A.useState(null),[g,y]=A.useState("idle"),[p,x]=A.useState(null),[w,v]=A.useState([]),[S,C]=A.useState([]),[E,T]=A.useState([]);A.useEffect(()=>{const P=new Ar(e);return s(P),k(P),n&&j(P),()=>{P.disconnect().catch(console.error)}},[e,n]);const k=P=>{P.on("connection.connecting",()=>{c(!0),u(null)}),P.on("connection.connected",()=>{i(!0),c(!1),u(null)}),P.on("connection.disconnected",()=>{i(!1),c(!1),h(null),y("idle"),v([]),C([]),T([])}),P.on("connection.error",Y=>{u(Y),c(!1)}),P.on("session.created",Y=>{h(Y),y(Y.state)}),P.on("session.state.changed",Y=>{y(Y),f&&h({...f,state:Y})}),P.on("session.ended",(Y,R)=>{h(null),y("idle"),x(R),v([]),C([]),T([])}),P.on("participant.joined",Y=>{v(R=>[...R,Y])}),P.on("participant.left",Y=>{v(R=>R.filter(V=>V.id!==Y.id))}),P.on("chat.message.received",Y=>{C(R=>[...R,Y])}),P.on("chat.message.sent",Y=>{C(R=>[...R,Y])}),P.on("transcription.received",Y=>{T(R=>[...R,Y])})},j=async P=>{const Y=P||r;if(Y)try{await Y.connect()}catch(R){console.error("Failed to connect:",R)}},z={client:r,isConnected:o,isConnecting:a,connectionError:l,currentSession:f,sessionState:g,sessionMetrics:p,participants:w,chatMessages:S,transcriptions:E,connect:()=>j(),disconnect:async()=>{if(r)try{await r.disconnect()}catch(P){console.error("Failed to disconnect:",P)}},createSession:async(P,Y={})=>{if(!r)throw new Error("Client not initialized");const R={agentId:P,participantName:Y.participantName||"User",metadata:Y.metadata,modalities:Y.modalities||["voice"]};return await r.createSession(R)},endSession:async()=>r?await r.endSession():null,sendChatMessage:async P=>{if(!r)throw new Error("Client not initialized");await r.sendChatMessage(P)},setMicrophoneEnabled:async P=>{if(!r)throw new Error("Client not initialized");await r.setMicrophoneEnabled(P)},setCameraEnabled:async P=>{if(!r)throw new Error("Client not initialized");await r.setCameraEnabled(P)},startScreenShare:async()=>{if(!r)throw new Error("Client not initialized");await r.startScreenShare()},stopScreenShare:async()=>{if(!r)throw new Error("Client not initialized");await r.stopScreenShare()}};return d.jsx(Jh.Provider,{value:z,children:t})}function bt(){const e=A.useContext(Jh);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}class J8 extends ja{constructor(n){super();Te(this,"room",null);Te(this,"registeredMethods",new Map);Te(this,"activeInteractions",new Map);Te(this,"currentInteraction",null);n&&this.setRoom(n)}setRoom(n){this.room=n}async registerFrontendRPC(n,r,s="embedded"){if(console.log(`RpcManager: Starting registration for method '${n}'`),!this.room)throw console.error(`RpcManager: Cannot register '${n}' - no room instance`),new Error("Room not initialized. Cannot register RPC method.");if(!this.room.localParticipant)throw console.error(`RpcManager: Cannot register '${n}' - no local participant`),new Error("Local participant not available for RPC registration");console.log(`RpcManager: Room state: ${this.room.state}`),console.log(`RpcManager: Local participant: ${this.room.localParticipant.identity}`),console.log(`RpcManager: Registering frontend RPC method: ${n}`);const o={methodName:n,component:r,presentationMode:s};this.registeredMethods.set(n,o);try{this.room.registerRpcMethod(n,async i=>{console.log(`RpcManager: RPC method '${n}' called by ${i.callerIdentity}`),console.log("RpcManager: Payload:",i.payload),this.emit("rpc.method.called",{methodName:n,data:i});let a;console.log(`RpcManager: Current registration for '${n}':`,o);let c=i.responseTimeout||30;try{a=JSON.parse(i.payload)}catch{a=i.payload}try{const l=await this.awaitUserInteraction(n,r,s,a,c);return JSON.stringify(l)}catch(l){throw console.error(`RpcManager: Error in RPC method '${n}':`,l),l}}),this.emit("rpc.method.registered",{methodName:n}),console.log(`RpcManager: Successfully registered RPC method: ${n}`)}catch(i){throw console.error(`RpcManager: Failed to register RPC method '${n}':`,i),i}}async awaitUserInteraction(n,r,s,o,i){return new Promise((a,c)=>{const l=`${n}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${n}, timeout: ${i} seconds`);const u={didSuccess:(h,g)=>{console.log(`RpcManager: User interaction successful for method: ${n}`,h),this.clearInteraction(l),this.currentInteraction=null;const y={success:!0,message:"User interaction completed successfully",data:h,timestamp:new Date,...g?{successView:g}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:y}),a(y)},didFail:h=>{console.log(`RpcManager: User interaction failed for method: ${n}`,h),this.clearInteraction(l);const g={success:!1,message:"User interaction failed",error:h,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:g}),a(g)},dismissView:()=>{var g;console.log(`RpcManager: User dismissed interaction for method: ${n}`),console.log("RpcManager: Current interaction before dismiss:",(g=this.currentInteraction)==null?void 0:g.methodName),this.clearInteraction(l),this.currentInteraction=null,console.log("RpcManager: Current interaction after dismiss:",this.currentInteraction);const h={success:!0,data:{dismissed:!0,reason:"User dismissed the interaction"},message:"User interaction dismissed",timestamp:new Date};this.emit("rpc.interaction.dismissed",{methodName:n,response:h}),this.emit("rpc.interaction.completed",{methodName:n,response:h}),setTimeout(()=>{var y;((y=this.currentInteraction)==null?void 0:y.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(h)},didTimeout:h=>{console.log(`RpcManager: User interaction timeout for method: ${n}`),this.clearInteraction(l),this.currentInteraction=null;const g={success:!0,message:`User interaction timed out after ${i} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...h?{timeoutView:h}:{}};this.emit("rpc.interaction.timeout",{methodName:n,response:g}),setTimeout(()=>{var y;((y=this.currentInteraction)==null?void 0:y.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(g)}},f=setTimeout(()=>{u.didTimeout&&u.didTimeout()},i);this.activeInteractions.set(l,{resolve:h=>a(JSON.parse(h)),reject:c,timeoutId:f}),this.currentInteraction={isVisible:!0,methodName:n,component:r,presentationMode:s,timeout:i,data:o,handler:u},this.emit("rpc.interaction.started",{methodName:n,presentationMode:s}),setTimeout(async()=>{var h;if((h=this.currentInteraction)!=null&&h.handler)try{console.log(`RpcManager: Component created for method: ${n} with data:`,o)}catch(g){console.error("RpcManager: Error loading data into component:",g),u.didFail({error:"Failed to load data into component"})}},100)})}clearInteraction(n){const r=this.activeInteractions.get(n);r&&(console.log(`RpcManager: Clearing interaction: ${n}`),clearTimeout(r.timeoutId),this.activeInteractions.delete(n))}getCurrentInteraction(){return this.currentInteraction}dismissCurrentInteraction(){var n;this.currentInteraction&&(console.log(`RpcManager: Dismissing current interaction: ${this.currentInteraction.methodName}`),(n=this.currentInteraction.handler)==null||n.dismissView(),setTimeout(()=>{this.currentInteraction&&(console.log("RpcManager: Force clearing lingering interaction"),this.currentInteraction=null)},0))}getRegisteredMethods(){return Array.from(this.registeredMethods.keys())}unregisterMethod(n){this.registeredMethods.delete(n),console.log(`RpcManager: Unregistered RPC method: ${n}`)}clear(){for(const[n,r]of this.activeInteractions)clearTimeout(r.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null,console.log("RpcManager: Cleared all registrations and interactions")}}class ue extends Error{constructor(t,n,r){super(t),this.code=n,this.details=r,this.name="VoxketError"}}function Q8(e){if(!Ws.createRoot||typeof Ws.createRoot!="function")throw new Error("createRoot is not available. Make sure React 18+ and react-dom/client are properly installed and accessible.");try{const t=Ws.createRoot(e);if(!t)throw new Error("createRoot returned null or undefined");return{render:n=>{if(!t||typeof t.render!="function")throw new Error("React root render method is not available");try{t.render(n)}catch(r){throw console.error("Error rendering React element:",r),r}},unmount:()=>{try{t&&typeof t.unmount=="function"&&t.unmount()}catch(n){console.warn("Error unmounting React root:",n);try{e.innerHTML=""}catch(r){console.warn("Error clearing container:",r)}}}}}catch(t){throw console.error("Error creating React root:",t),new Error(`Failed to create React root: ${t instanceof Error?t.message:"Unknown error"}`)}}class Ar extends ja{constructor(n){super();Te(this,"config");Te(this,"room",null);Te(this,"pluginManager");Te(this,"rpcManager");Te(this,"isConnected",!1);Te(this,"currentSession",null);Te(this,"connectionState",te.ConnectionState.Disconnected);Te(this,"renderedComponents",new Map);Te(this,"textStreamHandlersRegistered",!1);Te(this,"currentAgentInfo",null);Te(this,"chatMessages",[]);this.config=n,this.pluginManager=new Xh(this),this.rpcManager=new J8,this.setupEventListeners(),this.initializeClient()}setupEventListeners(){this.on("connection.connected",()=>{var n,r;this.isConnected=!0,(r=(n=this.config).onConnected)==null||r.call(n)}),this.on("connection.disconnected",n=>{var r,s;this.isConnected=!1,(s=(r=this.config).onDisconnected)==null||s.call(r,n)}),this.on("connection.error",n=>{var r,s;(s=(r=this.config).onError)==null||s.call(r,n)}),this.on("chat.message.received",n=>{var r,s;this.addChatMessage(n),(s=(r=this.config).onMessageReceived)==null||s.call(r,n)}),this.on("chat.message.updated",n=>{this.updateChatMessage(n)}),this.on("chat.message.sent",n=>{this.addChatMessage(n)}),this.on("transcription.received",n=>{var r,s;(s=(r=this.config).onTranscriptionReceived)==null||s.call(r,n)}),this.on("session.state.changed",n=>{var r,s;(s=(r=this.config).onSessionStateChanged)==null||s.call(r,n)}),this.on("session.created",n=>{var r,s;(s=(r=this.config).onSessionStart)==null||s.call(r,n.id)}),this.on("session.ended",(n,r)=>{var s,o;(o=(s=this.config).onSessionEnd)==null||o.call(s,r)}),this.on("participant.joined",n=>{var r,s;(s=(r=this.config).onUserJoined)==null||s.call(r,n.id)}),this.on("participant.left",n=>{var r,s;(s=(r=this.config).onUserLeft)==null||s.call(r,n.id)}),this.setupRpcEventForwarding()}setupRpcEventForwarding(){if(!this.rpcManager){console.warn("RpcManager not initialized, skipping event forwarding setup");return}this.rpcManager.on("rpc.method.registered",n=>this.emit("rpc.method.registered",n)),this.rpcManager.on("rpc.method.called",n=>this.emit("rpc.method.called",n)),this.rpcManager.on("rpc.interaction.started",n=>this.emit("rpc.interaction.started",n)),this.rpcManager.on("rpc.interaction.completed",n=>this.emit("rpc.interaction.completed",n)),this.rpcManager.on("rpc.interaction.timeout",n=>this.emit("rpc.interaction.timeout",n)),this.rpcManager.on("rpc.interaction.dismissed",n=>this.emit("rpc.interaction.dismissed",n))}initializeClient(){this.room=new te.Room,this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(te.RoomEvent.Connected,()=>{var n,r;this.connectionState=te.ConnectionState.Connected,this.emit("connection.connected"),this.rpcManager.setRoom(this.room),(r=(n=this.currentSession)==null?void 0:n.activeModalities)!=null&&r.includes("voice")&&setTimeout(async()=>{var s;try{(s=this.room)!=null&&s.localParticipant&&(this.room.localParticipant.isMicrophoneEnabled?this.emit("track.unmuted",{source:"microphone",enabled:!0}):(await this.room.localParticipant.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0})))}catch(o){console.warn("VoxketClient: Failed to enable microphone after room connection:",o)}},1e3),this.textStreamHandlersRegistered||this.setupTextStreamHandlers()}),this.room.on(te.RoomEvent.Disconnected,n=>{this.connectionState=te.ConnectionState.Disconnected,this.textStreamHandlersRegistered=!1,this.emit("connection.disconnected",n==null?void 0:n.toString())}),this.room.on(te.RoomEvent.ConnectionStateChanged,n=>{this.connectionState=n,n===te.ConnectionState.Connecting&&this.emit("connection.connecting")}),this.room.on(te.RoomEvent.ParticipantConnected,n=>{const r={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.joined",r)}),this.room.on(te.RoomEvent.ParticipantDisconnected,n=>{const r={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.left",r)}))}setupTextStreamHandlers(){if(this.room){try{this.room.registerTextStreamHandler("lk.chat",async(n,r)=>{try{const s=await n.readAll(),o={id:`msg_${Date.now()}_${r.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:s,timestamp:new Date,sender:{id:r.identity||"user",name:r.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.emit("chat.message.received",o)}catch(s){console.error("VoxketClient: Failed to process lk.chat message:",s)}})}catch(n){console.warn("VoxketClient: lk.chat handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("lk.transcription",async(n,r)=>{var s,o;try{const i=`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`;let a="";const c=((s=this.currentAgentInfo)==null?void 0:s.name)||r.identity||"AI Assistant",l={id:i,content:"",timestamp:new Date,sender:{id:r.identity||"agent",name:c,type:"agent"},metadata:{topic:"lk.transcription",streaming:!0}};this.emit("chat.message.received",l);for await(const h of n){a+=h;const g=this.convertMarkdownToText(a),y={...l,content:g,metadata:{...l.metadata,streaming:!0}};this.emit("chat.message.updated",y)}const u=this.convertMarkdownToText(a),f={...l,content:u,metadata:{...l.metadata,streaming:!1}};this.emit("chat.message.updated",f)}catch(i){console.error("VoxketClient: Failed to process lk.transcription message:",i);try{const a=await n.readAll(),c=((o=this.currentAgentInfo)==null?void 0:o.name)||r.identity||"AI Assistant",l={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:a,timestamp:new Date,sender:{id:r.identity||"agent",name:c,type:"agent"},metadata:{topic:"lk.transcription"}};this.emit("chat.message.received",l)}catch(a){console.error("VoxketClient: Fallback failed for lk.transcription:",a)}}})}catch(n){console.warn("VoxketClient: lk.transcription handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("suggested_response",async n=>{const r=await n.readAll();let s=[];try{s=["tes","hello how are you","algebra make me learn that ","what is the meaning of life"]}catch(o){console.warn("VoxketClient: Failed to parse suggested_response:",o,r)}this.emit("suggested.response",s)})}catch(n){console.warn("VoxketClient: suggested_response handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("agent_state_changed",async(n,r)=>{const s=await n.readAll();let o={};try{o=typeof s=="string"?JSON.parse(s.replace(/'/g,'"')):s}catch(i){console.warn("VoxketClient: Failed to parse agent_state_changed:",i,s)}o.new_state==="speaking"?this.emit("agent.speaking",o):o.new_state==="thinking"&&this.emit("agent.thinking",o)})}catch(n){console.warn("VoxketClient: conversation_item_added handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("images",async(n,r)=>{try{const s=await n.readAll()}catch(s){console.error("VoxketClient: Error processing images stream:",s)}})}catch(n){console.warn("VoxketClient: images handler already registered, skipping:",n)}try{this.room.registerByteStreamHandler("images",async(n,r)=>{var s,o;try{const i=n.info,a={id:`img_${Date.now()}_${r.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`�️ ${i.name||"Image"}`,sender:{id:r.identity||"agent",name:r.identity||"Agent",type:r.identity===((o=(s=this.room)==null?void 0:s.localParticipant)==null?void 0:o.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:i.name,fileSize:i.size,mimeType:i.mimeType,streamId:i.id,downloading:!0}};this.emit("chat.message.received",a),n.onProgress&&(n.onProgress=h=>{const g={...a,metadata:{...a.metadata,downloadProgress:h||0}};this.emit("chat.message.updated",g)});const c=[];for await(const h of n)c.push(h);const l=new Blob(c,{type:i.mimeType||"application/octet-stream"}),u=URL.createObjectURL(l),f={...a,metadata:{...a.metadata,downloading:!1,downloadProgress:1,downloadUrl:u,blob:l}};this.emit("chat.message.updated",f)}catch(i){console.error("VoxketClient: Error processing image attachment:",i)}})}catch(n){console.warn("VoxketClient: image handler already registered, skipping:",n)}this.textStreamHandlersRegistered=!0}}async fetchConnectionDetails(n,r,s){const o=n||this.config.agentId||"default-agent",i=r||this.config.participantName||"User",a=s||this.config.modalities||["voice"];try{const c={agent_id:o,participant_name:i,participant_metadata:{user_id:""},modality:a[0]},l=await fetch(`${this.config.baseUrl}/api/live/agent/session`,{method:"POST",headers:{accept:"application/json","X-APP-ID":this.config.appId,"X-APP-SECRET":this.config.appSecret,"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){let h=`HTTP ${l.status}: Failed to fetch connection details`;try{const g=await l.json();g&&(g.error?h=`API Error: ${g.error}`:g.detail?h=`API Error: ${g.detail}`:g.message&&(h=`API Error: ${g.message}`))}catch{try{const y=await l.text();y&&(h=`API Error: ${y}`)}catch{}}throw new Error(h)}const u=await l.json();let f;return u.agent_info&&(f={id:u.agent_info.id||o,name:u.agent_info.name||"AI Assistant",avatar:u.agent_info.avatar,capabilities:u.agent_info.capabilities||["voice_interaction","text_chat"],metadata:u.agent_info.metadata||{}},this.currentAgentInfo=f),{serverUrl:u.wss_url,participantToken:u.token,voxketSessionId:u.session_id,agentInfo:f}}catch(c){console.error("VoxketClient: fetchConnectionDetails failed:",c);const l=new ue(`Failed to fetch connection details: ${c instanceof Error?c.message:"Unknown error"}`,"CONNECTION_FAILED",c);throw this.emit("connection.error",l),l}}async connect(n,r,s){var o;try{this.emit("connection.connecting");const i=await this.fetchConnectionDetails(n,r,s);return await((o=this.room)==null?void 0:o.connect(i.serverUrl,i.participantToken)),this.isConnected=!0,i}catch(i){console.error("VoxketClient: Connection failed:",i);const a=new ue(`Failed to connect to Voxket services: ${i instanceof Error?i.message:"Unknown error"}`,"CONNECTION_FAILED",i);throw this.emit("connection.error",a),a}}async disconnect(){var n;try{await((n=this.room)==null?void 0:n.disconnect()),this.isConnected=!1,this.currentSession=null,this.currentAgentInfo=null,this.textStreamHandlersRegistered=!1,this.clearChatMessages(),this.room=new te.Room,this.setupRoomEventListeners()}catch(r){const s=new ue("Failed to disconnect properly","NETWORK_ERROR",r);throw this.emit("connection.error",s),s}}async createSession(n){var r,s;try{const o=await this.connect(n.agentId,n.participantName,n.modalities),i={id:o.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:o.agentInfo||this.currentAgentInfo};if(this.currentSession=i,this.emit("session.created",i),(r=n.modalities)!=null&&r.includes("voice"))try{await new Promise(a=>setTimeout(a,500)),(s=this.room)!=null&&s.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(a){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",a)}return setTimeout(()=>{this.currentSession&&(this.currentSession.state="active",this.emit("session.state.changed","active",this.currentSession.state))},1e3),i}catch(o){throw console.error("VoxketClient: Failed to create session:",o),o instanceof ue?o:o instanceof TypeError&&o.message.includes("fetch")?new ue("Network connection failed","CONNECTION_FAILED",o):o instanceof Error&&o.message.includes("Failed to fetch connection details")?new ue(`API connection failed: ${o.message}`,"CONNECTION_FAILED",o):new ue(`Failed to create session: ${o instanceof Error?o.message:"Unknown error"}`,"SESSION_NOT_FOUND",o)}}async startSession(n,r){const s={agentId:n||this.config.agentId||"default-agent",participantName:(r==null?void 0:r.participantName)||this.config.participantName||"User",modalities:(r==null?void 0:r.modalities)||this.config.modalities||["voice","chat"],metadata:r==null?void 0:r.metadata};return this.createSession(s)}async endSession(){var n,r;if(!this.currentSession)return null;try{const s={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.room)==null?void 0:r.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]};return this.currentSession.endedAt=new Date,this.currentSession.state="disconnected",this.emit("session.ended",this.currentSession,s),await this.disconnect(),s}catch(s){throw new ue("Failed to end session","SESSION_NOT_FOUND",s)}}getCurrentSession(){return this.currentSession}getCurrentAgentInfo(){return this.currentAgentInfo}getChatMessages(){return[...this.chatMessages]}addChatMessage(n){this.chatMessages.some(s=>s.id===n.id)||this.chatMessages.push(n)}updateChatMessage(n){const r=this.chatMessages.findIndex(s=>s.id===n.id);r!==-1&&(this.chatMessages[r]=n)}clearChatMessages(){this.chatMessages=[],this.dismissCurrentInteraction(),this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays(),this.emit("chat.history.cleared")}renderUI(n={}){var c,l,u;const r=this.resolveTarget(n.target||"body"),s=this.getTargetKey(r),o=this.renderedComponents.get(s);o&&o.target===r||this.removeUI(r);const i=(o==null?void 0:o.root)||Q8(r),a={agentId:n.agentId||this.config.agentId||"default-agent",participantName:n.participantName||this.config.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:n.className,theme:typeof n.theme=="string"?n.theme:void 0,modalities:n.modality||this.config.modalities||["voice"],suportsChatInput:((c=n.modality)==null?void 0:c.includes("chat"))!==!1,suportsVideoInput:((l=n.modality)==null?void 0:l.includes("video"))===!0,suportsScreenShare:((u=n.modality)==null?void 0:u.includes("screen_share"))===!0,autoStart:n.autoStart,displayType:n.displayType||"widget",popupPosition:n.popupPosition||"bottom-right",popupTriggerText:n.popupTriggerText||"Open Chat",width:n.width,height:n.height,onDisplayTypeChange:n.onDisplayTypeChange,prompts:n.prompts,statusMessage:n.statusMessage,welcomeTitle:n.welcomeTitle,welcomeSubTitle:n.welcomeSubTitle,loadingText:n.loadingText,voxketClient:this};if(!i||typeof i.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{i.render(m.createElement(Qh,{config:this.config,autoConnect:n.autoStart||!1,children:m.createElement(em,a)}))}catch(f){throw console.error("Error rendering Voxket widget:",f),new Error(`Failed to render Voxket widget: ${f instanceof Error?f.message:"Unknown error"}`)}this.renderedComponents.set(s,{root:i,target:r})}removeUI(n){const r=n?this.resolveTarget(n):null;if(r){const s=this.getTargetKey(r),o=this.renderedComponents.get(s);if(o){try{o.root&&typeof o.root.unmount=="function"&&o.root.unmount()}catch(a){console.warn("Error unmounting React component:",a);try{r&&(r.innerHTML="")}catch(c){console.warn("Error during manual cleanup:",c)}}this.renderedComponents.delete(s),r.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(a=>{try{a.remove()}catch(c){console.warn("Failed to remove element:",c)}}),r===document.body&&r.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(c=>{if(c.classList.contains("bg-black")&&c.classList.contains("backdrop-blur-sm"))try{c.remove()}catch(l){console.warn("Failed to remove fixed element:",l)}})}}}removeAllUI(){var n,r;for(const[s,o]of this.renderedComponents)(r=(n=o.root).unmount)==null||r.call(n);this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(r=>{if(r.classList.contains("bg-black")&&(r.classList.contains("backdrop-blur-sm")||r.classList.contains("bg-opacity-30")))try{r.remove()}catch(s){console.warn("Failed to remove overlay:",s)}})}resolveTarget(n){if(typeof n=="string"){const r=document.querySelector(n);if(!r)throw new Error(`Target element not found: ${n}`);return r}return n}getTargetKey(n){return n.id?n.id:n.className?n.tagName+"_"+n.className.replace(/\s+/g,"_"):n.tagName+"_"+n.outerHTML.length%1e3}async sendMessage(n,r){var s;if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new ue("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new ue("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new ue("No local participant","CONNECTION_FAILED");this.dismissCurrentInteraction();try{const o={id:`msg_${Date.now()}`,content:n,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:r||{}},i=await((s=this.room)==null?void 0:s.localParticipant.sendText(n,{topic:"lk.chat",destinationIdentities:[]}));this.emit("chat.message.sent",o)}catch(o){throw console.error("VoxketClient: Failed to send chat message:",o),new ue("Failed to send message","NETWORK_ERROR",o)}}async sendChatMessage(n,r){return this.sendMessage(n,r)}async sendAttachments(n,r){if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new ue("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new ue("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new ue("No local participant","CONNECTION_FAILED");if(!n||n.length===0)throw new ue("No files provided","INVALID_PARAMETER");this.dismissCurrentInteraction();const s=n.filter(o=>o.type.startsWith("image/"));if(s.length===0)throw new ue("Only image files are allowed","INVALID_PARAMETER");s.length!==n.length&&console.warn("VoxketClient: Some non-image files were filtered out");try{const o=s.map(async(i,a)=>{const l={id:`att_${Date.now()}_${a}`,content:`📎 ${i.name}`,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:{...r,type:"attachment",fileName:i.name,fileSize:i.size,mimeType:i.type,uploading:!0}};this.emit("chat.message.sent",l);const u=await this.room.localParticipant.sendFile(i,{mimeType:i.type,topic:"images",onProgress:h=>{const g={...l,metadata:{...l.metadata,uploadProgress:h}};this.emit("chat.message.updated",g)}});try{const h=new FileReader,g=new Promise((x,w)=>{h.onload=()=>{typeof h.result=="string"?x(h.result):w(new Error("Failed to convert to base64"))},h.onerror=w});h.readAsDataURL(i);const p={type:"image",data:await g,filename:i.name,mimeType:i.type,size:i.size};await this.room.localParticipant.sendText(JSON.stringify(p),{topic:"images",destinationIdentities:[]})}catch(h){console.warn("VoxketClient: Failed to send image data to agent:",h);try{const g=`I've shared an image: ${i.name}`;await this.room.localParticipant.sendText(g,{topic:"lk.chat",destinationIdentities:[]})}catch(g){console.warn("VoxketClient: Failed to send image notification to agent:",g)}}const f={...l,metadata:{...l.metadata,uploading:!1,uploadProgress:1,streamId:u.id}};return this.emit("chat.message.updated",f),u});await Promise.all(o)}catch(o){throw console.error("VoxketClient: Failed to send attachments:",o),new ue("Failed to send attachments","NETWORK_ERROR",o)}}async sendAttachment(n,r){return this.sendAttachments([n],r)}toggleMicrophone(n){return this.setMicrophoneEnabled(n!==!1)}async setMicrophoneEnabled(n){var r,s;try{const o=(r=this.room)==null?void 0:r.localParticipant.isMicrophoneEnabled,i=n??!o;await((s=this.room)==null?void 0:s.localParticipant.setMicrophoneEnabled(i)),i?this.emit("track.unmuted",{source:"microphone",enabled:!0}):this.emit("track.muted",{source:"microphone",enabled:!1})}catch(o){throw console.error("VoxketClient: Failed to toggle microphone:",o),new ue("Failed to toggle microphone","PERMISSION_DENIED",o)}}toggleCamera(n){return this.setCameraEnabled(n!==!1)}async setCameraEnabled(n){var r,s;try{const o=(r=this.room)==null?void 0:r.localParticipant.isCameraEnabled,i=n??!o;await((s=this.room)==null?void 0:s.localParticipant.setCameraEnabled(i)),i?this.emit("track.unmuted",{source:"camera",enabled:!0}):this.emit("track.muted",{source:"camera",enabled:!1})}catch(o){throw console.error("VoxketClient: Failed to toggle camera:",o),new ue("Failed to toggle camera","PERMISSION_DENIED",o)}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!0))}catch(r){throw new ue("Failed to start screen share","PERMISSION_DENIED",r)}}async stopScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!1))}catch(r){throw new ue("Failed to stop screen share","PERMISSION_DENIED",r)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="audioinput")}catch(n){throw new ue("Failed to get audio input devices","DEVICE_ERROR",n)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch(n){throw new ue("Failed to get video input devices","DEVICE_ERROR",n)}}async setAudioInputDevice(n){var r;try{if(!((r=this.room)!=null&&r.localParticipant))throw new Error("Not connected to room")}catch(s){throw new ue("Failed to set audio input device","DEVICE_ERROR",s)}}async setVideoInputDevice(n){var r;try{if(!((r=this.room)!=null&&r.localParticipant))throw new Error("Not connected to room")}catch(s){throw new ue("Failed to set video input device","DEVICE_ERROR",s)}}getLocalParticipant(){var n;return((n=this.room)==null?void 0:n.localParticipant)??null}getRemoteParticipants(){var n;return Array.from(((n=this.room)==null?void 0:n.remoteParticipants.values())??[])}getPublishPermissions(){const n=this.getLocalParticipant();if(!n)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const r=n.permissions;if(!r)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const s=o=>!!r.canPublish&&(r.canPublishSources.length===0||r.canPublishSources.includes(o));return{camera:s(1),microphone:s(2),screenShare:s(3),data:r.canPublishData??!1}}canPublishSource(n){return this.getPublishPermissions()[n]}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===te.ConnectionState.Connected}getMicrophoneTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,r]of n.trackPublications)if(r.source===te.Track.Source.Microphone)return r.track;return null}getCameraTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,r]of n.trackPublications)if(r.source===te.Track.Source.Camera)return r.track;return null}getScreenShareTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,r]of n.trackPublications)if(r.source===te.Track.Source.ScreenShare)return r.track;return null}get isMicrophoneEnabled(){const n=this.getMicrophoneTrack();return n?!n.isMuted:!1}get isCameraEnabled(){const n=this.getCameraTrack();return n?!n.isMuted:!1}get isScreenShareEnabled(){const n=this.getScreenShareTrack();return n?!n.isMuted:!1}registerPlugin(n){this.pluginManager.register(n)}getPluginManager(){return this.pluginManager}getParticipants(){if(!this.room)return[];const n=[];return this.room.localParticipant&&n.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(r=>{n.push({id:r.identity,name:r.name||r.identity,isLocal:!1})}),n}getSessionMetrics(){var n,r;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.room)==null?void 0:r.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]}:null}updateConfig(n){this.config={...this.config,...n}}async startRecording(){var n;try{this.emit("recording.started",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(r){throw new ue("Failed to start recording","RECORDING_ERROR",r)}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(r){throw new ue("Failed to stop recording","RECORDING_ERROR",r)}}async registerFrontendRPC(n,r,s="embedded"){return this.rpcManager.registerFrontendRPC(n,r,s)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}registerEventListener(n,r){return this.on(n,r)}registerEventEmitter(n,r){if(!this.room)throw new Error("Room not available");try{this.room.registerTextStreamHandler(n,async s=>{try{const o=await s.readAll();r(o)}catch(o){console.error(`Error processing event for topic '${n}':`,o)}})}catch(s){console.warn(`VoxketClient: Handler for topic '${n}' may already be registered:`,s)}}convertMarkdownToText(n){if(!n)return"";let r=n;return r=r.replace(/\*\*(.*?)\*\*/g,"$1"),r=r.replace(/__(.*?)__/g,"$1"),r=r.replace(/\*(.*?)\*/g,"$1"),r=r.replace(/_(.*?)_/g,"$1"),r=r.replace(/~~(.*?)~~/g,"$1"),r=r.replace(/`([^`]+)`/g,"$1"),r=r.replace(/```[\s\S]*?```/g,""),r=r.replace(/^#{1,6}\s+/gm,""),r=r.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),r.trim()}}const e6=ae.create(N8),t6=ae.create(B8),n6=ae.create(U8),r6=ae.create(K8);function s6({onClick:e,text:t="Open Chat",position:n="bottom-right",theme:r}){const s={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},o=Ie(r);return d.jsx(ae.button,{onClick:e,className:`fixed ${s[n]} z-50 px-4 py-2 rounded-full shadow-lg ${o.popupTrigger} transition-all duration-200 hover:scale-105`,initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},exit:{scale:0,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},children:t})}function ad({children:e,theme:t,displayType:n="widget",onClose:r,popupPosition:s="bottom-right",onExpand:o}){const i=Ie(t);if(n==="fullscreen")return d.jsx("div",{className:"fixed inset-0 z-50 bg-black bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",children:d.jsxs("div",{className:"w-full h-full max-w-6xl max-h-[90vh] rounded-2xl relative bg-transparent",children:[r&&d.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),r()},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:d.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:d.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"})})}),d.jsxs("div",{id:"voice-card",className:`${i.card} w-full h-full flex flex-col rounded-xl shadow-2xl`,style:{minHeight:"600px"},children:[d.jsx("div",{className:i.cardTopGradient}),d.jsx("div",{className:i.cardPurpleBlur}),d.jsx("div",{className:i.cardPinkBlur}),d.jsx("div",{className:" flex flex-col h-full",children:e}),d.jsx("div",{className:i.cardPulse1}),d.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(n==="popup"){const a={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"};return d.jsx("div",{className:"fixed rounded-2xl inset-0 z-50 pointer-events-none",children:d.jsxs("div",{className:`fixed rounded-2xl ${a[s]} pointer-events-auto`,children:[r&&d.jsx("button",{onClick:r,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:"×"}),d.jsxs("div",{id:"voice-card",className:`${i.card} rounded-2xl flex flex-col`,style:{width:"300px",height:"450px"},children:[d.jsx("div",{className:i.cardPurpleBlur}),d.jsx("div",{className:i.cardPinkBlur}),d.jsx("div",{className:" flex flex-col h-full",children:e}),d.jsx("div",{className:i.cardPulse1}),d.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return d.jsxs("div",{id:"voice-card",className:`${i.card}`,children:[o&&d.jsx("button",{onClick:o,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:d.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:d.jsx("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})})}),d.jsx("div",{className:i.cardTopGradient}),d.jsx("div",{className:i.cardPurpleBlur}),d.jsx("div",{className:i.cardPinkBlur}),e,d.jsx("div",{className:i.cardPulse1}),d.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})}function em(e){if(typeof window>"u")return null;console.log("🎯 Widget component rendering with props:",{displayType:e.displayType,popupPosition:e.popupPosition,theme:e.theme});const{agentId:t,participantName:n,baseUrl:r,appSecret:s,appId:o,prompts:i,statusMessage:a,welcomeTitle:c,welcomeSubTitle:l,className:u,width:f,height:h,loadingText:g,suportsChatInput:y=!0,suportsVideoInput:p=!0,suportsScreenShare:x=!0,theme:w="vox",onSessionStart:v,onSessionEnd:S,enableSessionLogging:C=!0,onSessionLogsUpdate:E,onSessionMetricsUpdate:T,modalities:k=["voice"],displayType:j="widget",popupPosition:$="bottom-right",popupTriggerText:b="Open Chat",onPopupToggle:I,voxketClient:L,onDisplayTypeChange:Z}=e,[K,q]=m.useState(()=>L?!!L.getCurrentSession():!1),[G,z]=m.useState(!1),[P,Y]=m.useState(t||""),[R,V]=m.useState(n||"User"),[W,M]=m.useState(()=>L?L.getCurrentSession():null),[_,H]=m.useState(()=>{var ie,Mt,et;if(L){const be=L.getCurrentSession();if((ie=be==null?void 0:be.activeModalities)!=null&&ie.includes("chat"))return"chat";if((Mt=be==null?void 0:be.activeModalities)!=null&&Mt.includes("voice"))return"voice";if((et=be==null?void 0:be.activeModalities)!=null&&et.includes("video"))return"video"}return"welcome"}),[B,N]=m.useState(!1);m.useEffect(()=>{console.log("🎯 Widget displayType prop changed to:",j)},[j]),m.useEffect(()=>{console.log("📊 Session state changed:",{currentMode:_,sessionStarted:K,loading:G,currentSession:W==null?void 0:W.id,isPopupOpen:B})},[_,K,G,W,B]);const F=m.useMemo(()=>{if(L)return console.log("🔄 Using passed VoxketClient to preserve session state"),L;console.log("🆕 Creating new VoxketClient instance");const ie={appId:o,appSecret:s,baseUrl:r,agentId:P,participantName:R||"User",modalities:k};return new Ar(ie)},[L,o,s,r,P,R,k]),U=k,O=m.useMemo(()=>F.getRoom()||new te.Room,[F]),J={suportsChatInput:y,suportsVideoInput:p,suportsScreenShare:x},{sessionMetrics:X,sessionLogs:se,logEvent:me}=qh({room:O,onSessionStart:v,onSessionEnd:S,enableConsoleLogging:C,enableLocalStorage:C,voxketSessionId:W==null?void 0:W.id});m.useEffect(()=>{E&&E(se)},[se,E]),m.useEffect(()=>{T&&X&&T(X)},[X,T]),m.useEffect(()=>{const ie=et=>{console.log("🔴 Room disconnected:",et),z(!1),q(!1),M(null),H("welcome")},Mt=et=>{console.log("📹 Media devices error:",et),Dr({title:"Allow access to your microphone/camera",description:`${et.name}: ${et.message}`})};return O.on(te.RoomEvent.MediaDevicesError,Mt),O.on(te.RoomEvent.Disconnected,ie),()=>{O.off(te.RoomEvent.Disconnected,ie),O.off(te.RoomEvent.MediaDevicesError,Mt)}},[O]);const $e=async()=>{try{console.log("🎤 Starting voice session...",{agentId:P,participantName:R}),console.log("🎤 Pre-start state:",{currentMode:_,sessionStarted:K,loading:G}),z(!0),q(!0),H("voice"),console.log("🎤 State after mode change:",{currentMode:"voice",sessionStarted:!0,loading:!0}),me("USER_STARTED_VOICE_SESSION",{agentId:P,participantName:R});const ie=await F.startSession(P,{participantName:R||"User",modalities:["voice",...p?["video"]:[]]});console.log("✅ Voice session started successfully:",ie.id),M(ie),z(!1),v&&v(ie.id)}catch(ie){console.error("❌ Failed to start voice session:",ie),Dr({title:"Failed to start voice session",description:ie instanceof Error?ie.message:"Unknown error occurred"}),z(!1),q(!1),H("welcome")}},at=async()=>{try{z(!0),q(!0),H("chat"),me("USER_STARTED_CHAT_SESSION",{agentId:P,participantName:R});const ie=await F.startSession(P,{participantName:R||"User",modalities:["chat"]});M(ie),z(!1),v&&v(ie.id)}catch(ie){console.error("Failed to start chat session:",ie),Dr({title:"Failed to start chat session",description:ie instanceof Error?ie.message:"Unknown error occurred"}),z(!1),q(!1),H("welcome")}},Ut=async()=>{try{console.log("📺 Starting video session...",{agentId:P,participantName:R}),console.log("📺 Pre-start state:",{currentMode:_,sessionStarted:K,loading:G}),z(!0),q(!0),H("video"),console.log("📺 State after mode change:",{currentMode:"video",sessionStarted:!0,loading:!0}),me("USER_STARTED_VIDEO_SESSION",{agentId:P,participantName:R});const ie=await F.startSession(P,{participantName:R||"User",modalities:["video","voice"]});console.log("✅ Video session started successfully:",ie.id),M(ie),z(!1),v&&v(ie.id)}catch(ie){console.error("❌ Failed to start video session:",ie),Dr({title:"Failed to start video session",description:ie instanceof Error?ie.message:"Unknown error occurred"}),z(!1),q(!1),H("welcome")}},Wt=()=>{H("welcome"),Z&&Z(e.displayType||"widget"),W&&K&&(q(!1),M(null),F.disconnect()),j==="popup"&&!B&&N(!0)},ct=()=>{const ie=!B;N(ie),I&&I(ie),!ie&&!(W&&K)&&(H("welcome"),q(!1),M(null))},ym=()=>{console.log("🔄 Closing fullscreen, switching to widget display type"),e.onDisplayTypeChange?e.onDisplayTypeChange("widget"):console.warn("⚠️ No onDisplayTypeChange callback provided")},xm=()=>{e.onDisplayTypeChange&&e.onDisplayTypeChange("fullscreen")};m.useEffect(()=>{var ie,Mt,et;if(L&&F){console.log("🔄 Syncing widget state with existing client session state");const be=F.getCurrentSession(),bm=F.connected;console.log("🔍 Existing session state:",{hasSession:!!be,sessionId:be==null?void 0:be.id,isConnected:bm,activeModalities:be==null?void 0:be.activeModalities}),be&&(console.log("✅ Restoring session state from existing client"),M(be),q(!0),z(!1),(ie=be.activeModalities)!=null&&ie.includes("chat")?H("chat"):(Mt=be.activeModalities)!=null&&Mt.includes("voice")?H("voice"):(et=be.activeModalities)!=null&&et.includes("video")&&H("video"))}},[L,F]),m.useEffect(()=>()=>{console.log("🧹 Cleaning up widget component"),L?console.log("🔄 Widget cleanup: preserving passed client instance"):(console.log("🧹 Widget cleanup: disconnecting self-created client"),F.disconnect())},[F,L]);let Bs="w-96",Hs="h-[25rem]",zs={};if(f&&(f.startsWith("w-")?Bs=f:(zs.width=f,Bs="")),h&&(h.startsWith("h-")?Hs=h:(zs.height=h,Hs="")),j==="popup"&&!B)return console.log("🟡 Showing popup trigger button"),d.jsx(s6,{onClick:ct,text:b,position:$,theme:w});console.log("🟢 Rendering widget content, displayType:",j,"isPopupOpen:",B,"currentMode:",_,"sessionStarted:",K,"loading:",G);let Us=`voxket-widget-root theme-${w}`,jr={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};j==="widget"?(Us+=` flex items-center justify-center min-h-fit ${Bs} ${Hs} ${u}`,jr={...jr,...zs}):(Us=`${u||""}`,jr={});const Ia=d.jsx(d.Fragment,{children:d.jsxs(Cn,{mode:"wait",children:[_==="welcome"&&!G&&d.jsx(r6,{agentId:P,participantName:R||"",onAgentIdChange:Y,onParticipantNameChange:V,onStartCall:$e,onStartChat:at,onStartVideo:Ut,disabled:K||G,prompts:i,statusMessage:a,title:c,subTitle:l,theme:w,modalities:U,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),_==="voice"&&d.jsxs(Ee.RoomContext.Provider,{value:O,children:[d.jsx(Ee.RoomAudioRenderer,{}),d.jsx(Ee.StartAudio,{label:"Start Audio"}),d.jsx(e6,{loadingText:g,participantName:R||"User",capabilities:J,sessionStarted:K,disabled:!K,theme:w,client:F,displayType:j,onBack:j==="popup"?ct:Wt,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"session-view")]}),_==="chat"&&d.jsx(t6,{client:F,theme:w,displayType:j,onBack:j==="popup"?ct:Wt,onEndChat:Wt,disabled:!K,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),_==="video"&&d.jsxs(Ee.RoomContext.Provider,{value:O,children:[d.jsx(Ee.RoomAudioRenderer,{}),d.jsx(Ee.StartAudio,{label:"Start Audio"}),d.jsx(n6,{client:F,theme:w,displayType:j,onBack:j==="popup"?ct:Wt,onEndCall:Wt,disabled:!K,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-view")]})]})});return j==="fullscreen"||j==="popup"?(console.log("📱 Rendering fullscreen/popup mode, displayType:",j),d.jsx(ad,{theme:w,displayType:j,popupPosition:$,onClose:j==="fullscreen"?ym:ct,children:Ia})):(console.log("📦 Rendering widget mode"),d.jsx("div",{className:Us,style:jr,children:d.jsx(ad,{theme:w,displayType:j,popupPosition:$,onExpand:xm,children:Ia})}))}class tm extends m.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("VoxketWidget Error:",t,n)}render(){if(this.state.hasError){if(this.props.fallback){const t=this.props.fallback;return m.createElement(t,{error:this.state.error})}return m.createElement("div",{style:{padding:"20px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"}},"VoxketWidget encountered an error. Please check the console for details.")}return this.props.children}}function o6({logs:e,onClear:t,onExport:n}){const[r,s]=A.useState(!1),[o,i]=A.useState(""),a=e.filter(c=>!o||c.event.toLowerCase().includes(o.toLowerCase()));return r?d.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:d.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[d.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[d.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"text",placeholder:"Filter events...",value:o,onChange:c=>i(c.target.value),className:"px-3 py-1 border rounded text-sm"}),d.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),d.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),d.jsx("button",{onClick:()=>s(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),d.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?d.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):d.jsx("div",{className:"space-y-2",children:a.map((c,l)=>d.jsxs("div",{className:"border rounded p-3 text-sm",children:[d.jsxs("div",{className:"flex items-center justify-between mb-1",children:[d.jsx("span",{className:"font-semibold text-blue-600",children:c.event}),d.jsx("span",{className:"text-gray-500 text-xs",children:new Date(c.timestamp).toLocaleTimeString()})]}),c.sessionId&&d.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",c.sessionId]}),c.data&&d.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:d.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(c.data,null,2)})})]},l))})})]})}):d.jsxs("button",{onClick:()=>s(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",e.length,")"]})}function i6({metrics:e}){return e?d.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[d.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),d.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[d.jsxs("div",{children:[d.jsx("span",{className:"text-gray-600",children:"Session ID:"}),d.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),d.jsxs("div",{children:[d.jsx("span",{className:"text-gray-600",children:"Start Time:"}),d.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),d.jsxs("div",{children:[d.jsx("span",{className:"text-gray-600",children:"Messages:"}),d.jsx("div",{children:e.totalMessages})]}),d.jsxs("div",{children:[d.jsx("span",{className:"text-gray-600",children:"Participants:"}),d.jsx("div",{children:e.participantCount})]}),d.jsxs("div",{children:[d.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),d.jsx("div",{children:e.connectionIssues})]}),d.jsxs("div",{children:[d.jsx("span",{className:"text-gray-600",children:"Duration:"}),d.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function cn(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:r,endSession:s}=bt(),o=A.useCallback(async(a,c)=>await r(a,c),[r]),i=A.useCallback(async()=>await s(),[s]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:o,stop:i}}function nm(){const{sessionMetrics:e,currentSession:t}=bt();return{metrics:e,sessionId:t==null?void 0:t.id,duration:e==null?void 0:e.duration,participantCount:e==null?void 0:e.participantCount,messageCount:e==null?void 0:e.messageCount,audioQuality:e==null?void 0:e.audioQuality,networkStats:e==null?void 0:e.networkStats}}function rm(){const{setMicrophoneEnabled:e,client:t}=bt(),[n,r]=A.useState(!1),[s,o]=A.useState(!1),i=A.useCallback(async()=>{if(!s){o(!0);try{const l=!n;await e(l),r(l)}catch(l){console.error("Failed to toggle microphone:",l)}finally{o(!1)}}},[n,s,e]),a=A.useCallback(async()=>{if(!(n||s)){o(!0);try{await e(!0),r(!0)}catch(l){console.error("Failed to enable microphone:",l)}finally{o(!1)}}},[n,s,e]),c=A.useCallback(async()=>{if(!(!n||s)){o(!0);try{await e(!1),r(!1)}catch(l){console.error("Failed to disable microphone:",l)}finally{o(!1)}}},[n,s,e]);return{isEnabled:n,isLoading:s,toggle:i,enable:a,disable:c}}function sm(){const{setCameraEnabled:e}=bt(),[t,n]=A.useState(!1),[r,s]=A.useState(!1),o=A.useCallback(async()=>{if(!r){s(!0);try{const c=!t;await e(c),n(c)}catch(c){console.error("Failed to toggle camera:",c)}finally{s(!1)}}},[t,r,e]),i=A.useCallback(async()=>{if(!(t||r)){s(!0);try{await e(!0),n(!0)}catch(c){console.error("Failed to enable camera:",c)}finally{s(!1)}}},[t,r,e]),a=A.useCallback(async()=>{if(!(!t||r)){s(!0);try{await e(!1),n(!1)}catch(c){console.error("Failed to disable camera:",c)}finally{s(!1)}}},[t,r,e]);return{isEnabled:t,isLoading:r,toggle:o,enable:i,disable:a}}function om(){const{startScreenShare:e,stopScreenShare:t}=bt(),[n,r]=A.useState(!1),[s,o]=A.useState(!1),i=A.useCallback(async()=>{if(!(n||s)){o(!0);try{await e(),r(!0)}catch(l){console.error("Failed to start screen share:",l)}finally{o(!1)}}},[n,s,e]),a=A.useCallback(async()=>{if(!(!n||s)){o(!0);try{await t(),r(!1)}catch(l){console.error("Failed to stop screen share:",l)}finally{o(!1)}}},[n,s,t]),c=A.useCallback(async()=>{n?await a():await i()},[n,i,a]);return{isSharing:n,isLoading:s,start:i,stop:a,toggle:c}}function a6(){const{client:e}=bt(),[t,n]=A.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),r=A.useMemo(()=>t.tracks.find(p=>p.isLocal),[t.tracks]),s=A.useMemo(()=>t.tracks.filter(p=>!p.isLocal),[t.tracks]),o=A.useCallback(async()=>{try{r!=null&&r.isEnabled?await(e==null?void 0:e.disableCamera()):await(e==null?void 0:e.enableCamera())}catch(p){throw console.error("Failed to toggle camera:",p),p}},[e,r]),i=A.useCallback(async()=>{try{t.tracks.find(x=>x.isScreenShare)?await(e==null?void 0:e.stopScreenShare()):await(e==null?void 0:e.startScreenShare())}catch(p){throw console.error("Failed to toggle screen share:",p),p}},[e,t.tracks]),a=A.useCallback(p=>{n(x=>({...x,layout:p}))},[]),c=A.useCallback(p=>{n(x=>({...x,pinnedTrack:p}))},[]),l=A.useCallback(()=>{n(p=>({...p,pinnedTrack:void 0}))},[]),u=A.useCallback(async()=>{try{await(e==null?void 0:e.startRecording()),n(p=>({...p,isRecording:!0}))}catch(p){throw console.error("Failed to start recording:",p),p}},[e]),f=A.useCallback(async()=>{try{await(e==null?void 0:e.stopRecording()),n(p=>({...p,isRecording:!1}))}catch(p){throw console.error("Failed to stop recording:",p),p}},[e]),h=A.useCallback(p=>t.tracks.find(x=>x.id===p),[t.tracks]),g=A.useCallback(p=>t.tracks.filter(x=>x.participantId===p),[t.tracks]),y=A.useCallback(p=>p.isEnabled&&t.tracks.includes(p),[t.tracks]);return A.useEffect(()=>{if(!e)return;const p=v=>{n(S=>({...S,tracks:[...S.tracks.filter(C=>C.id!==v.id),v]}))},x=v=>{n(S=>{var C;return{...S,tracks:S.tracks.filter(E=>E.id!==v),pinnedTrack:((C=S.pinnedTrack)==null?void 0:C.id)===v?void 0:S.pinnedTrack}})},w=v=>{n(S=>({...S,tracks:S.tracks.map(C=>C.id===v.id?v:C)}))};return e.on("videoTrackAdded",p),e.on("videoTrackRemoved",x),e.on("videoTrackUpdated",w),()=>{e.off("videoTrackAdded",p),e.off("videoTrackRemoved",x),e.off("videoTrackUpdated",w)}},[e]),{tracks:t.tracks,localTrack:r,remoteTraracks:s,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:o,toggleScreenShare:i,setLayout:a,pinTrack:c,unpinTrack:l,startRecording:u,stopRecording:f,getTrackById:h,getTracksByParticipant:g,isTrackActive:y}}function _s(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=bt(),[r,s]=A.useState(!1),o=A.useCallback(async l=>{if(!(!l.trim()||r||!n)){s(!0);try{await t(l.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{s(!1)}}},[t,r,n]),{userMessages:i,agentMessages:a,allMessages:c}=A.useMemo(()=>{const l=e.filter(f=>f.sender.type==="participant"),u=e.filter(f=>f.sender.type==="agent");return{userMessages:l,agentMessages:u,allMessages:e}},[e]);return{messages:c,userMessages:i,agentMessages:a,messageCount:c.length,isSending:r,canSend:!!n&&!r,send:o}}function c6(){const{send:e,isSending:t,canSend:n}=_s(),[r,s]=A.useState(""),o=A.useCallback(async()=>{if(!(!r.trim()||!n))try{await e(r),s("")}catch(a){throw a}},[r,e,n]),i=A.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),o())},[o]);return{value:r,setValue:s,send:o,handleKeyPress:i,isSending:t,canSend:n&&r.trim().length>0}}function Ma(){const{isConnected:e,isConnecting:t,connectionError:n,connect:r,disconnect:s}=bt(),o=A.useCallback(async()=>{if(!(e||t))try{await r()}catch(a){throw console.error("Failed to connect:",a),a}},[r,e,t]),i=A.useCallback(async()=>{if(e)try{await s()}catch(a){throw console.error("Failed to disconnect:",a),a}},[s,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:o,disconnect:i}}function im(){const{participants:e}=bt();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const am=A.createContext({}),Tr=()=>A.useContext(am);function cm({children:e,...t}){return d.jsx(am.Provider,{value:t,children:e})}function Qr({name:e,children:t,fallback:n,className:r}){return d.jsx("div",{className:`voxket-slot voxket-slot--${e} ${r||""}`,children:t||n})}function lm(e,t={}){return Object.assign(e,t)}function dm({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:r=!0,customControls:s,className:o=""}){const i=cn(),a=rm(),c=sm(),l=om(),u=Tr(),f=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,i.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",o].filter(Boolean).join(" ");return!i.isActive&&!r?d.jsx("div",{className:f,children:d.jsx("div",{className:"voxket-controls-inactive",children:d.jsx("p",{children:"Controls available during active session"})})}):d.jsxs("div",{className:f,children:[r&&d.jsx("div",{className:"voxket-session-actions",children:i.isActive?d.jsx("button",{onClick:i.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):d.jsx(l6,{})}),i.isActive&&d.jsxs("div",{className:"voxket-media-controls",children:[e&&d.jsxs("button",{onClick:a.toggle,disabled:a.isLoading,className:`voxket-button voxket-button--media ${a.isEnabled?"voxket-button--active":""}`,title:a.isEnabled?"Mute microphone":"Unmute microphone",children:[d.jsx("span",{className:"voxket-icon",children:"🎤"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&d.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isEnabled?"voxket-button--active":""}`,title:c.isEnabled?"Stop camera":"Start camera",children:[d.jsx("span",{className:"voxket-icon",children:"📹"}),c.isLoading?"Loading...":c.isEnabled?"Stop Video":"Start Video"]}),n&&d.jsxs("button",{onClick:l.toggle,disabled:l.isLoading,className:`voxket-button voxket-button--media ${l.isSharing?"voxket-button--active":""}`,title:l.isSharing?"Stop screen share":"Start screen share",children:[d.jsx("span",{className:"voxket-icon",children:"🖥️"}),l.isLoading?"Loading...":l.isSharing?"Stop Share":"Share Screen"]})]}),s&&d.jsx("div",{className:"voxket-custom-controls",children:s})]})}function l6(){cn();const[e,t]=A.useState(!1),n=async()=>{t(!0);try{console.log("Start session - agentId needed")}catch(r){console.error("Failed to start session:",r)}finally{t(!1)}};return d.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function Na({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:r=""}){const s=cn(),o=Ma(),i=Tr(),a=["voxket-session-header",`voxket-session-header--${i.variant||"default"}`,`voxket-session-header--${i.size||"md"}`,r].filter(Boolean).join(" ");return d.jsxs("div",{className:a,children:[e&&d.jsxs("div",{className:"voxket-connection-status",children:[d.jsx("div",{className:`voxket-status-indicator ${o.isConnected?"connected":"disconnected"}`}),d.jsx("span",{className:"voxket-status-text",children:o.isConnecting?"Connecting...":o.isConnected?"Connected":"Disconnected"})]}),t&&s.session&&d.jsxs("div",{className:"voxket-session-info",children:[d.jsxs("div",{className:"voxket-session-id",children:["Session: ",s.session.id.slice(-8)]}),d.jsxs("div",{className:"voxket-session-state",children:["State: ",s.state]})]}),n&&s.session&&d.jsxs("div",{className:"voxket-agent-info",children:[d.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",s.session.agentId]}),d.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",s.session.activeModalities.join(", ")]})]}),o.error&&d.jsxs("div",{className:"voxket-error-message",children:["Error: ",o.error.message]})]})}function Ra({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:r=""}){const s=cn(),o=_s(),i=Tr(),a=["voxket-session-content",`voxket-session-content--${i.variant||"default"}`,`voxket-session-content--${i.size||"md"}`,r].filter(Boolean).join(" ");return s.isActive?d.jsx("div",{className:a,children:n||d.jsxs(d.Fragment,{children:[e&&d.jsxs("div",{className:"voxket-chat-container",children:[d.jsxs("div",{className:"voxket-chat-messages",children:[o.messages.map(c=>d.jsxs("div",{className:`voxket-message voxket-message--${c.sender.type}`,children:[d.jsxs("div",{className:"voxket-message-header",children:[d.jsx("span",{className:"voxket-message-sender",children:c.sender.name}),d.jsx("span",{className:"voxket-message-time",children:c.timestamp.toLocaleTimeString()})]}),d.jsx("div",{className:"voxket-message-content",children:c.content})]},c.id)),o.messages.length===0&&d.jsx("div",{className:"voxket-empty-messages",children:d.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),d.jsx(d6,{})]}),t&&d.jsx("div",{className:"voxket-transcriptions",children:d.jsx("div",{className:"voxket-transcription-placeholder",children:d.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):d.jsx("div",{className:a,children:d.jsx("div",{className:"voxket-inactive-state",children:d.jsxs("div",{className:"voxket-inactive-message",children:[d.jsx("h3",{children:"Start a conversation"}),d.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function d6(){const e=_s(),[t,n]=A.useState(""),r=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(o){console.error("Failed to send message:",o)}},s=o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),r())};return d.jsxs("div",{className:"voxket-chat-input",children:[d.jsx("input",{type:"text",value:t,onChange:o=>n(o.target.value),onKeyPress:s,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),d.jsx("button",{onClick:r,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function Va({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:r,className:s=""}){const o=cn(),i=nm(),a=im(),c=Tr(),l=["voxket-session-footer",`voxket-session-footer--${c.variant||"default"}`,`voxket-session-footer--${c.size||"md"}`,s].filter(Boolean).join(" ");return o.isActive?d.jsx("div",{className:l,children:r||d.jsxs(d.Fragment,{children:[n&&d.jsxs("div",{className:"voxket-session-status",children:[d.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),d.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&i.metrics&&d.jsxs("div",{className:"voxket-session-metrics",children:[d.jsxs("div",{className:"voxket-metric",children:[d.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),d.jsx("span",{className:"voxket-metric-value",children:u6(i.duration||0)})]}),d.jsxs("div",{className:"voxket-metric",children:[d.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),d.jsx("span",{className:"voxket-metric-value",children:i.metrics.messageCount})]})]}),t&&d.jsxs("div",{className:"voxket-participants-info",children:[d.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&d.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>d.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):d.jsx("div",{className:l,children:d.jsx("div",{className:"voxket-footer-inactive",children:d.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function u6(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60);return r>0?`${r}:${(n%60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}`:`${n}:${(t%60).toString().padStart(2,"0")}`}function f6({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:r,onSessionEnd:s,variant:o="default",size:i="md",theme:a,className:c="",children:l}){var g;const u=cn(),f=Ma();A.useEffect(()=>{n&&e&&f.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,f.isConnected,u.isActive]),A.useEffect(()=>{var y;(y=u.session)!=null&&y.id&&r&&r(u.session.id)},[(g=u.session)==null?void 0:g.id,r]),A.useEffect(()=>()=>{u.isActive&&s&&u.stop().then(s).catch(console.error)},[]);const h=["voxket-session",`voxket-session--${o}`,`voxket-session--${i}`,u.isActive?"voxket-session--active":"voxket-session--inactive",c].filter(Boolean).join(" ");return d.jsx(cm,{variant:o,size:i,theme:a,className:c,children:d.jsx("div",{className:h,children:l||d.jsxs(d.Fragment,{children:[d.jsx(Qr,{name:"header",fallback:d.jsx(Na,{})}),d.jsx(Qr,{name:"content",fallback:d.jsx(Ra,{})}),d.jsx(Qr,{name:"footer",fallback:d.jsx(Va,{})})]})})})}const um=lm(f6,{Header:Na,Content:Ra,Footer:Va,Controls:dm}),tn={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)"}},bi={...tn,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)"}},vi={...tn,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"}},fm=A.createContext(null),hm=()=>{const e=A.useContext(fm);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function h6({theme:e="default",themes:t={},children:n,cssVariables:r=!0,className:s=""}){const[o,i]=A.useState(()=>{const h={default:tn,dark:bi,enterprise:vi,...t};return typeof e=="string"?h[e]||tn:e}),[a,c]=A.useState(()=>({default:tn,dark:bi,enterprise:vi,...t})),l=h=>{if(typeof h=="string"){const g=a[h];g&&i(g)}else i(h)},u=h=>{c(g=>({...g,[h.name]:h}))};A.useEffect(()=>{if(r&&typeof document<"u"){const h=document.documentElement;Object.entries(mm(o)).forEach(([g,y])=>{h.style.setProperty(`--voxket-${g}`,y)})}},[o,r]);const f={theme:o,setTheme:l,themes:a,registerTheme:u};return d.jsx(fm.Provider,{value:f,children:d.jsx("div",{className:`voxket-theme voxket-theme--${o.name} ${s}`,children:n})})}function mm(e){const t={},n=(r,s="")=>{for(const[o,i]of Object.entries(r)){const a=s?`${s}-${o}`:o;typeof i=="object"&&i!==null&&!Array.isArray(i)?n(i,a):t[a]=String(i)}};return n(e),t}function m6(e=tn,t){return{...e,...t,colors:{...e.colors,...t.colors},typography:{...e.typography,...t.typography},spacing:{...e.spacing,...t.spacing},borderRadius:{...e.borderRadius,...t.borderRadius},shadows:{...e.shadows,...t.shadows}}}function p6(e){var n;const{theme:t}=hm();return((n=t.components)==null?void 0:n[e])||{}}const g6=Pa("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&y6(e),t.enableVoiceActivation&&x6(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&b6(e,t)}});function y6(e,t){e.on("participant.speaking.started",n=>{console.log("Transcription: Started for",n.name)}),e.on("participant.speaking.stopped",n=>{console.log("Transcription: Stopped for",n.name)})}function x6(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function b6(e,t){console.log("Playing audio response:",t.content)}const v6=Pa("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&w6(),t.enableFileUpload&&S6(e),t.enableCustomComponents&&C6(),console.log("Chat modality activated",t)},onDeactivate:async e=>{console.log("Chat modality deactivated")},onMessage:async(e,t)=>{const n=e.config;t.type==="ui_component"?k6(e,t):t.type==="text"&&n.enableRichText&&E6(e,t)}});function w6(e){console.log("Rich text support enabled")}function S6(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function C6(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",A6),t.set("form",T6),t.set("card",j6),t.set("chart",P6)}function k6(e,t){const{componentType:n,props:r}=t.metadata;console.log("Rendering custom component:",n,r),e.emit("chat.component.render",{type:n,props:r,timestamp:new Date})}function E6(e,t){console.log("Processing rich text message:",t.content)}function A6(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function T6(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function j6(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function P6(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function es({track:e,participantName:t,showControls:n=!0,showName:r=!0,showMuteIndicator:s=!0,isPinned:o=!1,className:i="",onClick:a,onPin:c,onUnpin:l}){const u=A.useRef(null),[f,h]=A.useState(!1);A.useEffect(()=>{if(!u.current||!e.isEnabled)return;const x=u.current;return x.srcObject=null,()=>{x.srcObject&&(x.srcObject=null)}},[e]);const g=()=>{a==null||a(e)},y=x=>{x.stopPropagation(),o?l==null||l(e):c==null||c(e)},p=["voxket-video-tile",e.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",e.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",o?"voxket-video-tile--pinned":"",e.isEnabled?"":"voxket-video-tile--disabled",f?"voxket-video-tile--hovered":"",i].filter(Boolean).join(" ");return d.jsxs("div",{className:p,onClick:g,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[d.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&d.jsxs("div",{className:"voxket-video-placeholder",children:[d.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"🖥️":"📹"}),d.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),d.jsxs("div",{className:"voxket-video-overlay",children:[r&&t&&d.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),s&&!e.isEnabled&&d.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),n&&(f||o)&&d.jsxs("div",{className:"voxket-video-controls",children:[d.jsx("button",{className:`voxket-video-control-btn ${o?"voxket-video-control-btn--active":""}`,onClick:y,title:o?"Unpin video":"Pin video",children:"📌"}),e.isScreenShare&&d.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),e.source&&d.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&d.jsx("div",{className:"voxket-video-loading",children:d.jsx("div",{className:"voxket-spinner"})})]})}function M6({tracks:e,layout:t,className:n="",onLayoutChange:r,onTrackClick:s,maxVisibleTracks:o=9,showPagination:i=!0}){const[a,c]=A.useState(0),[l,u]=A.useState(null),f=A.useMemo(()=>{let v=[...e];t.type==="speaker"&&l&&(v=[l,...e.filter(E=>E.id!==l.id)]);const S=a*o,C=S+o;return v.slice(S,C)},[e,t,l,a,o]),h=Math.ceil(e.length/o),g=A.useMemo(()=>{const v=f.length;switch(t.type){case"grid":const S=Math.ceil(Math.sqrt(v)),C=Math.ceil(v/S);return{display:"grid",gridTemplateColumns:`repeat(${S}, 1fr)`,gridTemplateRows:`repeat(${C}, 1fr)`,gap:"8px"};case"speaker":return{display:"flex",flexDirection:"column",gap:"8px"};case"sidebar":return{display:"flex",gap:"8px"};case"gallery":return{display:"flex",flexWrap:"wrap",gap:"8px",justifyContent:"center"};default:return{}}},[t.type,f.length]),y=v=>{u(v)},p=()=>{u(null)},x=v=>{r==null||r({...t,type:v})},w=["voxket-video-grid",`voxket-video-grid--${t.type}`,`voxket-video-grid--${f.length}-tracks`,n].filter(Boolean).join(" ");return e.length===0?d.jsx("div",{className:"voxket-video-grid-empty",children:d.jsxs("div",{className:"voxket-video-grid-empty-content",children:[d.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),d.jsx("p",{children:"No video tracks available"})]})}):d.jsxs("div",{className:w,children:[d.jsxs("div",{className:"voxket-video-grid-controls",children:[d.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(v=>d.jsx("button",{className:`voxket-layout-btn ${t.type===v?"voxket-layout-btn--active":""}`,onClick:()=>x(v),title:`Switch to ${v} layout`,children:N6(v)},v))}),d.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),d.jsx("div",{className:"voxket-video-grid-content",style:g,children:t.type==="speaker"&&l?d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"voxket-video-speaker-main",children:d.jsx(es,{track:l,participantName:`Participant ${l.participantId}`,isPinned:!0,onClick:s,onUnpin:p})}),d.jsx("div",{className:"voxket-video-speaker-sidebar",children:f.filter(v=>v.id!==l.id).map(v=>d.jsx(es,{track:v,participantName:`Participant ${v.participantId}`,showControls:!1,onClick:s,onPin:y},v.id))})]}):f.map(v=>d.jsx(es,{track:v,participantName:`Participant ${v.participantId}`,isPinned:(l==null?void 0:l.id)===v.id,onClick:s,onPin:y,onUnpin:p},v.id))}),i&&h>1&&d.jsxs("div",{className:"voxket-video-pagination",children:[d.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.max(0,a-1)),disabled:a===0,children:"←"}),d.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",h]}),d.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.min(h-1,a+1)),disabled:a===h-1,children:"→"})]})]})}function N6(e){switch(e){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function R6({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:r,showLayoutControls:s=!0,showCameraControls:o=!0,showScreenShareControls:i=!0,className:a=""}){const c=["voxket-video-controls",a].filter(Boolean).join(" "),l=u=>{r==null||r({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return d.jsxs("div",{className:c,children:[o&&d.jsxs("div",{className:"voxket-video-controls-section",children:[d.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),d.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isEnabled?"voxket-control-btn--active":""}`,onClick:t,title:e!=null&&e.isEnabled?"Turn off camera":"Turn on camera",children:[d.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"📹":"📷"}),d.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&d.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," × ",e.dimensions.height]})]}),i&&d.jsxs("div",{className:"voxket-video-controls-section",children:[d.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),d.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isScreenShare?"voxket-control-btn--active":""}`,onClick:n,title:e!=null&&e.isScreenShare?"Stop screen sharing":"Start screen sharing",children:[d.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"🛑":"🖥️"}),d.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),s&&d.jsxs("div",{className:"voxket-video-controls-section",children:[d.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),d.jsx("div",{className:"voxket-layout-buttons",children:[{type:"grid",icon:"⊞",label:"Grid"},{type:"speaker",icon:"🎤",label:"Speaker"},{type:"sidebar",icon:"⫸",label:"Sidebar"},{type:"gallery",icon:"⊡",label:"Gallery"}].map(({type:u,icon:f,label:h})=>d.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>l(u),title:`Switch to ${h} layout`,children:[d.jsx("span",{className:"voxket-control-icon",children:f}),d.jsx("span",{className:"voxket-control-label",children:h})]},u))})]}),d.jsxs("div",{className:"voxket-video-controls-section",children:[d.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),d.jsxs("div",{className:"voxket-video-settings",children:[d.jsxs("div",{className:"voxket-setting-group",children:[d.jsx("label",{className:"voxket-setting-label",children:"Quality"}),d.jsxs("select",{className:"voxket-setting-select",children:[d.jsx("option",{value:"high",children:"High (720p)"}),d.jsx("option",{value:"medium",children:"Medium (480p)"}),d.jsx("option",{value:"low",children:"Low (240p)"})]})]}),d.jsxs("div",{className:"voxket-setting-group",children:[d.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),d.jsxs("select",{className:"voxket-setting-select",children:[d.jsx("option",{value:"30",children:"30 fps"}),d.jsx("option",{value:"15",children:"15 fps"}),d.jsx("option",{value:"10",children:"10 fps"})]})]}),d.jsxs("div",{className:"voxket-setting-group",children:[d.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),d.jsxs("select",{className:"voxket-setting-select",children:[d.jsx("option",{value:"unlimited",children:"Unlimited"}),d.jsx("option",{value:"1000",children:"1 Mbps"}),d.jsx("option",{value:"500",children:"500 Kbps"}),d.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),d.jsxs("div",{className:"voxket-video-controls-section",children:[d.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),d.jsxs("div",{className:"voxket-video-stats",children:[d.jsxs("div",{className:"voxket-stat-item",children:[d.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),d.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}×${e.dimensions.height}`:"N/A"})]}),d.jsxs("div",{className:"voxket-stat-item",children:[d.jsx("span",{className:"voxket-stat-label",children:"Source:"}),d.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),d.jsxs("div",{className:"voxket-stat-item",children:[d.jsx("span",{className:"voxket-stat-label",children:"Status:"}),d.jsx("span",{className:`voxket-stat-value ${e!=null&&e.isEnabled?"voxket-stat-value--active":"voxket-stat-value--inactive"}`,children:e!=null&&e.isEnabled?"Active":"Inactive"})]})]})]})]})}const pm=({handler:e,loadData:t,data:n,client:r,addLocalMessage:s})=>{const[o,i]=m.useState(null),[a,c]=m.useState(!0),[l,u]=m.useState(!1),[f]=m.useState(Date.now());m.useEffect(()=>{(async()=>{try{if(c(!0),console.log("📋 AssignmentView: Loading assignment data..."),console.log("📋 AssignmentView: Received data from RPC:",n),n&&typeof n=="object"){const x={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};i(x),console.log("📋 AssignmentView: Assignment loaded from RPC data:",x)}}catch(x){console.error("📋 AssignmentView: Error loading assignment:",x),i({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{c(!1)}})()},[n,t]);const h=({message:p,assignment:x})=>{const w=p.toLowerCase().includes("declined"),v=w?"bg-red-50 border-red-200":"bg-green-50 border-green-200",S=w?"text-red-700":"text-green-700",C=w?"❌":"🎉";return d.jsxs("div",{className:`max-w-sm mx-auto ${v} border rounded-lg shadow p-3 flex flex-col items-center`,children:[d.jsx("div",{className:"text-2xl mb-2",children:C}),d.jsx("div",{className:`${S} font-semibold text-sm mb-1`,children:p}),d.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:x.title}),d.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},g=async()=>{if(!(!o||!e)){u(!0);try{const p={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",p),e.didSuccess(p,d.jsx(h,{message:"Assignment accepted!",assignment:o}))}catch(p){console.error("📋 AssignmentView: Error accepting assignment:",p),e.didFail({error:"Failed to accept assignment"})}finally{u(!1)}}},y=async()=>{if(!(!o||!e)){u(!0);try{const p={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",p),e.didSuccess(p,d.jsx(h,{message:"Assignment declined",assignment:o}))}catch(p){console.error("📋 AssignmentView: Error declining assignment:",p),e.didFail({error:"Failed to decline assignment"})}finally{u(!1)}}};return a?d.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:d.jsxs("div",{className:"flex items-center justify-center py-4",children:[d.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),d.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):o?d.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[d.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:d.jsx("div",{className:"flex items-center justify-between",children:d.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:o.title})})}),d.jsxs("div",{className:"p-3",children:[d.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:d.jsx("p",{className:"text-xs text-gray-700 leading-snug",children:o.description})}),d.jsx("div",{className:"mb-3",children:d.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[d.jsx("span",{className:"text-xs mr-1",children:"📅"}),d.jsxs("span",{children:["Est: ",o.estimated_time_of_completion]})]})}),d.jsxs("div",{className:"flex gap-2",children:[d.jsx("button",{onClick:g,disabled:l,className:"flex-1 bg-green-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:l?d.jsxs("span",{className:"flex items-center justify-center",children:[d.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),d.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),d.jsx("button",{onClick:y,disabled:l,className:"flex-1 bg-red-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Decline"})]})]})]}):d.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:d.jsxs("div",{className:"text-center py-4",children:[d.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),d.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function V6(){const[e,t]=m.useState(null),[n,r]=m.useState([]);m.useEffect(()=>{const a=new Ar({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return t(a),a.on("rpc.method.called",c=>{console.log("RPC Method Called:",c)}),a.on("rpc.interaction.completed",c=>{console.log("RPC Interaction Completed:",c)}),()=>{a.disconnect()}},[]);const s=async()=>{if(e)try{await e.registerFrontendRPC("test",pm,"embedded");const a=e.getRegisteredRpcMethods();r(a),console.log("✅ Assignment RPC registered successfully")}catch(a){console.error("❌ Failed to register assignment RPC:",a)}},o=async()=>{if(!e)return;const a=({handler:c,timeout:l})=>{const[u,f]=m.useState(""),h=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],g=p=>{f(p)},y=()=>{const p=h.find(x=>x.id===u);c==null||c.didSuccess({selectedProduct:u,productName:p==null?void 0:p.name,price:p==null?void 0:p.price,timestamp:new Date().toISOString()})};return d.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[d.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),d.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),d.jsx("div",{className:"space-y-3 mb-6",children:h.map(p=>d.jsx("div",{onClick:()=>g(p.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${u===p.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:d.jsxs("div",{className:"flex justify-between items-center",children:[d.jsxs("div",{children:[d.jsx("h4",{className:"font-medium",children:p.name}),d.jsx("p",{className:"text-gray-600 text-sm",children:p.price})]}),d.jsx("div",{className:`w-4 h-4 rounded-full ${u===p.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},p.id))}),d.jsxs("div",{className:"flex justify-end space-x-3",children:[d.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),d.jsx("button",{onClick:y,disabled:!u,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),l&&d.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",l," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const c=e.getRegisteredRpcMethods();r(c),console.log("✅ Product Recommendation RPC registered successfully")}catch(c){console.error("❌ Failed to register product recommendation RPC:",c)}},i=async()=>{if(!e)return;const a=({handler:c})=>{const[l,u]=m.useState(0),[f,h]=m.useState(""),g=()=>{c==null||c.didSuccess({rating:l,comment:f,timestamp:new Date().toISOString()})};return d.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[d.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),d.jsxs("div",{className:"mb-4",children:[d.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),d.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(y=>d.jsx("button",{onClick:()=>u(y),className:`text-2xl ${y<=l?"text-yellow-400":"text-gray-300"}`,children:"⭐"},y))})]}),d.jsxs("div",{className:"mb-4",children:[d.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),d.jsx("textarea",{value:f,onChange:y=>h(y.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),d.jsxs("div",{className:"flex justify-end space-x-2",children:[d.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),d.jsx("button",{onClick:g,disabled:l===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await e.registerFrontendRPC("collect_feedback",a,"embedded");const c=e.getRegisteredRpcMethods();r(c),console.log("✅ Feedback RPC registered successfully")}catch(c){console.error("❌ Failed to register feedback RPC:",c)}};return d.jsxs("div",{className:"p-6",children:[d.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),d.jsxs("div",{className:"space-y-4 mb-6",children:[d.jsxs("div",{children:[d.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),d.jsxs("div",{className:"space-x-2",children:[d.jsx("button",{onClick:s,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),d.jsx("button",{onClick:o,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),d.jsx("button",{onClick:i,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),d.jsxs("div",{children:[d.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?d.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>d.jsx("li",{className:"text-gray-700",children:d.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):d.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),d.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[d.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),d.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[d.jsxs("li",{children:["Register RPC methods with React components using ",d.jsx("code",{children:"client.registerFrontendRPC()"})]}),d.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),d.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),d.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),d.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),d.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[d.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),d.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),d.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
|
|
181
181
|
const response = await participant.performRpc({
|
|
182
182
|
method: 'give_assignment',
|
|
183
183
|
data: JSON.stringify({
|
package/dist/index.js
CHANGED
|
@@ -22633,7 +22633,7 @@ function PC() {
|
|
|
22633
22633
|
if (e)
|
|
22634
22634
|
try {
|
|
22635
22635
|
await e.registerFrontendRPC(
|
|
22636
|
-
"
|
|
22636
|
+
"test",
|
|
22637
22637
|
X6,
|
|
22638
22638
|
"embedded"
|
|
22639
22639
|
// or 'modal' or 'fullscreen'
|