@voxket-ai/voxket-live 1.0.125 โ 1.0.126
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 +2 -2
- package/dist/index.js +8 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -160,7 +160,7 @@ To suppress this warning, you need to explicitly provide the \`palette.${t}Chann
|
|
|
160
160
|
${n.promptSlider}
|
|
161
161
|
${o===r?"opacity-100":"opacity-0"}
|
|
162
162
|
whitespace-pre-line break-words
|
|
163
|
-
`,style:{minHeight:"2.5rem",display:o===r?"block":"none"},children:s},o))})}function yE({statusMessage:e,theme:t}){const n=et(t);return f.jsxs("div",{className:"z-10 flex items-center space-x-2 mt-2 pb-2",children:[f.jsx("div",{className:n.statusIndicator}),f.jsx("span",{className:`text-xs ${n.text.muted}`,children:e})]})}const Sm=j.forwardRef(({disabled:e,onStartCall:t,onStartChat:n,onStartVideo:r,prompts:i=['"Book a meeting with the marketing team"',`"What's the status of project Alpha?"`,`"Summarize yesterday's sales report"`,'"Find a good Italian restaurant nearby"','"Remind me to call John tomorrow at 10 AM"'],statusMessage:s="Agent is ready",title:o="Choose how to interact",subTitle:a="Ask me anything or give me a task to complete",theme:l="vox",modalities:c=["voice","chat","video"]},u)=>{const d=et(l),h=c.includes("voice"),m=c.includes("chat"),g=c.includes("video"),p=[h,m,g].filter(Boolean).length;return f.jsxs("div",{className:"flex p-8 flex-col items-center h-full justify-center w-full relative","aria-disabled":e,style:{background:"transparent"},children:[f.jsxs("div",{className:"mt-1 relative flex items-center justify-center mb-8 w-full",style:{minHeight:"120px"},children:[f.jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[f.jsx("div",{className:d.pulseRings.ring1}),f.jsx("div",{className:d.pulseRings.ring2,style:{animationDelay:"0.5s"}}),f.jsx("div",{className:d.pulseRings.ring3,style:{animationDelay:"1s"}})]}),f.jsx("div",{className:"relative z-10 flex items-center justify-center",children:h&&m&&g?f.jsxs("div",{className:"flex gap-4 items-center justify-center",children:[f.jsx(ni,{onClick:t,disabled:e,theme:l}),f.jsx($o,{onClick:n,disabled:e,theme:l}),f.jsx(_o,{onClick:r||t,disabled:e,theme:l})]}):p>1?f.jsxs("div",{className:"flex gap-6 items-center justify-center",children:[h&&f.jsx(ni,{onClick:t,disabled:e,theme:l}),m&&f.jsx($o,{onClick:n,disabled:e,theme:l}),g&&r&&f.jsx(_o,{onClick:r,disabled:e,theme:l})]}):f.jsx("div",{className:"flex items-center justify-center",children:h?f.jsx(ni,{onClick:t,disabled:e,theme:l}):m?f.jsx($o,{onClick:n,disabled:e,theme:l}):g&&r?f.jsx(_o,{onClick:r,disabled:e,theme:l}):f.jsx(ni,{onClick:t,disabled:e,theme:l})})})]}),f.jsxs("div",{className:"text-center flex flex-col items-center gap-y-2 mb-6 w-full",children:[f.jsx("h3",{className:`text-xl font-semibold mb-2 ${d.text.accent}`,children:o}),f.jsx("p",{className:`text-sm leading-relaxed px-4 ${d.text.secondary}`,children:a}),p>1&&f.jsxs("div",{className:"flex gap-6 mt-4 text-xs justify-center",children:[h&&f.jsxs("div",{className:"flex flex-col items-center gap-1",children:[f.jsx(gh,{className:"w-4 h-4"}),f.jsx("span",{className:d.text.muted,children:"Voice"})]}),m&&f.jsxs("div",{className:"flex flex-col items-center gap-1",children:[f.jsx(ph,{className:"w-4 h-4"}),f.jsx("span",{className:d.text.muted,children:"Chat"})]}),g&&f.jsxs("div",{className:"flex flex-col items-center gap-1",children:[f.jsx(yh,{className:"w-4 h-4"}),f.jsx("span",{className:d.text.muted,children:"Video"})]})]})]}),f.jsx(gE,{prompts:i,theme:l}),f.jsx(yE,{statusMessage:s,theme:l})]})});Sm.displayName="Welcome";class Ha extends x.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 x.createElement(t,{error:this.state.error})}return x.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 Cm({room:e,onSessionEnd:t,onSessionStart:n,enableConsoleLogging:r=!0,enableLocalStorage:i=!0,voxketSessionId:s}={}){const[o,a]=x.useState(null),[l,c]=x.useState([]),[u,d]=x.useState(null),[h,m]=x.useState([]),g=x.useCallback((k,S)=>{const A={timestamp:new Date,event:k,data:S,sessionId:o==null?void 0:o.sessionId,participantId:u==null?void 0:u.identity};if(c(T=>[...T,A]),i){const T=JSON.parse(localStorage.getItem("voxket-session-logs")||"[]");T.push(A),localStorage.setItem("voxket-session-logs",JSON.stringify(T))}return A},[o==null?void 0:o.sessionId,u==null?void 0:u.identity,r,i]);x.useEffect(()=>{if(!e)return;const k=()=>{const y=s||`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,M=new Date,D={sessionId:y,startTime:M,totalMessages:0,connectionIssues:0,participantCount:h.length,events:[]};a(D),g("SESSION_STARTED",{sessionId:y,startTime:M}),n==null||n(y)},S=()=>{if(o){const y=new Date,M=y.getTime()-o.startTime.getTime(),D={...o,endTime:y,duration:M,events:l};g("SESSION_ENDED",{sessionId:o.sessionId,duration:`${Math.round(M/1e3)}s`,totalMessages:o.totalMessages,connectionIssues:o.connectionIssues}),t==null||t(D),a(null),c([])}},A=y=>{g("CONNECTION_STATE_CHANGED",{state:y}),y===te.ConnectionState.Reconnecting&&o&&(a(M=>M?{...M,connectionIssues:M.connectionIssues+1}:null),g("CONNECTION_ISSUE",{type:"reconnecting"}))},T=y=>{g("TRACK_PUBLISHED",{trackKind:y.kind,trackSource:y.source})},C=y=>{g("TRACK_UNPUBLISHED",{trackKind:y.kind,trackSource:y.source})},N=(y,M)=>{o&&a(D=>D?{...D,totalMessages:D.totalMessages+1}:null),g("DATA_RECEIVED",{participantId:M==null?void 0:M.identity,dataSize:y.length})},P=y=>{g("PARTICIPANT_CONNECTED",{participantId:y.identity,participantName:y.name}),m(M=>[...M,y]),o&&a(M=>M?{...M,participantCount:M.participantCount+1}:null)},L=y=>{g("PARTICIPANT_DISCONNECTED",{participantId:y.identity,participantName:y.name}),m(M=>M.filter(D=>D.identity!==y.identity))};return e.localParticipant&&d(e.localParticipant),e.on(te.RoomEvent.Connected,k),e.on(te.RoomEvent.Disconnected,S),e.on(te.RoomEvent.ConnectionStateChanged,A),e.on(te.RoomEvent.TrackPublished,T),e.on(te.RoomEvent.TrackUnpublished,C),e.on(te.RoomEvent.DataReceived,N),e.on(te.RoomEvent.ParticipantConnected,P),e.on(te.RoomEvent.ParticipantDisconnected,L),()=>{e.off(te.RoomEvent.Connected,k),e.off(te.RoomEvent.Disconnected,S),e.off(te.RoomEvent.ConnectionStateChanged,A),e.off(te.RoomEvent.TrackPublished,T),e.off(te.RoomEvent.TrackUnpublished,C),e.off(te.RoomEvent.DataReceived,N),e.off(te.RoomEvent.ParticipantConnected,P),e.off(te.RoomEvent.ParticipantDisconnected,L)}},[e,o,l,h.length,g,t,n]);const p=x.useCallback(()=>i?JSON.parse(localStorage.getItem("voxket-session-logs")||"[]"):l,[l,i]),b=x.useCallback(()=>{i&&localStorage.removeItem("voxket-session-logs"),c([])},[i]),v=x.useCallback(()=>{const k=p(),S=JSON.stringify(k,null,2),A="data:application/json;charset=utf-8,"+encodeURIComponent(S),T=`voxket-session-logs-${new Date().toISOString().split("T")[0]}.json`,C=document.createElement("a");C.setAttribute("href",A),C.setAttribute("download",T),C.click()},[p]);return{sessionMetrics:o,sessionLogs:l,logEvent:g,getSessionLogs:p,clearSessionLogs:b,exportSessionLogs:v}}class Ua{constructor(){Ue(this,"listeners",{})}on(t,n){return this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(n),()=>this.off(t,n)}once(t,n){const r=(...i)=>{this.off(t,r),n(...i)};return this.on(t,r)}off(t,n){const r=this.listeners[t];if(!r)return;const i=r.indexOf(n);i>-1&&r.splice(i,1)}removeAllListeners(t){t?delete this.listeners[t]:this.listeners={}}emit(t,...n){const r=this.listeners[t];if(!r)return;const i=[...r];for(const s of i)try{s(...n)}catch(o){console.error(`Error in event listener for ${String(t)}:`,o)}}listenerCount(t){var n;return((n=this.listeners[t])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class As{constructor(t){Ue(this,"plugins",new Map);Ue(this,"installedPlugins",new Set);Ue(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 s of r.dependencies)this.installedPlugins.has(s)||await this.install(s);const i={...this.context,config:{...r.config,...n}};r.install&&await r.install(i),this.installedPlugins.add(t),this.setupPluginEvents(r,i)}async uninstall(t){var r;const n=this.plugins.get(t);if(!n)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t)){for(const[i,s]of this.plugins)if(this.installedPlugins.has(i)&&((r=s.dependencies)!=null&&r.includes(t)))throw new Error(`Cannot uninstall '${t}' because '${i}' depends on it`);n.uninstall&&await n.uninstall(this.context),this.installedPlugins.delete(t)}}isInstalled(t){return this.installedPlugins.has(t)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(t){return this.plugins.get(t)}setupPluginEvents(t,n){t.onSessionStart&&n.on("session.started",r=>{t.onSessionStart(n,r.id)}),t.onSessionEnd&&n.on("session.ended",r=>{t.onSessionEnd(n,r.id)}),t.onAgentResponse&&n.on("agent.response",r=>{t.onAgentResponse(n,r)})}}function xE(e){return e}function Wa(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 bE={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)})}},vE={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))}},wE={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})})}},Em=j.createContext(null);function ci({config:e,children:t,autoConnect:n=!1,client:r}){const[i,s]=j.useState(null),[o,a]=j.useState(!1),[l,c]=j.useState(!1),[u,d]=j.useState(null),[h,m]=j.useState(null),[g,p]=j.useState("idle"),[b,v]=j.useState(null),[k,S]=j.useState([]),[A,T]=j.useState([]),[C,N]=j.useState([]);j.useEffect(()=>{const W=r||new $r(e);s(W);const w=P(W);return n&&!r&&L(W),()=>{w(),r||W.disconnect().catch(console.error)}},[e,n,r]);const P=W=>{const w=()=>{c(!0),d(null)},z=()=>{a(!0),c(!1),d(null)},oe=()=>{a(!1),c(!1),m(null),p("idle"),S([]),T([]),N([])},E=re=>{d(re),c(!1)},U=re=>{m(re),p(re.state)},se=re=>{p(re),h&&m({...h,state:re})},$=(re,ne)=>{m(null),p("idle"),v(ne),S([]),T([]),N([])},ee=re=>{S(ne=>[...ne,re])},Q=re=>{S(ne=>ne.filter(me=>me.id!==re.id))},V=re=>{T(ne=>[...ne,re])},X=re=>{T(ne=>[...ne,re])},fe=re=>{console.log("๐ VoxketProvider: Received transcription:",re),N(ne=>ne.find(Z=>Z.id===re.id)?(console.log("๐ VoxketProvider: Duplicate transcription detected, skipping:",re.id),ne):(console.log("๐ VoxketProvider: Adding new transcription:",re.id),[...ne,re]))},R=()=>{console.log("๐งน VoxketProvider: Clearing chat messages and transcriptions"),T([]),N([])};return W.on("connection.connecting",w),W.on("connection.connected",z),W.on("connection.disconnected",oe),W.on("connection.error",E),W.on("session.created",U),W.on("session.state.changed",se),W.on("session.ended",$),W.on("participant.joined",ee),W.on("participant.left",Q),W.on("chat.message.received",V),W.on("chat.message.sent",X),W.on("transcription.received",fe),W.on("chat.history.cleared",R),()=>{console.log("๐ VoxketProvider: Cleaning up event listeners"),W.off("connection.connecting",w),W.off("connection.connected",z),W.off("connection.disconnected",oe),W.off("connection.error",E),W.off("session.created",U),W.off("session.state.changed",se),W.off("session.ended",$),W.off("participant.joined",ee),W.off("participant.left",Q),W.off("chat.message.received",V),W.off("chat.message.sent",X),W.off("chat.history.cleared",R),W.off("transcription.received",fe)}},L=async W=>{const w=W||i;if(w)try{await w.connect()}catch(z){console.error("Failed to connect:",z)}},F={client:i,isConnected:o,isConnecting:l,connectionError:u,currentSession:h,sessionState:g,sessionMetrics:b,participants:k,chatMessages:A,transcriptions:C,connect:()=>L(),disconnect:async()=>{if(i)try{await i.disconnect()}catch(W){console.error("Failed to disconnect:",W)}},createSession:async(W,w={})=>{if(!i)throw new Error("Client not initialized");const z={agentId:W,participantName:w.participantName||"User",metadata:w.metadata,modalities:w.modalities||["voice"]};return await i.createSession(z)},endSession:async()=>i?await i.endSession():null,sendChatMessage:async W=>{if(!i)throw new Error("Client not initialized");await i.sendChatMessage(W)},setMicrophoneEnabled:async W=>{if(!i)throw new Error("Client not initialized");await i.setMicrophoneEnabled(W)},setCameraEnabled:async W=>{if(!i)throw new Error("Client not initialized");await i.setCameraEnabled(W)},startScreenShare:async()=>{if(!i)throw new Error("Client not initialized");await i.startScreenShare()},stopScreenShare:async()=>{if(!i)throw new Error("Client not initialized");await i.stopScreenShare()}};return f.jsx(Em.Provider,{value:F,children:t})}function Dt(){const e=j.useContext(Em);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}class Gu extends Ua{constructor(n){super();Ue(this,"room",null);Ue(this,"registeredMethods",new Map);Ue(this,"activeInteractions",new Map);Ue(this,"currentInteraction",null);n&&this.setRoom(n)}setRoom(n){this.room=n}async registerFrontendRPC(n,r,i="embedded"){if(console.log(`RpcManager: Starting registration for method '${n}'`),!this.room)throw console.error(`RpcManager: Cannot register '${n}' - no room instance`),new Error("Room not initialized. Cannot register RPC method.");if(!this.room.localParticipant)throw console.error(`RpcManager: Cannot register '${n}' - no local participant`),new Error("Local participant not available for RPC registration");console.log(`RpcManager: Room state: ${this.room.state}`),console.log(`RpcManager: Local participant: ${this.room.localParticipant.identity}`),console.log(`RpcManager: Registering frontend RPC method: ${n}`);const s={methodName:n,component:r,presentationMode:i};this.registeredMethods.set(n,s);try{this.room.registerRpcMethod(n,async o=>{console.log(`RpcManager: RPC method '${n}' called by ${o.callerIdentity}`),console.log("RpcManager: Payload:",o.payload),this.emit("rpc.method.called",{methodName:n,data:o});let a;console.log(`RpcManager: Current registration for '${n}':`,s);let l=o.responseTimeout||30;try{a=JSON.parse(o.payload)}catch{a=o.payload}try{const c=await this.awaitUserInteraction(n,r,i,a,l);return JSON.stringify(c)}catch(c){throw console.error(`RpcManager: Error in RPC method '${n}':`,c),c}}),this.emit("rpc.method.registered",{methodName:n}),console.log(`RpcManager: Successfully registered RPC method: ${n}`)}catch(o){throw console.error(`RpcManager: Failed to register RPC method '${n}':`,o),o}}async awaitUserInteraction(n,r,i,s,o){return new Promise((a,l)=>{const c=`${n}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${n}, timeout: ${o} seconds`);const u={didSuccess:(h,m)=>{console.log(`RpcManager: User interaction successful for method: ${n}`,h),this.clearInteraction(c),this.currentInteraction=null;const g={success:!0,message:"User interaction completed successfully",data:h,timestamp:new Date,...m?{successView:m}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:g}),a(g)},didFail:h=>{console.log(`RpcManager: User interaction failed for method: ${n}`,h),this.clearInteraction(c);const m={success:!1,message:"User interaction failed",error:h,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:m}),a(m)},dismissView:()=>{var m;console.log(`RpcManager: User dismissed interaction for method: ${n}`),console.log("RpcManager: Current interaction before dismiss:",(m=this.currentInteraction)==null?void 0:m.methodName),this.clearInteraction(c),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 g;((g=this.currentInteraction)==null?void 0:g.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(c),this.currentInteraction=null;const m={success:!0,message:`User interaction timed out after ${o} 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:m}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(m)}},d=setTimeout(()=>{u.didTimeout&&u.didTimeout()},o);this.activeInteractions.set(c,{resolve:h=>a(JSON.parse(h)),reject:l,timeoutId:d}),this.currentInteraction={isVisible:!0,methodName:n,component:r,presentationMode:i,timeout:o,data:s,handler:u},this.emit("rpc.interaction.started",{methodName:n,presentationMode:i}),setTimeout(async()=>{var h;if((h=this.currentInteraction)!=null&&h.handler)try{console.log(`RpcManager: Component created for method: ${n} with data:`,s)}catch(m){console.error("RpcManager: Error loading data into component:",m),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 Ve extends Error{constructor(t,n,r){super(t),this.code=n,this.details=r,this.name="VoxketError"}}const Kt=new WeakSet,Bo=new WeakSet;class $r extends Ua{constructor(n){super();Ue(this,"config");Ue(this,"room",null);Ue(this,"pluginManager");Ue(this,"rpcManager");Ue(this,"isConnected",!1);Ue(this,"currentSession",null);Ue(this,"connectionState",te.ConnectionState.Disconnected);Ue(this,"renderedComponents",new Map);Ue(this,"textStreamHandlersRegistered",!1);Ue(this,"currentAgentInfo",null);Ue(this,"chatMessages",[]);Ue(this,"activeTranscriptions",new Map);Ue(this,"isAgentConnected",!1);Ue(this,"agentState","idle");if(typeof window>"u"){console.warn("VoxketClient: Skipping initialization in server-side environment"),this.config=n,this.pluginManager=new As(this),this.rpcManager=new Gu;return}this.config=n,this.pluginManager=new As(this),this.rpcManager=new Gu,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,i;this.isConnected=!1,(i=(r=this.config).onDisconnected)==null||i.call(r,n)}),this.on("connection.error",n=>{var r,i;(i=(r=this.config).onError)==null||i.call(r,n)}),this.on("chat.message.received",n=>{var r,i;this.addChatMessage(n),(i=(r=this.config).onMessageReceived)==null||i.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,i;(i=(r=this.config).onTranscriptionReceived)==null||i.call(r,n)}),this.on("session.state.changed",n=>{var r,i;(i=(r=this.config).onSessionStateChanged)==null||i.call(r,n)}),this.on("session.created",n=>{var r,i;(i=(r=this.config).onSessionStart)==null||i.call(r,n.id)}),this.on("session.ended",(n,r)=>{var i,s;(s=(i=this.config).onSessionEnd)==null||s.call(i,r)}),this.on("participant.joined",n=>{var r,i;(i=(r=this.config).onUserJoined)==null||i.call(r,n.id)}),this.on("participant.left",n=>{var r,i;(i=(r=this.config).onUserLeft)==null||i.call(r,n.id)}),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 i;try{(i=this.room)!=null&&i.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(s){console.warn("VoxketClient: Failed to enable microphone after room connection:",s)}},1e3),this.textStreamHandlersRegistered||this.setupTextStreamHandlers()}),this.room.on(te.RoomEvent.Disconnected,n=>{var r;console.log("๐ด VoxketClient: Room disconnected, reason:",n),this.connectionState=te.ConnectionState.Disconnected,this.textStreamHandlersRegistered=!1,this.isAgentConnected=!1,console.log("๐ค VoxketClient: Agent marked as disconnected"),this.clearChatMessages(),n&&console.log("๐ VoxketClient: Disconnect reason details:",{reason:n.toString(),currentSession:(r=this.currentSession)==null?void 0:r.id,agentConnected:this.isAgentConnected,connectionState:this.connectionState}),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)}),this.room.on(te.RoomEvent.LocalTrackPublished,n=>{console.log("๐ฌ VoxketClient: Local track published:",n.source),n.source===te.Track.Source.ScreenShare&&this.emit("track.unmuted",{source:"screenShare",enabled:!0})}),this.room.on(te.RoomEvent.LocalTrackUnpublished,n=>{console.log("๐ฌ VoxketClient: Local track unpublished:",n.source),n.source===te.Track.Source.ScreenShare&&this.emit("track.muted",{source:"screenShare",enabled:!1})}))}setupTextStreamHandlers(){if(!this.room)return;try{this.room.registerTextStreamHandler("lk.chat",async(r,i)=>{try{const s=await r.readAll(),o={id:`msg_${Date.now()}_${i.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:s,timestamp:new Date,sender:{id:i.identity||"user",name:i.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(r){console.warn("VoxketClient: lk.chat handler already registered, skipping:",r)}try{console.log("๐ VoxketClient: Registering lk.transcription handler..."),this.room.registerTextStreamHandler("lk.transcription",async(r,i)=>{var s,o,a,l,c,u;console.log("๐ VoxketClient: Received transcription stream from:",i.identity);try{console.log("๐ VoxketClient: Processing transcription stream...");const d=i.identity===((o=(s=this.room)==null?void 0:s.localParticipant)==null?void 0:o.identity),h=Date.now(),m=i.identity,g=this.activeTranscriptions.get(m);let p,b=!0;g&&h-g.timestamp<1e3?(p=g.messageId,b=!1,console.log("๐ VoxketClient: Reusing existing transcription message ID:",p)):(p=`msg_${d?"user":"agent"}_${i.identity}_${h}`,this.activeTranscriptions.set(m,{messageId:p,timestamp:h}),console.log("๐ VoxketClient: Created new transcription message ID:",p));let v="";const k=((a=this.currentAgentInfo)==null?void 0:a.name)||i.identity||"AI Assistant";console.log("๐ VoxketClient: Using agent name:",k);const S=d?"participant":"agent",A=d?this.config.participantName||"User":k;console.log("๐ VoxketClient: Transcription sender info:",{participantIdentity:i.identity,localParticipantIdentity:(c=(l=this.room)==null?void 0:l.localParticipant)==null?void 0:c.identity,isFromUser:d,senderType:S,senderName:A});const T={id:p,content:"",timestamp:new Date,sender:{id:i.identity||"unknown",name:A,type:S},metadata:{topic:"lk.transcription",streaming:!0}};b&&this.emit("chat.message.received",T),console.log("๐ VoxketClient: Starting to read transcription stream...");for await(const L of r){console.log("๐ VoxketClient: Received chunk:",L.length,"chars"),v+=L;const y=this.convertMarkdownToText(v),M={...T,content:y,metadata:{...T.metadata,streaming:!0}};this.emit("chat.message.updated",M)}const C=this.convertMarkdownToText(v),N={...T,content:C,metadata:{...T.metadata,streaming:!1}};this.emit("chat.message.updated",N);const P={id:p,text:C,isFinal:!0,startTime:T.timestamp.getTime(),participantId:i.identity||"agent"};this.emit("transcription.received",P),console.log("๐ VoxketClient: Emitted transcription event:",P)}catch(d){console.error("VoxketClient: Failed to process lk.transcription message:",d);try{const h=await r.readAll(),m=((u=this.currentAgentInfo)==null?void 0:u.name)||i.identity||"AI Assistant",g={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:h,timestamp:new Date,sender:{id:i.identity||"agent",name:m,type:"agent"},metadata:{topic:"lk.transcription"}};this.emit("chat.message.received",g);const p={id:g.id,text:g.content,isFinal:!0,startTime:g.timestamp.getTime(),participantId:i.identity||"agent"};this.emit("transcription.received",p),console.log("๐ VoxketClient: Emitted fallback transcription event:",p)}catch(h){console.error("VoxketClient: Fallback failed for lk.transcription:",h)}}})}catch(r){console.warn("VoxketClient: lk.transcription handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("suggested_response",async r=>{const i=await r.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,i)}this.emit("suggested.response",s)})}catch(r){console.warn("VoxketClient: suggested_response handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("agent_state_changed",async(r,i)=>{const s=await r.readAll();console.log("๐ค VoxketClient: agent_state_changed stream received:",s);let o={};try{o=typeof s=="string"?JSON.parse(s.replace(/'/g,'"')):s}catch(a){console.warn("VoxketClient: Failed to parse agent_state_changed:",a,s)}this.isAgentConnected||(this.isAgentConnected=!0,console.log("๐ค VoxketClient: Agent marked as connected (first state change received)"),this.emit("agent.connected",o)),o.new_state==="speaking"?(this.setAgentState("speaking"),this.emit("agent.speaking",o)):o.new_state==="thinking"?(this.setAgentState("thinking"),this.emit("agent.thinking",o)):(o.new_state==="idle"||o.new_state==="listening")&&this.setAgentState("idle")})}catch(r){console.warn("VoxketClient: conversation_item_added handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("images",async(r,i)=>{try{const s=await r.readAll()}catch(s){console.error("VoxketClient: Error processing images stream:",s)}})}catch(r){console.warn("VoxketClient: images handler already registered, skipping:",r)}try{this.room.registerByteStreamHandler("images",async(r,i)=>{var s,o;try{const a=r.info,l={id:`img_${Date.now()}_${i.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`๏ฟฝ๏ธ ${a.name||"Image"}`,sender:{id:i.identity||"agent",name:i.identity||"Agent",type:i.identity===((o=(s=this.room)==null?void 0:s.localParticipant)==null?void 0:o.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:a.name,fileSize:a.size,mimeType:a.mimeType,streamId:a.id,downloading:!0}};this.emit("chat.message.received",l),r.onProgress&&(r.onProgress=m=>{const g={...l,metadata:{...l.metadata,downloadProgress:m||0}};this.emit("chat.message.updated",g)});const c=[];for await(const m of r)c.push(m);const u=new Blob(c,{type:a.mimeType||"application/octet-stream"}),d=URL.createObjectURL(u),h={...l,metadata:{...l.metadata,downloading:!1,downloadProgress:1,downloadUrl:d,blob:u}};this.emit("chat.message.updated",h)}catch(a){console.error("VoxketClient: Error processing image attachment:",a)}})}catch(r){console.warn("VoxketClient: image handler already registered, skipping:",r)}["error","warning","status","system","debug","info"].forEach(r=>{try{this.room.registerTextStreamHandler(r,async(i,s)=>{try{const o=await i.readAll();if(console.log(`๐ VoxketClient: Received '${r}' stream:`,o),r==="error"){let a={};try{a=typeof o=="string"?JSON.parse(o):o}catch{a={message:o}}console.warn("๏ฟฝ VoxketClient: Agent error:",a),this.emit("agent.error",a)}else this.emit("text.stream.received",{topic:r,data:o,participantInfo:s})}catch(o){console.error(`VoxketClient: Failed to process '${r}' stream:`,o)}})}catch(i){console.warn(`VoxketClient: Handler for '${r}' already registered, skipping:`,i)}});try{this.room.registerTextStreamHandler("*",async(r,i)=>{var s;try{const o=await r.readAll(),a=((s=r.info)==null?void 0:s.topic)||"unknown";console.log(`๐ VoxketClient: Received unhandled text stream for topic '${a}':`,o),this.emit("text.stream.unhandled",{topic:a,data:o,participantInfo:i})}catch(o){console.error("VoxketClient: Failed to process unhandled text stream:",o)}})}catch(r){console.warn("VoxketClient: Generic text stream handler already registered, skipping:",r)}this.textStreamHandlersRegistered=!0}async fetchConnectionDetails(n,r,i){const s=n||this.config.agentId||"default-agent",o=r||this.config.participantName||"User",a=i||this.config.modalities||["voice"];try{const l={agent_id:s,participant_name:o,participant_metadata:{user_id:""},modality:a[0],modalities:a};console.log("๐ VoxketClient: Creating session with modalities:",a);const c=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(l)});if(!c.ok){let h=`HTTP ${c.status}: Failed to fetch connection details`;try{const m=await c.json();m&&(m.error?h=`API Error: ${m.error}`:m.detail?h=`API Error: ${m.detail}`:m.message&&(h=`API Error: ${m.message}`))}catch{try{const g=await c.text();g&&(h=`API Error: ${g}`)}catch{}}throw new Error(h)}const u=await c.json();let d;return u.agent_info&&(d={id:u.agent_info.id||s,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=d),{serverUrl:u.wss_url,participantToken:u.token,voxketSessionId:u.session_id,agentInfo:d}}catch(l){console.error("VoxketClient: fetchConnectionDetails failed:",l);const c=new Ve(`Failed to fetch connection details: ${l instanceof Error?l.message:"Unknown error"}`,"CONNECTION_FAILED",l);throw this.emit("connection.error",c),c}}async connect(n,r,i){var s;try{this.emit("connection.connecting");const o=await this.fetchConnectionDetails(n,r,i);return await((s=this.room)==null?void 0:s.connect(o.serverUrl,o.participantToken)),this.isConnected=!0,o}catch(o){console.error("VoxketClient: Connection failed:",o);const a=new Ve(`Failed to connect to Voxket services: ${o instanceof Error?o.message:"Unknown error"}`,"CONNECTION_FAILED",o);throw this.emit("connection.error",a),a}}async disconnect(){var n;try{console.log("๐ VoxketClient: Starting disconnect process..."),this.room&&(console.log("๐ VoxketClient: Disconnecting from room:",{roomState:this.room.state,numParticipants:this.room.numParticipants,sessionId:(n=this.currentSession)==null?void 0:n.id}),await this.room.disconnect()),this.isConnected=!1,this.currentSession=null,this.currentAgentInfo=null,this.textStreamHandlersRegistered=!1,this.clearChatMessages(),console.log("๐ VoxketClient: Creating new room instance..."),this.room=new te.Room,this.setupRoomEventListeners(),console.log("โ
VoxketClient: Disconnect completed successfully"),this.emit("connection.disconnected")}catch(r){console.error("โ VoxketClient: Disconnect failed:",r);const i=new Ve("Failed to disconnect properly","NETWORK_ERROR",r);throw this.emit("connection.error",i),i}}async createSession(n){var r,i,s,o;try{const a=await this.connect(n.agentId,n.participantName,n.modalities),l={id:a.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:a.agentInfo||this.currentAgentInfo};if(this.currentSession=l,this.emit("session.created",l),(r=n.modalities)!=null&&r.includes("voice"))try{await new Promise(c=>setTimeout(c,500)),(i=this.room)!=null&&i.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(c){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",c)}if((s=n.modalities)!=null&&s.includes("video"))try{await new Promise(c=>setTimeout(c,200)),(o=this.room)!=null&&o.localParticipant&&(console.log("๐ฅ VoxketClient: Attempting to enable camera for video session"),await this.room.localParticipant.setCameraEnabled(!0),this.emit("track.unmuted",{source:"camera",enabled:!0}),console.log("๐ฅ VoxketClient: Camera enabled successfully"))}catch(c){console.warn("VoxketClient: Failed to enable camera, but continuing with session:",c)}return setTimeout(()=>{var c;this.currentSession&&(this.currentSession.state="active",this.emit("session.state.changed","active",this.currentSession.state),this.forceAgentConnected(),console.log("๐ค VoxketClient: Session marked as active:",{sessionId:this.currentSession.id,modalities:this.currentSession.activeModalities,agentConnected:this.isAgentConnected,hasRoom:!!this.room,remoteParticipants:((c=this.room)==null?void 0:c.remoteParticipants.size)||0}))},1e3),l}catch(a){throw console.error("VoxketClient: Failed to create session:",a),a instanceof Ve?a:a instanceof TypeError&&a.message.includes("fetch")?new Ve("Network connection failed","CONNECTION_FAILED",a):a instanceof Error&&a.message.includes("Failed to fetch connection details")?new Ve(`API connection failed: ${a.message}`,"CONNECTION_FAILED",a):new Ve(`Failed to create session: ${a instanceof Error?a.message:"Unknown error"}`,"SESSION_NOT_FOUND",a)}}async startSession(n,r){const i={agentId:n||this.config.agentId||"default-agent",participantName:(r==null?void 0:r.participantName)||this.config.participantName||"User",modalities:(r==null?void 0:r.modalities)||this.config.modalities||["voice","chat"],metadata:r==null?void 0:r.metadata};return this.createSession(i)}async endSession(){var n,r;if(!this.currentSession)return null;try{const i={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.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,i),await this.disconnect(),i}catch(i){throw new Ve("Failed to end session","SESSION_NOT_FOUND",i)}}getCurrentSession(){return this.currentSession}getCurrentAgentInfo(){return this.currentAgentInfo}getIsAgentConnected(){return this.isAgentConnected}forceAgentConnected(){this.isAgentConnected||(this.isAgentConnected=!0,console.log("๐ค VoxketClient: Agent manually marked as connected"),this.emit("agent.connected",{forced:!0}))}getAgentState(){return this.agentState}setAgentState(n){this.agentState!==n&&(this.agentState=n,this.emit("agent.state.changed",{state:n}))}getAgentAudioTrack(){const n=this.getRemoteParticipants();for(const r of n){const i=r.getTrackPublication(te.Track.Source.Microphone);if(i!=null&&i.track)return{source:te.Track.Source.Microphone,participant:r,publication:i}}return null}getAgentVideoTrack(){const n=this.getRemoteParticipants();for(const r of n){const i=r.getTrackPublication(te.Track.Source.Camera);if(i!=null&&i.track)return{source:te.Track.Source.Camera,participant:r,publication:i}}return null}getVideoTrackRefs(){const n=[],r=this.getLocalParticipant();if(r){const s=r.getTrackPublication(te.Track.Source.Camera);s!=null&&s.track&&n.push({source:te.Track.Source.Camera,participant:r,publication:s});const o=r.getTrackPublication(te.Track.Source.ScreenShare);o!=null&&o.track&&n.push({source:te.Track.Source.ScreenShare,participant:r,publication:o})}const i=this.getRemoteParticipants();for(const s of i){const o=s.getTrackPublication(te.Track.Source.Camera);o!=null&&o.track&&n.push({source:te.Track.Source.Camera,participant:s,publication:o});const a=s.getTrackPublication(te.Track.Source.ScreenShare);a!=null&&a.track&&n.push({source:te.Track.Source.ScreenShare,participant:s,publication:a})}return n}getCameraTrackRefs(){return this.getVideoTrackRefs().filter(n=>n.source===te.Track.Source.Camera)}getScreenShareTrackRefs(){return this.getVideoTrackRefs().filter(n=>n.source===te.Track.Source.ScreenShare)}getChatMessages(){return[...this.chatMessages]}addChatMessage(n){this.chatMessages.some(i=>i.id===n.id)||this.chatMessages.push(n)}updateChatMessage(n){const r=this.chatMessages.findIndex(i=>i.id===n.id);r!==-1&&(this.chatMessages[r]=n)}clearChatMessages(){this.chatMessages=[],this.activeTranscriptions.clear(),this.dismissCurrentInteraction(),this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays(),console.log("๐งน VoxketClient: Cleared chat messages and transcription history"),this.emit("chat.history.cleared")}renderUI(n={}){var o,a,l,c,u,d,h,m,g;if(typeof window>"u"){console.warn("VoxketClient: Cannot render UI in server-side environment");return}const r=this.resolveTarget(n.target||"body"),i=this.getTargetKey(r);if(Bo.has(r)){console.warn("โ ๏ธ VoxketClient: Target is already being processed, skipping renderUI");return}if(Kt.has(r)){console.log("โ VoxketClient: Target already has a React root in registry, updating existing props...");const p=this.renderedComponents.get(i);if(p&&p.root){const b={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:((o=n.modality)==null?void 0:o.includes("chat"))!==!1,suportsVideoInput:((a=n.modality)==null?void 0:a.includes("video"))===!0,suportsScreenShare:((l=n.modality)==null?void 0:l.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};try{p.root.render(j.createElement(ci,{config:this.config,autoConnect:n.autoStart||!1,client:this,children:j.createElement(ui,b)})),console.log("โ
VoxketClient: Successfully updated existing widget with new props");return}catch(v){throw console.error("Error re-rendering existing widget:",v),new Error(`Failed to update existing widget: ${v instanceof Error?v.message:"Unknown error"}`)}}else console.warn("โ ๏ธ Registry inconsistency detected, cleaning up"),Kt.delete(r)}let s=this.renderedComponents.get(i);if(s&&s.target===r&&Kt.has(r)){console.log("๐ VoxketClient: Reusing existing React root for target:",i);const p=s.root,b={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:((u=n.modality)==null?void 0:u.includes("video"))===!0,suportsScreenShare:((d=n.modality)==null?void 0:d.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};try{p.render(j.createElement(ci,{config:this.config,autoConnect:n.autoStart||!1,client:this,children:j.createElement(ui,b)}))}catch(v){throw console.error("Error rendering Voxket widget:",v),new Error(`Failed to render Voxket widget: ${v instanceof Error?v.message:"Unknown error"}`)}return}Bo.add(r);try{if(s){console.log("๐งน VoxketClient: Cleaning up existing component for different target");try{s.root.unmount(),this.renderedComponents.delete(i),Kt.delete(s.target),r.innerHTML=""}catch(v){console.warn("Failed to cleanup existing root:",v)}}if(Kt.has(r)){console.warn("โ ๏ธ VoxketClient: Target already in registry, skipping root creation");return}console.log("๐ VoxketClient: Creating new React root for target:",i);const p=Zm.createRoot(r);this.renderedComponents.set(i,{root:p,target:r}),Kt.add(r);const b={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:((h=n.modality)==null?void 0:h.includes("chat"))!==!1,suportsVideoInput:((m=n.modality)==null?void 0:m.includes("video"))===!0,suportsScreenShare:((g=n.modality)==null?void 0:g.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(!p||typeof p.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{p.render(j.createElement(ci,{config:this.config,autoConnect:n.autoStart||!1,client:this,children:j.createElement(ui,b)}))}catch(v){throw console.error("Error rendering Voxket widget:",v),new Error(`Failed to render Voxket widget: ${v instanceof Error?v.message:"Unknown error"}`)}}finally{Bo.delete(r)}}removeUI(n){var i;const r=n?this.resolveTarget(n):null;if(r){const s=this.getTargetKey(r),o=this.renderedComponents.get(s);if(o){console.log("๐๏ธ VoxketClient: Removing UI for target:",s),this.renderedComponents.delete(s),Kt.delete(r);try{const l=o.target;l&&l.isConnected?(typeof((i=o.root)==null?void 0:i.unmount)=="function"&&(o.root.unmount(),console.log("โ
VoxketClient: UI unmounted for target:",s)),l.hasChildNodes()&&(l.innerHTML="")):console.log("โน๏ธ VoxketClient: Target element already disconnected, skipping unmount")}catch(l){console.warn("Failed to unmount React root:",l)}}else console.log("โน๏ธ VoxketClient: No component found for target, cleaning registry:",s),Kt.delete(r),r.isConnected&&r.hasChildNodes()&&(r.innerHTML="");r.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(l=>{try{l.remove()}catch(c){console.warn("Failed to remove element:",c)}}),typeof document<"u"&&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")||c.classList.contains("bg-opacity-30")))try{c.remove()}catch(u){console.warn("Failed to remove fixed element:",u)}})}}removeAllUI(){for(const[n,r]of this.renderedComponents)r.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){if(typeof document>"u")return;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(i){console.warn("Failed to remove overlay:",i)}})}resolveTarget(n){if(typeof window>"u"||typeof document>"u")throw new Error("VoxketClient: Cannot resolve DOM target in server-side environment");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 i;if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new Ve("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new Ve("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new Ve("No local participant","CONNECTION_FAILED");this.dismissCurrentInteraction();try{const s={id:`msg_${Date.now()}`,content:n,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:r||{}},o=await((i=this.room)==null?void 0:i.localParticipant.sendText(n,{topic:"lk.chat",destinationIdentities:[]}));this.emit("chat.message.sent",s)}catch(s){throw console.error("VoxketClient: Failed to send chat message:",s),new Ve("Failed to send message","NETWORK_ERROR",s)}}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 Ve("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new Ve("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new Ve("No local participant","CONNECTION_FAILED");if(!n||n.length===0)throw new Ve("No files provided","INVALID_PARAMETER");this.dismissCurrentInteraction();const i=n.filter(s=>s.type.startsWith("image/"));if(i.length===0)throw new Ve("Only image files are allowed","INVALID_PARAMETER");i.length!==n.length&&console.warn("VoxketClient: Some non-image files were filtered out");try{const s=i.map(async(o,a)=>{const c={id:`att_${Date.now()}_${a}`,content:`๐ ${o.name}`,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:{...r,type:"attachment",fileName:o.name,fileSize:o.size,mimeType:o.type,uploading:!0}};this.emit("chat.message.sent",c);const u=await this.room.localParticipant.sendFile(o,{mimeType:o.type,topic:"images",onProgress:h=>{const m={...c,metadata:{...c.metadata,uploadProgress:h}};this.emit("chat.message.updated",m)}});try{const h=new FileReader,m=new Promise((b,v)=>{h.onload=()=>{typeof h.result=="string"?b(h.result):v(new Error("Failed to convert to base64"))},h.onerror=v});h.readAsDataURL(o);const p={type:"image",data:await m,filename:o.name,mimeType:o.type,size:o.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 m=`I've shared an image: ${o.name}`;await this.room.localParticipant.sendText(m,{topic:"lk.chat",destinationIdentities:[]})}catch(m){console.warn("VoxketClient: Failed to send image notification to agent:",m)}}const d={...c,metadata:{...c.metadata,uploading:!1,uploadProgress:1,streamId:u.id}};return this.emit("chat.message.updated",d),u});await Promise.all(s)}catch(s){throw console.error("VoxketClient: Failed to send attachments:",s),new Ve("Failed to send attachments","NETWORK_ERROR",s)}}async sendAttachment(n,r){return this.sendAttachments([n],r)}toggleMicrophone(n){return this.setMicrophoneEnabled(n!==!1)}async setMicrophoneEnabled(n){var r,i;try{const s=(r=this.room)==null?void 0:r.localParticipant.isMicrophoneEnabled,o=n??!s;await((i=this.room)==null?void 0:i.localParticipant.setMicrophoneEnabled(o)),o?this.emit("track.unmuted",{source:"microphone",enabled:!0}):this.emit("track.muted",{source:"microphone",enabled:!1})}catch(s){throw console.error("VoxketClient: Failed to toggle microphone:",s),new Ve("Failed to toggle microphone","PERMISSION_DENIED",s)}}toggleCamera(n){return this.setCameraEnabled(n!==!1)}async setCameraEnabled(n){var r,i;try{const s=(r=this.room)==null?void 0:r.localParticipant.isCameraEnabled,o=n??!s;await((i=this.room)==null?void 0:i.localParticipant.setCameraEnabled(o)),o?this.emit("track.unmuted",{source:"camera",enabled:!0}):this.emit("track.muted",{source:"camera",enabled:!1})}catch(s){throw console.error("VoxketClient: Failed to toggle camera:",s),new Ve("Failed to toggle camera","PERMISSION_DENIED",s)}}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)),this.emit("track.unmuted",{source:"screenShare",enabled:!0})}catch(r){throw new Ve("Failed to start screen share","PERMISSION_DENIED",r)}}async stopScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!1)),this.emit("track.muted",{source:"screenShare",enabled:!1})}catch(r){throw new Ve("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 Ve("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 Ve("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(i){throw new Ve("Failed to set audio input device","DEVICE_ERROR",i)}}async setVideoInputDevice(n){var r;try{if(!((r=this.room)!=null&&r.localParticipant))throw new Error("Not connected to room")}catch(i){throw new Ve("Failed to set video input device","DEVICE_ERROR",i)}}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 i=s=>!!r.canPublish&&(r.canPublishSources.length===0||r.canPublishSources.includes(s));return{camera:i(1),microphone:i(2),screenShare:i(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 console.log("๐ฌ VoxketClient: getScreenShareTrack - no local participant"),null;for(const[,r]of n.trackPublications)if(r.source===te.Track.Source.ScreenShare)return console.log("๐ฌ VoxketClient: getScreenShareTrack - found screen share track:",{trackSid:r.trackSid,isMuted:r.isMuted,hasTrack:!!r.track}),r.track;return console.log("๐ฌ VoxketClient: getScreenShareTrack - no screen share track found"),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(),r=n?!n.isMuted:!1;return console.log("๐ฌ VoxketClient: isScreenShareEnabled check:",{hasTrack:!!n,trackMuted:n==null?void 0:n.isMuted,enabled:r}),r}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 Ve("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 Ve("Failed to stop recording","RECORDING_ERROR",r)}}async registerFrontendRPC(n,r,i="embedded"){return this.rpcManager.registerFrontendRPC(n,r,i)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}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 i=>{try{const s=await i.readAll();r(s)}catch(s){console.error(`Error processing event for topic '${n}':`,s)}})}catch(i){console.warn(`VoxketClient: Handler for topic '${n}' may already be registered:`,i)}}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 kE=ge.create(xh),SE=ge.create(dE),CE=ge.create(pE),EE=ge.create(Sm);function TE({theme:e,mode:t,loadingText:n}){const r=et(e),i=()=>{switch(t){case"voice":return n||"Connecting to voice agent...";case"chat":return n||"Starting chat session...";case"video":return n||"Connecting to video call...";default:return n||"Connecting..."}};return f.jsxs("div",{className:"flex flex-col items-center justify-center h-full w-full p-8",children:[f.jsxs("div",{className:"text-center",children:[f.jsx("h3",{className:`text-lg font-semibold mb-2 ${r.text.accent}`,children:i()}),f.jsx("p",{className:`text-sm ${r.text.muted}`,children:"Please wait a moment..."})]}),f.jsxs("div",{className:"flex space-x-1 mt-4",children:[f.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"0ms"}}),f.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"150ms"}}),f.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"300ms"}})]})]})}const AE=ge.create(TE);function jE({onClick:e,text:t="Open Chat",position:n="bottom-right",theme:r}){const i={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},s=et(r);return f.jsx(ge.button,{onClick:e,className:`voxket-popup-trigger fixed ${i[n]} z-50 px-4 py-2 rounded-full shadow-lg ${s.popupTrigger} transition-all duration-200 hover:scale-105`,initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},exit:{scale:0,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},"data-position":n,children:t})}function Ku({children:e,theme:t,displayType:n="widget",onClose:r,popupPosition:i="bottom-right",onExpand:s}){const o=et(t);if(n==="fullscreen")return f.jsx("div",{className:"fixed inset-0 z-[9999] bg-black/40 bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",onClick:a=>{a.target===a.currentTarget&&r&&r()},children:f.jsxs("div",{className:"w-full h-full max-w-7xl max-h-[95vh] rounded-2xl relative bg-transparent flex flex-col",onClick:a=>{a.stopPropagation()},children:[r&&f.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),r()},className:"absolute top-4 cursor-pointer right-4 z-[10000] w-12 h-12 rounded-full 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:f.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:f.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"})})}),f.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${o.card} w-full h-full flex flex-col rounded-xl shadow-2xl relative overflow-hidden`,"data-theme":t,style:{minHeight:"600px",height:"100%",contain:"layout style paint",overscrollBehavior:"contain"},children:[f.jsx("div",{className:o.cardTopGradient}),f.jsx("div",{className:o.cardPurpleBlur}),f.jsx("div",{className:o.cardPinkBlur}),f.jsx("div",{className:"relative z-10 flex flex-col h-full",children:e}),f.jsx("div",{className:o.cardPulse1}),f.jsx("div",{className:o.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 f.jsx("div",{className:"fixed rounded-2xl inset-0 z-[9999] pointer-events-none",children:f.jsxs("div",{className:`fixed rounded-2xl ${a[i]} pointer-events-auto`,children:[r&&f.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:"ร"}),f.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${o.card} rounded-2xl flex flex-col relative overflow-hidden`,"data-theme":t,style:{width:"350px",height:"500px",contain:"layout style paint",overscrollBehavior:"contain"},children:[f.jsx("div",{className:o.cardTopGradient}),f.jsx("div",{className:o.cardPurpleBlur}),f.jsx("div",{className:o.cardPinkBlur}),f.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),f.jsx("div",{className:o.cardPulse1}),f.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return f.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${o.card} relative overflow-hidden`,"data-theme":t,style:{height:"100%",maxHeight:"100%",contain:"layout style paint",overscrollBehavior:"contain"},children:[f.jsx("div",{className:o.cardTopGradient}),f.jsx("div",{className:o.cardPurpleBlur}),f.jsx("div",{className:o.cardPinkBlur}),f.jsx("div",{className:"relative z-10 flex flex-col h-full",children:e}),f.jsx("div",{className:o.cardPulse1}),f.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})}function PE(e){if(typeof window>"u")return null;const{agentId:t,participantName:n,baseUrl:r,appSecret:i,appId:s,prompts:o,statusMessage:a,welcomeTitle:l,welcomeSubTitle:c,className:u,width:d,height:h,loadingText:m,suportsChatInput:g=!0,suportsVideoInput:p=!0,suportsScreenShare:b=!0,theme:v="vox",onSessionStart:k,onSessionEnd:S,enableSessionLogging:A=!0,onSessionLogsUpdate:T,onSessionMetricsUpdate:C,modalities:N=["voice"],displayType:P="widget",popupPosition:L="bottom-right",popupTriggerText:y="Open Chat",onPopupToggle:M,voxketClient:D,onDisplayTypeChange:B}=e,[H,K]=x.useState(!1),[de,ie]=x.useState(null),[F,W]=x.useState(()=>{try{if(D)return!!D.getCurrentSession()}catch(G){console.error("Error checking existing session:",G)}return!1}),[w,z]=x.useState(!1),[oe,E]=x.useState(t||""),[U,se]=x.useState(n||"User"),[$,ee]=x.useState(()=>{try{if(D)return D.getCurrentSession()}catch(G){console.error("Error getting current session:",G)}return null}),[Q,V]=x.useState(()=>{var G,be,Ce;try{if(D){const je=D.getCurrentSession();if((G=je==null?void 0:je.activeModalities)!=null&&G.includes("chat"))return"chat";if((be=je==null?void 0:je.activeModalities)!=null&&be.includes("voice"))return"voice";if((Ce=je==null?void 0:je.activeModalities)!=null&&Ce.includes("video"))return"video"}}catch(je){console.error("Error determining current mode:",je)}return"welcome"}),[X,fe]=x.useState(!1);x.useEffect(()=>{P==="fullscreen"&&console.log("๐ฏ Widget: Switched to fullscreen mode")},[P]),x.useEffect(()=>{F&&!w?console.log("๐ Session started:",{currentMode:Q,sessionId:$==null?void 0:$.id}):!F&&!w&&Q==="welcome"&&console.log("๐ Returned to welcome screen")},[F,Q,w]);const R=x.useMemo(()=>{try{if(D)return console.log("๐ Using existing VoxketClient to preserve session state"),D;if(!s||!i||!r){const be=`Missing required props: ${s?"":"appId "}${i?"":"appSecret "}${r?"":"baseUrl"}`;return console.error("โ VoxketClient creation failed:",be),ie(new Error(be)),K(!0),null}const G={appId:s,appSecret:i,baseUrl:r,agentId:oe,participantName:U||"User",modalities:N};return console.log("๐ง Creating new VoxketClient with config:",{appId:s.substring(0,8)+"...",baseUrl:r,agentId:oe,participantName:U||"User",modalities:N}),new $r(G)}catch(G){return console.error("โ Failed to create VoxketClient:",G),ie(G),K(!0),null}},[D,s,i,r,oe,U,N]),re=N,ne=x.useMemo(()=>{try{if(!R)return console.warn("โ ๏ธ No VoxketClient available, creating fallback room"),new te.Room;const G=R.getRoom();return console.log("๐ Widget: Room reference updated:",{roomExists:!!G,roomState:G==null?void 0:G.state,sessionStarted:F,currentMode:Q}),G||new te.Room}catch(G){return console.error("โ Error getting room from client:",G),new te.Room}},[R,F,Q]);x.useEffect(()=>{if(ne){const G=()=>{console.log("๐ Widget: Room state changed:",{state:ne.state,numParticipants:ne.numParticipants,isConnected:ne.state==="connected",sessionId:$==null?void 0:$.id})},be=(Ce,je,$e)=>{console.log("๐ต Widget: Track subscribed:",{trackKind:Ce.kind,trackSource:Ce.source,participantSid:$e.sid,participantIdentity:$e.identity,sessionId:$==null?void 0:$.id})};return ne.on(te.RoomEvent.Connected,G),ne.on(te.RoomEvent.Disconnected,G),ne.on(te.RoomEvent.TrackSubscribed,be),()=>{ne.off(te.RoomEvent.Connected,G),ne.off(te.RoomEvent.Disconnected,G),ne.off(te.RoomEvent.TrackSubscribed,be)}}},[ne,$==null?void 0:$.id]),x.useEffect(()=>{!w&&Q==="welcome"?console.log("๐ฌ Widget: Welcome screen ready"):F&&Q!=="welcome"&&console.log("๐ฌ Widget: Session mode active:",Q)},[Q,w,F]);const me={suportsChatInput:g,suportsVideoInput:p,suportsScreenShare:b};x.useEffect(()=>{(Q==="voice"||Q==="video"||Q==="chat")&&!$&&!F&&!w&&R&&!R.connected&&(console.log("๐ Auto-correcting: Found orphaned mode without session, returning to welcome"),V("welcome"),z(!1))},[Q,$,F,w,R]);const{sessionMetrics:Z,sessionLogs:pe,logEvent:Ae}=Cm({room:ne,onSessionStart:k,onSessionEnd:S,enableConsoleLogging:A,enableLocalStorage:A,voxketSessionId:$==null?void 0:$.id});x.useEffect(()=>{T&&T(pe)},[pe,T]),x.useEffect(()=>{C&&Z&&C(Z)},[Z,C]),x.useEffect(()=>{if(!R)return;const G=()=>{const be=R.connected,Ce=R.getCurrentSession();console.log("๐ Connection state changed:",{isConnected:be,currentSessionId:Ce==null?void 0:Ce.id,currentMode:Q,loading:w,sessionStarted:F}),!be&&F&&!w&&(console.log("๐ด Connection lost during active session - returning to welcome"),z(!1),W(!1),ee(null),V("welcome")),be&&Ce&&w&&(console.log("๐ข Connected with active session - removing loader"),z(!1),W(!0),ee(Ce))};return R.on("connectionStateChanged",G),R.on("sessionEnded",()=>{console.log("๐ Session ended - returning to welcome"),z(!1),W(!1),ee(null),V("welcome")}),()=>{R.off("connectionStateChanged",G),R.off("sessionEnded",()=>{})}},[R,Q,w,F]),x.useEffect(()=>{const G=Ce=>{console.log("๐ด Widget: Room disconnected:",Ce),console.log("๐ Widget: Current state on disconnect:",{currentMode:Q,sessionStarted:F,currentSessionId:$==null?void 0:$.id,loading:w}),z(!1),W(!1),ee(null),V("welcome"),console.log("๐ Widget: Automatically returning to welcome screen after disconnect")},be=Ce=>{console.log("๐น Media devices error:",Ce)};return ne.on(te.RoomEvent.MediaDevicesError,be),ne.on(te.RoomEvent.Disconnected,G),()=>{ne.off(te.RoomEvent.Disconnected,G),ne.off(te.RoomEvent.MediaDevicesError,be)}},[ne,Q,F,$==null?void 0:$.id,w]);const xe=async()=>{try{if(!R){console.error("โ VoxketClient not available"),ie(new Error("VoxketClient not initialized")),K(!0);return}z(!0),V("voice"),console.log("๐ค Starting voice session...",{agentId:oe,participantName:U}),console.log("๐ค Pre-start state:",{currentMode:"voice",sessionStarted:!1,loading:!0}),Ae("USER_STARTED_VOICE_SESSION",{agentId:oe,participantName:U});const G=await R.startSession(oe,{participantName:U||"User",modalities:["voice",...p?["video"]:[]]});console.log("โ
Voice session started successfully:",G.id),ee(G),W(!0),z(!1),k&&k(G.id)}catch(G){console.error("โ Failed to start voice session:",G),z(!1),W(!1),V("welcome")}},Ne=async()=>{try{if(!R){console.error("โ VoxketClient not available"),ie(new Error("VoxketClient not initialized")),K(!0);return}z(!0),V("chat"),console.log("๐ฌ Starting chat session...",{agentId:oe,participantName:U}),Ae("USER_STARTED_CHAT_SESSION",{agentId:oe,participantName:U});const G=await R.startSession(oe,{participantName:U||"User",modalities:["chat"]});console.log("โ
Chat session started successfully:",G.id),ee(G),W(!0),z(!1),k&&k(G.id)}catch(G){console.error("โ Failed to start chat session:",G),z(!1),W(!1),V("welcome")}},ze=async()=>{try{if(!R){console.error("โ VoxketClient not available"),ie(new Error("VoxketClient not initialized")),K(!0);return}z(!0),V("video"),console.log("๐บ Starting video session...",{agentId:oe,participantName:U}),console.log("๐บ Pre-start state:",{currentMode:"video",sessionStarted:!1,loading:!0}),Ae("USER_STARTED_VIDEO_SESSION",{agentId:oe,participantName:U});const G=await R.startSession(oe,{participantName:U||"User",modalities:["video","voice"]});console.log("โ
Video session started successfully:",G.id),ee(G),W(!0),z(!1),k&&k(G.id)}catch(G){console.error("โ Failed to start video session:",G),z(!1),W(!1),V("welcome")}},He=()=>{console.log("๐ Widget: handleBackToWelcome called",{currentMode:Q,sessionStarted:F,currentSessionId:$==null?void 0:$.id,displayType:P,loading:w}),V("welcome"),z(!1),B&&B(e.displayType||"widget"),$&&F?(console.log("๐งน Widget: Cleaning up active session"),W(!1),ee(null),R&&(console.log("๐ Widget: Disconnecting client and cleaning up room"),R.disconnect().catch(G=>{console.error("โ Widget: Error during disconnect:",G)}))):(console.log("๐ Widget: No active session to clean up"),R&&R.connected&&(console.log("๐ Widget: Force disconnecting client for fresh state"),R.disconnect().catch(G=>{console.error("โ Widget: Error during force disconnect:",G)}))),P==="popup"&&!X&&fe(!0),console.log("โ
Widget: handleBackToWelcome completed",{newCurrentMode:"welcome",newLoading:!1,newSessionStarted:!1})},nt=()=>{const G=!X;fe(G),M&&M(G),!G&&!($&&F)&&(V("welcome"),W(!1),ee(null))},Zt=()=>{console.log("๐ Closing fullscreen, switching to widget display type"),e.onDisplayTypeChange?e.onDisplayTypeChange("widget"):console.warn("โ ๏ธ No onDisplayTypeChange callback provided")},Ft=()=>{if(console.log("๐ Expand to fullscreen requested"),e.onDisplayTypeChange)e.onDisplayTypeChange("fullscreen");else{console.warn("โ ๏ธ No onDisplayTypeChange callback provided for expand functionality");const G=document.getElementById("voice-card")||document.querySelector(".voxket-widget-container");G&&G.requestFullscreen&&G.requestFullscreen().catch(be=>{console.warn("โ ๏ธ Fullscreen API not supported or failed:",be)})}};x.useEffect(()=>{var G,be,Ce;if(D&&R){const je=R.getCurrentSession();R.connected,je&&(console.log("โ
Restoring session state:",je.id),ee(je),W(!0),z(!1),(G=je.activeModalities)!=null&&G.includes("chat")?V("chat"):(be=je.activeModalities)!=null&&be.includes("voice")?V("voice"):(Ce=je.activeModalities)!=null&&Ce.includes("video")&&V("video"))}},[D,R]),x.useEffect(()=>()=>{!D&&R&&R.disconnect()},[R,D]);let _=Q==="video"?"w-[32rem]":"w-96",I=Q==="video"?"h-[30rem]":"h-[25rem]",q={};if(d&&(d.startsWith("w-")?_=d:(q.width=d,_="")),h&&(h.startsWith("h-")?I=h:(q.height=h,I="")),P==="popup"&&!X)return console.log("๐ก Showing popup trigger button"),f.jsx(jE,{onClick:nt,text:y,position:L,theme:v});if(H||!R){const G=(de==null?void 0:de.message)||"VoxketWidget encountered an error. Please check your configuration.";return f.jsx("div",{className:`voxket-widget-root theme-${v} flex items-center justify-center p-8 ${u||""}`,style:{width:d||"400px",height:h||"500px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"},children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"text-4xl mb-4",children:"โ ๏ธ"}),f.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Widget Error"}),f.jsx("p",{className:"text-sm mb-4",children:G}),f.jsx("button",{onClick:()=>{K(!1),ie(null),window.location.reload()},className:"px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"Retry"})]})})}let ue=`voxket-widget-root theme-${v}`,J={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};P==="widget"?(ue+=` flex items-center justify-center min-h-fit ${_} ${I} ${u}`,J={...J,...q}):(ue=`${u||""}`,J={});const ke=f.jsx("div",{className:"h-full flex flex-col overflow-hidden relative z-10",children:f.jsxs(Qt,{mode:"wait",children:[Q==="welcome"&&!w&&f.jsx(EE,{agentId:oe,participantName:U||"",onAgentIdChange:E,onParticipantNameChange:se,onStartCall:xe,onStartChat:Ne,onStartVideo:ze,disabled:F||w,prompts:o,statusMessage:a,title:l,subTitle:c,theme:v,modalities:re,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),w&&(Q==="voice"||Q==="chat"||Q==="video")&&f.jsx(AE,{theme:v,mode:Q,loadingText:m,initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.3,ease:"easeInOut"}},`loading-${Q}`),Q==="voice"&&!w&&F&&R&&f.jsxs(ut.RoomContext.Provider,{value:ne,children:[f.jsx(ut.RoomAudioRenderer,{},`audio-${($==null?void 0:$.id)||"no-session"}`),f.jsx(ut.StartAudio,{label:"Start Audio"},`start-audio-${($==null?void 0:$.id)||"no-session"}`),f.jsx(kE,{loadingText:m,participantName:U||"User",capabilities:me,sessionStarted:F,disabled:!1,theme:v,client:R,displayType:P,onBack:P==="popup"?nt:He,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"voice-session")]}),Q==="chat"&&!w&&F&&R&&f.jsx(SE,{client:R,theme:v,displayType:P,onBack:P==="popup"?nt:He,onEndChat:He,disabled:!1,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),Q==="video"&&!w&&F&&R&&f.jsxs(ut.RoomContext.Provider,{value:ne,children:[f.jsx(ut.RoomAudioRenderer,{},`audio-video-${($==null?void 0:$.id)||"no-session"}`),f.jsx(ut.StartAudio,{label:"Start Audio"},`start-audio-video-${($==null?void 0:$.id)||"no-session"}`),f.jsx(CE,{client:R,theme:v,displayType:P,onBack:P==="popup"?nt:He,onEndCall:He,disabled:!1,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-session")]})]})});return P==="fullscreen"||P==="popup"?f.jsx(Ku,{theme:v,displayType:P,popupPosition:L,onClose:P==="fullscreen"?Zt:nt,children:ke}):f.jsx("div",{className:ue,style:J,children:f.jsx(Ku,{theme:v,displayType:P,popupPosition:L,onExpand:Ft,children:ke})})}function ui(e){return f.jsx(Ha,{children:f.jsx(PE,{...e})})}function ME({logs:e,onClear:t,onExport:n}){const[r,i]=j.useState(!1),[s,o]=j.useState(""),a=e.filter(l=>!s||l.event.toLowerCase().includes(s.toLowerCase()));return r?f.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:f.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[f.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[f.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("input",{type:"text",placeholder:"Filter events...",value:s,onChange:l=>o(l.target.value),className:"px-3 py-1 border rounded text-sm"}),f.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),f.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),f.jsx("button",{onClick:()=>i(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),f.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?f.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):f.jsx("div",{className:"space-y-2",children:a.map((l,c)=>f.jsxs("div",{className:"border rounded p-3 text-sm",children:[f.jsxs("div",{className:"flex items-center justify-between mb-1",children:[f.jsx("span",{className:"font-semibold text-blue-600",children:l.event}),f.jsx("span",{className:"text-gray-500 text-xs",children:new Date(l.timestamp).toLocaleTimeString()})]}),l.sessionId&&f.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",l.sessionId]}),l.data&&f.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:f.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(l.data,null,2)})})]},c))})})]})}):f.jsxs("button",{onClick:()=>i(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",e.length,")"]})}function NE({metrics:e}){return e?f.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[f.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),f.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[f.jsxs("div",{children:[f.jsx("span",{className:"text-gray-600",children:"Session ID:"}),f.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),f.jsxs("div",{children:[f.jsx("span",{className:"text-gray-600",children:"Start Time:"}),f.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),f.jsxs("div",{children:[f.jsx("span",{className:"text-gray-600",children:"Messages:"}),f.jsx("div",{children:e.totalMessages})]}),f.jsxs("div",{children:[f.jsx("span",{className:"text-gray-600",children:"Participants:"}),f.jsx("div",{children:e.participantCount})]}),f.jsxs("div",{children:[f.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),f.jsx("div",{children:e.connectionIssues})]}),f.jsxs("div",{children:[f.jsx("span",{className:"text-gray-600",children:"Duration:"}),f.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function kn(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:r,endSession:i}=Dt(),s=j.useCallback(async(a,l)=>await r(a,l),[r]),o=j.useCallback(async()=>await i(),[i]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:s,stop:o}}function Tm(){const{sessionMetrics:e,currentSession:t}=Dt();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 Am(){const{setMicrophoneEnabled:e,client:t}=Dt(),[n,r]=j.useState(!1),[i,s]=j.useState(!1),o=j.useCallback(async()=>{if(!i){s(!0);try{const c=!n;await e(c),r(c)}catch(c){console.error("Failed to toggle microphone:",c)}finally{s(!1)}}},[n,i,e]),a=j.useCallback(async()=>{if(!(n||i)){s(!0);try{await e(!0),r(!0)}catch(c){console.error("Failed to enable microphone:",c)}finally{s(!1)}}},[n,i,e]),l=j.useCallback(async()=>{if(!(!n||i)){s(!0);try{await e(!1),r(!1)}catch(c){console.error("Failed to disable microphone:",c)}finally{s(!1)}}},[n,i,e]);return{isEnabled:n,isLoading:i,toggle:o,enable:a,disable:l}}function jm(){const{setCameraEnabled:e}=Dt(),[t,n]=j.useState(!1),[r,i]=j.useState(!1),s=j.useCallback(async()=>{if(!r){i(!0);try{const l=!t;await e(l),n(l)}catch(l){console.error("Failed to toggle camera:",l)}finally{i(!1)}}},[t,r,e]),o=j.useCallback(async()=>{if(!(t||r)){i(!0);try{await e(!0),n(!0)}catch(l){console.error("Failed to enable camera:",l)}finally{i(!1)}}},[t,r,e]),a=j.useCallback(async()=>{if(!(!t||r)){i(!0);try{await e(!1),n(!1)}catch(l){console.error("Failed to disable camera:",l)}finally{i(!1)}}},[t,r,e]);return{isEnabled:t,isLoading:r,toggle:s,enable:o,disable:a}}function Pm(){const{startScreenShare:e,stopScreenShare:t}=Dt(),[n,r]=j.useState(!1),[i,s]=j.useState(!1),o=j.useCallback(async()=>{if(!(n||i)){s(!0);try{await e(),r(!0)}catch(c){console.error("Failed to start screen share:",c)}finally{s(!1)}}},[n,i,e]),a=j.useCallback(async()=>{if(!(!n||i)){s(!0);try{await t(),r(!1)}catch(c){console.error("Failed to stop screen share:",c)}finally{s(!1)}}},[n,i,t]),l=j.useCallback(async()=>{n?await a():await o()},[n,o,a]);return{isSharing:n,isLoading:i,start:o,stop:a,toggle:l}}function IE(){const{client:e}=Dt(),[t,n]=j.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),r=j.useMemo(()=>t.tracks.find(p=>p.isLocal),[t.tracks]),i=j.useMemo(()=>t.tracks.filter(p=>!p.isLocal),[t.tracks]),s=j.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]),o=j.useCallback(async()=>{try{t.tracks.find(b=>b.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=j.useCallback(p=>{n(b=>({...b,layout:p}))},[]),l=j.useCallback(p=>{n(b=>({...b,pinnedTrack:p}))},[]),c=j.useCallback(()=>{n(p=>({...p,pinnedTrack:void 0}))},[]),u=j.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]),d=j.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=j.useCallback(p=>t.tracks.find(b=>b.id===p),[t.tracks]),m=j.useCallback(p=>t.tracks.filter(b=>b.participantId===p),[t.tracks]),g=j.useCallback(p=>p.isEnabled&&t.tracks.includes(p),[t.tracks]);return j.useEffect(()=>{if(!e)return;const p=k=>{n(S=>({...S,tracks:[...S.tracks.filter(A=>A.id!==k.id),k]}))},b=k=>{n(S=>{var A;return{...S,tracks:S.tracks.filter(T=>T.id!==k),pinnedTrack:((A=S.pinnedTrack)==null?void 0:A.id)===k?void 0:S.pinnedTrack}})},v=k=>{n(S=>({...S,tracks:S.tracks.map(A=>A.id===k.id?k:A)}))};return e.on("videoTrackAdded",p),e.on("videoTrackRemoved",b),e.on("videoTrackUpdated",v),()=>{e.off("videoTrackAdded",p),e.off("videoTrackRemoved",b),e.off("videoTrackUpdated",v)}},[e]),{tracks:t.tracks,localTrack:r,remoteTraracks:i,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:s,toggleScreenShare:o,setLayout:a,pinTrack:l,unpinTrack:c,startRecording:u,stopRecording:d,getTrackById:h,getTracksByParticipant:m,isTrackActive:g}}function Zi(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=Dt(),[r,i]=j.useState(!1),s=j.useCallback(async c=>{if(!(!c.trim()||r||!n)){i(!0);try{await t(c.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{i(!1)}}},[t,r,n]),{userMessages:o,agentMessages:a,allMessages:l}=j.useMemo(()=>{const c=e.filter(d=>d.sender.type==="participant"),u=e.filter(d=>d.sender.type==="agent");return{userMessages:c,agentMessages:u,allMessages:e}},[e]);return{messages:l,userMessages:o,agentMessages:a,messageCount:l.length,isSending:r,canSend:!!n&&!r,send:s}}function RE(){const{send:e,isSending:t,canSend:n}=Zi(),[r,i]=j.useState(""),s=j.useCallback(async()=>{if(!(!r.trim()||!n))try{await e(r),i("")}catch(a){throw a}},[r,e,n]),o=j.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),s())},[s]);return{value:r,setValue:i,send:s,handleKeyPress:o,isSending:t,canSend:n&&r.trim().length>0}}function Za(){const{isConnected:e,isConnecting:t,connectionError:n,connect:r,disconnect:i}=Dt(),s=j.useCallback(async()=>{if(!(e||t))try{await r()}catch(a){throw console.error("Failed to connect:",a),a}},[r,e,t]),o=j.useCallback(async()=>{if(e)try{await i()}catch(a){throw console.error("Failed to disconnect:",a),a}},[i,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:s,disconnect:o}}function Mm(){const{participants:e}=Dt();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const Nm=j.createContext({}),_r=()=>j.useContext(Nm);function Im({children:e,...t}){return f.jsx(Nm.Provider,{value:t,children:e})}function di({name:e,children:t,fallback:n,className:r}){return f.jsx("div",{className:`voxket-slot voxket-slot--${e} ${r||""}`,children:t||n})}function Rm(e,t={}){return Object.assign(e,t)}function Vm({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:r=!0,customControls:i,className:s=""}){const o=kn(),a=Am(),l=jm(),c=Pm(),u=_r(),d=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,o.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",s].filter(Boolean).join(" ");return!o.isActive&&!r?f.jsx("div",{className:d,children:f.jsx("div",{className:"voxket-controls-inactive",children:f.jsx("p",{children:"Controls available during active session"})})}):f.jsxs("div",{className:d,children:[r&&f.jsx("div",{className:"voxket-session-actions",children:o.isActive?f.jsx("button",{onClick:o.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):f.jsx(VE,{})}),o.isActive&&f.jsxs("div",{className:"voxket-media-controls",children:[e&&f.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:[f.jsx("span",{className:"voxket-icon",children:"๐ค"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&f.jsxs("button",{onClick:l.toggle,disabled:l.isLoading,className:`voxket-button voxket-button--media ${l.isEnabled?"voxket-button--active":""}`,title:l.isEnabled?"Stop camera":"Start camera",children:[f.jsx("span",{className:"voxket-icon",children:"๐น"}),l.isLoading?"Loading...":l.isEnabled?"Stop Video":"Start Video"]}),n&&f.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isSharing?"voxket-button--active":""}`,title:c.isSharing?"Stop screen share":"Start screen share",children:[f.jsx("span",{className:"voxket-icon",children:"๐ฅ๏ธ"}),c.isLoading?"Loading...":c.isSharing?"Stop Share":"Share Screen"]})]}),i&&f.jsx("div",{className:"voxket-custom-controls",children:i})]})}function VE(){kn();const[e,t]=j.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 f.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function qa({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:r=""}){const i=kn(),s=Za(),o=_r(),a=["voxket-session-header",`voxket-session-header--${o.variant||"default"}`,`voxket-session-header--${o.size||"md"}`,r].filter(Boolean).join(" ");return f.jsxs("div",{className:a,children:[e&&f.jsxs("div",{className:"voxket-connection-status",children:[f.jsx("div",{className:`voxket-status-indicator ${s.isConnected?"connected":"disconnected"}`}),f.jsx("span",{className:"voxket-status-text",children:s.isConnecting?"Connecting...":s.isConnected?"Connected":"Disconnected"})]}),t&&i.session&&f.jsxs("div",{className:"voxket-session-info",children:[f.jsxs("div",{className:"voxket-session-id",children:["Session: ",i.session.id.slice(-8)]}),f.jsxs("div",{className:"voxket-session-state",children:["State: ",i.state]})]}),n&&i.session&&f.jsxs("div",{className:"voxket-agent-info",children:[f.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",i.session.agentId]}),f.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",i.session.activeModalities.join(", ")]})]}),s.error&&f.jsxs("div",{className:"voxket-error-message",children:["Error: ",s.error.message]})]})}function Ga({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:r=""}){const i=kn(),s=Zi(),o=_r(),a=["voxket-session-content",`voxket-session-content--${o.variant||"default"}`,`voxket-session-content--${o.size||"md"}`,r].filter(Boolean).join(" ");return i.isActive?f.jsx("div",{className:a,children:n||f.jsxs(f.Fragment,{children:[e&&f.jsxs("div",{className:"voxket-chat-container",children:[f.jsxs("div",{className:"voxket-chat-messages",children:[s.messages.map(l=>f.jsxs("div",{className:`voxket-message voxket-message--${l.sender.type}`,children:[f.jsxs("div",{className:"voxket-message-header",children:[f.jsx("span",{className:"voxket-message-sender",children:l.sender.name}),f.jsx("span",{className:"voxket-message-time",children:l.timestamp.toLocaleTimeString()})]}),f.jsx("div",{className:"voxket-message-content",children:l.content})]},l.id)),s.messages.length===0&&f.jsx("div",{className:"voxket-empty-messages",children:f.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),f.jsx(DE,{})]}),t&&f.jsx("div",{className:"voxket-transcriptions",children:f.jsx("div",{className:"voxket-transcription-placeholder",children:f.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):f.jsx("div",{className:a,children:f.jsx("div",{className:"voxket-inactive-state",children:f.jsxs("div",{className:"voxket-inactive-message",children:[f.jsx("h3",{children:"Start a conversation"}),f.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function DE(){const e=Zi(),[t,n]=j.useState(""),r=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(s){console.error("Failed to send message:",s)}},i=s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),r())};return f.jsxs("div",{className:"voxket-chat-input",children:[f.jsx("input",{type:"text",value:t,onChange:s=>n(s.target.value),onKeyPress:i,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),f.jsx("button",{onClick:r,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function Ka({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:r,className:i=""}){const s=kn(),o=Tm(),a=Mm(),l=_r(),c=["voxket-session-footer",`voxket-session-footer--${l.variant||"default"}`,`voxket-session-footer--${l.size||"md"}`,i].filter(Boolean).join(" ");return s.isActive?f.jsx("div",{className:c,children:r||f.jsxs(f.Fragment,{children:[n&&f.jsxs("div",{className:"voxket-session-status",children:[f.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),f.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&o.metrics&&f.jsxs("div",{className:"voxket-session-metrics",children:[f.jsxs("div",{className:"voxket-metric",children:[f.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),f.jsx("span",{className:"voxket-metric-value",children:FE(o.duration||0)})]}),f.jsxs("div",{className:"voxket-metric",children:[f.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),f.jsx("span",{className:"voxket-metric-value",children:o.metrics.messageCount})]})]}),t&&f.jsxs("div",{className:"voxket-participants-info",children:[f.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&f.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>f.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):f.jsx("div",{className:c,children:f.jsx("div",{className:"voxket-footer-inactive",children:f.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function FE(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 LE({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:r,onSessionEnd:i,variant:s="default",size:o="md",theme:a,className:l="",children:c}){var m;const u=kn(),d=Za();j.useEffect(()=>{n&&e&&d.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,d.isConnected,u.isActive]),j.useEffect(()=>{var g;(g=u.session)!=null&&g.id&&r&&r(u.session.id)},[(m=u.session)==null?void 0:m.id,r]),j.useEffect(()=>()=>{u.isActive&&i&&u.stop().then(i).catch(console.error)},[]);const h=["voxket-session",`voxket-session--${s}`,`voxket-session--${o}`,u.isActive?"voxket-session--active":"voxket-session--inactive",l].filter(Boolean).join(" ");return f.jsx(Im,{variant:s,size:o,theme:a,className:l,children:f.jsx("div",{className:h,children:c||f.jsxs(f.Fragment,{children:[f.jsx(di,{name:"header",fallback:f.jsx(qa,{})}),f.jsx(di,{name:"content",fallback:f.jsx(Ga,{})}),f.jsx(di,{name:"footer",fallback:f.jsx(Ka,{})})]})})})}const Dm=Rm(LE,{Header:qa,Content:Ga,Footer:Ka,Controls:Vm}),xn={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)"}},js={...xn,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)"}},Ps={...xn,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=j.createContext(null),Lm=()=>{const e=j.useContext(Fm);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function OE({theme:e="default",themes:t={},children:n,cssVariables:r=!0,className:i=""}){const[s,o]=j.useState(()=>{const h={default:xn,dark:js,enterprise:Ps,...t};return typeof e=="string"?h[e]||xn:e}),[a,l]=j.useState(()=>({default:xn,dark:js,enterprise:Ps,...t})),c=h=>{if(typeof h=="string"){const m=a[h];m&&o(m)}else o(h)},u=h=>{l(m=>({...m,[h.name]:h}))};j.useEffect(()=>{if(r&&typeof document<"u"){const h=document.documentElement;Object.entries(Om(s)).forEach(([m,g])=>{h.style.setProperty(`--voxket-${m}`,g)})}},[s,r]);const d={theme:s,setTheme:c,themes:a,registerTheme:u};return f.jsx(Fm.Provider,{value:d,children:f.jsx("div",{className:`voxket-theme voxket-theme--${s.name} ${i}`,children:n})})}function Om(e){const t={},n=(r,i="")=>{for(const[s,o]of Object.entries(r)){const a=i?`${i}-${s}`:s;typeof o=="object"&&o!==null&&!Array.isArray(o)?n(o,a):t[a]=String(o)}};return n(e),t}function $E(e=xn,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 _E(e){var n;const{theme:t}=Lm();return((n=t.components)==null?void 0:n[e])||{}}const BE=Wa("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&zE(e),t.enableVoiceActivation&&HE(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&UE(e,t)}});function zE(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 HE(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function UE(e,t){console.log("Playing audio response:",t.content)}const WE=Wa("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&ZE(),t.enableFileUpload&&qE(e),t.enableCustomComponents&&GE(),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"?KE(e,t):t.type==="text"&&n.enableRichText&&YE(e,t)}});function ZE(e){console.log("Rich text support enabled")}function qE(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function GE(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",XE),t.set("form",QE),t.set("card",JE),t.set("chart",eT)}function KE(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 YE(e,t){console.log("Processing rich text message:",t.content)}function XE(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function QE(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function JE(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function eT(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function fi({track:e,participantName:t,showControls:n=!0,showName:r=!0,showMuteIndicator:i=!0,isPinned:s=!1,className:o="",onClick:a,onPin:l,onUnpin:c}){const u=j.useRef(null),[d,h]=j.useState(!1);j.useEffect(()=>{if(!u.current||!e.isEnabled)return;const b=u.current;return b.srcObject=null,()=>{b.srcObject&&(b.srcObject=null)}},[e]);const m=()=>{a==null||a(e)},g=b=>{b.stopPropagation(),s?c==null||c(e):l==null||l(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",s?"voxket-video-tile--pinned":"",e.isEnabled?"":"voxket-video-tile--disabled",d?"voxket-video-tile--hovered":"",o].filter(Boolean).join(" ");return f.jsxs("div",{className:p,onClick:m,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[f.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&f.jsxs("div",{className:"voxket-video-placeholder",children:[f.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"๐ฅ๏ธ":"๐น"}),f.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),f.jsxs("div",{className:"voxket-video-overlay",children:[r&&t&&f.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),i&&!e.isEnabled&&f.jsx("div",{className:"voxket-video-mute-indicator",children:"๐"}),n&&(d||s)&&f.jsxs("div",{className:"voxket-video-controls",children:[f.jsx("button",{className:`voxket-video-control-btn ${s?"voxket-video-control-btn--active":""}`,onClick:g,title:s?"Unpin video":"Pin video",children:"๐"}),e.isScreenShare&&f.jsx("div",{className:"voxket-video-indicator",children:"๐ฅ๏ธ"}),e.source&&f.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&f.jsx("div",{className:"voxket-video-loading",children:f.jsx("div",{className:"voxket-spinner"})})]})}function tT({tracks:e,layout:t,className:n="",onLayoutChange:r,onTrackClick:i,maxVisibleTracks:s=9,showPagination:o=!0}){const[a,l]=j.useState(0),[c,u]=j.useState(null),d=j.useMemo(()=>{let k=[...e];t.type==="speaker"&&c&&(k=[c,...e.filter(T=>T.id!==c.id)]);const S=a*s,A=S+s;return k.slice(S,A)},[e,t,c,a,s]),h=Math.ceil(e.length/s),m=j.useMemo(()=>{const k=d.length;switch(t.type){case"grid":const S=Math.ceil(Math.sqrt(k)),A=Math.ceil(k/S);return{display:"grid",gridTemplateColumns:`repeat(${S}, 1fr)`,gridTemplateRows:`repeat(${A}, 1fr)`,gap:"8px"};case"speaker":return{display:"flex",flexDirection:"column",gap:"8px"};case"sidebar":return{display:"flex",gap:"8px"};case"gallery":return{display:"flex",flexWrap:"wrap",gap:"8px",justifyContent:"center"};default:return{}}},[t.type,d.length]),g=k=>{u(k)},p=()=>{u(null)},b=k=>{r==null||r({...t,type:k})},v=["voxket-video-grid",`voxket-video-grid--${t.type}`,`voxket-video-grid--${d.length}-tracks`,n].filter(Boolean).join(" ");return e.length===0?f.jsx("div",{className:"voxket-video-grid-empty",children:f.jsxs("div",{className:"voxket-video-grid-empty-content",children:[f.jsx("div",{className:"voxket-video-grid-empty-icon",children:"๐น"}),f.jsx("p",{children:"No video tracks available"})]})}):f.jsxs("div",{className:v,children:[f.jsxs("div",{className:"voxket-video-grid-controls",children:[f.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(k=>f.jsx("button",{className:`voxket-layout-btn ${t.type===k?"voxket-layout-btn--active":""}`,onClick:()=>b(k),title:`Switch to ${k} layout`,children:nT(k)},k))}),f.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),f.jsx("div",{className:"voxket-video-grid-content",style:m,children:t.type==="speaker"&&c?f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"voxket-video-speaker-main",children:f.jsx(fi,{track:c,participantName:`Participant ${c.participantId}`,isPinned:!0,onClick:i,onUnpin:p})}),f.jsx("div",{className:"voxket-video-speaker-sidebar",children:d.filter(k=>k.id!==c.id).map(k=>f.jsx(fi,{track:k,participantName:`Participant ${k.participantId}`,showControls:!1,onClick:i,onPin:g},k.id))})]}):d.map(k=>f.jsx(fi,{track:k,participantName:`Participant ${k.participantId}`,isPinned:(c==null?void 0:c.id)===k.id,onClick:i,onPin:g,onUnpin:p},k.id))}),o&&h>1&&f.jsxs("div",{className:"voxket-video-pagination",children:[f.jsx("button",{className:"voxket-pagination-btn",onClick:()=>l(Math.max(0,a-1)),disabled:a===0,children:"โ"}),f.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",h]}),f.jsx("button",{className:"voxket-pagination-btn",onClick:()=>l(Math.min(h-1,a+1)),disabled:a===h-1,children:"โ"})]})]})}function nT(e){switch(e){case"grid":return"โ";case"speaker":return"๐ค";case"sidebar":return"โซธ";case"gallery":return"โก";case"picture-in-picture":return"โง";default:return"โ"}}function rT({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:r,showLayoutControls:i=!0,showCameraControls:s=!0,showScreenShareControls:o=!0,className:a=""}){const l=["voxket-video-controls",a].filter(Boolean).join(" "),c=u=>{r==null||r({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return f.jsxs("div",{className:l,children:[s&&f.jsxs("div",{className:"voxket-video-controls-section",children:[f.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),f.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:[f.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"๐น":"๐ท"}),f.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&f.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," ร ",e.dimensions.height]})]}),o&&f.jsxs("div",{className:"voxket-video-controls-section",children:[f.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),f.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:[f.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"๐":"๐ฅ๏ธ"}),f.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),i&&f.jsxs("div",{className:"voxket-video-controls-section",children:[f.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),f.jsx("div",{className:"voxket-layout-buttons",children:[{type:"grid",icon:"โ",label:"Grid"},{type:"speaker",icon:"๐ค",label:"Speaker"},{type:"sidebar",icon:"โซธ",label:"Sidebar"},{type:"gallery",icon:"โก",label:"Gallery"}].map(({type:u,icon:d,label:h})=>f.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>c(u),title:`Switch to ${h} layout`,children:[f.jsx("span",{className:"voxket-control-icon",children:d}),f.jsx("span",{className:"voxket-control-label",children:h})]},u))})]}),f.jsxs("div",{className:"voxket-video-controls-section",children:[f.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),f.jsxs("div",{className:"voxket-video-settings",children:[f.jsxs("div",{className:"voxket-setting-group",children:[f.jsx("label",{className:"voxket-setting-label",children:"Quality"}),f.jsxs("select",{className:"voxket-setting-select",children:[f.jsx("option",{value:"high",children:"High (720p)"}),f.jsx("option",{value:"medium",children:"Medium (480p)"}),f.jsx("option",{value:"low",children:"Low (240p)"})]})]}),f.jsxs("div",{className:"voxket-setting-group",children:[f.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),f.jsxs("select",{className:"voxket-setting-select",children:[f.jsx("option",{value:"30",children:"30 fps"}),f.jsx("option",{value:"15",children:"15 fps"}),f.jsx("option",{value:"10",children:"10 fps"})]})]}),f.jsxs("div",{className:"voxket-setting-group",children:[f.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),f.jsxs("select",{className:"voxket-setting-select",children:[f.jsx("option",{value:"unlimited",children:"Unlimited"}),f.jsx("option",{value:"1000",children:"1 Mbps"}),f.jsx("option",{value:"500",children:"500 Kbps"}),f.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),f.jsxs("div",{className:"voxket-video-controls-section",children:[f.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),f.jsxs("div",{className:"voxket-video-stats",children:[f.jsxs("div",{className:"voxket-stat-item",children:[f.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),f.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}ร${e.dimensions.height}`:"N/A"})]}),f.jsxs("div",{className:"voxket-stat-item",children:[f.jsx("span",{className:"voxket-stat-label",children:"Source:"}),f.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),f.jsxs("div",{className:"voxket-stat-item",children:[f.jsx("span",{className:"voxket-stat-label",children:"Status:"}),f.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 $m=({handler:e,loadData:t,data:n,client:r,addLocalMessage:i})=>{const[s,o]=x.useState(null),[a,l]=x.useState(!0),[c,u]=x.useState(!1),[d]=x.useState(Date.now());x.useEffect(()=>{(async()=>{try{if(l(!0),console.log("๐ AssignmentView: Loading assignment data..."),console.log("๐ AssignmentView: Received data from RPC:",n),n&&typeof n=="object"){const b={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};o(b),console.log("๐ AssignmentView: Assignment loaded from RPC data:",b)}}catch(b){console.error("๐ AssignmentView: Error loading assignment:",b),o({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{l(!1)}})()},[n,t]);const h=({message:p,assignment:b})=>{const v=p.toLowerCase().includes("declined"),k=v?"bg-red-50 border-red-200":"bg-green-50 border-green-200",S=v?"text-red-700":"text-green-700",A=v?"โ":"๐";return f.jsxs("div",{className:`max-w-sm mx-auto ${k} border rounded-lg shadow p-3 flex flex-col items-center`,children:[f.jsx("div",{className:"text-2xl mb-2",children:A}),f.jsx("div",{className:`${S} font-semibold text-sm mb-1`,children:p}),f.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:b.title}),f.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},m=async()=>{if(!(!s||!e)){u(!0);try{const p={message:"accepted"};console.log("๐ AssignmentView: Assignment accepted:",p),e.didSuccess(p,f.jsx(h,{message:"Assignment accepted!",assignment:s}))}catch(p){console.error("๐ AssignmentView: Error accepting assignment:",p),e.didFail({error:"Failed to accept assignment"})}finally{u(!1)}}},g=async()=>{if(!(!s||!e)){u(!0);try{const p={message:"declined"};console.log("๐ AssignmentView: Assignment declined:",p),e.didSuccess(p,f.jsx(h,{message:"Assignment declined",assignment:s}))}catch(p){console.error("๐ AssignmentView: Error declining assignment:",p),e.didFail({error:"Failed to decline assignment"})}finally{u(!1)}}};return a?f.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:f.jsxs("div",{className:"flex items-center justify-center py-4",children:[f.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),f.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):s?f.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[f.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:f.jsx("div",{className:"flex items-center justify-between",children:f.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:s.title})})}),f.jsxs("div",{className:"p-3 text-black",children:[f.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:f.jsx("p",{className:"text-xs text-black leading-snug",children:s.description})}),f.jsx("div",{className:"mb-3 text-black",children:f.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[f.jsx("span",{className:"text-xs mr-1",children:"๐
"}),f.jsxs("span",{children:["Est: ",s.estimated_time_of_completion]})]})}),f.jsxs("div",{className:"flex gap-2",children:[f.jsx("button",{onClick:m,disabled:c,className:"flex-1 bg-green-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:c?f.jsxs("span",{className:"flex items-center justify-center",children:[f.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),f.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),f.jsx("button",{onClick:g,disabled:c,className:"flex-1 bg-red-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Decline"})]})]})]}):f.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:f.jsxs("div",{className:"text-center py-4",children:[f.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"โ ๏ธ Assignment Error"}),f.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function iT(){const[e,t]=x.useState(null),[n,r]=x.useState([]);x.useEffect(()=>{const a=new $r({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return t(a),a.on("rpc.method.called",l=>{console.log("RPC Method Called:",l)}),a.on("rpc.interaction.completed",l=>{console.log("RPC Interaction Completed:",l)}),()=>{a.disconnect()}},[]);const i=async()=>{if(e)try{await e.registerFrontendRPC("give_assignment",$m,"embedded");const a=e.getRegisteredRpcMethods();r(a),console.log("โ
Assignment RPC registered successfully")}catch(a){console.error("โ Failed to register assignment RPC:",a)}},s=async()=>{if(!e)return;const a=({handler:l,timeout:c})=>{const[u,d]=x.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"}],m=p=>{d(p)},g=()=>{const p=h.find(b=>b.id===u);l==null||l.didSuccess({selectedProduct:u,productName:p==null?void 0:p.name,price:p==null?void 0:p.price,timestamp:new Date().toISOString()})};return f.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[f.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),f.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),f.jsx("div",{className:"space-y-3 mb-6",children:h.map(p=>f.jsx("div",{onClick:()=>m(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:f.jsxs("div",{className:"flex justify-between items-center",children:[f.jsxs("div",{children:[f.jsx("h4",{className:"font-medium",children:p.name}),f.jsx("p",{className:"text-gray-600 text-sm",children:p.price})]}),f.jsx("div",{className:`w-4 h-4 rounded-full ${u===p.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},p.id))}),f.jsxs("div",{className:"flex justify-end space-x-3",children:[f.jsx("button",{onClick:()=>l==null?void 0:l.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),f.jsx("button",{onClick:g,disabled:!u,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),c&&f.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",c," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const l=e.getRegisteredRpcMethods();r(l),console.log("โ
Product Recommendation RPC registered successfully")}catch(l){console.error("โ Failed to register product recommendation RPC:",l)}},o=async()=>{if(!e)return;const a=({handler:l})=>{const[c,u]=x.useState(0),[d,h]=x.useState(""),m=()=>{l==null||l.didSuccess({rating:c,comment:d,timestamp:new Date().toISOString()})};return f.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[f.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),f.jsxs("div",{className:"mb-4",children:[f.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),f.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(g=>f.jsx("button",{onClick:()=>u(g),className:`text-2xl ${g<=c?"text-yellow-400":"text-gray-300"}`,children:"โญ"},g))})]}),f.jsxs("div",{className:"mb-4",children:[f.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),f.jsx("textarea",{value:d,onChange:g=>h(g.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),f.jsxs("div",{className:"flex justify-end space-x-2",children:[f.jsx("button",{onClick:()=>l==null?void 0:l.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),f.jsx("button",{onClick:m,disabled:c===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await e.registerFrontendRPC("collect_feedback",a,"embedded");const l=e.getRegisteredRpcMethods();r(l),console.log("โ
Feedback RPC registered successfully")}catch(l){console.error("โ Failed to register feedback RPC:",l)}};return f.jsxs("div",{className:"p-6",children:[f.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),f.jsxs("div",{className:"space-y-4 mb-6",children:[f.jsxs("div",{children:[f.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),f.jsxs("div",{className:"space-x-2",children:[f.jsx("button",{onClick:i,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),f.jsx("button",{onClick:s,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),f.jsx("button",{onClick:o,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),f.jsxs("div",{children:[f.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?f.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>f.jsx("li",{className:"text-gray-700",children:f.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):f.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),f.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[f.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),f.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[f.jsxs("li",{children:["Register RPC methods with React components using ",f.jsx("code",{children:"client.registerFrontendRPC()"})]}),f.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),f.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),f.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),f.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),f.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[f.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),f.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),f.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
|
|
163
|
+
`,style:{minHeight:"2.5rem",display:o===r?"block":"none"},children:s},o))})}function yE({statusMessage:e,theme:t}){const n=et(t);return f.jsxs("div",{className:"z-10 flex items-center space-x-2 mt-2 pb-2",children:[f.jsx("div",{className:n.statusIndicator}),f.jsx("span",{className:`text-xs ${n.text.muted}`,children:e})]})}const Sm=j.forwardRef(({disabled:e,onStartCall:t,onStartChat:n,onStartVideo:r,prompts:i=['"Book a meeting with the marketing team"',`"What's the status of project Alpha?"`,`"Summarize yesterday's sales report"`,'"Find a good Italian restaurant nearby"','"Remind me to call John tomorrow at 10 AM"'],statusMessage:s="Agent is ready",title:o="Choose how to interact",subTitle:a="Ask me anything or give me a task to complete",theme:l="vox",modalities:c=["voice","chat","video"]},u)=>{const d=et(l),h=c.includes("voice"),m=c.includes("chat"),g=c.includes("video"),p=[h,m,g].filter(Boolean).length;return f.jsxs("div",{className:"flex p-8 flex-col items-center h-full justify-center w-full relative","aria-disabled":e,style:{background:"transparent"},children:[f.jsxs("div",{className:"mt-1 relative flex items-center justify-center mb-8 w-full",style:{minHeight:"120px"},children:[f.jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[f.jsx("div",{className:d.pulseRings.ring1}),f.jsx("div",{className:d.pulseRings.ring2,style:{animationDelay:"0.5s"}}),f.jsx("div",{className:d.pulseRings.ring3,style:{animationDelay:"1s"}})]}),f.jsx("div",{className:"relative z-10 flex items-center justify-center",children:h&&m&&g?f.jsxs("div",{className:"flex gap-4 items-center justify-center",children:[f.jsx(ni,{onClick:t,disabled:e,theme:l}),f.jsx($o,{onClick:n,disabled:e,theme:l}),f.jsx(_o,{onClick:r||t,disabled:e,theme:l})]}):p>1?f.jsxs("div",{className:"flex gap-6 items-center justify-center",children:[h&&f.jsx(ni,{onClick:t,disabled:e,theme:l}),m&&f.jsx($o,{onClick:n,disabled:e,theme:l}),g&&r&&f.jsx(_o,{onClick:r,disabled:e,theme:l})]}):f.jsx("div",{className:"flex items-center justify-center",children:h?f.jsx(ni,{onClick:t,disabled:e,theme:l}):m?f.jsx($o,{onClick:n,disabled:e,theme:l}):g&&r?f.jsx(_o,{onClick:r,disabled:e,theme:l}):f.jsx(ni,{onClick:t,disabled:e,theme:l})})})]}),f.jsxs("div",{className:"text-center flex flex-col items-center gap-y-2 mb-6 w-full",children:[f.jsx("h3",{className:`text-xl font-semibold mb-2 ${d.text.accent}`,children:o}),f.jsx("p",{className:`text-sm leading-relaxed px-4 ${d.text.secondary}`,children:a}),p>1&&f.jsxs("div",{className:"flex gap-6 mt-4 text-xs justify-center",children:[h&&f.jsxs("div",{className:"flex flex-col items-center gap-1",children:[f.jsx(gh,{className:"w-4 h-4"}),f.jsx("span",{className:d.text.muted,children:"Voice"})]}),m&&f.jsxs("div",{className:"flex flex-col items-center gap-1",children:[f.jsx(ph,{className:"w-4 h-4"}),f.jsx("span",{className:d.text.muted,children:"Chat"})]}),g&&f.jsxs("div",{className:"flex flex-col items-center gap-1",children:[f.jsx(yh,{className:"w-4 h-4"}),f.jsx("span",{className:d.text.muted,children:"Video"})]})]})]}),f.jsx(gE,{prompts:i,theme:l}),f.jsx(yE,{statusMessage:s,theme:l})]})});Sm.displayName="Welcome";class Ha extends x.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 x.createElement(t,{error:this.state.error})}return x.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 Cm({room:e,onSessionEnd:t,onSessionStart:n,enableConsoleLogging:r=!0,enableLocalStorage:i=!0,voxketSessionId:s}={}){const[o,a]=x.useState(null),[l,c]=x.useState([]),[u,d]=x.useState(null),[h,m]=x.useState([]),g=x.useCallback((k,S)=>{const A={timestamp:new Date,event:k,data:S,sessionId:o==null?void 0:o.sessionId,participantId:u==null?void 0:u.identity};if(c(T=>[...T,A]),i){const T=JSON.parse(localStorage.getItem("voxket-session-logs")||"[]");T.push(A),localStorage.setItem("voxket-session-logs",JSON.stringify(T))}return A},[o==null?void 0:o.sessionId,u==null?void 0:u.identity,r,i]);x.useEffect(()=>{if(!e)return;const k=()=>{const y=s||`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,M=new Date,D={sessionId:y,startTime:M,totalMessages:0,connectionIssues:0,participantCount:h.length,events:[]};a(D),g("SESSION_STARTED",{sessionId:y,startTime:M}),n==null||n(y)},S=()=>{if(o){const y=new Date,M=y.getTime()-o.startTime.getTime(),D={...o,endTime:y,duration:M,events:l};g("SESSION_ENDED",{sessionId:o.sessionId,duration:`${Math.round(M/1e3)}s`,totalMessages:o.totalMessages,connectionIssues:o.connectionIssues}),t==null||t(D),a(null),c([])}},A=y=>{g("CONNECTION_STATE_CHANGED",{state:y}),y===te.ConnectionState.Reconnecting&&o&&(a(M=>M?{...M,connectionIssues:M.connectionIssues+1}:null),g("CONNECTION_ISSUE",{type:"reconnecting"}))},T=y=>{g("TRACK_PUBLISHED",{trackKind:y.kind,trackSource:y.source})},C=y=>{g("TRACK_UNPUBLISHED",{trackKind:y.kind,trackSource:y.source})},N=(y,M)=>{o&&a(D=>D?{...D,totalMessages:D.totalMessages+1}:null),g("DATA_RECEIVED",{participantId:M==null?void 0:M.identity,dataSize:y.length})},P=y=>{g("PARTICIPANT_CONNECTED",{participantId:y.identity,participantName:y.name}),m(M=>[...M,y]),o&&a(M=>M?{...M,participantCount:M.participantCount+1}:null)},L=y=>{g("PARTICIPANT_DISCONNECTED",{participantId:y.identity,participantName:y.name}),m(M=>M.filter(D=>D.identity!==y.identity))};return e.localParticipant&&d(e.localParticipant),e.on(te.RoomEvent.Connected,k),e.on(te.RoomEvent.Disconnected,S),e.on(te.RoomEvent.ConnectionStateChanged,A),e.on(te.RoomEvent.TrackPublished,T),e.on(te.RoomEvent.TrackUnpublished,C),e.on(te.RoomEvent.DataReceived,N),e.on(te.RoomEvent.ParticipantConnected,P),e.on(te.RoomEvent.ParticipantDisconnected,L),()=>{e.off(te.RoomEvent.Connected,k),e.off(te.RoomEvent.Disconnected,S),e.off(te.RoomEvent.ConnectionStateChanged,A),e.off(te.RoomEvent.TrackPublished,T),e.off(te.RoomEvent.TrackUnpublished,C),e.off(te.RoomEvent.DataReceived,N),e.off(te.RoomEvent.ParticipantConnected,P),e.off(te.RoomEvent.ParticipantDisconnected,L)}},[e,o,l,h.length,g,t,n]);const p=x.useCallback(()=>i?JSON.parse(localStorage.getItem("voxket-session-logs")||"[]"):l,[l,i]),b=x.useCallback(()=>{i&&localStorage.removeItem("voxket-session-logs"),c([])},[i]),v=x.useCallback(()=>{const k=p(),S=JSON.stringify(k,null,2),A="data:application/json;charset=utf-8,"+encodeURIComponent(S),T=`voxket-session-logs-${new Date().toISOString().split("T")[0]}.json`,C=document.createElement("a");C.setAttribute("href",A),C.setAttribute("download",T),C.click()},[p]);return{sessionMetrics:o,sessionLogs:l,logEvent:g,getSessionLogs:p,clearSessionLogs:b,exportSessionLogs:v}}class Ua{constructor(){Ue(this,"listeners",{})}on(t,n){return this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(n),()=>this.off(t,n)}once(t,n){const r=(...i)=>{this.off(t,r),n(...i)};return this.on(t,r)}off(t,n){const r=this.listeners[t];if(!r)return;const i=r.indexOf(n);i>-1&&r.splice(i,1)}removeAllListeners(t){t?delete this.listeners[t]:this.listeners={}}emit(t,...n){const r=this.listeners[t];if(!r)return;const i=[...r];for(const s of i)try{s(...n)}catch(o){console.error(`Error in event listener for ${String(t)}:`,o)}}listenerCount(t){var n;return((n=this.listeners[t])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class As{constructor(t){Ue(this,"plugins",new Map);Ue(this,"installedPlugins",new Set);Ue(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 s of r.dependencies)this.installedPlugins.has(s)||await this.install(s);const i={...this.context,config:{...r.config,...n}};r.install&&await r.install(i),this.installedPlugins.add(t),this.setupPluginEvents(r,i)}async uninstall(t){var r;const n=this.plugins.get(t);if(!n)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t)){for(const[i,s]of this.plugins)if(this.installedPlugins.has(i)&&((r=s.dependencies)!=null&&r.includes(t)))throw new Error(`Cannot uninstall '${t}' because '${i}' depends on it`);n.uninstall&&await n.uninstall(this.context),this.installedPlugins.delete(t)}}isInstalled(t){return this.installedPlugins.has(t)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(t){return this.plugins.get(t)}setupPluginEvents(t,n){t.onSessionStart&&n.on("session.started",r=>{t.onSessionStart(n,r.id)}),t.onSessionEnd&&n.on("session.ended",r=>{t.onSessionEnd(n,r.id)}),t.onAgentResponse&&n.on("agent.response",r=>{t.onAgentResponse(n,r)})}}function xE(e){return e}function Wa(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 bE={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)})}},vE={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))}},wE={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})})}},Em=j.createContext(null);function ci({config:e,children:t,autoConnect:n=!1,client:r}){const[i,s]=j.useState(null),[o,a]=j.useState(!1),[l,c]=j.useState(!1),[u,d]=j.useState(null),[h,m]=j.useState(null),[g,p]=j.useState("idle"),[b,v]=j.useState(null),[k,S]=j.useState([]),[A,T]=j.useState([]),[C,N]=j.useState([]);j.useEffect(()=>{const W=r||new $r(e);s(W);const w=P(W);return n&&!r&&L(W),()=>{w(),r||W.disconnect().catch(console.error)}},[e,n,r]);const P=W=>{const w=()=>{c(!0),d(null)},z=()=>{a(!0),c(!1),d(null)},oe=()=>{a(!1),c(!1),m(null),p("idle"),S([]),T([]),N([])},E=re=>{d(re),c(!1)},U=re=>{m(re),p(re.state)},se=re=>{p(re),h&&m({...h,state:re})},$=(re,ne)=>{m(null),p("idle"),v(ne),S([]),T([]),N([])},ee=re=>{S(ne=>[...ne,re])},Q=re=>{S(ne=>ne.filter(me=>me.id!==re.id))},V=re=>{T(ne=>[...ne,re])},X=re=>{T(ne=>[...ne,re])},fe=re=>{console.log("๐ VoxketProvider: Received transcription:",re),N(ne=>ne.find(Z=>Z.id===re.id)?(console.log("๐ VoxketProvider: Duplicate transcription detected, skipping:",re.id),ne):(console.log("๐ VoxketProvider: Adding new transcription:",re.id),[...ne,re]))},R=()=>{console.log("๐งน VoxketProvider: Clearing chat messages and transcriptions"),T([]),N([])};return W.on("connection.connecting",w),W.on("connection.connected",z),W.on("connection.disconnected",oe),W.on("connection.error",E),W.on("session.created",U),W.on("session.state.changed",se),W.on("session.ended",$),W.on("participant.joined",ee),W.on("participant.left",Q),W.on("chat.message.received",V),W.on("chat.message.sent",X),W.on("transcription.received",fe),W.on("chat.history.cleared",R),()=>{console.log("๐ VoxketProvider: Cleaning up event listeners"),W.off("connection.connecting",w),W.off("connection.connected",z),W.off("connection.disconnected",oe),W.off("connection.error",E),W.off("session.created",U),W.off("session.state.changed",se),W.off("session.ended",$),W.off("participant.joined",ee),W.off("participant.left",Q),W.off("chat.message.received",V),W.off("chat.message.sent",X),W.off("chat.history.cleared",R),W.off("transcription.received",fe)}},L=async W=>{const w=W||i;if(w)try{await w.connect()}catch(z){console.error("Failed to connect:",z)}},F={client:i,isConnected:o,isConnecting:l,connectionError:u,currentSession:h,sessionState:g,sessionMetrics:b,participants:k,chatMessages:A,transcriptions:C,connect:()=>L(),disconnect:async()=>{if(i)try{await i.disconnect()}catch(W){console.error("Failed to disconnect:",W)}},createSession:async(W,w={})=>{if(!i)throw new Error("Client not initialized");const z={agentId:W,participantName:w.participantName||"User",metadata:w.metadata,modalities:w.modalities||["voice"]};return await i.createSession(z)},endSession:async()=>i?await i.endSession():null,sendChatMessage:async W=>{if(!i)throw new Error("Client not initialized");await i.sendChatMessage(W)},setMicrophoneEnabled:async W=>{if(!i)throw new Error("Client not initialized");await i.setMicrophoneEnabled(W)},setCameraEnabled:async W=>{if(!i)throw new Error("Client not initialized");await i.setCameraEnabled(W)},startScreenShare:async()=>{if(!i)throw new Error("Client not initialized");await i.startScreenShare()},stopScreenShare:async()=>{if(!i)throw new Error("Client not initialized");await i.stopScreenShare()}};return f.jsx(Em.Provider,{value:F,children:t})}function Dt(){const e=j.useContext(Em);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}class Gu extends Ua{constructor(n){super();Ue(this,"room",null);Ue(this,"registeredMethods",new Map);Ue(this,"activeInteractions",new Map);Ue(this,"currentInteraction",null);n&&this.setRoom(n)}setRoom(n){this.room=n}async registerFrontendRPC(n,r,i="embedded"){if(console.log(`RpcManager: Starting registration for method '${n}'`),!this.room)throw console.error(`RpcManager: Cannot register '${n}' - no room instance`),new Error("Room not initialized. Cannot register RPC method.");if(!this.room.localParticipant)throw console.error(`RpcManager: Cannot register '${n}' - no local participant`),new Error("Local participant not available for RPC registration");console.log(`RpcManager: Room state: ${this.room.state}`),console.log(`RpcManager: Local participant: ${this.room.localParticipant.identity}`),console.log(`RpcManager: Registering frontend RPC method: ${n}`);const s={methodName:n,component:r,presentationMode:i};this.registeredMethods.set(n,s);try{this.room.registerRpcMethod(n,async o=>{console.log(`RpcManager: RPC method '${n}' called by ${o.callerIdentity}`),console.log("RpcManager: Payload:",o.payload),this.emit("rpc.method.called",{methodName:n,data:o});let a;console.log(`RpcManager: Current registration for '${n}':`,s);let l=o.responseTimeout||30;try{a=JSON.parse(o.payload)}catch{a=o.payload}try{const c=await this.awaitUserInteraction(n,r,i,a,l);return JSON.stringify(c)}catch(c){throw console.error(`RpcManager: Error in RPC method '${n}':`,c),c}}),this.emit("rpc.method.registered",{methodName:n}),console.log(`RpcManager: Successfully registered RPC method: ${n}`)}catch(o){throw console.error(`RpcManager: Failed to register RPC method '${n}':`,o),o}}async awaitUserInteraction(n,r,i,s,o){return new Promise((a,l)=>{const c=`${n}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${n}, timeout: ${o} seconds`);const u={didSuccess:(h,m)=>{console.log(`RpcManager: User interaction successful for method: ${n}`,h),this.clearInteraction(c),this.currentInteraction=null;const g={success:!0,message:"User interaction completed successfully",data:h,timestamp:new Date,...m?{successView:m}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:g}),a(g)},didFail:h=>{console.log(`RpcManager: User interaction failed for method: ${n}`,h),this.clearInteraction(c);const m={success:!1,message:"User interaction failed",error:h,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:m}),a(m)},dismissView:()=>{var m;console.log(`RpcManager: User dismissed interaction for method: ${n}`),console.log("RpcManager: Current interaction before dismiss:",(m=this.currentInteraction)==null?void 0:m.methodName),this.clearInteraction(c),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 g;((g=this.currentInteraction)==null?void 0:g.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(c),this.currentInteraction=null;const m={success:!0,message:`User interaction timed out after ${o} 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:m}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(m)}},d=setTimeout(()=>{u.didTimeout&&u.didTimeout()},o);this.activeInteractions.set(c,{resolve:h=>a(JSON.parse(h)),reject:l,timeoutId:d}),this.currentInteraction={isVisible:!0,methodName:n,component:r,presentationMode:i,timeout:o,data:s,handler:u},this.emit("rpc.interaction.started",{methodName:n,presentationMode:i}),setTimeout(async()=>{var h;if((h=this.currentInteraction)!=null&&h.handler)try{console.log(`RpcManager: Component created for method: ${n} with data:`,s)}catch(m){console.error("RpcManager: Error loading data into component:",m),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 Ve extends Error{constructor(t,n,r){super(t),this.code=n,this.details=r,this.name="VoxketError"}}const Kt=new WeakSet,Bo=new WeakSet;class $r extends Ua{constructor(n){super();Ue(this,"config");Ue(this,"room",null);Ue(this,"pluginManager");Ue(this,"rpcManager");Ue(this,"isConnected",!1);Ue(this,"currentSession",null);Ue(this,"connectionState",te.ConnectionState.Disconnected);Ue(this,"renderedComponents",new Map);Ue(this,"textStreamHandlersRegistered",!1);Ue(this,"currentAgentInfo",null);Ue(this,"chatMessages",[]);Ue(this,"activeTranscriptions",new Map);Ue(this,"isAgentConnected",!1);Ue(this,"agentState","idle");if(typeof window>"u"){console.warn("VoxketClient: Skipping initialization in server-side environment"),this.config=n,this.pluginManager=new As(this),this.rpcManager=new Gu;return}this.config=n,this.pluginManager=new As(this),this.rpcManager=new Gu,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,i;this.isConnected=!1,(i=(r=this.config).onDisconnected)==null||i.call(r,n)}),this.on("connection.error",n=>{var r,i;(i=(r=this.config).onError)==null||i.call(r,n)}),this.on("chat.message.received",n=>{var r,i;this.addChatMessage(n),(i=(r=this.config).onMessageReceived)==null||i.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,i;(i=(r=this.config).onTranscriptionReceived)==null||i.call(r,n)}),this.on("session.state.changed",n=>{var r,i;(i=(r=this.config).onSessionStateChanged)==null||i.call(r,n)}),this.on("session.created",n=>{var r,i;(i=(r=this.config).onSessionStart)==null||i.call(r,n.id)}),this.on("session.ended",(n,r)=>{var i,s;(s=(i=this.config).onSessionEnd)==null||s.call(i,r)}),this.on("participant.joined",n=>{var r,i;(i=(r=this.config).onUserJoined)==null||i.call(r,n.id)}),this.on("participant.left",n=>{var r,i;(i=(r=this.config).onUserLeft)==null||i.call(r,n.id)}),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(){if(typeof window>"u"){console.warn("VoxketClient: Skipping room initialization in server-side environment");return}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 i;try{(i=this.room)!=null&&i.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(s){console.warn("VoxketClient: Failed to enable microphone after room connection:",s)}},1e3),this.textStreamHandlersRegistered||this.setupTextStreamHandlers()}),this.room.on(te.RoomEvent.Disconnected,n=>{var r;console.log("๐ด VoxketClient: Room disconnected, reason:",n),this.connectionState=te.ConnectionState.Disconnected,this.textStreamHandlersRegistered=!1,this.isAgentConnected=!1,console.log("๐ค VoxketClient: Agent marked as disconnected"),this.clearChatMessages(),n&&console.log("๐ VoxketClient: Disconnect reason details:",{reason:n.toString(),currentSession:(r=this.currentSession)==null?void 0:r.id,agentConnected:this.isAgentConnected,connectionState:this.connectionState}),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)}),this.room.on(te.RoomEvent.LocalTrackPublished,n=>{console.log("๐ฌ VoxketClient: Local track published:",n.source),n.source===te.Track.Source.ScreenShare&&this.emit("track.unmuted",{source:"screenShare",enabled:!0})}),this.room.on(te.RoomEvent.LocalTrackUnpublished,n=>{console.log("๐ฌ VoxketClient: Local track unpublished:",n.source),n.source===te.Track.Source.ScreenShare&&this.emit("track.muted",{source:"screenShare",enabled:!1})}))}setupTextStreamHandlers(){if(!this.room)return;try{this.room.registerTextStreamHandler("lk.chat",async(r,i)=>{try{const s=await r.readAll(),o={id:`msg_${Date.now()}_${i.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:s,timestamp:new Date,sender:{id:i.identity||"user",name:i.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(r){console.warn("VoxketClient: lk.chat handler already registered, skipping:",r)}try{console.log("๐ VoxketClient: Registering lk.transcription handler..."),this.room.registerTextStreamHandler("lk.transcription",async(r,i)=>{var s,o,a,l,c,u;console.log("๐ VoxketClient: Received transcription stream from:",i.identity);try{console.log("๐ VoxketClient: Processing transcription stream...");const d=i.identity===((o=(s=this.room)==null?void 0:s.localParticipant)==null?void 0:o.identity),h=Date.now(),m=i.identity,g=this.activeTranscriptions.get(m);let p,b=!0;g&&h-g.timestamp<1e3?(p=g.messageId,b=!1,console.log("๐ VoxketClient: Reusing existing transcription message ID:",p)):(p=`msg_${d?"user":"agent"}_${i.identity}_${h}`,this.activeTranscriptions.set(m,{messageId:p,timestamp:h}),console.log("๐ VoxketClient: Created new transcription message ID:",p));let v="";const k=((a=this.currentAgentInfo)==null?void 0:a.name)||i.identity||"AI Assistant";console.log("๐ VoxketClient: Using agent name:",k);const S=d?"participant":"agent",A=d?this.config.participantName||"User":k;console.log("๐ VoxketClient: Transcription sender info:",{participantIdentity:i.identity,localParticipantIdentity:(c=(l=this.room)==null?void 0:l.localParticipant)==null?void 0:c.identity,isFromUser:d,senderType:S,senderName:A});const T={id:p,content:"",timestamp:new Date,sender:{id:i.identity||"unknown",name:A,type:S},metadata:{topic:"lk.transcription",streaming:!0}};b&&this.emit("chat.message.received",T),console.log("๐ VoxketClient: Starting to read transcription stream...");for await(const L of r){console.log("๐ VoxketClient: Received chunk:",L.length,"chars"),v+=L;const y=this.convertMarkdownToText(v),M={...T,content:y,metadata:{...T.metadata,streaming:!0}};this.emit("chat.message.updated",M)}const C=this.convertMarkdownToText(v),N={...T,content:C,metadata:{...T.metadata,streaming:!1}};this.emit("chat.message.updated",N);const P={id:p,text:C,isFinal:!0,startTime:T.timestamp.getTime(),participantId:i.identity||"agent"};this.emit("transcription.received",P),console.log("๐ VoxketClient: Emitted transcription event:",P)}catch(d){console.error("VoxketClient: Failed to process lk.transcription message:",d);try{const h=await r.readAll(),m=((u=this.currentAgentInfo)==null?void 0:u.name)||i.identity||"AI Assistant",g={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:h,timestamp:new Date,sender:{id:i.identity||"agent",name:m,type:"agent"},metadata:{topic:"lk.transcription"}};this.emit("chat.message.received",g);const p={id:g.id,text:g.content,isFinal:!0,startTime:g.timestamp.getTime(),participantId:i.identity||"agent"};this.emit("transcription.received",p),console.log("๐ VoxketClient: Emitted fallback transcription event:",p)}catch(h){console.error("VoxketClient: Fallback failed for lk.transcription:",h)}}})}catch(r){console.warn("VoxketClient: lk.transcription handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("suggested_response",async r=>{const i=await r.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,i)}this.emit("suggested.response",s)})}catch(r){console.warn("VoxketClient: suggested_response handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("agent_state_changed",async(r,i)=>{const s=await r.readAll();console.log("๐ค VoxketClient: agent_state_changed stream received:",s);let o={};try{o=typeof s=="string"?JSON.parse(s.replace(/'/g,'"')):s}catch(a){console.warn("VoxketClient: Failed to parse agent_state_changed:",a,s)}this.isAgentConnected||(this.isAgentConnected=!0,console.log("๐ค VoxketClient: Agent marked as connected (first state change received)"),this.emit("agent.connected",o)),o.new_state==="speaking"?(this.setAgentState("speaking"),this.emit("agent.speaking",o)):o.new_state==="thinking"?(this.setAgentState("thinking"),this.emit("agent.thinking",o)):(o.new_state==="idle"||o.new_state==="listening")&&this.setAgentState("idle")})}catch(r){console.warn("VoxketClient: conversation_item_added handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("images",async(r,i)=>{try{const s=await r.readAll()}catch(s){console.error("VoxketClient: Error processing images stream:",s)}})}catch(r){console.warn("VoxketClient: images handler already registered, skipping:",r)}try{this.room.registerByteStreamHandler("images",async(r,i)=>{var s,o;try{const a=r.info,l={id:`img_${Date.now()}_${i.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`๏ฟฝ๏ธ ${a.name||"Image"}`,sender:{id:i.identity||"agent",name:i.identity||"Agent",type:i.identity===((o=(s=this.room)==null?void 0:s.localParticipant)==null?void 0:o.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:a.name,fileSize:a.size,mimeType:a.mimeType,streamId:a.id,downloading:!0}};this.emit("chat.message.received",l),r.onProgress&&(r.onProgress=m=>{const g={...l,metadata:{...l.metadata,downloadProgress:m||0}};this.emit("chat.message.updated",g)});const c=[];for await(const m of r)c.push(m);const u=new Blob(c,{type:a.mimeType||"application/octet-stream"}),d=URL.createObjectURL(u),h={...l,metadata:{...l.metadata,downloading:!1,downloadProgress:1,downloadUrl:d,blob:u}};this.emit("chat.message.updated",h)}catch(a){console.error("VoxketClient: Error processing image attachment:",a)}})}catch(r){console.warn("VoxketClient: image handler already registered, skipping:",r)}["error","warning","status","system","debug","info"].forEach(r=>{try{this.room.registerTextStreamHandler(r,async(i,s)=>{try{const o=await i.readAll();if(console.log(`๐ VoxketClient: Received '${r}' stream:`,o),r==="error"){let a={};try{a=typeof o=="string"?JSON.parse(o):o}catch{a={message:o}}console.warn("๏ฟฝ VoxketClient: Agent error:",a),this.emit("agent.error",a)}else this.emit("text.stream.received",{topic:r,data:o,participantInfo:s})}catch(o){console.error(`VoxketClient: Failed to process '${r}' stream:`,o)}})}catch(i){console.warn(`VoxketClient: Handler for '${r}' already registered, skipping:`,i)}});try{this.room.registerTextStreamHandler("*",async(r,i)=>{var s;try{const o=await r.readAll(),a=((s=r.info)==null?void 0:s.topic)||"unknown";console.log(`๐ VoxketClient: Received unhandled text stream for topic '${a}':`,o),this.emit("text.stream.unhandled",{topic:a,data:o,participantInfo:i})}catch(o){console.error("VoxketClient: Failed to process unhandled text stream:",o)}})}catch(r){console.warn("VoxketClient: Generic text stream handler already registered, skipping:",r)}this.textStreamHandlersRegistered=!0}async fetchConnectionDetails(n,r,i){const s=n||this.config.agentId||"default-agent",o=r||this.config.participantName||"User",a=i||this.config.modalities||["voice"];try{const l={agent_id:s,participant_name:o,participant_metadata:{user_id:""},modality:a[0],modalities:a};console.log("๐ VoxketClient: Creating session with modalities:",a);const c=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(l)});if(!c.ok){let h=`HTTP ${c.status}: Failed to fetch connection details`;try{const m=await c.json();m&&(m.error?h=`API Error: ${m.error}`:m.detail?h=`API Error: ${m.detail}`:m.message&&(h=`API Error: ${m.message}`))}catch{try{const g=await c.text();g&&(h=`API Error: ${g}`)}catch{}}throw new Error(h)}const u=await c.json();let d;return u.agent_info&&(d={id:u.agent_info.id||s,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=d),{serverUrl:u.wss_url,participantToken:u.token,voxketSessionId:u.session_id,agentInfo:d}}catch(l){console.error("VoxketClient: fetchConnectionDetails failed:",l);const c=new Ve(`Failed to fetch connection details: ${l instanceof Error?l.message:"Unknown error"}`,"CONNECTION_FAILED",l);throw this.emit("connection.error",c),c}}async connect(n,r,i){var s;try{this.emit("connection.connecting");const o=await this.fetchConnectionDetails(n,r,i);return await((s=this.room)==null?void 0:s.connect(o.serverUrl,o.participantToken)),this.isConnected=!0,o}catch(o){console.error("VoxketClient: Connection failed:",o);const a=new Ve(`Failed to connect to Voxket services: ${o instanceof Error?o.message:"Unknown error"}`,"CONNECTION_FAILED",o);throw this.emit("connection.error",a),a}}async disconnect(){var n;try{console.log("๐ VoxketClient: Starting disconnect process..."),this.room&&(console.log("๐ VoxketClient: Disconnecting from room:",{roomState:this.room.state,numParticipants:this.room.numParticipants,sessionId:(n=this.currentSession)==null?void 0:n.id}),await this.room.disconnect()),this.isConnected=!1,this.currentSession=null,this.currentAgentInfo=null,this.textStreamHandlersRegistered=!1,this.clearChatMessages(),console.log("๐ VoxketClient: Creating new room instance..."),typeof window<"u"&&(this.room=new te.Room,this.setupRoomEventListeners()),console.log("โ
VoxketClient: Disconnect completed successfully"),this.emit("connection.disconnected")}catch(r){console.error("โ VoxketClient: Disconnect failed:",r);const i=new Ve("Failed to disconnect properly","NETWORK_ERROR",r);throw this.emit("connection.error",i),i}}async createSession(n){var r,i,s,o;try{const a=await this.connect(n.agentId,n.participantName,n.modalities),l={id:a.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:a.agentInfo||this.currentAgentInfo};if(this.currentSession=l,this.emit("session.created",l),(r=n.modalities)!=null&&r.includes("voice"))try{await new Promise(c=>setTimeout(c,500)),(i=this.room)!=null&&i.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(c){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",c)}if((s=n.modalities)!=null&&s.includes("video"))try{await new Promise(c=>setTimeout(c,200)),(o=this.room)!=null&&o.localParticipant&&(console.log("๐ฅ VoxketClient: Attempting to enable camera for video session"),await this.room.localParticipant.setCameraEnabled(!0),this.emit("track.unmuted",{source:"camera",enabled:!0}),console.log("๐ฅ VoxketClient: Camera enabled successfully"))}catch(c){console.warn("VoxketClient: Failed to enable camera, but continuing with session:",c)}return setTimeout(()=>{var c;this.currentSession&&(this.currentSession.state="active",this.emit("session.state.changed","active",this.currentSession.state),this.forceAgentConnected(),console.log("๐ค VoxketClient: Session marked as active:",{sessionId:this.currentSession.id,modalities:this.currentSession.activeModalities,agentConnected:this.isAgentConnected,hasRoom:!!this.room,remoteParticipants:((c=this.room)==null?void 0:c.remoteParticipants.size)||0}))},1e3),l}catch(a){throw console.error("VoxketClient: Failed to create session:",a),a instanceof Ve?a:a instanceof TypeError&&a.message.includes("fetch")?new Ve("Network connection failed","CONNECTION_FAILED",a):a instanceof Error&&a.message.includes("Failed to fetch connection details")?new Ve(`API connection failed: ${a.message}`,"CONNECTION_FAILED",a):new Ve(`Failed to create session: ${a instanceof Error?a.message:"Unknown error"}`,"SESSION_NOT_FOUND",a)}}async startSession(n,r){const i={agentId:n||this.config.agentId||"default-agent",participantName:(r==null?void 0:r.participantName)||this.config.participantName||"User",modalities:(r==null?void 0:r.modalities)||this.config.modalities||["voice","chat"],metadata:r==null?void 0:r.metadata};return this.createSession(i)}async endSession(){var n,r;if(!this.currentSession)return null;try{const i={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.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,i),await this.disconnect(),i}catch(i){throw new Ve("Failed to end session","SESSION_NOT_FOUND",i)}}getCurrentSession(){return this.currentSession}getCurrentAgentInfo(){return this.currentAgentInfo}getIsAgentConnected(){return this.isAgentConnected}forceAgentConnected(){this.isAgentConnected||(this.isAgentConnected=!0,console.log("๐ค VoxketClient: Agent manually marked as connected"),this.emit("agent.connected",{forced:!0}))}getAgentState(){return this.agentState}setAgentState(n){this.agentState!==n&&(this.agentState=n,this.emit("agent.state.changed",{state:n}))}getAgentAudioTrack(){const n=this.getRemoteParticipants();for(const r of n){const i=r.getTrackPublication(te.Track.Source.Microphone);if(i!=null&&i.track)return{source:te.Track.Source.Microphone,participant:r,publication:i}}return null}getAgentVideoTrack(){const n=this.getRemoteParticipants();for(const r of n){const i=r.getTrackPublication(te.Track.Source.Camera);if(i!=null&&i.track)return{source:te.Track.Source.Camera,participant:r,publication:i}}return null}getVideoTrackRefs(){const n=[],r=this.getLocalParticipant();if(r){const s=r.getTrackPublication(te.Track.Source.Camera);s!=null&&s.track&&n.push({source:te.Track.Source.Camera,participant:r,publication:s});const o=r.getTrackPublication(te.Track.Source.ScreenShare);o!=null&&o.track&&n.push({source:te.Track.Source.ScreenShare,participant:r,publication:o})}const i=this.getRemoteParticipants();for(const s of i){const o=s.getTrackPublication(te.Track.Source.Camera);o!=null&&o.track&&n.push({source:te.Track.Source.Camera,participant:s,publication:o});const a=s.getTrackPublication(te.Track.Source.ScreenShare);a!=null&&a.track&&n.push({source:te.Track.Source.ScreenShare,participant:s,publication:a})}return n}getCameraTrackRefs(){return this.getVideoTrackRefs().filter(n=>n.source===te.Track.Source.Camera)}getScreenShareTrackRefs(){return this.getVideoTrackRefs().filter(n=>n.source===te.Track.Source.ScreenShare)}getChatMessages(){return[...this.chatMessages]}addChatMessage(n){this.chatMessages.some(i=>i.id===n.id)||this.chatMessages.push(n)}updateChatMessage(n){const r=this.chatMessages.findIndex(i=>i.id===n.id);r!==-1&&(this.chatMessages[r]=n)}clearChatMessages(){this.chatMessages=[],this.activeTranscriptions.clear(),this.dismissCurrentInteraction(),this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays(),console.log("๐งน VoxketClient: Cleared chat messages and transcription history"),this.emit("chat.history.cleared")}renderUI(n={}){var o,a,l,c,u,d,h,m,g;if(typeof window>"u"){console.warn("VoxketClient: Cannot render UI in server-side environment");return}const r=this.resolveTarget(n.target||"body"),i=this.getTargetKey(r);if(Bo.has(r)){console.warn("โ ๏ธ VoxketClient: Target is already being processed, skipping renderUI");return}if(Kt.has(r)){console.log("โ VoxketClient: Target already has a React root in registry, updating existing props...");const p=this.renderedComponents.get(i);if(p&&p.root){const b={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:((o=n.modality)==null?void 0:o.includes("chat"))!==!1,suportsVideoInput:((a=n.modality)==null?void 0:a.includes("video"))===!0,suportsScreenShare:((l=n.modality)==null?void 0:l.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};try{p.root.render(j.createElement(ci,{config:this.config,autoConnect:n.autoStart||!1,client:this,children:j.createElement(ui,b)})),console.log("โ
VoxketClient: Successfully updated existing widget with new props");return}catch(v){throw console.error("Error re-rendering existing widget:",v),new Error(`Failed to update existing widget: ${v instanceof Error?v.message:"Unknown error"}`)}}else console.warn("โ ๏ธ Registry inconsistency detected, cleaning up"),Kt.delete(r)}let s=this.renderedComponents.get(i);if(s&&s.target===r&&Kt.has(r)){console.log("๐ VoxketClient: Reusing existing React root for target:",i);const p=s.root,b={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:((u=n.modality)==null?void 0:u.includes("video"))===!0,suportsScreenShare:((d=n.modality)==null?void 0:d.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};try{p.render(j.createElement(ci,{config:this.config,autoConnect:n.autoStart||!1,client:this,children:j.createElement(ui,b)}))}catch(v){throw console.error("Error rendering Voxket widget:",v),new Error(`Failed to render Voxket widget: ${v instanceof Error?v.message:"Unknown error"}`)}return}Bo.add(r);try{if(s){console.log("๐งน VoxketClient: Cleaning up existing component for different target");try{s.root.unmount(),this.renderedComponents.delete(i),Kt.delete(s.target),r.innerHTML=""}catch(v){console.warn("Failed to cleanup existing root:",v)}}if(Kt.has(r)){console.warn("โ ๏ธ VoxketClient: Target already in registry, skipping root creation");return}console.log("๐ VoxketClient: Creating new React root for target:",i);const p=Zm.createRoot(r);this.renderedComponents.set(i,{root:p,target:r}),Kt.add(r);const b={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:((h=n.modality)==null?void 0:h.includes("chat"))!==!1,suportsVideoInput:((m=n.modality)==null?void 0:m.includes("video"))===!0,suportsScreenShare:((g=n.modality)==null?void 0:g.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(!p||typeof p.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{p.render(j.createElement(ci,{config:this.config,autoConnect:n.autoStart||!1,client:this,children:j.createElement(ui,b)}))}catch(v){throw console.error("Error rendering Voxket widget:",v),new Error(`Failed to render Voxket widget: ${v instanceof Error?v.message:"Unknown error"}`)}}finally{Bo.delete(r)}}removeUI(n){var i;const r=n?this.resolveTarget(n):null;if(r){const s=this.getTargetKey(r),o=this.renderedComponents.get(s);if(o){console.log("๐๏ธ VoxketClient: Removing UI for target:",s),this.renderedComponents.delete(s),Kt.delete(r);try{const l=o.target;l&&l.isConnected?(typeof((i=o.root)==null?void 0:i.unmount)=="function"&&(o.root.unmount(),console.log("โ
VoxketClient: UI unmounted for target:",s)),l.hasChildNodes()&&(l.innerHTML="")):console.log("โน๏ธ VoxketClient: Target element already disconnected, skipping unmount")}catch(l){console.warn("Failed to unmount React root:",l)}}else console.log("โน๏ธ VoxketClient: No component found for target, cleaning registry:",s),Kt.delete(r),r.isConnected&&r.hasChildNodes()&&(r.innerHTML="");r.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(l=>{try{l.remove()}catch(c){console.warn("Failed to remove element:",c)}}),typeof document<"u"&&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")||c.classList.contains("bg-opacity-30")))try{c.remove()}catch(u){console.warn("Failed to remove fixed element:",u)}})}}removeAllUI(){for(const[n,r]of this.renderedComponents)r.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){if(typeof document>"u")return;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(i){console.warn("Failed to remove overlay:",i)}})}resolveTarget(n){if(typeof window>"u"||typeof document>"u")throw new Error("VoxketClient: Cannot resolve DOM target in server-side environment");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 i;if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new Ve("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new Ve("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new Ve("No local participant","CONNECTION_FAILED");this.dismissCurrentInteraction();try{const s={id:`msg_${Date.now()}`,content:n,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:r||{}},o=await((i=this.room)==null?void 0:i.localParticipant.sendText(n,{topic:"lk.chat",destinationIdentities:[]}));this.emit("chat.message.sent",s)}catch(s){throw console.error("VoxketClient: Failed to send chat message:",s),new Ve("Failed to send message","NETWORK_ERROR",s)}}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 Ve("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new Ve("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new Ve("No local participant","CONNECTION_FAILED");if(!n||n.length===0)throw new Ve("No files provided","INVALID_PARAMETER");this.dismissCurrentInteraction();const i=n.filter(s=>s.type.startsWith("image/"));if(i.length===0)throw new Ve("Only image files are allowed","INVALID_PARAMETER");i.length!==n.length&&console.warn("VoxketClient: Some non-image files were filtered out");try{const s=i.map(async(o,a)=>{const c={id:`att_${Date.now()}_${a}`,content:`๐ ${o.name}`,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:{...r,type:"attachment",fileName:o.name,fileSize:o.size,mimeType:o.type,uploading:!0}};this.emit("chat.message.sent",c);const u=await this.room.localParticipant.sendFile(o,{mimeType:o.type,topic:"images",onProgress:h=>{const m={...c,metadata:{...c.metadata,uploadProgress:h}};this.emit("chat.message.updated",m)}});try{const h=new FileReader,m=new Promise((b,v)=>{h.onload=()=>{typeof h.result=="string"?b(h.result):v(new Error("Failed to convert to base64"))},h.onerror=v});h.readAsDataURL(o);const p={type:"image",data:await m,filename:o.name,mimeType:o.type,size:o.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 m=`I've shared an image: ${o.name}`;await this.room.localParticipant.sendText(m,{topic:"lk.chat",destinationIdentities:[]})}catch(m){console.warn("VoxketClient: Failed to send image notification to agent:",m)}}const d={...c,metadata:{...c.metadata,uploading:!1,uploadProgress:1,streamId:u.id}};return this.emit("chat.message.updated",d),u});await Promise.all(s)}catch(s){throw console.error("VoxketClient: Failed to send attachments:",s),new Ve("Failed to send attachments","NETWORK_ERROR",s)}}async sendAttachment(n,r){return this.sendAttachments([n],r)}toggleMicrophone(n){return this.setMicrophoneEnabled(n!==!1)}async setMicrophoneEnabled(n){var r,i;try{const s=(r=this.room)==null?void 0:r.localParticipant.isMicrophoneEnabled,o=n??!s;await((i=this.room)==null?void 0:i.localParticipant.setMicrophoneEnabled(o)),o?this.emit("track.unmuted",{source:"microphone",enabled:!0}):this.emit("track.muted",{source:"microphone",enabled:!1})}catch(s){throw console.error("VoxketClient: Failed to toggle microphone:",s),new Ve("Failed to toggle microphone","PERMISSION_DENIED",s)}}toggleCamera(n){return this.setCameraEnabled(n!==!1)}async setCameraEnabled(n){var r,i;try{const s=(r=this.room)==null?void 0:r.localParticipant.isCameraEnabled,o=n??!s;await((i=this.room)==null?void 0:i.localParticipant.setCameraEnabled(o)),o?this.emit("track.unmuted",{source:"camera",enabled:!0}):this.emit("track.muted",{source:"camera",enabled:!1})}catch(s){throw console.error("VoxketClient: Failed to toggle camera:",s),new Ve("Failed to toggle camera","PERMISSION_DENIED",s)}}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)),this.emit("track.unmuted",{source:"screenShare",enabled:!0})}catch(r){throw new Ve("Failed to start screen share","PERMISSION_DENIED",r)}}async stopScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!1)),this.emit("track.muted",{source:"screenShare",enabled:!1})}catch(r){throw new Ve("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 Ve("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 Ve("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(i){throw new Ve("Failed to set audio input device","DEVICE_ERROR",i)}}async setVideoInputDevice(n){var r;try{if(!((r=this.room)!=null&&r.localParticipant))throw new Error("Not connected to room")}catch(i){throw new Ve("Failed to set video input device","DEVICE_ERROR",i)}}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 i=s=>!!r.canPublish&&(r.canPublishSources.length===0||r.canPublishSources.includes(s));return{camera:i(1),microphone:i(2),screenShare:i(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 console.log("๐ฌ VoxketClient: getScreenShareTrack - no local participant"),null;for(const[,r]of n.trackPublications)if(r.source===te.Track.Source.ScreenShare)return console.log("๐ฌ VoxketClient: getScreenShareTrack - found screen share track:",{trackSid:r.trackSid,isMuted:r.isMuted,hasTrack:!!r.track}),r.track;return console.log("๐ฌ VoxketClient: getScreenShareTrack - no screen share track found"),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(),r=n?!n.isMuted:!1;return console.log("๐ฌ VoxketClient: isScreenShareEnabled check:",{hasTrack:!!n,trackMuted:n==null?void 0:n.isMuted,enabled:r}),r}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 Ve("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 Ve("Failed to stop recording","RECORDING_ERROR",r)}}async registerFrontendRPC(n,r,i="embedded"){return this.rpcManager.registerFrontendRPC(n,r,i)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}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 i=>{try{const s=await i.readAll();r(s)}catch(s){console.error(`Error processing event for topic '${n}':`,s)}})}catch(i){console.warn(`VoxketClient: Handler for topic '${n}' may already be registered:`,i)}}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 kE=ge.create(xh),SE=ge.create(dE),CE=ge.create(pE),EE=ge.create(Sm);function TE({theme:e,mode:t,loadingText:n}){const r=et(e),i=()=>{switch(t){case"voice":return n||"Connecting to voice agent...";case"chat":return n||"Starting chat session...";case"video":return n||"Connecting to video call...";default:return n||"Connecting..."}};return f.jsxs("div",{className:"flex flex-col items-center justify-center h-full w-full p-8",children:[f.jsxs("div",{className:"text-center",children:[f.jsx("h3",{className:`text-lg font-semibold mb-2 ${r.text.accent}`,children:i()}),f.jsx("p",{className:`text-sm ${r.text.muted}`,children:"Please wait a moment..."})]}),f.jsxs("div",{className:"flex space-x-1 mt-4",children:[f.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"0ms"}}),f.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"150ms"}}),f.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"300ms"}})]})]})}const AE=ge.create(TE);function jE({onClick:e,text:t="Open Chat",position:n="bottom-right",theme:r}){const i={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},s=et(r);return f.jsx(ge.button,{onClick:e,className:`voxket-popup-trigger fixed ${i[n]} z-50 px-4 py-2 rounded-full shadow-lg ${s.popupTrigger} transition-all duration-200 hover:scale-105`,initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},exit:{scale:0,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},"data-position":n,children:t})}function Ku({children:e,theme:t,displayType:n="widget",onClose:r,popupPosition:i="bottom-right",onExpand:s}){const o=et(t);if(n==="fullscreen")return f.jsx("div",{className:"fixed inset-0 z-[9999] bg-black/40 bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",onClick:a=>{a.target===a.currentTarget&&r&&r()},children:f.jsxs("div",{className:"w-full h-full max-w-7xl max-h-[95vh] rounded-2xl relative bg-transparent flex flex-col",onClick:a=>{a.stopPropagation()},children:[r&&f.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),r()},className:"absolute top-4 cursor-pointer right-4 z-[10000] w-12 h-12 rounded-full 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:f.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:f.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"})})}),f.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${o.card} w-full h-full flex flex-col rounded-xl shadow-2xl relative overflow-hidden`,"data-theme":t,style:{minHeight:"600px",height:"100%",contain:"layout style paint",overscrollBehavior:"contain"},children:[f.jsx("div",{className:o.cardTopGradient}),f.jsx("div",{className:o.cardPurpleBlur}),f.jsx("div",{className:o.cardPinkBlur}),f.jsx("div",{className:"relative z-10 flex flex-col h-full",children:e}),f.jsx("div",{className:o.cardPulse1}),f.jsx("div",{className:o.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 f.jsx("div",{className:"fixed rounded-2xl inset-0 z-[9999] pointer-events-none",children:f.jsxs("div",{className:`fixed rounded-2xl ${a[i]} pointer-events-auto`,children:[r&&f.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:"ร"}),f.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${o.card} rounded-2xl flex flex-col relative overflow-hidden`,"data-theme":t,style:{width:"350px",height:"500px",contain:"layout style paint",overscrollBehavior:"contain"},children:[f.jsx("div",{className:o.cardTopGradient}),f.jsx("div",{className:o.cardPurpleBlur}),f.jsx("div",{className:o.cardPinkBlur}),f.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),f.jsx("div",{className:o.cardPulse1}),f.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return f.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${o.card} relative overflow-hidden`,"data-theme":t,style:{height:"100%",maxHeight:"100%",contain:"layout style paint",overscrollBehavior:"contain"},children:[f.jsx("div",{className:o.cardTopGradient}),f.jsx("div",{className:o.cardPurpleBlur}),f.jsx("div",{className:o.cardPinkBlur}),f.jsx("div",{className:"relative z-10 flex flex-col h-full",children:e}),f.jsx("div",{className:o.cardPulse1}),f.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})}function PE(e){if(typeof window>"u")return null;const{agentId:t,participantName:n,baseUrl:r,appSecret:i,appId:s,prompts:o,statusMessage:a,welcomeTitle:l,welcomeSubTitle:c,className:u,width:d,height:h,loadingText:m,suportsChatInput:g=!0,suportsVideoInput:p=!0,suportsScreenShare:b=!0,theme:v="vox",onSessionStart:k,onSessionEnd:S,enableSessionLogging:A=!0,onSessionLogsUpdate:T,onSessionMetricsUpdate:C,modalities:N=["voice"],displayType:P="widget",popupPosition:L="bottom-right",popupTriggerText:y="Open Chat",onPopupToggle:M,voxketClient:D,onDisplayTypeChange:B}=e,[H,K]=x.useState(!1),[de,ie]=x.useState(null),[F,W]=x.useState(()=>{try{if(D)return!!D.getCurrentSession()}catch(G){console.error("Error checking existing session:",G)}return!1}),[w,z]=x.useState(!1),[oe,E]=x.useState(t||""),[U,se]=x.useState(n||"User"),[$,ee]=x.useState(()=>{try{if(D)return D.getCurrentSession()}catch(G){console.error("Error getting current session:",G)}return null}),[Q,V]=x.useState(()=>{var G,be,Ce;try{if(D){const je=D.getCurrentSession();if((G=je==null?void 0:je.activeModalities)!=null&&G.includes("chat"))return"chat";if((be=je==null?void 0:je.activeModalities)!=null&&be.includes("voice"))return"voice";if((Ce=je==null?void 0:je.activeModalities)!=null&&Ce.includes("video"))return"video"}}catch(je){console.error("Error determining current mode:",je)}return"welcome"}),[X,fe]=x.useState(!1);x.useEffect(()=>{P==="fullscreen"&&console.log("๐ฏ Widget: Switched to fullscreen mode")},[P]),x.useEffect(()=>{F&&!w?console.log("๐ Session started:",{currentMode:Q,sessionId:$==null?void 0:$.id}):!F&&!w&&Q==="welcome"&&console.log("๐ Returned to welcome screen")},[F,Q,w]);const R=x.useMemo(()=>{try{if(D)return console.log("๐ Using existing VoxketClient to preserve session state"),D;if(!s||!i||!r){const be=`Missing required props: ${s?"":"appId "}${i?"":"appSecret "}${r?"":"baseUrl"}`;return console.error("โ VoxketClient creation failed:",be),ie(new Error(be)),K(!0),null}const G={appId:s,appSecret:i,baseUrl:r,agentId:oe,participantName:U||"User",modalities:N};return console.log("๐ง Creating new VoxketClient with config:",{appId:s.substring(0,8)+"...",baseUrl:r,agentId:oe,participantName:U||"User",modalities:N}),new $r(G)}catch(G){return console.error("โ Failed to create VoxketClient:",G),ie(G),K(!0),null}},[D,s,i,r,oe,U,N]),re=N,ne=x.useMemo(()=>{try{if(!R)return console.warn("โ ๏ธ No VoxketClient available, creating fallback room"),new te.Room;const G=R.getRoom();return console.log("๐ Widget: Room reference updated:",{roomExists:!!G,roomState:G==null?void 0:G.state,sessionStarted:F,currentMode:Q}),G||new te.Room}catch(G){return console.error("โ Error getting room from client:",G),new te.Room}},[R,F,Q]);x.useEffect(()=>{if(ne){const G=()=>{console.log("๐ Widget: Room state changed:",{state:ne.state,numParticipants:ne.numParticipants,isConnected:ne.state==="connected",sessionId:$==null?void 0:$.id})},be=(Ce,je,$e)=>{console.log("๐ต Widget: Track subscribed:",{trackKind:Ce.kind,trackSource:Ce.source,participantSid:$e.sid,participantIdentity:$e.identity,sessionId:$==null?void 0:$.id})};return ne.on(te.RoomEvent.Connected,G),ne.on(te.RoomEvent.Disconnected,G),ne.on(te.RoomEvent.TrackSubscribed,be),()=>{ne.off(te.RoomEvent.Connected,G),ne.off(te.RoomEvent.Disconnected,G),ne.off(te.RoomEvent.TrackSubscribed,be)}}},[ne,$==null?void 0:$.id]),x.useEffect(()=>{!w&&Q==="welcome"?console.log("๐ฌ Widget: Welcome screen ready"):F&&Q!=="welcome"&&console.log("๐ฌ Widget: Session mode active:",Q)},[Q,w,F]);const me={suportsChatInput:g,suportsVideoInput:p,suportsScreenShare:b};x.useEffect(()=>{(Q==="voice"||Q==="video"||Q==="chat")&&!$&&!F&&!w&&R&&!R.connected&&(console.log("๐ Auto-correcting: Found orphaned mode without session, returning to welcome"),V("welcome"),z(!1))},[Q,$,F,w,R]);const{sessionMetrics:Z,sessionLogs:pe,logEvent:Ae}=Cm({room:ne,onSessionStart:k,onSessionEnd:S,enableConsoleLogging:A,enableLocalStorage:A,voxketSessionId:$==null?void 0:$.id});x.useEffect(()=>{T&&T(pe)},[pe,T]),x.useEffect(()=>{C&&Z&&C(Z)},[Z,C]),x.useEffect(()=>{if(!R)return;const G=()=>{const be=R.connected,Ce=R.getCurrentSession();console.log("๐ Connection state changed:",{isConnected:be,currentSessionId:Ce==null?void 0:Ce.id,currentMode:Q,loading:w,sessionStarted:F}),!be&&F&&!w&&(console.log("๐ด Connection lost during active session - returning to welcome"),z(!1),W(!1),ee(null),V("welcome")),be&&Ce&&w&&(console.log("๐ข Connected with active session - removing loader"),z(!1),W(!0),ee(Ce))};return R.on("connectionStateChanged",G),R.on("sessionEnded",()=>{console.log("๐ Session ended - returning to welcome"),z(!1),W(!1),ee(null),V("welcome")}),()=>{R.off("connectionStateChanged",G),R.off("sessionEnded",()=>{})}},[R,Q,w,F]),x.useEffect(()=>{const G=Ce=>{console.log("๐ด Widget: Room disconnected:",Ce),console.log("๐ Widget: Current state on disconnect:",{currentMode:Q,sessionStarted:F,currentSessionId:$==null?void 0:$.id,loading:w}),z(!1),W(!1),ee(null),V("welcome"),console.log("๐ Widget: Automatically returning to welcome screen after disconnect")},be=Ce=>{console.log("๐น Media devices error:",Ce)};return ne.on(te.RoomEvent.MediaDevicesError,be),ne.on(te.RoomEvent.Disconnected,G),()=>{ne.off(te.RoomEvent.Disconnected,G),ne.off(te.RoomEvent.MediaDevicesError,be)}},[ne,Q,F,$==null?void 0:$.id,w]);const xe=async()=>{try{if(!R){console.error("โ VoxketClient not available"),ie(new Error("VoxketClient not initialized")),K(!0);return}z(!0),V("voice"),console.log("๐ค Starting voice session...",{agentId:oe,participantName:U}),console.log("๐ค Pre-start state:",{currentMode:"voice",sessionStarted:!1,loading:!0}),Ae("USER_STARTED_VOICE_SESSION",{agentId:oe,participantName:U});const G=await R.startSession(oe,{participantName:U||"User",modalities:["voice",...p?["video"]:[]]});console.log("โ
Voice session started successfully:",G.id),ee(G),W(!0),z(!1),k&&k(G.id)}catch(G){console.error("โ Failed to start voice session:",G),z(!1),W(!1),V("welcome")}},Ne=async()=>{try{if(!R){console.error("โ VoxketClient not available"),ie(new Error("VoxketClient not initialized")),K(!0);return}z(!0),V("chat"),console.log("๐ฌ Starting chat session...",{agentId:oe,participantName:U}),Ae("USER_STARTED_CHAT_SESSION",{agentId:oe,participantName:U});const G=await R.startSession(oe,{participantName:U||"User",modalities:["chat"]});console.log("โ
Chat session started successfully:",G.id),ee(G),W(!0),z(!1),k&&k(G.id)}catch(G){console.error("โ Failed to start chat session:",G),z(!1),W(!1),V("welcome")}},ze=async()=>{try{if(!R){console.error("โ VoxketClient not available"),ie(new Error("VoxketClient not initialized")),K(!0);return}z(!0),V("video"),console.log("๐บ Starting video session...",{agentId:oe,participantName:U}),console.log("๐บ Pre-start state:",{currentMode:"video",sessionStarted:!1,loading:!0}),Ae("USER_STARTED_VIDEO_SESSION",{agentId:oe,participantName:U});const G=await R.startSession(oe,{participantName:U||"User",modalities:["video","voice"]});console.log("โ
Video session started successfully:",G.id),ee(G),W(!0),z(!1),k&&k(G.id)}catch(G){console.error("โ Failed to start video session:",G),z(!1),W(!1),V("welcome")}},He=()=>{console.log("๐ Widget: handleBackToWelcome called",{currentMode:Q,sessionStarted:F,currentSessionId:$==null?void 0:$.id,displayType:P,loading:w}),V("welcome"),z(!1),B&&B(e.displayType||"widget"),$&&F?(console.log("๐งน Widget: Cleaning up active session"),W(!1),ee(null),R&&(console.log("๐ Widget: Disconnecting client and cleaning up room"),R.disconnect().catch(G=>{console.error("โ Widget: Error during disconnect:",G)}))):(console.log("๐ Widget: No active session to clean up"),R&&R.connected&&(console.log("๐ Widget: Force disconnecting client for fresh state"),R.disconnect().catch(G=>{console.error("โ Widget: Error during force disconnect:",G)}))),P==="popup"&&!X&&fe(!0),console.log("โ
Widget: handleBackToWelcome completed",{newCurrentMode:"welcome",newLoading:!1,newSessionStarted:!1})},nt=()=>{const G=!X;fe(G),M&&M(G),!G&&!($&&F)&&(V("welcome"),W(!1),ee(null))},Zt=()=>{console.log("๐ Closing fullscreen, switching to widget display type"),e.onDisplayTypeChange?e.onDisplayTypeChange("widget"):console.warn("โ ๏ธ No onDisplayTypeChange callback provided")},Ft=()=>{if(console.log("๐ Expand to fullscreen requested"),e.onDisplayTypeChange)e.onDisplayTypeChange("fullscreen");else{console.warn("โ ๏ธ No onDisplayTypeChange callback provided for expand functionality");const G=document.getElementById("voice-card")||document.querySelector(".voxket-widget-container");G&&G.requestFullscreen&&G.requestFullscreen().catch(be=>{console.warn("โ ๏ธ Fullscreen API not supported or failed:",be)})}};x.useEffect(()=>{var G,be,Ce;if(D&&R){const je=R.getCurrentSession();R.connected,je&&(console.log("โ
Restoring session state:",je.id),ee(je),W(!0),z(!1),(G=je.activeModalities)!=null&&G.includes("chat")?V("chat"):(be=je.activeModalities)!=null&&be.includes("voice")?V("voice"):(Ce=je.activeModalities)!=null&&Ce.includes("video")&&V("video"))}},[D,R]),x.useEffect(()=>()=>{!D&&R&&R.disconnect()},[R,D]);let _=Q==="video"?"w-[32rem]":"w-96",I=Q==="video"?"h-[30rem]":"h-[25rem]",q={};if(d&&(d.startsWith("w-")?_=d:(q.width=d,_="")),h&&(h.startsWith("h-")?I=h:(q.height=h,I="")),P==="popup"&&!X)return console.log("๐ก Showing popup trigger button"),f.jsx(jE,{onClick:nt,text:y,position:L,theme:v});if(H||!R){const G=(de==null?void 0:de.message)||"VoxketWidget encountered an error. Please check your configuration.";return f.jsx("div",{className:`voxket-widget-root theme-${v} flex items-center justify-center p-8 ${u||""}`,style:{width:d||"400px",height:h||"500px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"},children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"text-4xl mb-4",children:"โ ๏ธ"}),f.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Widget Error"}),f.jsx("p",{className:"text-sm mb-4",children:G}),f.jsx("button",{onClick:()=>{K(!1),ie(null),window.location.reload()},className:"px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"Retry"})]})})}let ue=`voxket-widget-root theme-${v}`,J={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};P==="widget"?(ue+=` flex items-center justify-center min-h-fit ${_} ${I} ${u}`,J={...J,...q}):(ue=`${u||""}`,J={});const ke=f.jsx("div",{className:"h-full flex flex-col overflow-hidden relative z-10",children:f.jsxs(Qt,{mode:"wait",children:[Q==="welcome"&&!w&&f.jsx(EE,{agentId:oe,participantName:U||"",onAgentIdChange:E,onParticipantNameChange:se,onStartCall:xe,onStartChat:Ne,onStartVideo:ze,disabled:F||w,prompts:o,statusMessage:a,title:l,subTitle:c,theme:v,modalities:re,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),w&&(Q==="voice"||Q==="chat"||Q==="video")&&f.jsx(AE,{theme:v,mode:Q,loadingText:m,initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.3,ease:"easeInOut"}},`loading-${Q}`),Q==="voice"&&!w&&F&&R&&f.jsxs(ut.RoomContext.Provider,{value:ne,children:[f.jsx(ut.RoomAudioRenderer,{},`audio-${($==null?void 0:$.id)||"no-session"}`),f.jsx(ut.StartAudio,{label:"Start Audio"},`start-audio-${($==null?void 0:$.id)||"no-session"}`),f.jsx(kE,{loadingText:m,participantName:U||"User",capabilities:me,sessionStarted:F,disabled:!1,theme:v,client:R,displayType:P,onBack:P==="popup"?nt:He,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"voice-session")]}),Q==="chat"&&!w&&F&&R&&f.jsx(SE,{client:R,theme:v,displayType:P,onBack:P==="popup"?nt:He,onEndChat:He,disabled:!1,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),Q==="video"&&!w&&F&&R&&f.jsxs(ut.RoomContext.Provider,{value:ne,children:[f.jsx(ut.RoomAudioRenderer,{},`audio-video-${($==null?void 0:$.id)||"no-session"}`),f.jsx(ut.StartAudio,{label:"Start Audio"},`start-audio-video-${($==null?void 0:$.id)||"no-session"}`),f.jsx(CE,{client:R,theme:v,displayType:P,onBack:P==="popup"?nt:He,onEndCall:He,disabled:!1,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-session")]})]})});return P==="fullscreen"||P==="popup"?f.jsx(Ku,{theme:v,displayType:P,popupPosition:L,onClose:P==="fullscreen"?Zt:nt,children:ke}):f.jsx("div",{className:ue,style:J,children:f.jsx(Ku,{theme:v,displayType:P,popupPosition:L,onExpand:Ft,children:ke})})}function ui(e){return f.jsx(Ha,{children:f.jsx(PE,{...e})})}function ME({logs:e,onClear:t,onExport:n}){const[r,i]=j.useState(!1),[s,o]=j.useState(""),a=e.filter(l=>!s||l.event.toLowerCase().includes(s.toLowerCase()));return r?f.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:f.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[f.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[f.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("input",{type:"text",placeholder:"Filter events...",value:s,onChange:l=>o(l.target.value),className:"px-3 py-1 border rounded text-sm"}),f.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),f.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),f.jsx("button",{onClick:()=>i(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),f.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?f.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):f.jsx("div",{className:"space-y-2",children:a.map((l,c)=>f.jsxs("div",{className:"border rounded p-3 text-sm",children:[f.jsxs("div",{className:"flex items-center justify-between mb-1",children:[f.jsx("span",{className:"font-semibold text-blue-600",children:l.event}),f.jsx("span",{className:"text-gray-500 text-xs",children:new Date(l.timestamp).toLocaleTimeString()})]}),l.sessionId&&f.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",l.sessionId]}),l.data&&f.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:f.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(l.data,null,2)})})]},c))})})]})}):f.jsxs("button",{onClick:()=>i(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",e.length,")"]})}function NE({metrics:e}){return e?f.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[f.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),f.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[f.jsxs("div",{children:[f.jsx("span",{className:"text-gray-600",children:"Session ID:"}),f.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),f.jsxs("div",{children:[f.jsx("span",{className:"text-gray-600",children:"Start Time:"}),f.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),f.jsxs("div",{children:[f.jsx("span",{className:"text-gray-600",children:"Messages:"}),f.jsx("div",{children:e.totalMessages})]}),f.jsxs("div",{children:[f.jsx("span",{className:"text-gray-600",children:"Participants:"}),f.jsx("div",{children:e.participantCount})]}),f.jsxs("div",{children:[f.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),f.jsx("div",{children:e.connectionIssues})]}),f.jsxs("div",{children:[f.jsx("span",{className:"text-gray-600",children:"Duration:"}),f.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function kn(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:r,endSession:i}=Dt(),s=j.useCallback(async(a,l)=>await r(a,l),[r]),o=j.useCallback(async()=>await i(),[i]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:s,stop:o}}function Tm(){const{sessionMetrics:e,currentSession:t}=Dt();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 Am(){const{setMicrophoneEnabled:e,client:t}=Dt(),[n,r]=j.useState(!1),[i,s]=j.useState(!1),o=j.useCallback(async()=>{if(!i){s(!0);try{const c=!n;await e(c),r(c)}catch(c){console.error("Failed to toggle microphone:",c)}finally{s(!1)}}},[n,i,e]),a=j.useCallback(async()=>{if(!(n||i)){s(!0);try{await e(!0),r(!0)}catch(c){console.error("Failed to enable microphone:",c)}finally{s(!1)}}},[n,i,e]),l=j.useCallback(async()=>{if(!(!n||i)){s(!0);try{await e(!1),r(!1)}catch(c){console.error("Failed to disable microphone:",c)}finally{s(!1)}}},[n,i,e]);return{isEnabled:n,isLoading:i,toggle:o,enable:a,disable:l}}function jm(){const{setCameraEnabled:e}=Dt(),[t,n]=j.useState(!1),[r,i]=j.useState(!1),s=j.useCallback(async()=>{if(!r){i(!0);try{const l=!t;await e(l),n(l)}catch(l){console.error("Failed to toggle camera:",l)}finally{i(!1)}}},[t,r,e]),o=j.useCallback(async()=>{if(!(t||r)){i(!0);try{await e(!0),n(!0)}catch(l){console.error("Failed to enable camera:",l)}finally{i(!1)}}},[t,r,e]),a=j.useCallback(async()=>{if(!(!t||r)){i(!0);try{await e(!1),n(!1)}catch(l){console.error("Failed to disable camera:",l)}finally{i(!1)}}},[t,r,e]);return{isEnabled:t,isLoading:r,toggle:s,enable:o,disable:a}}function Pm(){const{startScreenShare:e,stopScreenShare:t}=Dt(),[n,r]=j.useState(!1),[i,s]=j.useState(!1),o=j.useCallback(async()=>{if(!(n||i)){s(!0);try{await e(),r(!0)}catch(c){console.error("Failed to start screen share:",c)}finally{s(!1)}}},[n,i,e]),a=j.useCallback(async()=>{if(!(!n||i)){s(!0);try{await t(),r(!1)}catch(c){console.error("Failed to stop screen share:",c)}finally{s(!1)}}},[n,i,t]),l=j.useCallback(async()=>{n?await a():await o()},[n,o,a]);return{isSharing:n,isLoading:i,start:o,stop:a,toggle:l}}function IE(){const{client:e}=Dt(),[t,n]=j.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),r=j.useMemo(()=>t.tracks.find(p=>p.isLocal),[t.tracks]),i=j.useMemo(()=>t.tracks.filter(p=>!p.isLocal),[t.tracks]),s=j.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]),o=j.useCallback(async()=>{try{t.tracks.find(b=>b.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=j.useCallback(p=>{n(b=>({...b,layout:p}))},[]),l=j.useCallback(p=>{n(b=>({...b,pinnedTrack:p}))},[]),c=j.useCallback(()=>{n(p=>({...p,pinnedTrack:void 0}))},[]),u=j.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]),d=j.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=j.useCallback(p=>t.tracks.find(b=>b.id===p),[t.tracks]),m=j.useCallback(p=>t.tracks.filter(b=>b.participantId===p),[t.tracks]),g=j.useCallback(p=>p.isEnabled&&t.tracks.includes(p),[t.tracks]);return j.useEffect(()=>{if(!e)return;const p=k=>{n(S=>({...S,tracks:[...S.tracks.filter(A=>A.id!==k.id),k]}))},b=k=>{n(S=>{var A;return{...S,tracks:S.tracks.filter(T=>T.id!==k),pinnedTrack:((A=S.pinnedTrack)==null?void 0:A.id)===k?void 0:S.pinnedTrack}})},v=k=>{n(S=>({...S,tracks:S.tracks.map(A=>A.id===k.id?k:A)}))};return e.on("videoTrackAdded",p),e.on("videoTrackRemoved",b),e.on("videoTrackUpdated",v),()=>{e.off("videoTrackAdded",p),e.off("videoTrackRemoved",b),e.off("videoTrackUpdated",v)}},[e]),{tracks:t.tracks,localTrack:r,remoteTraracks:i,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:s,toggleScreenShare:o,setLayout:a,pinTrack:l,unpinTrack:c,startRecording:u,stopRecording:d,getTrackById:h,getTracksByParticipant:m,isTrackActive:g}}function Zi(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=Dt(),[r,i]=j.useState(!1),s=j.useCallback(async c=>{if(!(!c.trim()||r||!n)){i(!0);try{await t(c.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{i(!1)}}},[t,r,n]),{userMessages:o,agentMessages:a,allMessages:l}=j.useMemo(()=>{const c=e.filter(d=>d.sender.type==="participant"),u=e.filter(d=>d.sender.type==="agent");return{userMessages:c,agentMessages:u,allMessages:e}},[e]);return{messages:l,userMessages:o,agentMessages:a,messageCount:l.length,isSending:r,canSend:!!n&&!r,send:s}}function RE(){const{send:e,isSending:t,canSend:n}=Zi(),[r,i]=j.useState(""),s=j.useCallback(async()=>{if(!(!r.trim()||!n))try{await e(r),i("")}catch(a){throw a}},[r,e,n]),o=j.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),s())},[s]);return{value:r,setValue:i,send:s,handleKeyPress:o,isSending:t,canSend:n&&r.trim().length>0}}function Za(){const{isConnected:e,isConnecting:t,connectionError:n,connect:r,disconnect:i}=Dt(),s=j.useCallback(async()=>{if(!(e||t))try{await r()}catch(a){throw console.error("Failed to connect:",a),a}},[r,e,t]),o=j.useCallback(async()=>{if(e)try{await i()}catch(a){throw console.error("Failed to disconnect:",a),a}},[i,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:s,disconnect:o}}function Mm(){const{participants:e}=Dt();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const Nm=j.createContext({}),_r=()=>j.useContext(Nm);function Im({children:e,...t}){return f.jsx(Nm.Provider,{value:t,children:e})}function di({name:e,children:t,fallback:n,className:r}){return f.jsx("div",{className:`voxket-slot voxket-slot--${e} ${r||""}`,children:t||n})}function Rm(e,t={}){return Object.assign(e,t)}function Vm({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:r=!0,customControls:i,className:s=""}){const o=kn(),a=Am(),l=jm(),c=Pm(),u=_r(),d=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,o.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",s].filter(Boolean).join(" ");return!o.isActive&&!r?f.jsx("div",{className:d,children:f.jsx("div",{className:"voxket-controls-inactive",children:f.jsx("p",{children:"Controls available during active session"})})}):f.jsxs("div",{className:d,children:[r&&f.jsx("div",{className:"voxket-session-actions",children:o.isActive?f.jsx("button",{onClick:o.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):f.jsx(VE,{})}),o.isActive&&f.jsxs("div",{className:"voxket-media-controls",children:[e&&f.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:[f.jsx("span",{className:"voxket-icon",children:"๐ค"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&f.jsxs("button",{onClick:l.toggle,disabled:l.isLoading,className:`voxket-button voxket-button--media ${l.isEnabled?"voxket-button--active":""}`,title:l.isEnabled?"Stop camera":"Start camera",children:[f.jsx("span",{className:"voxket-icon",children:"๐น"}),l.isLoading?"Loading...":l.isEnabled?"Stop Video":"Start Video"]}),n&&f.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isSharing?"voxket-button--active":""}`,title:c.isSharing?"Stop screen share":"Start screen share",children:[f.jsx("span",{className:"voxket-icon",children:"๐ฅ๏ธ"}),c.isLoading?"Loading...":c.isSharing?"Stop Share":"Share Screen"]})]}),i&&f.jsx("div",{className:"voxket-custom-controls",children:i})]})}function VE(){kn();const[e,t]=j.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 f.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function qa({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:r=""}){const i=kn(),s=Za(),o=_r(),a=["voxket-session-header",`voxket-session-header--${o.variant||"default"}`,`voxket-session-header--${o.size||"md"}`,r].filter(Boolean).join(" ");return f.jsxs("div",{className:a,children:[e&&f.jsxs("div",{className:"voxket-connection-status",children:[f.jsx("div",{className:`voxket-status-indicator ${s.isConnected?"connected":"disconnected"}`}),f.jsx("span",{className:"voxket-status-text",children:s.isConnecting?"Connecting...":s.isConnected?"Connected":"Disconnected"})]}),t&&i.session&&f.jsxs("div",{className:"voxket-session-info",children:[f.jsxs("div",{className:"voxket-session-id",children:["Session: ",i.session.id.slice(-8)]}),f.jsxs("div",{className:"voxket-session-state",children:["State: ",i.state]})]}),n&&i.session&&f.jsxs("div",{className:"voxket-agent-info",children:[f.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",i.session.agentId]}),f.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",i.session.activeModalities.join(", ")]})]}),s.error&&f.jsxs("div",{className:"voxket-error-message",children:["Error: ",s.error.message]})]})}function Ga({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:r=""}){const i=kn(),s=Zi(),o=_r(),a=["voxket-session-content",`voxket-session-content--${o.variant||"default"}`,`voxket-session-content--${o.size||"md"}`,r].filter(Boolean).join(" ");return i.isActive?f.jsx("div",{className:a,children:n||f.jsxs(f.Fragment,{children:[e&&f.jsxs("div",{className:"voxket-chat-container",children:[f.jsxs("div",{className:"voxket-chat-messages",children:[s.messages.map(l=>f.jsxs("div",{className:`voxket-message voxket-message--${l.sender.type}`,children:[f.jsxs("div",{className:"voxket-message-header",children:[f.jsx("span",{className:"voxket-message-sender",children:l.sender.name}),f.jsx("span",{className:"voxket-message-time",children:l.timestamp.toLocaleTimeString()})]}),f.jsx("div",{className:"voxket-message-content",children:l.content})]},l.id)),s.messages.length===0&&f.jsx("div",{className:"voxket-empty-messages",children:f.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),f.jsx(DE,{})]}),t&&f.jsx("div",{className:"voxket-transcriptions",children:f.jsx("div",{className:"voxket-transcription-placeholder",children:f.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):f.jsx("div",{className:a,children:f.jsx("div",{className:"voxket-inactive-state",children:f.jsxs("div",{className:"voxket-inactive-message",children:[f.jsx("h3",{children:"Start a conversation"}),f.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function DE(){const e=Zi(),[t,n]=j.useState(""),r=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(s){console.error("Failed to send message:",s)}},i=s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),r())};return f.jsxs("div",{className:"voxket-chat-input",children:[f.jsx("input",{type:"text",value:t,onChange:s=>n(s.target.value),onKeyPress:i,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),f.jsx("button",{onClick:r,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function Ka({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:r,className:i=""}){const s=kn(),o=Tm(),a=Mm(),l=_r(),c=["voxket-session-footer",`voxket-session-footer--${l.variant||"default"}`,`voxket-session-footer--${l.size||"md"}`,i].filter(Boolean).join(" ");return s.isActive?f.jsx("div",{className:c,children:r||f.jsxs(f.Fragment,{children:[n&&f.jsxs("div",{className:"voxket-session-status",children:[f.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),f.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&o.metrics&&f.jsxs("div",{className:"voxket-session-metrics",children:[f.jsxs("div",{className:"voxket-metric",children:[f.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),f.jsx("span",{className:"voxket-metric-value",children:FE(o.duration||0)})]}),f.jsxs("div",{className:"voxket-metric",children:[f.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),f.jsx("span",{className:"voxket-metric-value",children:o.metrics.messageCount})]})]}),t&&f.jsxs("div",{className:"voxket-participants-info",children:[f.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&f.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>f.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):f.jsx("div",{className:c,children:f.jsx("div",{className:"voxket-footer-inactive",children:f.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function FE(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 LE({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:r,onSessionEnd:i,variant:s="default",size:o="md",theme:a,className:l="",children:c}){var m;const u=kn(),d=Za();j.useEffect(()=>{n&&e&&d.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,d.isConnected,u.isActive]),j.useEffect(()=>{var g;(g=u.session)!=null&&g.id&&r&&r(u.session.id)},[(m=u.session)==null?void 0:m.id,r]),j.useEffect(()=>()=>{u.isActive&&i&&u.stop().then(i).catch(console.error)},[]);const h=["voxket-session",`voxket-session--${s}`,`voxket-session--${o}`,u.isActive?"voxket-session--active":"voxket-session--inactive",l].filter(Boolean).join(" ");return f.jsx(Im,{variant:s,size:o,theme:a,className:l,children:f.jsx("div",{className:h,children:c||f.jsxs(f.Fragment,{children:[f.jsx(di,{name:"header",fallback:f.jsx(qa,{})}),f.jsx(di,{name:"content",fallback:f.jsx(Ga,{})}),f.jsx(di,{name:"footer",fallback:f.jsx(Ka,{})})]})})})}const Dm=Rm(LE,{Header:qa,Content:Ga,Footer:Ka,Controls:Vm}),xn={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)"}},js={...xn,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)"}},Ps={...xn,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=j.createContext(null),Lm=()=>{const e=j.useContext(Fm);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function OE({theme:e="default",themes:t={},children:n,cssVariables:r=!0,className:i=""}){const[s,o]=j.useState(()=>{const h={default:xn,dark:js,enterprise:Ps,...t};return typeof e=="string"?h[e]||xn:e}),[a,l]=j.useState(()=>({default:xn,dark:js,enterprise:Ps,...t})),c=h=>{if(typeof h=="string"){const m=a[h];m&&o(m)}else o(h)},u=h=>{l(m=>({...m,[h.name]:h}))};j.useEffect(()=>{if(r&&typeof document<"u"){const h=document.documentElement;Object.entries(Om(s)).forEach(([m,g])=>{h.style.setProperty(`--voxket-${m}`,g)})}},[s,r]);const d={theme:s,setTheme:c,themes:a,registerTheme:u};return f.jsx(Fm.Provider,{value:d,children:f.jsx("div",{className:`voxket-theme voxket-theme--${s.name} ${i}`,children:n})})}function Om(e){const t={},n=(r,i="")=>{for(const[s,o]of Object.entries(r)){const a=i?`${i}-${s}`:s;typeof o=="object"&&o!==null&&!Array.isArray(o)?n(o,a):t[a]=String(o)}};return n(e),t}function $E(e=xn,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 _E(e){var n;const{theme:t}=Lm();return((n=t.components)==null?void 0:n[e])||{}}const BE=Wa("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&zE(e),t.enableVoiceActivation&&HE(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&UE(e,t)}});function zE(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 HE(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function UE(e,t){console.log("Playing audio response:",t.content)}const WE=Wa("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&ZE(),t.enableFileUpload&&qE(e),t.enableCustomComponents&&GE(),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"?KE(e,t):t.type==="text"&&n.enableRichText&&YE(e,t)}});function ZE(e){console.log("Rich text support enabled")}function qE(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function GE(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",XE),t.set("form",QE),t.set("card",JE),t.set("chart",eT)}function KE(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 YE(e,t){console.log("Processing rich text message:",t.content)}function XE(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function QE(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function JE(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function eT(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function fi({track:e,participantName:t,showControls:n=!0,showName:r=!0,showMuteIndicator:i=!0,isPinned:s=!1,className:o="",onClick:a,onPin:l,onUnpin:c}){const u=j.useRef(null),[d,h]=j.useState(!1);j.useEffect(()=>{if(!u.current||!e.isEnabled)return;const b=u.current;return b.srcObject=null,()=>{b.srcObject&&(b.srcObject=null)}},[e]);const m=()=>{a==null||a(e)},g=b=>{b.stopPropagation(),s?c==null||c(e):l==null||l(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",s?"voxket-video-tile--pinned":"",e.isEnabled?"":"voxket-video-tile--disabled",d?"voxket-video-tile--hovered":"",o].filter(Boolean).join(" ");return f.jsxs("div",{className:p,onClick:m,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[f.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&f.jsxs("div",{className:"voxket-video-placeholder",children:[f.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"๐ฅ๏ธ":"๐น"}),f.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),f.jsxs("div",{className:"voxket-video-overlay",children:[r&&t&&f.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),i&&!e.isEnabled&&f.jsx("div",{className:"voxket-video-mute-indicator",children:"๐"}),n&&(d||s)&&f.jsxs("div",{className:"voxket-video-controls",children:[f.jsx("button",{className:`voxket-video-control-btn ${s?"voxket-video-control-btn--active":""}`,onClick:g,title:s?"Unpin video":"Pin video",children:"๐"}),e.isScreenShare&&f.jsx("div",{className:"voxket-video-indicator",children:"๐ฅ๏ธ"}),e.source&&f.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&f.jsx("div",{className:"voxket-video-loading",children:f.jsx("div",{className:"voxket-spinner"})})]})}function tT({tracks:e,layout:t,className:n="",onLayoutChange:r,onTrackClick:i,maxVisibleTracks:s=9,showPagination:o=!0}){const[a,l]=j.useState(0),[c,u]=j.useState(null),d=j.useMemo(()=>{let k=[...e];t.type==="speaker"&&c&&(k=[c,...e.filter(T=>T.id!==c.id)]);const S=a*s,A=S+s;return k.slice(S,A)},[e,t,c,a,s]),h=Math.ceil(e.length/s),m=j.useMemo(()=>{const k=d.length;switch(t.type){case"grid":const S=Math.ceil(Math.sqrt(k)),A=Math.ceil(k/S);return{display:"grid",gridTemplateColumns:`repeat(${S}, 1fr)`,gridTemplateRows:`repeat(${A}, 1fr)`,gap:"8px"};case"speaker":return{display:"flex",flexDirection:"column",gap:"8px"};case"sidebar":return{display:"flex",gap:"8px"};case"gallery":return{display:"flex",flexWrap:"wrap",gap:"8px",justifyContent:"center"};default:return{}}},[t.type,d.length]),g=k=>{u(k)},p=()=>{u(null)},b=k=>{r==null||r({...t,type:k})},v=["voxket-video-grid",`voxket-video-grid--${t.type}`,`voxket-video-grid--${d.length}-tracks`,n].filter(Boolean).join(" ");return e.length===0?f.jsx("div",{className:"voxket-video-grid-empty",children:f.jsxs("div",{className:"voxket-video-grid-empty-content",children:[f.jsx("div",{className:"voxket-video-grid-empty-icon",children:"๐น"}),f.jsx("p",{children:"No video tracks available"})]})}):f.jsxs("div",{className:v,children:[f.jsxs("div",{className:"voxket-video-grid-controls",children:[f.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(k=>f.jsx("button",{className:`voxket-layout-btn ${t.type===k?"voxket-layout-btn--active":""}`,onClick:()=>b(k),title:`Switch to ${k} layout`,children:nT(k)},k))}),f.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),f.jsx("div",{className:"voxket-video-grid-content",style:m,children:t.type==="speaker"&&c?f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"voxket-video-speaker-main",children:f.jsx(fi,{track:c,participantName:`Participant ${c.participantId}`,isPinned:!0,onClick:i,onUnpin:p})}),f.jsx("div",{className:"voxket-video-speaker-sidebar",children:d.filter(k=>k.id!==c.id).map(k=>f.jsx(fi,{track:k,participantName:`Participant ${k.participantId}`,showControls:!1,onClick:i,onPin:g},k.id))})]}):d.map(k=>f.jsx(fi,{track:k,participantName:`Participant ${k.participantId}`,isPinned:(c==null?void 0:c.id)===k.id,onClick:i,onPin:g,onUnpin:p},k.id))}),o&&h>1&&f.jsxs("div",{className:"voxket-video-pagination",children:[f.jsx("button",{className:"voxket-pagination-btn",onClick:()=>l(Math.max(0,a-1)),disabled:a===0,children:"โ"}),f.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",h]}),f.jsx("button",{className:"voxket-pagination-btn",onClick:()=>l(Math.min(h-1,a+1)),disabled:a===h-1,children:"โ"})]})]})}function nT(e){switch(e){case"grid":return"โ";case"speaker":return"๐ค";case"sidebar":return"โซธ";case"gallery":return"โก";case"picture-in-picture":return"โง";default:return"โ"}}function rT({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:r,showLayoutControls:i=!0,showCameraControls:s=!0,showScreenShareControls:o=!0,className:a=""}){const l=["voxket-video-controls",a].filter(Boolean).join(" "),c=u=>{r==null||r({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return f.jsxs("div",{className:l,children:[s&&f.jsxs("div",{className:"voxket-video-controls-section",children:[f.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),f.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:[f.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"๐น":"๐ท"}),f.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&f.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," ร ",e.dimensions.height]})]}),o&&f.jsxs("div",{className:"voxket-video-controls-section",children:[f.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),f.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:[f.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"๐":"๐ฅ๏ธ"}),f.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),i&&f.jsxs("div",{className:"voxket-video-controls-section",children:[f.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),f.jsx("div",{className:"voxket-layout-buttons",children:[{type:"grid",icon:"โ",label:"Grid"},{type:"speaker",icon:"๐ค",label:"Speaker"},{type:"sidebar",icon:"โซธ",label:"Sidebar"},{type:"gallery",icon:"โก",label:"Gallery"}].map(({type:u,icon:d,label:h})=>f.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>c(u),title:`Switch to ${h} layout`,children:[f.jsx("span",{className:"voxket-control-icon",children:d}),f.jsx("span",{className:"voxket-control-label",children:h})]},u))})]}),f.jsxs("div",{className:"voxket-video-controls-section",children:[f.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),f.jsxs("div",{className:"voxket-video-settings",children:[f.jsxs("div",{className:"voxket-setting-group",children:[f.jsx("label",{className:"voxket-setting-label",children:"Quality"}),f.jsxs("select",{className:"voxket-setting-select",children:[f.jsx("option",{value:"high",children:"High (720p)"}),f.jsx("option",{value:"medium",children:"Medium (480p)"}),f.jsx("option",{value:"low",children:"Low (240p)"})]})]}),f.jsxs("div",{className:"voxket-setting-group",children:[f.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),f.jsxs("select",{className:"voxket-setting-select",children:[f.jsx("option",{value:"30",children:"30 fps"}),f.jsx("option",{value:"15",children:"15 fps"}),f.jsx("option",{value:"10",children:"10 fps"})]})]}),f.jsxs("div",{className:"voxket-setting-group",children:[f.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),f.jsxs("select",{className:"voxket-setting-select",children:[f.jsx("option",{value:"unlimited",children:"Unlimited"}),f.jsx("option",{value:"1000",children:"1 Mbps"}),f.jsx("option",{value:"500",children:"500 Kbps"}),f.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),f.jsxs("div",{className:"voxket-video-controls-section",children:[f.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),f.jsxs("div",{className:"voxket-video-stats",children:[f.jsxs("div",{className:"voxket-stat-item",children:[f.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),f.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}ร${e.dimensions.height}`:"N/A"})]}),f.jsxs("div",{className:"voxket-stat-item",children:[f.jsx("span",{className:"voxket-stat-label",children:"Source:"}),f.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),f.jsxs("div",{className:"voxket-stat-item",children:[f.jsx("span",{className:"voxket-stat-label",children:"Status:"}),f.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 $m=({handler:e,loadData:t,data:n,client:r,addLocalMessage:i})=>{const[s,o]=x.useState(null),[a,l]=x.useState(!0),[c,u]=x.useState(!1),[d]=x.useState(Date.now());x.useEffect(()=>{(async()=>{try{if(l(!0),console.log("๐ AssignmentView: Loading assignment data..."),console.log("๐ AssignmentView: Received data from RPC:",n),n&&typeof n=="object"){const b={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};o(b),console.log("๐ AssignmentView: Assignment loaded from RPC data:",b)}}catch(b){console.error("๐ AssignmentView: Error loading assignment:",b),o({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{l(!1)}})()},[n,t]);const h=({message:p,assignment:b})=>{const v=p.toLowerCase().includes("declined"),k=v?"bg-red-50 border-red-200":"bg-green-50 border-green-200",S=v?"text-red-700":"text-green-700",A=v?"โ":"๐";return f.jsxs("div",{className:`max-w-sm mx-auto ${k} border rounded-lg shadow p-3 flex flex-col items-center`,children:[f.jsx("div",{className:"text-2xl mb-2",children:A}),f.jsx("div",{className:`${S} font-semibold text-sm mb-1`,children:p}),f.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:b.title}),f.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},m=async()=>{if(!(!s||!e)){u(!0);try{const p={message:"accepted"};console.log("๐ AssignmentView: Assignment accepted:",p),e.didSuccess(p,f.jsx(h,{message:"Assignment accepted!",assignment:s}))}catch(p){console.error("๐ AssignmentView: Error accepting assignment:",p),e.didFail({error:"Failed to accept assignment"})}finally{u(!1)}}},g=async()=>{if(!(!s||!e)){u(!0);try{const p={message:"declined"};console.log("๐ AssignmentView: Assignment declined:",p),e.didSuccess(p,f.jsx(h,{message:"Assignment declined",assignment:s}))}catch(p){console.error("๐ AssignmentView: Error declining assignment:",p),e.didFail({error:"Failed to decline assignment"})}finally{u(!1)}}};return a?f.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:f.jsxs("div",{className:"flex items-center justify-center py-4",children:[f.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),f.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):s?f.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[f.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:f.jsx("div",{className:"flex items-center justify-between",children:f.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:s.title})})}),f.jsxs("div",{className:"p-3 text-black",children:[f.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:f.jsx("p",{className:"text-xs text-black leading-snug",children:s.description})}),f.jsx("div",{className:"mb-3 text-black",children:f.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[f.jsx("span",{className:"text-xs mr-1",children:"๐
"}),f.jsxs("span",{children:["Est: ",s.estimated_time_of_completion]})]})}),f.jsxs("div",{className:"flex gap-2",children:[f.jsx("button",{onClick:m,disabled:c,className:"flex-1 bg-green-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:c?f.jsxs("span",{className:"flex items-center justify-center",children:[f.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),f.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),f.jsx("button",{onClick:g,disabled:c,className:"flex-1 bg-red-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Decline"})]})]})]}):f.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:f.jsxs("div",{className:"text-center py-4",children:[f.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"โ ๏ธ Assignment Error"}),f.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function iT(){const[e,t]=x.useState(null),[n,r]=x.useState([]);x.useEffect(()=>{const a=new $r({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return t(a),a.on("rpc.method.called",l=>{console.log("RPC Method Called:",l)}),a.on("rpc.interaction.completed",l=>{console.log("RPC Interaction Completed:",l)}),()=>{a.disconnect()}},[]);const i=async()=>{if(e)try{await e.registerFrontendRPC("give_assignment",$m,"embedded");const a=e.getRegisteredRpcMethods();r(a),console.log("โ
Assignment RPC registered successfully")}catch(a){console.error("โ Failed to register assignment RPC:",a)}},s=async()=>{if(!e)return;const a=({handler:l,timeout:c})=>{const[u,d]=x.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"}],m=p=>{d(p)},g=()=>{const p=h.find(b=>b.id===u);l==null||l.didSuccess({selectedProduct:u,productName:p==null?void 0:p.name,price:p==null?void 0:p.price,timestamp:new Date().toISOString()})};return f.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[f.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),f.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),f.jsx("div",{className:"space-y-3 mb-6",children:h.map(p=>f.jsx("div",{onClick:()=>m(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:f.jsxs("div",{className:"flex justify-between items-center",children:[f.jsxs("div",{children:[f.jsx("h4",{className:"font-medium",children:p.name}),f.jsx("p",{className:"text-gray-600 text-sm",children:p.price})]}),f.jsx("div",{className:`w-4 h-4 rounded-full ${u===p.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},p.id))}),f.jsxs("div",{className:"flex justify-end space-x-3",children:[f.jsx("button",{onClick:()=>l==null?void 0:l.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),f.jsx("button",{onClick:g,disabled:!u,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),c&&f.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",c," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const l=e.getRegisteredRpcMethods();r(l),console.log("โ
Product Recommendation RPC registered successfully")}catch(l){console.error("โ Failed to register product recommendation RPC:",l)}},o=async()=>{if(!e)return;const a=({handler:l})=>{const[c,u]=x.useState(0),[d,h]=x.useState(""),m=()=>{l==null||l.didSuccess({rating:c,comment:d,timestamp:new Date().toISOString()})};return f.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[f.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),f.jsxs("div",{className:"mb-4",children:[f.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),f.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(g=>f.jsx("button",{onClick:()=>u(g),className:`text-2xl ${g<=c?"text-yellow-400":"text-gray-300"}`,children:"โญ"},g))})]}),f.jsxs("div",{className:"mb-4",children:[f.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),f.jsx("textarea",{value:d,onChange:g=>h(g.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),f.jsxs("div",{className:"flex justify-end space-x-2",children:[f.jsx("button",{onClick:()=>l==null?void 0:l.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),f.jsx("button",{onClick:m,disabled:c===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await e.registerFrontendRPC("collect_feedback",a,"embedded");const l=e.getRegisteredRpcMethods();r(l),console.log("โ
Feedback RPC registered successfully")}catch(l){console.error("โ Failed to register feedback RPC:",l)}};return f.jsxs("div",{className:"p-6",children:[f.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),f.jsxs("div",{className:"space-y-4 mb-6",children:[f.jsxs("div",{children:[f.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),f.jsxs("div",{className:"space-x-2",children:[f.jsx("button",{onClick:i,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),f.jsx("button",{onClick:s,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),f.jsx("button",{onClick:o,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),f.jsxs("div",{children:[f.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?f.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>f.jsx("li",{className:"text-gray-700",children:f.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):f.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),f.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[f.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),f.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[f.jsxs("li",{children:["Register RPC methods with React components using ",f.jsx("code",{children:"client.registerFrontendRPC()"})]}),f.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),f.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),f.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),f.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),f.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[f.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),f.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),f.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
|
|
164
164
|
const response = await participant.performRpc({
|
|
165
165
|
method: 'give_assignment',
|
|
166
166
|
data: JSON.stringify({
|
|
@@ -171,4 +171,4 @@ const response = await participant.performRpc({
|
|
|
171
171
|
})
|
|
172
172
|
});
|
|
173
173
|
|
|
174
|
-
console.log('User response:', response);`})]})]})}const oT={async checkAvailableRpcs(e){const t=e.getRegisteredRpcMethods();return console.log("๐ Agent: Available RPC methods:",t),t},async triggerAssignment(e,t){const n={title:"Complete Q4 Sales Analysis Report",description:"Please analyze the Q4 sales data and create a comprehensive report with insights, trends, and recommendations for the upcoming quarter. Include visualizations and executive summary.",estimated_time_of_completion:"2-3 hours"};try{console.log("๐ค Agent: Triggering give_assignment RPC with data:",n);const r=await e.localParticipant.performRpc(t,"give_assignment",JSON.stringify(n),{responseTimeout:12e4}),i=JSON.parse(r);return console.log("โ
Agent: Received user response:",i),await this.processAssignmentResponse(i),i}catch(r){throw console.error("โ Agent: RPC failed:",r),r}},async processAssignmentResponse(e){console.log("๐ง Agent: Processing assignment response...");const t=e.status,n=e.assignmentId,r=e.timeSpent;return t==="accepted"?(console.log("๐ Agent: User accepted the assignment!"),console.log(`๏ฟฝ Assignment ID: ${n}`),console.log(`โฑ๏ธ Time to respond: ${r}ms`),console.log("๐ฌ Agent: Sending follow-up:","Great! I've recorded that you've accepted the assignment. You'll receive the detailed requirements and access to the data shortly. Let me know if you need any clarification!")):t==="declined"?(console.log("โ Agent: User declined the assignment"),console.log("๐ฌ Agent: Sending follow-up:","No problem! Is there anything specific about this assignment that doesn't work for you? I can suggest alternatives or modify the requirements.")):t==="completed"&&(console.log("โ
Agent: User completed the assignment"),console.log("๐ฌ Agent: Sending follow-up:","Excellent work! Could you please share the completed report? I'm excited to review your analysis and insights.")),{status:t,assignmentId:n,timeSpent:r,processed:!0,followupAction:t==="accepted"?"send_requirements":t==="declined"?"offer_alternatives":"request_deliverables"}},getAssignmentExamples(){return{marketing:{title:"Create Social Media Campaign",description:"Design and plan a social media campaign for our new product launch. Include content calendar, post designs, and engagement strategy.",estimated_time_of_completion:"4-5 hours"},technical:{title:"API Integration Documentation",description:"Create comprehensive documentation for our new API endpoints, including examples, error codes, and best practices for developers.",estimated_time_of_completion:"6-8 hours"},research:{title:"Market Research Analysis",description:"Research and analyze competitor pricing strategies in our target market. Provide recommendations for our pricing model.",estimated_time_of_completion:"3-4 hours"},quick:{title:"Customer Feedback Summary",description:"Review this week's customer feedback and create a summary of key themes and actionable insights.",estimated_time_of_completion:"30-45 minutes"}}}}
|
|
174
|
+
console.log('User response:', response);`})]})]})}const oT={async checkAvailableRpcs(e){const t=e.getRegisteredRpcMethods();return console.log("๐ Agent: Available RPC methods:",t),t},async triggerAssignment(e,t){const n={title:"Complete Q4 Sales Analysis Report",description:"Please analyze the Q4 sales data and create a comprehensive report with insights, trends, and recommendations for the upcoming quarter. Include visualizations and executive summary.",estimated_time_of_completion:"2-3 hours"};try{console.log("๐ค Agent: Triggering give_assignment RPC with data:",n);const r=await e.localParticipant.performRpc(t,"give_assignment",JSON.stringify(n),{responseTimeout:12e4}),i=JSON.parse(r);return console.log("โ
Agent: Received user response:",i),await this.processAssignmentResponse(i),i}catch(r){throw console.error("โ Agent: RPC failed:",r),r}},async processAssignmentResponse(e){console.log("๐ง Agent: Processing assignment response...");const t=e.status,n=e.assignmentId,r=e.timeSpent;return t==="accepted"?(console.log("๐ Agent: User accepted the assignment!"),console.log(`๏ฟฝ Assignment ID: ${n}`),console.log(`โฑ๏ธ Time to respond: ${r}ms`),console.log("๐ฌ Agent: Sending follow-up:","Great! I've recorded that you've accepted the assignment. You'll receive the detailed requirements and access to the data shortly. Let me know if you need any clarification!")):t==="declined"?(console.log("โ Agent: User declined the assignment"),console.log("๐ฌ Agent: Sending follow-up:","No problem! Is there anything specific about this assignment that doesn't work for you? I can suggest alternatives or modify the requirements.")):t==="completed"&&(console.log("โ
Agent: User completed the assignment"),console.log("๐ฌ Agent: Sending follow-up:","Excellent work! Could you please share the completed report? I'm excited to review your analysis and insights.")),{status:t,assignmentId:n,timeSpent:r,processed:!0,followupAction:t==="accepted"?"send_requirements":t==="declined"?"offer_alternatives":"request_deliverables"}},getAssignmentExamples(){return{marketing:{title:"Create Social Media Campaign",description:"Design and plan a social media campaign for our new product launch. Include content calendar, post designs, and engagement strategy.",estimated_time_of_completion:"4-5 hours"},technical:{title:"API Integration Documentation",description:"Create comprehensive documentation for our new API endpoints, including examples, error codes, and best practices for developers.",estimated_time_of_completion:"6-8 hours"},research:{title:"Market Research Analysis",description:"Research and analyze competitor pricing strategies in our target market. Provide recommendations for our pricing model.",estimated_time_of_completion:"3-4 hours"},quick:{title:"Customer Feedback Summary",description:"Review this week's customer feedback and create a summary of key themes and actionable insights.",estimated_time_of_completion:"30-45 minutes"}}}};typeof window<"u"&&Promise.resolve().then(()=>require("./index-Dyvby5gX.cjs"));const sT=e=>typeof window>"u"?null:x.createElement(Ha,{children:x.createElement(ui,e)}),aT=e=>{if(typeof window>"u")return console.warn("VoxketClient: Cannot create client in server-side environment"),null;const{VoxketClient:t}=require("./core/client");return new t(e)};exports.AssignmentView=$m;exports.CompoundProvider=Im;exports.InteractiveComponent=Tr;exports.PluginManager=As;exports.RpcExamples=iT;exports.SessionContainer=Dm;exports.SessionContent=Ga;exports.SessionControls=Vm;exports.SessionFooter=Ka;exports.SessionHeader=qa;exports.SessionLogViewer=ME;exports.SessionMetricsComponent=NE;exports.Slot=di;exports.ThemeProvider=OE;exports.VideoControls=rT;exports.VideoGrid=tT;exports.VideoTile=fi;exports.VoxketClient=$r;exports.VoxketErrorBoundary=Ha;exports.VoxketEventEmitter=Ua;exports.VoxketProvider=ci;exports.VoxketSDK=$r;exports.VoxketSessionComponent=Dm;exports.agentRpcExample=oT;exports.analyticsPlugin=bE;exports.chatModalityPlugin=WE;exports.createCustomTheme=$E;exports.createModalityPlugin=Wa;exports.createPlugin=xE;exports.createVoxketClient=aT;exports.darkTheme=js;exports.debugPlugin=vE;exports.default=sT;exports.defaultTheme=xn;exports.enterpriseTheme=Ps;exports.flattenTheme=Om;exports.metricsPlugin=wE;exports.useComponentTheme=_E;exports.useCompoundContext=_r;exports.useSessionLogging=Cm;exports.useTheme=Lm;exports.useVoxket=Dt;exports.useVoxketCamera=jm;exports.useVoxketChat=Zi;exports.useVoxketChatInput=RE;exports.useVoxketConnection=Za;exports.useVoxketMetrics=Tm;exports.useVoxketMicrophone=Am;exports.useVoxketParticipants=Mm;exports.useVoxketScreenShare=Pm;exports.useVoxketSession=kn;exports.useVoxketVideo=IE;exports.voiceModalityPlugin=BE;exports.withCompoundComponent=Rm;
|
package/dist/index.js
CHANGED
|
@@ -24876,6 +24876,10 @@ class Ga extends _m {
|
|
|
24876
24876
|
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));
|
|
24877
24877
|
}
|
|
24878
24878
|
initializeClient() {
|
|
24879
|
+
if (typeof window > "u") {
|
|
24880
|
+
console.warn("VoxketClient: Skipping room initialization in server-side environment");
|
|
24881
|
+
return;
|
|
24882
|
+
}
|
|
24879
24883
|
this.room = new wr(), this.setupRoomEventListeners();
|
|
24880
24884
|
}
|
|
24881
24885
|
setupRoomEventListeners() {
|
|
@@ -25244,7 +25248,7 @@ class Ga extends _m {
|
|
|
25244
25248
|
roomState: this.room.state,
|
|
25245
25249
|
numParticipants: this.room.numParticipants,
|
|
25246
25250
|
sessionId: (n = this.currentSession) == null ? void 0 : n.id
|
|
25247
|
-
}), await this.room.disconnect()), this.isConnected = !1, this.currentSession = null, this.currentAgentInfo = null, this.textStreamHandlersRegistered = !1, this.clearChatMessages(), console.log("๐ VoxketClient: Creating new room instance..."), this.room = new wr(), this.setupRoomEventListeners(), console.log("โ
VoxketClient: Disconnect completed successfully"), this.emit("connection.disconnected");
|
|
25251
|
+
}), await this.room.disconnect()), this.isConnected = !1, this.currentSession = null, this.currentAgentInfo = null, this.textStreamHandlersRegistered = !1, this.clearChatMessages(), console.log("๐ VoxketClient: Creating new room instance..."), typeof window < "u" && (this.room = new wr(), this.setupRoomEventListeners()), console.log("โ
VoxketClient: Disconnect completed successfully"), this.emit("connection.disconnected");
|
|
25248
25252
|
} catch (r) {
|
|
25249
25253
|
console.error("โ VoxketClient: Disconnect failed:", r);
|
|
25250
25254
|
const i = new Oe(
|
|
@@ -28604,7 +28608,9 @@ const aE = {
|
|
|
28604
28608
|
}
|
|
28605
28609
|
};
|
|
28606
28610
|
}
|
|
28607
|
-
}
|
|
28611
|
+
};
|
|
28612
|
+
typeof window < "u" && Promise.resolve({ });
|
|
28613
|
+
const lE = (e) => typeof window > "u" ? null : b.createElement($m, {
|
|
28608
28614
|
children: b.createElement(gi, e)
|
|
28609
28615
|
}), cE = (e) => {
|
|
28610
28616
|
if (typeof window > "u")
|