@nice2dev/ui-communication 1.0.8 โ 1.0.11
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/__tests__/encryptionService.test.d.ts +8 -0
- package/dist/__tests__/helpers.test.d.ts +7 -0
- package/dist/__tests__/setup.d.ts +1 -0
- package/dist/__tests__/storageService.test.d.ts +7 -0
- package/dist/__tests__/transport.test.d.ts +8 -0
- package/dist/collaboration/collaborative-datagrid.d.ts +95 -0
- package/dist/collaboration/collaborative-form.d.ts +75 -0
- package/dist/collaboration/yjs-integration.d.ts +135 -0
- package/dist/communication-controls.d.ts +369 -0
- package/dist/hooks/useCommunication.d.ts +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.mjs +4720 -2695
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),l=require("react");class mt{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){var i;(i=this.listeners.get(e))==null||i.delete(t)}emit(e,t){var i;(i=this.listeners.get(e))==null||i.forEach(r=>r(t))}removeAll(){this.listeners.clear()}}class yt extends mt{constructor(e={}){super(),this.type="webrtc",this.signalingWs=null,this.localStream=null,this.screenStream=null,this.peers=new Map,this.userId="",this.connected=!1,this.config={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],...e}}async connect(e,t){return this.userId=t,new Promise((i,r)=>{const a=new WebSocket(e);a.onopen=()=>{this.signalingWs=a,this.connected=!0,a.send(JSON.stringify({type:"register",userId:t})),this.emit("transport:connected",{}),i()},a.onerror=o=>{r(new Error(`Signaling WebSocket error: ${String(o)}`))},a.onclose=o=>{this.connected=!1,this.emit("transport:disconnected",{reason:o.reason})},a.onmessage=o=>{try{const c=JSON.parse(String(o.data));this.handleSignalingMessage(c).catch(console.error)}catch{}}})}disconnect(){var e;this.releaseLocalStream();for(const[,t]of this.peers)t.close();this.peers.clear(),(e=this.signalingWs)==null||e.close(),this.signalingWs=null,this.connected=!1,this.removeAll()}isConnected(){return this.connected}async getLocalStream(e){return this.localStream?this.localStream:(this.localStream=await navigator.mediaDevices.getUserMedia(e),this.localStream)}releaseLocalStream(){this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null),this.screenStream&&(this.screenStream.getTracks().forEach(e=>e.stop()),this.screenStream=null)}async startCall(e,t){const i=crypto.randomUUID();return this.sendSignal({type:"call:request",callId:i,callType:t,from:this.userId,to:e}),{id:i,type:t,participants:[],status:"ringing",isRecording:!1,isTranscribing:!1,layout:"grid"}}async acceptCall(e){this.sendSignal({type:"call:accept",callId:e,from:this.userId})}declineCall(e){this.sendSignal({type:"call:decline",callId:e,from:this.userId})}endCall(e){this.sendSignal({type:"call:end",callId:e,from:this.userId});for(const[t,i]of this.peers)i.close(),this.peers.delete(t)}muteAudio(e){var t;(t=this.localStream)==null||t.getAudioTracks().forEach(i=>{i.enabled=!e}),this.sendSignal({type:"peer:mute",from:this.userId,audio:e,video:!1})}muteVideo(e){var t;(t=this.localStream)==null||t.getVideoTracks().forEach(i=>{i.enabled=!e}),this.sendSignal({type:"peer:mute",from:this.userId,audio:!1,video:e})}async setAudioDevice(e){var i;const t=(i=this.localStream)==null?void 0:i.getAudioTracks()[0];t&&await t.applyConstraints({deviceId:{exact:e}})}async setVideoDevice(e){var i;const t=(i=this.localStream)==null?void 0:i.getVideoTracks()[0];t&&await t.applyConstraints({deviceId:{exact:e}})}async startScreenShare(){this.screenStream=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:15},audio:!0});const[e]=this.screenStream.getVideoTracks();e.addEventListener("ended",()=>this.stopScreenShare());for(const[,t]of this.peers)this.screenStream.getTracks().forEach(i=>t.addTrack(i,this.screenStream));return this.sendSignal({type:"screen:started",from:this.userId}),this.screenStream}stopScreenShare(){this.screenStream&&(this.screenStream.getTracks().forEach(e=>e.stop()),this.screenStream=null,this.sendSignal({type:"screen:stopped",from:this.userId}),this.emit("screen:stopped",{participantId:this.userId}))}sendSignal(e){var t;((t=this.signalingWs)==null?void 0:t.readyState)===WebSocket.OPEN&&this.signalingWs.send(JSON.stringify(e))}async handleSignalingMessage(e){var t;switch(e.type){case"call:request":this.emit("call:incoming",{callId:e.callId,callType:e.callType??"audio",callerId:e.from});break;case"call:accept":await this.createPeerConnection(e.from),this.emit("call:accepted",{callId:e.callId,participantId:e.from});break;case"call:decline":this.emit("call:declined",{callId:e.callId,participantId:e.from});break;case"call:end":(t=this.peers.get(e.from))==null||t.close(),this.peers.delete(e.from),this.emit("call:ended",{callId:e.callId,reason:"remote-ended"});break;case"offer":{const i=await this.getOrCreatePeer(e.from);await i.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:e.sdp}));const r=await i.createAnswer();await i.setLocalDescription(r),this.sendSignal({type:"answer",to:e.from,from:this.userId,sdp:r.sdp});break}case"answer":{const i=this.peers.get(e.from);i&&await i.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e.sdp}));break}case"ice-candidate":{const i=this.peers.get(e.from);i&&e.candidate&&await i.addIceCandidate(new RTCIceCandidate(e.candidate));break}case"peer:mute":this.emit("peer:muted",{participantId:e.from,audio:e.audio??!1,video:e.video??!1});break;case"screen:started":break;case"screen:stopped":this.emit("screen:stopped",{participantId:e.from});break}}async getOrCreatePeer(e){return this.peers.has(e)?this.peers.get(e):this.createPeerConnection(e)}async createPeerConnection(e){var r,a;const t=new RTCPeerConnection({iceServers:(r=this.config.iceServers)==null?void 0:r.map(o=>({urls:o.urls,username:o.username,credential:o.credential})),iceTransportPolicy:this.config.iceTransportPolicy});if(this.peers.set(e,t),(a=this.localStream)==null||a.getTracks().forEach(o=>t.addTrack(o,this.localStream)),t.onicecandidate=o=>{o.candidate&&this.sendSignal({type:"ice-candidate",to:e,from:this.userId,candidate:o.candidate})},t.ontrack=o=>{const c=o.streams[0];c&&this.emit("stream:added",{participantId:e,stream:c})},t.onconnectionstatechange=()=>{(t.connectionState==="failed"||t.connectionState==="disconnected")&&this.emit("stream:removed",{participantId:e})},this.config.maxBitrate){const o=t.getSenders();for(const c of o){if(!c.track)continue;const p=c.getParameters();p.encodings||(p.encodings=[{}]),c.track.kind==="audio"&&this.config.maxBitrate.audio?p.encodings[0].maxBitrate=this.config.maxBitrate.audio:c.track.kind==="video"&&this.config.maxBitrate.video&&(p.encodings[0].maxBitrate=this.config.maxBitrate.video),await c.setParameters(p)}}const i=await t.createOffer();return await t.setLocalDescription(i),this.sendSignal({type:"offer",to:e,from:this.userId,sdp:i.sdp}),t}}class xt extends mt{constructor(){super(...arguments),this.type="mock",this.connected=!1,this.localStream=null}async connect(e,t){this.connected=!0,this.emit("transport:connected",{})}disconnect(){this.releaseLocalStream(),this.connected=!1,this.removeAll()}isConnected(){return this.connected}async getLocalStream(e){const t=new AudioContext,i=t.createMediaStreamDestination();t.createOscillator().connect(i);const a=i.stream,o=document.createElement("canvas");o.width=640,o.height=480;const c=o.captureStream(15),p=[...a.getTracks(),...c.getTracks()];return this.localStream=new MediaStream(p),this.localStream}releaseLocalStream(){var e;(e=this.localStream)==null||e.getTracks().forEach(t=>t.stop()),this.localStream=null}async startCall(e,t){const i={id:crypto.randomUUID(),type:t,participants:[],status:"connecting",startedAt:new Date,isRecording:!1,isTranscribing:!1,layout:e.length>2?"grid":"spotlight"};return setTimeout(()=>this.emit("call:accepted",{callId:i.id,participantId:e[0]??"mock"}),800),i}async acceptCall(e){this.emit("call:accepted",{callId:e,participantId:"mock-remote"})}declineCall(e){this.emit("call:declined",{callId:e,participantId:"mock-remote"})}endCall(e){this.emit("call:ended",{callId:e,reason:"local-ended"})}muteAudio(e){}muteVideo(e){}async setAudioDevice(e){}async setVideoDevice(e){}async startScreenShare(){const e=document.createElement("canvas");return e.width=1920,e.height=1080,e.captureStream(15)}stopScreenShare(){this.emit("screen:stopped",{participantId:"local"})}}function bt(s,e){switch(s){case"mock":return new xt;case"webrtc":case"sfu":default:return new yt(e)}}function vt(s){const{currentUser:e,transport:t="webrtc",rtcConfig:i,signalingUrl:r,autoConnect:a=!1,onCallEnded:o,onIncomingCall:c,onStreamAdded:p,onStreamRemoved:u,onError:m}=s,f=l.useRef(null),[y,h]=l.useState({isConnected:!1,activeCall:null,incomingCall:null,localStream:null,isMicMuted:!1,isCameraMuted:!1,isScreenSharing:!1,screenStream:null,isHandRaised:!1,connectionError:null}),S=l.useCallback(()=>{if(f.current)return f.current;const j=bt(t,i);return j.on("transport:connected",()=>h(b=>({...b,isConnected:!0,connectionError:null}))),j.on("transport:disconnected",()=>h(b=>({...b,isConnected:!1}))),j.on("transport:error",b=>{const{error:z}=b;h(K=>({...K,connectionError:z.message})),m==null||m(z)}),j.on("call:incoming",b=>{const{callId:z,callType:K,callerId:J}=b,P={callId:z,callType:K,caller:{id:J,name:J,presence:{status:"online"}},startedAt:new Date};h(O=>({...O,incomingCall:P})),c==null||c(P)}),j.on("call:ended",b=>{const{callId:z}=b;h(K=>{var J;return{...K,activeCall:((J=K.activeCall)==null?void 0:J.id)===z?null:K.activeCall,localStream:null}}),o==null||o(z)}),j.on("stream:added",b=>{const{participantId:z,stream:K}=b;p==null||p(z,K)}),j.on("stream:removed",b=>{const{participantId:z}=b;u==null||u(z)}),f.current=j,j},[t,i,o,c,p,u,m]);l.useEffect(()=>!a||!r?void 0:(S().connect(r,e.id).catch(b=>{const z=b instanceof Error?b:new Error(String(b));h(K=>({...K,connectionError:z.message})),m==null||m(z)}),()=>{var b;(b=f.current)==null||b.disconnect(),f.current=null}),[a,r,e.id,S,m]);const C=l.useCallback(async j=>{await S().connect(j,e.id)},[S,e.id]),d=l.useCallback(()=>{var j;(j=f.current)==null||j.disconnect(),f.current=null,h(b=>({...b,isConnected:!1}))},[]),R=l.useCallback(async(j,b="video")=>{const z=f.current??S(),K=b==="video"?{audio:!0,video:{width:1280,height:720}}:{audio:!0,video:!1},J=await z.getLocalStream(K),P=await z.startCall(j,b);return h(O=>({...O,activeCall:P,localStream:J})),P},[S]),T=l.useCallback(async()=>{const j=f.current,{incomingCall:b}=y;if(!j||!b)return;const z=b.callType==="video"?{audio:!0,video:{width:1280,height:720}}:{audio:!0,video:!1},K=await j.getLocalStream(z);await j.acceptCall(b.callId);const J={id:b.callId,type:b.callType,participants:[],status:"active",startedAt:new Date,isRecording:!1,isTranscribing:!1,layout:"spotlight"};h(P=>({...P,activeCall:J,incomingCall:null,localStream:K}))},[y]),D=l.useCallback(()=>{var b;const{incomingCall:j}=y;j&&((b=f.current)==null||b.declineCall(j.callId),h(z=>({...z,incomingCall:null})))},[y]),W=l.useCallback(()=>{var b,z;const{activeCall:j}=y;j&&((b=f.current)==null||b.endCall(j.id),(z=f.current)==null||z.releaseLocalStream(),h(K=>({...K,activeCall:null,localStream:null,isScreenSharing:!1,screenStream:null})))},[y]),M=l.useCallback(()=>{var b;const j=!y.isMicMuted;(b=f.current)==null||b.muteAudio(j),h(z=>({...z,isMicMuted:j}))},[y.isMicMuted]),F=l.useCallback(()=>{var b;const j=!y.isCameraMuted;(b=f.current)==null||b.muteVideo(j),h(z=>({...z,isCameraMuted:j}))},[y.isCameraMuted]),U=l.useCallback(async()=>{const j=f.current;if(!j)return;const b=await j.startScreenShare();h(z=>({...z,isScreenSharing:!0,screenStream:b}))},[]),N=l.useCallback(()=>{var j;(j=f.current)==null||j.stopScreenShare(),h(b=>({...b,isScreenSharing:!1,screenStream:null}))},[]),H=l.useCallback(()=>{h(j=>({...j,isHandRaised:!j.isHandRaised}))},[]);return{state:y,connect:C,disconnect:d,startCall:R,acceptCall:T,declineCall:D,endCall:W,toggleMic:M,toggleCamera:F,startScreenShare:U,stopScreenShare:N,toggleHand:H,transport:f}}function Wt(s,e,t,i="text"){return{id:`optimistic-${crypto.randomUUID()}`,conversationId:s,authorId:e,content:t,contentType:i,timestamp:new Date,status:"sending",reactions:[],attachments:[],mentions:[],isPinned:!1}}function He(s,e,t){if(s.type!=="dm")return;const i=s.participantIds.find(r=>r!==e);return t.find(r=>r.id===i)}function Xe(s){return s.reduce((e,t)=>e+t.unreadCount,0)}function Ft(s){return s.reduce((e,t)=>e+t.mentionCount,0)}function _t(s,e){return s?"workspace":e?"messenger":"bubble"}const Bt={online:"Online",away:"Away",busy:"Busy",dnd:"Do not disturb",offline:"Offline",invisible:"Invisible",unknown:"Unknown"},Ut={online:"#22c55e",away:"#f59e0b",busy:"#ef4444",dnd:"#ef4444",offline:"#9ca3af",invisible:"#9ca3af",unknown:"#d1d5db"},Ht={xs:6,sm:8,md:10,lg:14};function ue({status:s,size:e="sm",showLabel:t=!1,showTooltip:i=!1,className:r,style:a,id:o,"data-testid":c}){const p=Ht[e],u=Ut[s],m=Bt[s],f=n.jsx("span",{className:`nice-presence-dot nice-presence-dot--${s} nice-presence-dot--${e}`,title:i?m:void 0,"aria-label":m,role:"img",style:{display:"inline-block",width:p,height:p,borderRadius:"50%",backgroundColor:u,flexShrink:0,border:s==="offline"||s==="invisible"?"1.5px solid #9ca3af":"none",boxSizing:"border-box"}});return t?n.jsxs("span",{id:o,"data-testid":c,className:`nice-presence-indicator nice-presence-indicator--with-label${r?` ${r}`:""}`,style:{display:"inline-flex",alignItems:"center",gap:6,...a},children:[f,n.jsx("span",{className:"nice-presence-label",style:{fontSize:p+4,color:u},children:m})]}):n.jsx("span",{id:o,"data-testid":c,className:`nice-presence-indicator${r?` ${r}`:""}`,style:a,children:f})}const Kt=["๐","โค๏ธ","๐","๐ฎ","๐ข","๐"];function Le({message:s,author:e,isMine:t,showAvatar:i,enableReactions:r,onReact:a,onReply:o,onEdit:c,onDelete:p,onPin:u,onOpenThread:m}){var R,T,D,W;const[f,y]=l.useState(!1),[h,S]=l.useState(!1),C=s.isDeleted,d=s.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.jsxs("div",{className:`nice-chat-message${t?" nice-chat-message--mine":""}${s.isPinned?" nice-chat-message--pinned":""}`,onMouseEnter:()=>y(!0),onMouseLeave:()=>{y(!1),S(!1)},style:{display:"flex",flexDirection:t?"row-reverse":"row",alignItems:"flex-end",gap:8,padding:"2px 16px",position:"relative"},children:[i&&!t&&n.jsxs("div",{style:{position:"relative",flexShrink:0},children:[n.jsx("div",{className:"nice-chat-avatar",style:{width:32,height:32,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontSize:13,fontWeight:600,flexShrink:0},children:!(e!=null&&e.avatarUrl)&&(((T=(R=e==null?void 0:e.name)==null?void 0:R[0])==null?void 0:T.toUpperCase())??"?")}),n.jsx(ue,{status:((D=e==null?void 0:e.presence)==null?void 0:D.status)??"unknown",size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),n.jsxs("div",{style:{maxWidth:"70%",display:"flex",flexDirection:"column",alignItems:t?"flex-end":"flex-start"},children:[!t&&e&&n.jsx("span",{style:{fontSize:11,color:"#6b7280",marginBottom:2,paddingLeft:2},children:e.displayName??e.name}),s.replyTo&&n.jsx("div",{className:"nice-chat-reply-preview",style:{borderLeft:"3px solid #6366f1",paddingLeft:6,fontSize:12,color:"#6b7280",marginBottom:4,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.replyTo.content}),n.jsx("div",{className:`nice-chat-bubble${t?" nice-chat-bubble--mine":""}`,style:{padding:"8px 12px",borderRadius:t?"18px 18px 4px 18px":"18px 18px 18px 4px",background:t?"#6366f1":"#f3f4f6",color:t?"#fff":"#111827",fontSize:14,lineHeight:1.5,wordBreak:"break-word"},children:C?n.jsx("span",{style:{fontStyle:"italic",opacity:.6},children:"This message was deleted"}):s.contentType==="image"&&((W=s.attachments)!=null&&W[0])?n.jsx("img",{src:s.attachments[0].url,alt:s.attachments[0].name,style:{maxWidth:280,maxHeight:280,borderRadius:8,display:"block"}}):n.jsx("span",{children:s.content})}),!C&&s.attachments&&s.attachments.length>0&&s.contentType!=="image"&&n.jsx("div",{className:"nice-chat-attachments",style:{marginTop:4},children:s.attachments.map(M=>n.jsxs("a",{href:M.url,target:"_blank",rel:"noreferrer",className:"nice-chat-attachment",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:12,color:t?"rgba(255,255,255,0.85)":"#6366f1",textDecoration:"none",background:t?"rgba(255,255,255,0.15)":"#e0e7ff",borderRadius:6,padding:"3px 8px",marginTop:2},children:["๐ ",M.name]},M.id))}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:2},children:[n.jsx("span",{style:{fontSize:11,color:"#9ca3af"},children:d}),s.editedAt&&n.jsx("span",{style:{fontSize:11,color:"#9ca3af"},children:"(edited)"}),t&&n.jsx("span",{style:{fontSize:11,color:s.status==="read"?"#6366f1":"#9ca3af"},children:s.status==="sending"?"โ":s.status==="sent"?"โ":(s.status==="delivered","โโ")})]}),s.reactions&&s.reactions.length>0&&n.jsx("div",{className:"nice-chat-reactions",style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:s.reactions.map(M=>n.jsxs("button",{onClick:()=>a(s.id,M.emoji),style:{background:M.mine?"#e0e7ff":"#f3f4f6",border:M.mine?"1px solid #6366f1":"1px solid transparent",borderRadius:12,padding:"2px 7px",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",gap:3},children:[M.emoji," ",M.count]},M.emoji))}),(s.threadCount??0)>0&&n.jsxs("button",{className:"nice-chat-thread-btn",onClick:()=>m==null?void 0:m(s),style:{background:"none",border:"none",color:"#6366f1",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:2},children:["๐ฌ ",s.threadCount," repl",s.threadCount===1?"y":"ies"]})]}),f&&!C&&n.jsxs("div",{className:"nice-chat-actions",style:{position:"absolute",top:-16,[t?"left":"right"]:16,display:"flex",gap:2,background:"#fff",borderRadius:8,boxShadow:"0 2px 8px rgba(0,0,0,0.12)",padding:"3px 6px",zIndex:10},children:[r&&n.jsxs("div",{style:{position:"relative"},children:[n.jsx("button",{title:"React",onClick:()=>S(M=>!M),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"๐"}),h&&n.jsx("div",{style:{position:"absolute",bottom:"100%",left:0,display:"flex",gap:4,background:"#fff",borderRadius:8,boxShadow:"0 2px 8px rgba(0,0,0,0.15)",padding:"6px 8px",zIndex:20},children:Kt.map(M=>n.jsx("button",{onClick:()=>{a(s.id,M),S(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:M},M))})]}),n.jsx("button",{title:"Reply",onClick:()=>o(s),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"โฉ"}),t&&c&&n.jsx("button",{title:"Edit",onClick:()=>c(s),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"โ๏ธ"}),u&&n.jsx("button",{title:s.isPinned?"Unpin":"Pin",onClick:()=>u(s),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"๐"}),t&&p&&n.jsx("button",{title:"Delete",onClick:()=>p(s),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px",color:"#ef4444"},children:"๐"})]})]})}function at({placeholder:s="Type a messageโฆ",maxLength:e,replyTo:t,onCancelReply:i,onSend:r,onAttach:a,disabled:o}){const[c,p]=l.useState(""),u=l.useRef(null);l.useEffect(()=>{t&&u.current&&u.current.focus()},[t]);const m=h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),f())},f=()=>{const h=c.trim();h&&(r(h),p(""),u.current&&(u.current.style.height="auto"))},y=h=>{p(h.target.value),h.target.style.height="auto",h.target.style.height=`${Math.min(h.target.scrollHeight,120)}px`};return n.jsxs("div",{className:"nice-chat-input-area",style:{padding:"8px 12px",borderTop:"1px solid #e5e7eb",background:"#fff"},children:[t&&n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",background:"#f3f4f6",borderLeft:"3px solid #6366f1",padding:"4px 8px",marginBottom:6,borderRadius:"0 4px 4px 0",fontSize:12,color:"#6b7280"},children:[n.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Replying: ",t.content]}),n.jsx("button",{onClick:i,style:{background:"none",border:"none",cursor:"pointer",fontSize:16,color:"#9ca3af",marginLeft:8},children:"ร"})]}),n.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:8},children:[a&&n.jsx("button",{onClick:a,title:"Attach file",style:{background:"none",border:"none",cursor:"pointer",fontSize:18,color:"#9ca3af",padding:"4px",flexShrink:0},children:"๐"}),n.jsx("textarea",{ref:u,value:c,onChange:y,onKeyDown:m,placeholder:s,maxLength:e,disabled:o,rows:1,style:{flex:1,resize:"none",border:"1px solid #e5e7eb",borderRadius:20,padding:"8px 14px",fontSize:14,outline:"none",fontFamily:"inherit",lineHeight:1.5,overflow:"hidden"}}),n.jsx("button",{onClick:f,disabled:!c.trim()||o,style:{background:c.trim()?"#6366f1":"#e5e7eb",border:"none",borderRadius:"50%",width:36,height:36,cursor:c.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:16,transition:"background 0.15s"},children:"โค"})]}),e&&c.length>e*.8&&n.jsxs("div",{style:{textAlign:"right",fontSize:11,color:c.length>=e?"#ef4444":"#9ca3af",marginTop:2},children:[c.length,"/",e]})]})}function Re({conversation:s,messages:e,users:t,currentUser:i,isLoading:r=!1,hasMore:a=!1,showHeader:o=!0,showUserAvatars:c=!0,enableReactions:p=!0,enableThreads:u=!0,enableAttachments:m=!0,placeholder:f,maxMessageLength:y,onSendMessage:h,onEditMessage:S,onDeleteMessage:C,onReactToMessage:d,onPinMessage:R,onLoadMoreMessages:T,onStartCall:D,className:W,style:M,id:F,"data-testid":U}){var B,g;const N=l.useRef(null),H=l.useRef(null),[j,b]=l.useState(null),[z,K]=l.useState(null),J=l.useMemo(()=>{const w=new Map;return t.forEach(V=>w.set(V.id,V)),w},[t]);l.useEffect(()=>{var w;(w=N.current)==null||w.scrollIntoView({behavior:"smooth"})},[e]);const P=l.useCallback(()=>{const w=H.current;!w||!a||r||w.scrollTop===0&&e.length>0&&(T==null||T(s.id,e[0].id))},[a,r,e,s.id,T]),O=l.useCallback(w=>{h==null||h(s.id,w,"text"),b(null)},[s.id,h]),_=s.type==="dm"?J.get(s.participantIds.find(w=>w!==i.id)??""):void 0;return n.jsxs("div",{id:F,"data-testid":U,className:`nice-chat-window${W?` ${W}`:""}`,style:{display:"flex",flexDirection:"column",height:"100%",background:"#fff",...M},children:[o&&n.jsxs("div",{className:"nice-chat-header",style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid #e5e7eb",flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:(_??s).avatarUrl?`url(${(_??s).avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:15,flexShrink:0},children:!(_??s).avatarUrl&&((B=((_==null?void 0:_.name)??s.name??"?")[0])==null?void 0:B.toUpperCase())}),n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600,fontSize:15},children:(_==null?void 0:_.displayName)??(_==null?void 0:_.name)??s.name??"Chat"}),_&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:1},children:[n.jsx(ue,{status:_.presence.status,size:"xs"}),n.jsx("span",{style:{fontSize:12,color:"#6b7280"},children:_.presence.statusMessage??_.presence.status})]}),s.type!=="dm"&&n.jsxs("span",{style:{fontSize:12,color:"#6b7280"},children:[s.participantIds.length," members"]})]})]}),s.type==="dm"&&D&&_&&n.jsxs("div",{style:{display:"flex",gap:4},children:[n.jsx("button",{onClick:()=>D([_.id],"audio"),title:"Audio call",style:{background:"none",border:"1px solid #e5e7eb",borderRadius:6,padding:"5px 8px",cursor:"pointer",fontSize:16},children:"๐"}),n.jsx("button",{onClick:()=>D([_.id],"video"),title:"Video call",style:{background:"none",border:"1px solid #e5e7eb",borderRadius:6,padding:"5px 8px",cursor:"pointer",fontSize:16},children:"๐น"})]})]}),n.jsxs("div",{ref:H,className:"nice-chat-messages",onScroll:P,style:{flex:1,overflowY:"auto",padding:"8px 0",display:"flex",flexDirection:"column"},children:[a&&n.jsx("button",{onClick:()=>e.length>0&&(T==null?void 0:T(s.id,e[0].id)),disabled:r,style:{display:"block",margin:"8px auto",background:"none",border:"1px solid #e5e7eb",borderRadius:16,padding:"4px 16px",fontSize:12,color:"#6b7280",cursor:"pointer"},children:r?"Loadingโฆ":"Load older messages"}),e.map((w,V)=>{const q=e[V-1],Q=c&&(!q||q.authorId!==w.authorId);return n.jsx(Le,{message:w,author:J.get(w.authorId),isMine:w.authorId===i.id,showAvatar:Q,enableReactions:p,onReact:(Y,re)=>d==null?void 0:d(Y,re),onReply:Y=>b(Y),onEdit:S?Y=>S(Y.id,Y.content):void 0,onDelete:C?Y=>C(Y.id):void 0,onPin:R?Y=>R(Y.id):void 0,onOpenThread:u?Y=>K(Y):void 0},w.id)}),n.jsx("div",{ref:N})]}),z&&n.jsxs("div",{className:"nice-chat-thread-panel",style:{position:"absolute",right:0,top:o?57:0,bottom:0,width:320,background:"#fff",borderLeft:"1px solid #e5e7eb",display:"flex",flexDirection:"column",zIndex:5},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid #e5e7eb"},children:[n.jsx("span",{style:{fontWeight:600,fontSize:14},children:"Thread"}),n.jsx("button",{onClick:()=>K(null),style:{background:"none",border:"none",cursor:"pointer",fontSize:18,color:"#9ca3af"},children:"ร"})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[n.jsx(Le,{message:z,author:J.get(z.authorId),isMine:z.authorId===i.id,showAvatar:!0,enableReactions:p,onReact:(w,V)=>d==null?void 0:d(w,V),onReply:()=>{}}),(g=z.thread)==null?void 0:g.map(w=>n.jsx(Le,{message:w,author:J.get(w.authorId),isMine:w.authorId===i.id,showAvatar:!0,enableReactions:p,onReact:(V,q)=>d==null?void 0:d(V,q),onReply:()=>{}},w.id))]}),n.jsx(at,{placeholder:"Reply in threadโฆ",onSend:w=>h==null?void 0:h(s.id,w,"text")})]}),n.jsx(at,{placeholder:f,maxLength:y,replyTo:j,onCancelReply:()=>b(null),onSend:O,onAttach:m?()=>{}:void 0})]})}function Yt({conversation:s,partner:e,isActive:t,lastMessage:i,onClick:r}){var m;const a=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??s.name??"Group",o=((m=a[0])==null?void 0:m.toUpperCase())??"?",c=(e==null?void 0:e.avatarUrl)??s.avatarUrl,p=i?i.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"",u=i?i.isDeleted?"Message deleted":i.content.slice(0,50):"";return n.jsxs("button",{className:`nice-messenger-conv-item${t?" nice-messenger-conv-item--active":""}`,onClick:r,style:{display:"flex",alignItems:"center",gap:10,padding:"10px 14px",background:t?"#ede9fe":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",position:"relative"},children:[n.jsxs("div",{style:{position:"relative",flexShrink:0},children:[n.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:c?`url(${c}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:16},children:!c&&o}),e&&n.jsx(ue,{status:e.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}}),s.type!=="dm"&&n.jsx("span",{style:{position:"absolute",bottom:-2,right:-2,background:"#f3f4f6",border:"1px solid #e5e7eb",borderRadius:4,fontSize:9,padding:"0 3px",color:"#6b7280"},children:"#"})]}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline"},children:[n.jsx("span",{style:{fontWeight:s.unreadCount>0?700:500,fontSize:14,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),n.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0,marginLeft:4},children:p})]}),n.jsx("div",{style:{fontSize:12,color:"#6b7280",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:u})]}),(s.unreadCount>0||s.mentionCount>0)&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,alignItems:"flex-end",flexShrink:0},children:[s.mentionCount>0&&n.jsxs("span",{style:{background:"#ef4444",color:"#fff",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:["@",s.mentionCount]}),s.unreadCount>0&&n.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:s.unreadCount>99?"99+":s.unreadCount})]}),s.isMuted&&n.jsx("span",{style:{position:"absolute",bottom:8,right:8,fontSize:10,color:"#9ca3af"},children:"๐"})]})}function St({conversations:s,messages:e,users:t,currentUser:i,activeConversationId:r,teams:a,enableGroupConversations:o=!0,showPresence:c=!0,enableSearch:p=!0,onSendMessage:u,onEditMessage:m,onDeleteMessage:f,onReactToMessage:y,onPinMessage:h,onLoadMoreMessages:S,onMarkAsRead:C,onStartCall:d,onCreateConversation:R,className:T,style:D,id:W,"data-testid":M}){var B;const[F,U]=l.useState(r??null),[N,H]=l.useState(""),[j,b]=l.useState("all");l.useMemo(()=>{const g=new Map;return t.forEach(w=>g.set(w.id,w)),g},[t]);const z=l.useMemo(()=>{let g=s;if(j==="unread"&&(g=g.filter(w=>w.unreadCount>0)),j==="groups"&&(g=g.filter(w=>w.type!=="dm")),N.trim()){const w=N.toLowerCase();g=g.filter(V=>{var Q,Y;const q=He(V,i.id,t);return(q==null?void 0:q.name.toLowerCase().includes(w))||((Q=V.name)==null?void 0:Q.toLowerCase().includes(w))||((Y=V.lastMessage)==null?void 0:Y.content.toLowerCase().includes(w))})}return[...g].sort((w,V)=>{var Y,re;if(w.isPinned!==V.isPinned)return w.isPinned?-1:1;const q=((Y=w.lastMessage)==null?void 0:Y.timestamp.getTime())??w.updatedAt.getTime();return(((re=V.lastMessage)==null?void 0:re.timestamp.getTime())??V.updatedAt.getTime())-q})},[s,j,N,i.id,t]),K=l.useMemo(()=>s.find(g=>g.id===F)??null,[s,F]),J=l.useMemo(()=>F?e[F]??[]:[],[e,F]),P=l.useCallback(g=>{U(g),C==null||C(g)},[C]),O=l.useMemo(()=>Xe(s),[s]),_=a??[];return n.jsxs("div",{id:W,"data-testid":M,className:`nice-messenger${T?` ${T}`:""}`,style:{display:"flex",height:"100%",background:"#fff",overflow:"hidden",...D},children:[n.jsxs("div",{className:"nice-messenger-sidebar",style:{width:280,flexShrink:0,borderRight:"1px solid #e5e7eb",display:"flex",flexDirection:"column",background:"#fafafa"},children:[n.jsxs("div",{style:{padding:"14px 14px 8px",borderBottom:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("span",{style:{fontWeight:700,fontSize:16},children:["Messages ",O>0&&n.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:10,padding:"1px 6px",fontWeight:700,marginLeft:4},children:O})]}),o&&R&&n.jsx("button",{onClick:()=>R([],"group"),title:"New conversation",style:{background:"#6366f1",border:"none",borderRadius:6,padding:"5px 8px",cursor:"pointer",color:"#fff",fontSize:13},children:"+"})]}),p&&n.jsx("input",{type:"search",value:N,onChange:g=>H(g.target.value),placeholder:"Search conversationsโฆ",style:{width:"100%",marginTop:8,padding:"6px 10px",border:"1px solid #e5e7eb",borderRadius:16,fontSize:13,outline:"none",boxSizing:"border-box",background:"#fff"}}),n.jsx("div",{style:{display:"flex",gap:2,marginTop:8},children:["all","unread","groups"].map(g=>n.jsx("button",{onClick:()=>b(g),style:{flex:1,padding:"4px 0",border:"none",borderRadius:6,background:j===g?"#6366f1":"transparent",color:j===g?"#fff":"#6b7280",cursor:"pointer",fontSize:12,textTransform:"capitalize",fontWeight:j===g?600:400},children:g},g))})]}),c&&n.jsxs("div",{style:{padding:"8px 14px",borderBottom:"1px solid #f3f4f6",overflowX:"auto"},children:[n.jsx("div",{style:{fontSize:11,color:"#9ca3af",marginBottom:6},children:"ONLINE NOW"}),n.jsx("div",{style:{display:"flex",gap:10},children:t.filter(g=>g.id!==i.id&&g.presence.status==="online").slice(0,6).map(g=>{var w;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:3},children:[n.jsxs("div",{style:{position:"relative"},children:[n.jsx("div",{style:{width:34,height:34,borderRadius:"50%",background:g.avatarUrl?`url(${g.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer"},title:g.name,children:!g.avatarUrl&&((w=g.name[0])==null?void 0:w.toUpperCase())}),n.jsx(ue,{status:g.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),n.jsx("span",{style:{fontSize:10,color:"#6b7280",maxWidth:36,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.displayName??g.name.split(" ")[0]})]},g.id)})})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[_.length>0&&j==="all"&&n.jsx("div",{style:{padding:"8px 14px 4px",fontSize:11,color:"#9ca3af",fontWeight:600,letterSpacing:"0.05em"},children:"DIRECT MESSAGES"}),z.length===0?n.jsx("div",{style:{padding:24,textAlign:"center",color:"#9ca3af",fontSize:13},children:"No conversations"}):z.map(g=>n.jsx(Yt,{conversation:g,partner:He(g,i.id,t),isActive:g.id===F,lastMessage:g.lastMessage,onClick:()=>P(g.id)},g.id))]}),n.jsxs("div",{style:{padding:"10px 14px",borderTop:"1px solid #e5e7eb",display:"flex",alignItems:"center",gap:8},children:[n.jsxs("div",{style:{position:"relative"},children:[n.jsx("div",{style:{width:32,height:32,borderRadius:"50%",background:i.avatarUrl?`url(${i.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:13},children:!i.avatarUrl&&((B=i.name[0])==null?void 0:B.toUpperCase())}),n.jsx(ue,{status:i.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontWeight:600,fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.displayName??i.name}),n.jsx("div",{style:{fontSize:11,color:"#9ca3af",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.presence.statusMessage??i.presence.status})]})]})]}),n.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:K?n.jsx(Re,{conversation:K,messages:J,users:t,currentUser:i,onSendMessage:u,onEditMessage:m,onDeleteMessage:f,onReactToMessage:y,onPinMessage:h,onLoadMoreMessages:S,onStartCall:d,style:{height:"100%"}}):n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"#9ca3af",gap:12},children:[n.jsx("span",{style:{fontSize:48},children:"๐ฌ"}),n.jsx("span",{style:{fontSize:15},children:"Select a conversation to start messaging"})]})})]})}const Gt=["๐","โค๏ธ","๐","๐","๐ฎ","๐ข"];function We({message:s,author:e,isMine:t,enableReactions:i,enableThreads:r,onReact:a,onOpenThread:o,onReply:c}){var S,C,d;const[p,u]=l.useState(!1),[m,f]=l.useState(!1),y=s.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),h=s.timestamp.toLocaleDateString([],{month:"short",day:"numeric"});return n.jsxs("div",{className:`nice-channel-msg${p?" nice-channel-msg--hovered":""}${t?" nice-channel-msg--mine":""}`,onMouseEnter:()=>u(!0),onMouseLeave:()=>{u(!1),f(!1)},style:{display:"flex",gap:10,padding:"4px 16px",position:"relative",background:p?"rgba(99,102,241,0.04)":"transparent"},children:[n.jsx("div",{style:{width:36,flexShrink:0},children:n.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:14},children:!(e!=null&&e.avatarUrl)&&(((C=(S=e==null?void 0:e.name)==null?void 0:S[0])==null?void 0:C.toUpperCase())??"?")})}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:2},children:[n.jsx("span",{style:{fontWeight:600,fontSize:14,color:"#111827"},children:(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??"Unknown"}),e&&n.jsx(ue,{status:e.presence.status,size:"xs"}),n.jsxs("span",{style:{fontSize:11,color:"#9ca3af"},children:[h," ",y]}),s.editedAt&&n.jsx("span",{style:{fontSize:11,color:"#9ca3af"},children:"(edited)"}),s.isPinned&&n.jsx("span",{style:{fontSize:11,color:"#6366f1"},children:"๐ Pinned"})]}),s.isDeleted?n.jsx("span",{style:{fontStyle:"italic",color:"#9ca3af",fontSize:14},children:"This message was deleted"}):n.jsx("div",{style:{fontSize:14,lineHeight:1.6,color:"#1f2937",wordBreak:"break-word"},children:s.contentType==="image"&&((d=s.attachments)!=null&&d[0])?n.jsx("img",{src:s.attachments[0].url,alt:s.attachments[0].name,style:{maxWidth:400,maxHeight:300,borderRadius:8,display:"block",marginTop:4}}):s.content}),!s.isDeleted&&s.attachments&&s.attachments.length>0&&s.contentType!=="image"&&n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:4},children:s.attachments.map(R=>n.jsxs("a",{href:R.url,target:"_blank",rel:"noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:12,color:"#6366f1",background:"#ede9fe",borderRadius:6,padding:"3px 8px",textDecoration:"none"},children:["๐ ",R.name]},R.id))}),s.reactions&&s.reactions.length>0&&n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:s.reactions.map(R=>n.jsxs("button",{onClick:()=>a(s.id,R.emoji),style:{background:R.mine?"#ede9fe":"#f3f4f6",border:R.mine?"1px solid #6366f1":"1px solid transparent",borderRadius:12,padding:"2px 7px",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",gap:3},children:[R.emoji," ",R.count]},R.emoji))}),r&&(s.threadCount??0)>0&&n.jsxs("button",{onClick:()=>o(s),style:{background:"none",border:"none",color:"#6366f1",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:3},children:["๐ฌ ",s.threadCount," repl",s.threadCount===1?"y":"ies"," โ"]})]}),p&&!s.isDeleted&&n.jsxs("div",{style:{position:"absolute",top:-16,right:16,display:"flex",gap:2,background:"#fff",borderRadius:8,boxShadow:"0 2px 8px rgba(0,0,0,0.12)",padding:"3px 6px",zIndex:10},children:[i&&n.jsxs("div",{style:{position:"relative"},children:[n.jsx("button",{onClick:()=>f(R=>!R),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"๐"}),m&&n.jsx("div",{style:{position:"absolute",bottom:"100%",right:0,display:"flex",gap:4,background:"#fff",borderRadius:8,boxShadow:"0 2px 8px rgba(0,0,0,0.15)",padding:"6px 8px",zIndex:20},children:Gt.map(R=>n.jsx("button",{onClick:()=>{a(s.id,R),f(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:R},R))})]}),n.jsx("button",{onClick:()=>c(s),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},title:"Reply",children:"โฉ"}),r&&n.jsx("button",{onClick:()=>o(s),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},title:"Open thread",children:"๐ฌ"})]})]})}function wt({channel:s,messages:e,users:t,currentUser:i,team:r,isLoading:a=!1,hasMore:o=!1,enableThreads:c=!0,enableReactions:p=!0,enableAttachments:u=!0,onSendMessage:m,onEditMessage:f,onDeleteMessage:y,onReactToMessage:h,onPinMessage:S,onLoadMoreMessages:C,onStartCall:d,className:R,style:T,id:D,"data-testid":W}){var B;const M=l.useRef(null),F=l.useRef(null),[U,N]=l.useState(""),[H,j]=l.useState(null),[b,z]=l.useState(null),K=l.useMemo(()=>{const g=new Map;return t.forEach(w=>g.set(w.id,w)),g},[t]);l.useEffect(()=>{var g;(g=M.current)==null||g.scrollIntoView({behavior:"smooth"})},[e]);const J=l.useCallback(()=>{const g=F.current;!g||!o||a||g.scrollTop===0&&e.length>0&&(C==null||C(s.id,e[0].id))},[o,a,e,s.id,C]),P=l.useCallback(()=>{const g=U.trim();g&&(m==null||m(s.id,g,"text"),N(""),j(null))},[U,s.id,m]),O=g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),P())},_=t.filter(g=>g.presence.status==="online").length;return n.jsxs("div",{id:D,"data-testid":W,className:`nice-channel-view${R?` ${R}`:""}`,style:{display:"flex",height:"100%",background:"#fff",overflow:"hidden",...T},children:[n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid #e5e7eb",flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsx("span",{style:{fontSize:20,color:"#6b7280"},children:"#"}),n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:700,fontSize:16},children:s.name}),s.description&&n.jsx("div",{style:{fontSize:12,color:"#6b7280",marginTop:1},children:s.description})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsxs("span",{style:{fontSize:12,color:"#6b7280"},children:[n.jsx("span",{style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:"#22c55e",marginRight:4,verticalAlign:"middle"}}),_," online"]}),d&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>d(t.map(g=>g.id),"audio"),style:{background:"none",border:"1px solid #e5e7eb",borderRadius:6,padding:"5px 8px",cursor:"pointer",fontSize:15},title:"Audio call",children:"๐"}),n.jsx("button",{onClick:()=>d(t.map(g=>g.id),"video"),style:{background:"none",border:"1px solid #e5e7eb",borderRadius:6,padding:"5px 8px",cursor:"pointer",fontSize:15},title:"Video meet",children:"๐น"})]})]})]}),n.jsxs("div",{ref:F,onScroll:J,style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[o&&n.jsx("button",{onClick:()=>e.length>0&&(C==null?void 0:C(s.id,e[0].id)),disabled:a,style:{display:"block",margin:"8px auto",background:"none",border:"1px solid #e5e7eb",borderRadius:16,padding:"4px 16px",fontSize:12,color:"#6b7280",cursor:"pointer"},children:a?"Loadingโฆ":"Load older messages"}),e.map(g=>n.jsx(We,{message:g,author:K.get(g.authorId),isMine:g.authorId===i.id,enableReactions:p,enableThreads:c,onReact:(w,V)=>h==null?void 0:h(w,V),onOpenThread:w=>z(w),onReply:w=>j(w)},g.id)),n.jsx("div",{ref:M})]}),n.jsxs("div",{style:{padding:"8px 16px",borderTop:"1px solid #e5e7eb",flexShrink:0},children:[H&&n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",background:"#f3f4f6",borderLeft:"3px solid #6366f1",padding:"3px 8px",marginBottom:6,borderRadius:"0 4px 4px 0",fontSize:12,color:"#6b7280"},children:[n.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Replying to: ",H.content]}),n.jsx("button",{onClick:()=>j(null),style:{background:"none",border:"none",cursor:"pointer",fontSize:16,color:"#9ca3af"},children:"ร"})]}),n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-end"},children:[u&&n.jsx("button",{title:"Attach",style:{background:"none",border:"none",cursor:"pointer",fontSize:18,color:"#9ca3af",padding:"6px 4px"},children:"๐"}),n.jsx("textarea",{value:U,onChange:g=>N(g.target.value),onKeyDown:O,placeholder:`Message #${s.name}`,rows:1,style:{flex:1,resize:"none",border:"1px solid #e5e7eb",borderRadius:8,padding:"8px 12px",fontSize:14,outline:"none",fontFamily:"inherit",lineHeight:1.5,overflow:"hidden",maxHeight:100}}),n.jsx("button",{onClick:P,disabled:!U.trim(),style:{background:U.trim()?"#6366f1":"#e5e7eb",border:"none",borderRadius:"50%",width:36,height:36,cursor:U.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:15,transition:"background 0.15s"},children:"โค"})]})]})]}),b&&n.jsxs("div",{style:{width:340,flexShrink:0,borderLeft:"1px solid #e5e7eb",display:"flex",flexDirection:"column",overflow:"hidden"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid #e5e7eb",flexShrink:0},children:[n.jsx("span",{style:{fontWeight:600,fontSize:14},children:"Thread"}),n.jsx("button",{onClick:()=>z(null),style:{background:"none",border:"none",cursor:"pointer",fontSize:18,color:"#9ca3af"},children:"ร"})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[n.jsx(We,{message:b,author:K.get(b.authorId),isMine:b.authorId===i.id,enableReactions:p,enableThreads:!1,onReact:(g,w)=>h==null?void 0:h(g,w),onOpenThread:()=>{},onReply:()=>{}}),n.jsxs("div",{style:{padding:"6px 14px",color:"#9ca3af",fontSize:12,borderTop:"1px solid #f3f4f6"},children:[b.threadCount??0," repl",b.threadCount===1?"y":"ies"]}),(B=b.thread)==null?void 0:B.map(g=>n.jsx(We,{message:g,author:K.get(g.authorId),isMine:g.authorId===i.id,enableReactions:p,enableThreads:!1,onReact:(w,V)=>h==null?void 0:h(w,V),onOpenThread:()=>{},onReply:()=>{}},g.id))]}),n.jsx("div",{style:{padding:"8px 12px",borderTop:"1px solid #e5e7eb"},children:n.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-end"},children:[n.jsx("textarea",{placeholder:"Reply in threadโฆ",rows:1,onKeyDown:g=>{if(g.key==="Enter"&&!g.shiftKey){g.preventDefault();const w=g.target.value.trim();w&&(m==null||m(s.id,w,"text"),g.target.value="")}},style:{flex:1,resize:"none",border:"1px solid #e5e7eb",borderRadius:8,padding:"7px 10px",fontSize:13,outline:"none",fontFamily:"inherit",overflow:"hidden"}}),n.jsx("button",{style:{background:"#6366f1",border:"none",borderRadius:"50%",width:32,height:32,cursor:"pointer",color:"#fff",fontSize:14,display:"flex",alignItems:"center",justifyContent:"center"},children:"โค"})]})})]})]})}function Je({session:s,currentUser:e,localStream:t,enableScreenSharing:i=!0,enableRecording:r=!1,onEndCall:a,onMuteAudio:o,onMuteVideo:c,onStartScreenShare:p,onStopScreenShare:u,onRaiseHand:m,className:f,style:y,id:h,"data-testid":S}){var w,V;const C=l.useRef(null),d=l.useRef(null),[R,T]=l.useState(!1),[D,W]=l.useState(s.type==="audio"),[M,F]=l.useState(!1),[U,N]=l.useState(0),[H,j]=l.useState(!1),b=s.participants.find(q=>q.user.id!==e.id);l.useEffect(()=>{C.current&&t&&(C.current.srcObject=t)},[t]),l.useEffect(()=>{d.current&&(b!=null&&b.stream)&&(d.current.srcObject=b.stream)},[b==null?void 0:b.stream]),l.useEffect(()=>{if(s.status!=="active")return;const q=setInterval(()=>N(Q=>Q+1),1e3);return()=>clearInterval(q)},[s.status]);const z=q=>{const Q=Math.floor(q/3600),Y=Math.floor(q%3600/60),re=q%60;return Q>0?`${Q}:${String(Y).padStart(2,"0")}:${String(re).padStart(2,"0")}`:`${String(Y).padStart(2,"0")}:${String(re).padStart(2,"0")}`},K=()=>{const q=!R;T(q),o==null||o(q)},J=()=>{const q=!D;W(q),c==null||c(q)},P=async()=>{M?(F(!1),u==null||u()):(F(!0),await(p==null?void 0:p()))},O=()=>{a==null||a(s.id)},_={position:"relative",width:"100%",height:"100%",background:"#111827",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",overflow:"hidden",...y},B=s.status==="ringing"||s.status==="connecting",g=b==null?void 0:b.user;return n.jsxs("div",{id:h,"data-testid":S,className:`nice-call-screen${f?` ${f}`:""}`,style:_,children:[s.type==="video"&&(b!=null&&b.stream)&&!b.isCameraOff?n.jsx("video",{ref:d,autoPlay:!0,playsInline:!0,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}):n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[n.jsx("div",{style:{width:120,height:120,borderRadius:"50%",background:g!=null&&g.avatarUrl?`url(${g.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:48,boxShadow:B?"0 0 0 12px rgba(99,102,241,0.3)":void 0,animation:B?"nice-call-pulse 1.5s ease-in-out infinite":void 0},children:!(g!=null&&g.avatarUrl)&&(((V=(w=g==null?void 0:g.name)==null?void 0:w[0])==null?void 0:V.toUpperCase())??"?")}),n.jsx("span",{style:{color:"#fff",fontSize:22,fontWeight:600},children:(g==null?void 0:g.displayName)??(g==null?void 0:g.name)??"Callingโฆ"}),g&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[n.jsx(ue,{status:g.presence.status,size:"sm"}),n.jsx("span",{style:{color:"rgba(255,255,255,0.6)",fontSize:13},children:B?s.status==="ringing"?"Callingโฆ":"Connectingโฆ":z(U)})]})]}),s.status==="active"&&n.jsxs("div",{style:{position:"absolute",top:16,left:"50%",transform:"translateX(-50%)",color:"rgba(255,255,255,0.7)",fontSize:13},children:[z(U),s.isRecording&&n.jsx("span",{style:{marginLeft:8,color:"#ef4444"},children:"โ REC"})]}),(b==null?void 0:b.isMuted)&&n.jsxs("div",{style:{position:"absolute",top:16,right:70,background:"rgba(0,0,0,0.5)",borderRadius:6,padding:"3px 8px",display:"flex",alignItems:"center",gap:4,fontSize:12,color:"#fff"},children:["๐ ",g==null?void 0:g.name," is muted"]}),n.jsx("button",{onClick:()=>j(q=>!q),style:{position:"absolute",top:12,right:12,background:"rgba(0,0,0,0.4)",border:"none",borderRadius:6,padding:"5px 8px",color:"#fff",cursor:"pointer",fontSize:16},title:H?"Exit fullscreen":"Fullscreen",children:H?"โก":"โ"}),s.type==="video"&&!D&&t&&n.jsx("div",{style:{position:"absolute",bottom:90,right:20,width:140,height:90,borderRadius:10,overflow:"hidden",border:"2px solid rgba(255,255,255,0.3)",boxShadow:"0 4px 12px rgba(0,0,0,0.5)"},children:n.jsx("video",{ref:C,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"cover",transform:"scaleX(-1)"}})}),n.jsxs("div",{className:"nice-call-controls",style:{position:"absolute",bottom:24,left:"50%",transform:"translateX(-50%)",display:"flex",gap:12,background:"rgba(17,24,39,0.8)",backdropFilter:"blur(8px)",borderRadius:40,padding:"8px 16px"},children:[n.jsx(Se,{icon:R?"๐":"๐ค",label:R?"Unmute":"Mute",onClick:K,active:!R,style:{background:R?"#ef4444":void 0}}),s.type==="video"&&n.jsx(Se,{icon:D?"๐ท":"๐น",label:D?"Turn on camera":"Turn off camera",onClick:J,active:!D,style:{background:D?"#ef4444":void 0}}),i&&n.jsx(Se,{icon:"๐ฅ",label:M?"Stop sharing":"Share screen",onClick:()=>{P()},active:M,style:{background:M?"#22c55e":void 0}}),m&&n.jsx(Se,{icon:"โ",label:"Raise hand",onClick:()=>m(!0),active:!1}),r&&n.jsx(Se,{icon:"โบ",label:s.isRecording?"Stop recording":"Start recording",onClick:()=>{},active:s.isRecording,style:{background:s.isRecording?"#ef4444":void 0}}),n.jsx(Se,{icon:"๐ต",label:"End call",onClick:O,active:!1,style:{background:"#ef4444",color:"#fff"}})]}),n.jsx("style",{children:`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),l=require("react");class mt{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){var i;(i=this.listeners.get(e))==null||i.delete(t)}emit(e,t){var i;(i=this.listeners.get(e))==null||i.forEach(r=>r(t))}removeAll(){this.listeners.clear()}}class yt extends mt{constructor(e={}){super(),this.type="webrtc",this.signalingWs=null,this.localStream=null,this.screenStream=null,this.peers=new Map,this.userId="",this.connected=!1,this.config={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],...e}}async connect(e,t){return this.userId=t,new Promise((i,r)=>{const a=new WebSocket(e);a.onopen=()=>{this.signalingWs=a,this.connected=!0,a.send(JSON.stringify({type:"register",userId:t})),this.emit("transport:connected",{}),i()},a.onerror=o=>{r(new Error(`Signaling WebSocket error: ${String(o)}`))},a.onclose=o=>{this.connected=!1,this.emit("transport:disconnected",{reason:o.reason})},a.onmessage=o=>{try{const c=JSON.parse(String(o.data));this.handleSignalingMessage(c).catch(console.error)}catch{}}})}disconnect(){var e;this.releaseLocalStream();for(const[,t]of this.peers)t.close();this.peers.clear(),(e=this.signalingWs)==null||e.close(),this.signalingWs=null,this.connected=!1,this.removeAll()}isConnected(){return this.connected}async getLocalStream(e){return this.localStream?this.localStream:(this.localStream=await navigator.mediaDevices.getUserMedia(e),this.localStream)}releaseLocalStream(){this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null),this.screenStream&&(this.screenStream.getTracks().forEach(e=>e.stop()),this.screenStream=null)}async startCall(e,t){const i=crypto.randomUUID();return this.sendSignal({type:"call:request",callId:i,callType:t,from:this.userId,to:e}),{id:i,type:t,participants:[],status:"ringing",isRecording:!1,isTranscribing:!1,layout:"grid"}}async acceptCall(e){this.sendSignal({type:"call:accept",callId:e,from:this.userId})}declineCall(e){this.sendSignal({type:"call:decline",callId:e,from:this.userId})}endCall(e){this.sendSignal({type:"call:end",callId:e,from:this.userId});for(const[t,i]of this.peers)i.close(),this.peers.delete(t)}muteAudio(e){var t;(t=this.localStream)==null||t.getAudioTracks().forEach(i=>{i.enabled=!e}),this.sendSignal({type:"peer:mute",from:this.userId,audio:e,video:!1})}muteVideo(e){var t;(t=this.localStream)==null||t.getVideoTracks().forEach(i=>{i.enabled=!e}),this.sendSignal({type:"peer:mute",from:this.userId,audio:!1,video:e})}async setAudioDevice(e){var i;const t=(i=this.localStream)==null?void 0:i.getAudioTracks()[0];t&&await t.applyConstraints({deviceId:{exact:e}})}async setVideoDevice(e){var i;const t=(i=this.localStream)==null?void 0:i.getVideoTracks()[0];t&&await t.applyConstraints({deviceId:{exact:e}})}async startScreenShare(){this.screenStream=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:15},audio:!0});const[e]=this.screenStream.getVideoTracks();e.addEventListener("ended",()=>this.stopScreenShare());for(const[,t]of this.peers)this.screenStream.getTracks().forEach(i=>t.addTrack(i,this.screenStream));return this.sendSignal({type:"screen:started",from:this.userId}),this.screenStream}stopScreenShare(){this.screenStream&&(this.screenStream.getTracks().forEach(e=>e.stop()),this.screenStream=null,this.sendSignal({type:"screen:stopped",from:this.userId}),this.emit("screen:stopped",{participantId:this.userId}))}sendSignal(e){var t;((t=this.signalingWs)==null?void 0:t.readyState)===WebSocket.OPEN&&this.signalingWs.send(JSON.stringify(e))}async handleSignalingMessage(e){var t;switch(e.type){case"call:request":this.emit("call:incoming",{callId:e.callId,callType:e.callType??"audio",callerId:e.from});break;case"call:accept":await this.createPeerConnection(e.from),this.emit("call:accepted",{callId:e.callId,participantId:e.from});break;case"call:decline":this.emit("call:declined",{callId:e.callId,participantId:e.from});break;case"call:end":(t=this.peers.get(e.from))==null||t.close(),this.peers.delete(e.from),this.emit("call:ended",{callId:e.callId,reason:"remote-ended"});break;case"offer":{const i=await this.getOrCreatePeer(e.from);await i.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:e.sdp}));const r=await i.createAnswer();await i.setLocalDescription(r),this.sendSignal({type:"answer",to:e.from,from:this.userId,sdp:r.sdp});break}case"answer":{const i=this.peers.get(e.from);i&&await i.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e.sdp}));break}case"ice-candidate":{const i=this.peers.get(e.from);i&&e.candidate&&await i.addIceCandidate(new RTCIceCandidate(e.candidate));break}case"peer:mute":this.emit("peer:muted",{participantId:e.from,audio:e.audio??!1,video:e.video??!1});break;case"screen:started":break;case"screen:stopped":this.emit("screen:stopped",{participantId:e.from});break}}async getOrCreatePeer(e){return this.peers.has(e)?this.peers.get(e):this.createPeerConnection(e)}async createPeerConnection(e){var r,a;const t=new RTCPeerConnection({iceServers:(r=this.config.iceServers)==null?void 0:r.map(o=>({urls:o.urls,username:o.username,credential:o.credential})),iceTransportPolicy:this.config.iceTransportPolicy});if(this.peers.set(e,t),(a=this.localStream)==null||a.getTracks().forEach(o=>t.addTrack(o,this.localStream)),t.onicecandidate=o=>{o.candidate&&this.sendSignal({type:"ice-candidate",to:e,from:this.userId,candidate:o.candidate})},t.ontrack=o=>{const c=o.streams[0];c&&this.emit("stream:added",{participantId:e,stream:c})},t.onconnectionstatechange=()=>{(t.connectionState==="failed"||t.connectionState==="disconnected")&&this.emit("stream:removed",{participantId:e})},this.config.maxBitrate){const o=t.getSenders();for(const c of o){if(!c.track)continue;const p=c.getParameters();p.encodings||(p.encodings=[{}]),c.track.kind==="audio"&&this.config.maxBitrate.audio?p.encodings[0].maxBitrate=this.config.maxBitrate.audio:c.track.kind==="video"&&this.config.maxBitrate.video&&(p.encodings[0].maxBitrate=this.config.maxBitrate.video),await c.setParameters(p)}}const i=await t.createOffer();return await t.setLocalDescription(i),this.sendSignal({type:"offer",to:e,from:this.userId,sdp:i.sdp}),t}}class xt extends mt{constructor(){super(...arguments),this.type="mock",this.connected=!1,this.localStream=null}async connect(e,t){this.connected=!0,this.emit("transport:connected",{})}disconnect(){this.releaseLocalStream(),this.connected=!1,this.removeAll()}isConnected(){return this.connected}async getLocalStream(e){const t=new AudioContext,i=t.createMediaStreamDestination();t.createOscillator().connect(i);const a=i.stream,o=document.createElement("canvas");o.width=640,o.height=480;const c=o.captureStream(15),p=[...a.getTracks(),...c.getTracks()];return this.localStream=new MediaStream(p),this.localStream}releaseLocalStream(){var e;(e=this.localStream)==null||e.getTracks().forEach(t=>t.stop()),this.localStream=null}async startCall(e,t){const i={id:crypto.randomUUID(),type:t,participants:[],status:"connecting",startedAt:new Date,isRecording:!1,isTranscribing:!1,layout:e.length>2?"grid":"spotlight"};return setTimeout(()=>this.emit("call:accepted",{callId:i.id,participantId:e[0]??"mock"}),800),i}async acceptCall(e){this.emit("call:accepted",{callId:e,participantId:"mock-remote"})}declineCall(e){this.emit("call:declined",{callId:e,participantId:"mock-remote"})}endCall(e){this.emit("call:ended",{callId:e,reason:"local-ended"})}muteAudio(e){}muteVideo(e){}async setAudioDevice(e){}async setVideoDevice(e){}async startScreenShare(){const e=document.createElement("canvas");return e.width=1920,e.height=1080,e.captureStream(15)}stopScreenShare(){this.emit("screen:stopped",{participantId:"local"})}}function bt(s,e){switch(s){case"mock":return new xt;case"webrtc":case"sfu":default:return new yt(e)}}function vt(s){const{currentUser:e,transport:t="webrtc",rtcConfig:i,signalingUrl:r,autoConnect:a=!1,onCallEnded:o,onIncomingCall:c,onStreamAdded:p,onStreamRemoved:u,onError:m}=s,f=l.useRef(null),[y,h]=l.useState({isConnected:!1,activeCall:null,incomingCall:null,localStream:null,isMicMuted:!1,isCameraMuted:!1,isScreenSharing:!1,screenStream:null,isHandRaised:!1,connectionError:null}),S=l.useCallback(()=>{if(f.current)return f.current;const j=bt(t,i);return j.on("transport:connected",()=>h(b=>({...b,isConnected:!0,connectionError:null}))),j.on("transport:disconnected",()=>h(b=>({...b,isConnected:!1}))),j.on("transport:error",b=>{const{error:T}=b;h(K=>({...K,connectionError:T.message})),m==null||m(T)}),j.on("call:incoming",b=>{const{callId:T,callType:K,callerId:J}=b,R={callId:T,callType:K,caller:{id:J,name:J,presence:{status:"online"}},startedAt:new Date};h(O=>({...O,incomingCall:R})),c==null||c(R)}),j.on("call:ended",b=>{const{callId:T}=b;h(K=>{var J;return{...K,activeCall:((J=K.activeCall)==null?void 0:J.id)===T?null:K.activeCall,localStream:null}}),o==null||o(T)}),j.on("stream:added",b=>{const{participantId:T,stream:K}=b;p==null||p(T,K)}),j.on("stream:removed",b=>{const{participantId:T}=b;u==null||u(T)}),f.current=j,j},[t,i,o,c,p,u,m]);l.useEffect(()=>!a||!r?void 0:(S().connect(r,e.id).catch(b=>{const T=b instanceof Error?b:new Error(String(b));h(K=>({...K,connectionError:T.message})),m==null||m(T)}),()=>{var b;(b=f.current)==null||b.disconnect(),f.current=null}),[a,r,e.id,S,m]);const C=l.useCallback(async j=>{await S().connect(j,e.id)},[S,e.id]),d=l.useCallback(()=>{var j;(j=f.current)==null||j.disconnect(),f.current=null,h(b=>({...b,isConnected:!1}))},[]),z=l.useCallback(async(j,b="video")=>{const T=f.current??S(),K=b==="video"?{audio:!0,video:{width:1280,height:720}}:{audio:!0,video:!1},J=await T.getLocalStream(K),R=await T.startCall(j,b);return h(O=>({...O,activeCall:R,localStream:J})),R},[S]),P=l.useCallback(async()=>{const j=f.current,{incomingCall:b}=y;if(!j||!b)return;const T=b.callType==="video"?{audio:!0,video:{width:1280,height:720}}:{audio:!0,video:!1},K=await j.getLocalStream(T);await j.acceptCall(b.callId);const J={id:b.callId,type:b.callType,participants:[],status:"active",startedAt:new Date,isRecording:!1,isTranscribing:!1,layout:"spotlight"};h(R=>({...R,activeCall:J,incomingCall:null,localStream:K}))},[y]),D=l.useCallback(()=>{var b;const{incomingCall:j}=y;j&&((b=f.current)==null||b.declineCall(j.callId),h(T=>({...T,incomingCall:null})))},[y]),W=l.useCallback(()=>{var b,T;const{activeCall:j}=y;j&&((b=f.current)==null||b.endCall(j.id),(T=f.current)==null||T.releaseLocalStream(),h(K=>({...K,activeCall:null,localStream:null,isScreenSharing:!1,screenStream:null})))},[y]),M=l.useCallback(()=>{var b;const j=!y.isMicMuted;(b=f.current)==null||b.muteAudio(j),h(T=>({...T,isMicMuted:j}))},[y.isMicMuted]),F=l.useCallback(()=>{var b;const j=!y.isCameraMuted;(b=f.current)==null||b.muteVideo(j),h(T=>({...T,isCameraMuted:j}))},[y.isCameraMuted]),U=l.useCallback(async()=>{const j=f.current;if(!j)return;const b=await j.startScreenShare();h(T=>({...T,isScreenSharing:!0,screenStream:b}))},[]),N=l.useCallback(()=>{var j;(j=f.current)==null||j.stopScreenShare(),h(b=>({...b,isScreenSharing:!1,screenStream:null}))},[]),H=l.useCallback(()=>{h(j=>({...j,isHandRaised:!j.isHandRaised}))},[]);return{state:y,connect:C,disconnect:d,startCall:z,acceptCall:P,declineCall:D,endCall:W,toggleMic:M,toggleCamera:F,startScreenShare:U,stopScreenShare:N,toggleHand:H,transport:f}}function Wt(s,e,t,i="text"){return{id:`optimistic-${crypto.randomUUID()}`,conversationId:s,authorId:e,content:t,contentType:i,timestamp:new Date,status:"sending",reactions:[],attachments:[],mentions:[],isPinned:!1}}function He(s,e,t){if(s.type!=="dm")return;const i=s.participantIds.find(r=>r!==e);return t.find(r=>r.id===i)}function Xe(s){return s.reduce((e,t)=>e+t.unreadCount,0)}function Ft(s){return s.reduce((e,t)=>e+t.mentionCount,0)}function _t(s,e){return s?"workspace":e?"messenger":"bubble"}const Bt={online:"Online",away:"Away",busy:"Busy",dnd:"Do not disturb",offline:"Offline",invisible:"Invisible",unknown:"Unknown"},Ut={online:"#22c55e",away:"#f59e0b",busy:"#ef4444",dnd:"#ef4444",offline:"#9ca3af",invisible:"#9ca3af",unknown:"#d1d5db"},Ht={xs:6,sm:8,md:10,lg:14};function ue({status:s,size:e="sm",showLabel:t=!1,showTooltip:i=!1,className:r,style:a,id:o,"data-testid":c}){const p=Ht[e],u=Ut[s],m=Bt[s],f=n.jsx("span",{className:`nice-presence-dot nice-presence-dot--${s} nice-presence-dot--${e}`,title:i?m:void 0,"aria-label":m,role:"img",style:{display:"inline-block",width:p,height:p,borderRadius:"50%",backgroundColor:u,flexShrink:0,border:s==="offline"||s==="invisible"?"1.5px solid #9ca3af":"none",boxSizing:"border-box"}});return t?n.jsxs("span",{id:o,"data-testid":c,className:`nice-presence-indicator nice-presence-indicator--with-label${r?` ${r}`:""}`,style:{display:"inline-flex",alignItems:"center",gap:6,...a},children:[f,n.jsx("span",{className:"nice-presence-label",style:{fontSize:p+4,color:u},children:m})]}):n.jsx("span",{id:o,"data-testid":c,className:`nice-presence-indicator${r?` ${r}`:""}`,style:a,children:f})}function Je({session:s,currentUser:e,localStream:t,enableScreenSharing:i=!0,enableRecording:r=!1,onEndCall:a,onMuteAudio:o,onMuteVideo:c,onStartScreenShare:p,onStopScreenShare:u,onRaiseHand:m,className:f,style:y,id:h,"data-testid":S}){var w,V;const C=l.useRef(null),d=l.useRef(null),[z,P]=l.useState(!1),[D,W]=l.useState(s.type==="audio"),[M,F]=l.useState(!1),[U,N]=l.useState(0),[H,j]=l.useState(!1),b=s.participants.find(q=>q.user.id!==e.id);l.useEffect(()=>{C.current&&t&&(C.current.srcObject=t)},[t]),l.useEffect(()=>{d.current&&(b!=null&&b.stream)&&(d.current.srcObject=b.stream)},[b==null?void 0:b.stream]),l.useEffect(()=>{if(s.status!=="active")return;const q=setInterval(()=>N(Q=>Q+1),1e3);return()=>clearInterval(q)},[s.status]);const T=q=>{const Q=Math.floor(q/3600),Y=Math.floor(q%3600/60),re=q%60;return Q>0?`${Q}:${String(Y).padStart(2,"0")}:${String(re).padStart(2,"0")}`:`${String(Y).padStart(2,"0")}:${String(re).padStart(2,"0")}`},K=()=>{const q=!z;P(q),o==null||o(q)},J=()=>{const q=!D;W(q),c==null||c(q)},R=async()=>{M?(F(!1),u==null||u()):(F(!0),await(p==null?void 0:p()))},O=()=>{a==null||a(s.id)},_={position:"relative",width:"100%",height:"100%",background:"#111827",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",overflow:"hidden",...y},B=s.status==="ringing"||s.status==="connecting",g=b==null?void 0:b.user;return n.jsxs("div",{id:h,"data-testid":S,className:`nice-call-screen${f?` ${f}`:""}`,style:_,children:[s.type==="video"&&(b!=null&&b.stream)&&!b.isCameraOff?n.jsx("video",{ref:d,autoPlay:!0,playsInline:!0,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}):n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[n.jsx("div",{style:{width:120,height:120,borderRadius:"50%",background:g!=null&&g.avatarUrl?`url(${g.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:48,boxShadow:B?"0 0 0 12px rgba(99,102,241,0.3)":void 0,animation:B?"nice-call-pulse 1.5s ease-in-out infinite":void 0},children:!(g!=null&&g.avatarUrl)&&(((V=(w=g==null?void 0:g.name)==null?void 0:w[0])==null?void 0:V.toUpperCase())??"?")}),n.jsx("span",{style:{color:"#fff",fontSize:22,fontWeight:600},children:(g==null?void 0:g.displayName)??(g==null?void 0:g.name)??"Callingโฆ"}),g&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[n.jsx(ue,{status:g.presence.status,size:"sm"}),n.jsx("span",{style:{color:"rgba(255,255,255,0.6)",fontSize:13},children:B?s.status==="ringing"?"Callingโฆ":"Connectingโฆ":T(U)})]})]}),s.status==="active"&&n.jsxs("div",{style:{position:"absolute",top:16,left:"50%",transform:"translateX(-50%)",color:"rgba(255,255,255,0.7)",fontSize:13},children:[T(U),s.isRecording&&n.jsx("span",{style:{marginLeft:8,color:"#ef4444"},children:"โ REC"})]}),(b==null?void 0:b.isMuted)&&n.jsxs("div",{style:{position:"absolute",top:16,right:70,background:"rgba(0,0,0,0.5)",borderRadius:6,padding:"3px 8px",display:"flex",alignItems:"center",gap:4,fontSize:12,color:"#fff"},children:["๐ ",g==null?void 0:g.name," is muted"]}),n.jsx("button",{onClick:()=>j(q=>!q),style:{position:"absolute",top:12,right:12,background:"rgba(0,0,0,0.4)",border:"none",borderRadius:6,padding:"5px 8px",color:"#fff",cursor:"pointer",fontSize:16},title:H?"Exit fullscreen":"Fullscreen",children:H?"โก":"โ"}),s.type==="video"&&!D&&t&&n.jsx("div",{style:{position:"absolute",bottom:90,right:20,width:140,height:90,borderRadius:10,overflow:"hidden",border:"2px solid rgba(255,255,255,0.3)",boxShadow:"0 4px 12px rgba(0,0,0,0.5)"},children:n.jsx("video",{ref:C,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"cover",transform:"scaleX(-1)"}})}),n.jsxs("div",{className:"nice-call-controls",style:{position:"absolute",bottom:24,left:"50%",transform:"translateX(-50%)",display:"flex",gap:12,background:"rgba(17,24,39,0.8)",backdropFilter:"blur(8px)",borderRadius:40,padding:"8px 16px"},children:[n.jsx(Se,{icon:z?"๐":"๐ค",label:z?"Unmute":"Mute",onClick:K,active:!z,style:{background:z?"#ef4444":void 0}}),s.type==="video"&&n.jsx(Se,{icon:D?"๐ท":"๐น",label:D?"Turn on camera":"Turn off camera",onClick:J,active:!D,style:{background:D?"#ef4444":void 0}}),i&&n.jsx(Se,{icon:"๐ฅ",label:M?"Stop sharing":"Share screen",onClick:()=>{R()},active:M,style:{background:M?"#22c55e":void 0}}),m&&n.jsx(Se,{icon:"โ",label:"Raise hand",onClick:()=>m(!0),active:!1}),r&&n.jsx(Se,{icon:"โบ",label:s.isRecording?"Stop recording":"Start recording",onClick:()=>{},active:s.isRecording,style:{background:s.isRecording?"#ef4444":void 0}}),n.jsx(Se,{icon:"๐ต",label:"End call",onClick:O,active:!1,style:{background:"#ef4444",color:"#fff"}})]}),n.jsx("style",{children:`
|
|
2
2
|
@keyframes nice-call-pulse {
|
|
3
3
|
0%, 100% { box-shadow: 0 0 0 0 rgba(99,102,241,0.4); }
|
|
4
4
|
50% { box-shadow: 0 0 0 24px rgba(99,102,241,0); }
|
|
5
5
|
}
|
|
6
|
-
`})]})}function Se({icon:s,label:e,onClick:t,active:i,style:r}){return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[n.jsx("button",{onClick:t,title:e,style:{width:44,height:44,borderRadius:"50%",border:"none",background:i?"rgba(255,255,255,0.15)":"rgba(255,255,255,0.08)",color:"#fff",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.2s",...r},children:s}),n.jsx("span",{style:{fontSize:9,color:"rgba(255,255,255,0.5)",textAlign:"center",maxWidth:50},children:e})]})}function Fe({participant:s,isLocal:e,isPinned:t,onPin:i,size:r="medium"}){var C;const a=l.useRef(null),{user:o,isMuted:c,isCameraOff:p,isScreenSharing:u,isSpeaking:m,isHandRaised:f,stream:y,screenStream:h}=s;l.useEffect(()=>{if(!a.current)return;const d=u?h:y;d&&(a.current.srcObject=d)},[y,h,u]);const S=!p&&!!y;return n.jsxs("div",{className:`nice-conference-tile${m?" nice-conference-tile--speaking":""}${t?" nice-conference-tile--pinned":""}`,style:{position:"relative",background:"#1f2937",borderRadius:10,overflow:"hidden",border:m?"2px solid #22c55e":t?"2px solid #6366f1":"2px solid transparent",display:"flex",alignItems:"center",justifyContent:"center",aspectRatio:"16/9"},children:[S?n.jsx("video",{ref:a,autoPlay:!0,muted:e,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"cover",transform:e&&!u?"scaleX(-1)":"none"}}):n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:8},children:[n.jsx("div",{style:{width:r==="large"?64:r==="small"?28:44,height:r==="large"?64:r==="small"?28:44,borderRadius:"50%",background:o.avatarUrl?`url(${o.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:r==="large"?28:r==="small"?12:18},children:!o.avatarUrl&&((C=o.name[0])==null?void 0:C.toUpperCase())}),r!=="small"&&n.jsx("span",{style:{color:"#fff",fontSize:12},children:o.displayName??o.name})]}),n.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, rgba(0,0,0,0.6))",padding:"6px 8px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("span",{style:{color:"#fff",fontSize:11,fontWeight:500},children:[o.displayName??o.name,e&&" (You)"]}),n.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[f&&n.jsx("span",{style:{fontSize:13},children:"โ"}),c&&n.jsx("span",{style:{fontSize:12},children:"๐"}),u&&n.jsx("span",{style:{fontSize:12},children:"๐ฅ"}),r!=="small"&&n.jsx("div",{style:{width:6,height:6,borderRadius:"50%",background:m?"#22c55e":"transparent",border:"1px solid rgba(255,255,255,0.3)"}})]})]}),r!=="small"&&n.jsx("button",{onClick:i,style:{position:"absolute",top:6,right:6,background:"rgba(0,0,0,0.4)",border:"none",borderRadius:4,padding:"2px 5px",color:t?"#6366f1":"rgba(255,255,255,0.6)",cursor:"pointer",fontSize:12},title:t?"Unpin":"Pin",children:"๐"}),s.connectionQuality!=="none"&&r!=="small"&&n.jsx("div",{style:{position:"absolute",top:6,left:6,width:14,height:10,display:"flex",gap:2,alignItems:"flex-end"},children:[1,2,3].map(d=>n.jsx("div",{style:{flex:1,background:s.connectionQuality==="excellent"||s.connectionQuality==="good"&&d<=2||s.connectionQuality==="fair"&&d<=1?"#22c55e":"rgba(255,255,255,0.3)",height:`${d*30}%`,borderRadius:1}},d))})]})}function Qe({session:s,currentUser:e,localStream:t,enableScreenSharing:i=!0,enableRecording:r=!1,enableTranscription:a=!1,enableRaiseHand:o=!0,maxGridCols:c=4,onEndCall:p,onMuteAudio:u,onMuteVideo:m,onStartScreenShare:f,onStopScreenShare:y,onRaiseHand:h,className:S,style:C,id:d,"data-testid":R}){const[T,D]=l.useState(!1),[W,M]=l.useState(!1),[F,U]=l.useState(!1),[N,H]=l.useState(!1),[j,b]=l.useState(s.pinnedParticipantId??null),[z,K]=l.useState(s.layout==="sidebar"?"grid":s.layout??"grid"),[J,P]=l.useState(0),[O,_]=l.useState(!1);l.useEffect(()=>{if(s.status!=="active")return;const L=setInterval(()=>P(X=>X+1),1e3);return()=>clearInterval(L)},[s.status]);const B=L=>{const X=Math.floor(L/3600),ne=Math.floor(L%3600/60),se=L%60;return X>0?`${X}:${String(ne).padStart(2,"0")}:${String(se).padStart(2,"0")}`:`${String(ne).padStart(2,"0")}:${String(se).padStart(2,"0")}`},g=()=>{const L=!T;D(L),u==null||u(L)},w=()=>{const L=!W;M(L),m==null||m(L)},V=async()=>{F?(U(!1),y==null||y()):(U(!0),await(f==null?void 0:f()))},q=()=>{const L=!N;H(L),h==null||h(L)},Q=[{user:e,isMuted:T,isCameraOff:W,isScreenSharing:F,isSpeaking:!1,isHandRaised:N,stream:t,connectionQuality:"excellent"},...s.participants],Y=j?Q.find(L=>L.user.id===j):null,re=Q.filter(L=>L.user.id!==j),ae=Q.length,pe=Math.min(c,ae<=1?1:ae<=2||ae<=4?2:ae<=9?3:4),oe=z==="spotlight"||Y!=null;return n.jsxs("div",{id:d,"data-testid":R,className:`nice-video-conference${S?` ${S}`:""}`,style:{position:"relative",width:"100%",height:"100%",background:"#111827",display:"flex",flexDirection:"column",overflow:"hidden",...C},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 16px",flexShrink:0,color:"#fff"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[n.jsxs("span",{style:{fontSize:15,fontWeight:600},children:[s.id.slice(0,8),"โฆ"]}),n.jsx("span",{style:{fontSize:12,color:"rgba(255,255,255,0.6)"},children:B(J)}),s.isRecording&&n.jsx("span",{style:{fontSize:11,color:"#ef4444",display:"flex",alignItems:"center",gap:4},children:"โ Recording"})]}),n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[n.jsx("button",{onClick:()=>K(z==="grid"?"spotlight":"grid"),style:{background:"rgba(255,255,255,0.1)",border:"none",borderRadius:6,padding:"4px 10px",color:"#fff",cursor:"pointer",fontSize:12},children:z==="grid"?"โ Grid":"โก Spotlight"}),n.jsxs("button",{onClick:()=>_(L=>!L),style:{background:O?"#6366f1":"rgba(255,255,255,0.1)",border:"none",borderRadius:6,padding:"4px 10px",color:"#fff",cursor:"pointer",fontSize:12},children:["๐ฅ ",Q.length]})]})]}),n.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden",gap:4,padding:"0 8px 8px"},children:[n.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:4,overflow:"hidden"},children:oe&&Y?n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{flex:1},children:n.jsx(Fe,{participant:Y,isLocal:Y.user.id===e.id,isPinned:!0,onPin:()=>b(null),size:"large"})}),n.jsx("div",{style:{display:"flex",gap:4,height:90,flexShrink:0,overflowX:"auto"},children:re.map(L=>n.jsx("div",{style:{width:140,flexShrink:0},children:n.jsx(Fe,{participant:L,isLocal:L.user.id===e.id,isPinned:!1,onPin:()=>b(L.user.id),size:"small"})},L.user.id))})]}):n.jsx("div",{style:{flex:1,display:"grid",gridTemplateColumns:`repeat(${pe}, 1fr)`,gap:6,overflow:"hidden"},children:Q.map(L=>n.jsx(Fe,{participant:L,isLocal:L.user.id===e.id,isPinned:L.user.id===j,onPin:()=>b(X=>X===L.user.id?null:L.user.id),size:ae<=4?"large":"medium"},L.user.id))})}),O&&n.jsxs("div",{style:{width:220,flexShrink:0,background:"rgba(255,255,255,0.05)",borderRadius:10,display:"flex",flexDirection:"column",overflow:"hidden"},children:[n.jsxs("div",{style:{padding:"10px 12px",fontWeight:600,fontSize:13,color:"#fff",borderBottom:"1px solid rgba(255,255,255,0.1)"},children:["Participants (",Q.length,")"]}),n.jsx("div",{style:{flex:1,overflowY:"auto",padding:8},children:Q.map(L=>{var X;return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px"},children:[n.jsx("div",{style:{width:28,height:28,borderRadius:"50%",background:L.user.avatarUrl?`url(${L.user.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontSize:11,fontWeight:700},children:!L.user.avatarUrl&&((X=L.user.name[0])==null?void 0:X.toUpperCase())}),n.jsx("div",{style:{flex:1,minWidth:0},children:n.jsxs("div",{style:{color:"#fff",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[L.user.displayName??L.user.name,L.user.id===e.id&&" (You)"]})}),n.jsxs("div",{style:{display:"flex",gap:3},children:[L.isHandRaised&&n.jsx("span",{style:{fontSize:11},children:"โ"}),L.isMuted&&n.jsx("span",{style:{fontSize:11},children:"๐"}),n.jsx(ue,{status:L.user.presence.status,size:"xs"})]})]},L.user.id)})})]})]}),n.jsxs("div",{className:"nice-conference-controls",style:{display:"flex",justifyContent:"center",gap:10,padding:"10px 16px",flexShrink:0,background:"rgba(0,0,0,0.3)"},children:[n.jsx(xe,{icon:T?"๐":"๐ค",label:T?"Unmute":"Mute",onClick:g,danger:T}),n.jsx(xe,{icon:W?"๐ท":"๐น",label:W?"Start video":"Stop video",onClick:w,danger:W}),i&&n.jsx(xe,{icon:"๐ฅ",label:F?"Stop share":"Share",onClick:()=>{V()},active:F}),o&&n.jsx(xe,{icon:"โ",label:"Raise hand",onClick:q,active:N}),r&&n.jsx(xe,{icon:"โบ",label:s.isRecording?"Stop rec":"Record",onClick:()=>{},active:s.isRecording,danger:s.isRecording}),a&&n.jsx(xe,{icon:"๐",label:s.isTranscribing?"Stop captions":"Captions",onClick:()=>{},active:s.isTranscribing}),n.jsx(xe,{icon:"๐ต",label:"Leave",onClick:()=>p==null?void 0:p(s.id),end:!0})]})]})}function xe({icon:s,label:e,onClick:t,active:i,danger:r,end:a}){return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[n.jsx("button",{title:e,onClick:t,style:{width:46,height:46,borderRadius:"50%",border:"none",background:a?"#ef4444":r?"#450a0a":i?"#6366f1":"rgba(255,255,255,0.12)",color:"#fff",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.15s"},children:s}),n.jsx("span",{style:{fontSize:9,color:"rgba(255,255,255,0.5)",textAlign:"center",maxWidth:52},children:e})]})}function Ke(s){const e={days:864e5,weeks:6048e5,months:2592e6,years:31536e6,forever:Number.MAX_SAFE_INTEGER};return s.unit==="forever"?e.forever:e[s.unit]*s.value}function Ie(s,e=new Date){if(s.unit!=="forever")return new Date(e.getTime()+Ke(s))}class ot{constructor(e="nice2dev-communication"){this.storeName="nice_comm_store",this.db=null,this.dbName=e}async openDb(){return this.db?this.db:new Promise((e,t)=>{const i=indexedDB.open(this.dbName,1);i.onupgradeneeded=r=>{const a=r.target.result;a.objectStoreNames.contains(this.storeName)||a.createObjectStore(this.storeName,{keyPath:"key"})},i.onsuccess=r=>{this.db=r.target.result,e(this.db)},i.onerror=()=>t(i.error)})}async save(e,t,i){const r=await this.openDb();return new Promise((a,o)=>{const u=r.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:e,data:t,expiresAt:i==null?void 0:i.toISOString()});u.onsuccess=()=>a(),u.onerror=()=>o(u.error)})}async load(e){const t=await this.openDb();return new Promise((i,r)=>{const c=t.transaction(this.storeName,"readonly").objectStore(this.storeName).get(e);c.onsuccess=()=>{const p=c.result;if(!p){i(void 0);return}if(p.expiresAt&&new Date(p.expiresAt)<new Date){this.delete(e),i(void 0);return}i(p.data)},c.onerror=()=>r(c.error)})}async delete(e){const t=await this.openDb();return new Promise((i,r)=>{const c=t.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(e);c.onsuccess=()=>i(),c.onerror=()=>r(c.error)})}async list(e){const t=await this.openDb();return new Promise((i,r)=>{const c=t.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();c.onsuccess=()=>i((c.result??[]).filter(p=>p.startsWith(e))),c.onerror=()=>r(c.error)})}async clear(e){if(!e){const i=await this.openDb();return new Promise((r,a)=>{const p=i.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();p.onsuccess=()=>r(),p.onerror=()=>a(p.error)})}const t=await this.list(e);await Promise.all(t.map(i=>this.delete(i)))}}class qt{constructor(e="nice_comm__"){this.prefix=e}async save(e,t,i){const r={data:t,expiresAt:i==null?void 0:i.toISOString()};localStorage.setItem(this.prefix+e,JSON.stringify(r))}async load(e){const t=localStorage.getItem(this.prefix+e);if(t)try{const i=JSON.parse(t);if(i.expiresAt&&new Date(i.expiresAt)<new Date){await this.delete(e);return}return i.data}catch{return}}async delete(e){localStorage.removeItem(this.prefix+e)}async list(e){const t=[];for(let i=0;i<localStorage.length;i++){const r=localStorage.key(i);r&&r.startsWith(this.prefix+e)&&t.push(r.slice(this.prefix.length))}return t}async clear(e){(await this.list(e??"")).forEach(i=>localStorage.removeItem(this.prefix+i))}}class kt{constructor(e,t){this.config=e,this.encryption=t,this.adapter=this.buildAdapter()}buildAdapter(){switch(this.config.provider){case"localstorage":return new qt;case"custom":return this.config.customAdapter??new ot;default:return new ot}}getRuleFor(e){return this.config.retentionRules.find(t=>t.dataType===e)}async encode(e){var i;const t=JSON.stringify(e);return(i=this.encryption)!=null&&i.isEnabled()?this.encryption.encrypt(t,"messages"):t}async decode(e){var t;if(typeof e!="string")return e;if(!((t=this.encryption)!=null&&t.isEnabled()))try{return JSON.parse(e)}catch{return e}try{const i=await this.encryption.decrypt(e,"messages");return JSON.parse(i)}catch{return e}}async saveMessages(e,t){const i=this.getRuleFor("messages"),r=i?Ie(i.activePeriod):void 0,a=await this.encode(t);await this.adapter.save(`msg:${e}`,a,r)}async loadMessages(e){const t=await this.adapter.load(`msg:${e}`);if(!t)return[];const i=await this.decode(t);return Array.isArray(i)?i:[]}async appendMessage(e,t){const i=await this.loadMessages(e);await this.saveMessages(e,[...i,t])}async saveWhiteboardSnapshot(e,t){const i=this.getRuleFor("whiteboard-snapshots"),r=i?Ie(i.activePeriod):void 0,a=await this.encode(t);await this.adapter.save(`wb:${e}`,a,r)}async loadWhiteboardSnapshot(e){const t=await this.adapter.load(`wb:${e}`);return t?await this.decode(t):null}async saveRecordingMeta(e){const t=this.getRuleFor("recordings"),i=t?Ie(t.activePeriod):void 0,r=await this.encode(e);await this.adapter.save(`rec:${e.id}`,r,i)}async loadRecordingMeta(e){const t=await this.adapter.load(`rec:${e}`);return t?await this.decode(t):null}async listRecordings(){const e=await this.adapter.list("rec:");return(await Promise.all(e.map(i=>this.loadRecordingMeta(i.slice(4))))).filter(Boolean)}async deleteRecording(e){await this.adapter.delete(`rec:${e}`)}async saveDocument(e,t){const i=this.getRuleFor("documents"),r=i?Ie(i.activePeriod):void 0,a=await this.encode(t);await this.adapter.save(`doc:${e}`,a,r)}async loadDocument(e){const t=await this.adapter.load(`doc:${e}`);return t?this.decode(t):null}async enforceRetention(){let e=0,t=0;const i=new Date,r=[{prefix:"msg:",type:"messages"},{prefix:"wb:",type:"whiteboard-snapshots"},{prefix:"rec:",type:"recordings"},{prefix:"doc:",type:"documents"}];for(const{prefix:a,type:o}of r){const c=this.getRuleFor(o);if(!c)continue;const p=await this.adapter.list(a);for(const u of p){const m=await this.adapter.load(u);if(m){if(Ke(c.activePeriod),c.archivePeriod){const f=`archive:${u}`,y=Ie(c.archivePeriod,i);await this.adapter.save(f,m,y),e++}if(c.deleteAfterArchive&&c.archivePeriod){const f=Ke(c.archivePeriod);new Date(i.getTime()+f)<i&&(await this.adapter.delete(`archive:${u}`),t++)}}}}return{archived:e,deleted:t}}async estimateUsageBytes(){return typeof window<"u"&&"storage"in navigator&&"estimate"in navigator.storage?(await navigator.storage.estimate()).usage??0:0}updateConfig(e){this.config=e,this.adapter=this.buildAdapter()}getConfig(){return this.config}}const Ze=[{dataType:"messages",activePeriod:{value:1,unit:"years"},archivePeriod:{value:2,unit:"years"},deleteAfterArchive:!0,userCanDelete:!0},{dataType:"attachments",activePeriod:{value:6,unit:"months"},archivePeriod:{value:1,unit:"years"},deleteAfterArchive:!0,userCanDelete:!0},{dataType:"recordings",activePeriod:{value:3,unit:"months"},archivePeriod:{value:6,unit:"months"},deleteAfterArchive:!0,userCanDelete:!0},{dataType:"whiteboard-snapshots",activePeriod:{value:1,unit:"years"},deleteAfterArchive:!1,userCanDelete:!0},{dataType:"transcripts",activePeriod:{value:1,unit:"years"},archivePeriod:{value:2,unit:"years"},deleteAfterArchive:!0,userCanDelete:!0},{dataType:"documents",activePeriod:{value:3,unit:"years"},deleteAfterArchive:!1,userCanDelete:!0},{dataType:"call-logs",activePeriod:{value:90,unit:"days"},deleteAfterArchive:!0,userCanDelete:!1},{dataType:"audit-logs",activePeriod:{value:2,unit:"years"},deleteAfterArchive:!1,userCanDelete:!1,legalHoldEnabled:!0}],Me=new Map;function jt(s,e,t){return Me.has(s)||Me.set(s,new kt(e,t)),Me.get(s)}function Vt(s){Me.delete(s)}const lt=["#e91e63","#9c27b0","#3f51b5","#2196f3","#00bcd4","#4caf50","#ff9800","#ff5722","#795548","#607d8b"];function Xt(s){let e=0;for(let t=0;t<s.length;t++)e=e*31+s.charCodeAt(t)>>>0;return lt[e%lt.length]}function ct(s,e,t){const i={...s},r=[...e];switch(t.type){case"object:add":case"object:update":{const a=t.payload;if(i[a.id]=a,r.length>0&&!r[0].objectIds.includes(a.id)){const o=a.layerId?r.find(c=>c.id===a.layerId)??r[0]:r[0];o.objectIds=[...o.objectIds,a.id]}break}case"object:delete":{const{id:a}=t.payload;delete i[a],r.forEach(o=>{o.objectIds=o.objectIds.filter(c=>c!==a)});break}case"object:move":{const{id:a,x:o,y:c}=t.payload;i[a]&&(i[a]={...i[a],x:o,y:c,updatedAt:t.timestamp});break}case"layer:add":{const a=t.payload;r.find(o=>o.id===a.id)||r.push(a);break}case"layer:update":{const a=t.payload,o=r.findIndex(c=>c.id===a.id);o!==-1&&(r[o]={...r[o],...a});break}case"layer:delete":{const{id:a}=t.payload,o=r.findIndex(c=>c.id===a);o!==-1&&r.splice(o,1);break}}return{objects:i,layers:r}}function Jt(s,e){switch(e.type){case"LOAD_SESSION":return{...s,session:e.session,undoStack:[],redoStack:[],isDirty:!1};case"SET_TOOL":return{...s,activeTool:e.tool};case"APPLY_OP":{const{op:t,local:i}=e,{objects:r,layers:a}=ct(s.session.objects,s.session.layers,t),o={...s.session,objects:r,layers:a,updatedAt:t.timestamp},p=i&&["object:add","object:update","object:delete","object:move","layer:add","layer:update","layer:delete"].includes(t.type)?[...s.undoStack,[t]]:s.undoStack;return{...s,session:o,undoStack:p,redoStack:i?[]:s.redoStack,isDirty:!0}}case"UNDO":{if(s.undoStack.length===0)return s;const t=s.undoStack[s.undoStack.length-1],i=t.filter(o=>o.type==="object:add").map(o=>o.payload.id),r={...s.session.objects};i.forEach(o=>delete r[o]);const a=s.session.layers.map(o=>({...o,objectIds:o.objectIds.filter(c=>!i.includes(c))}));return{...s,session:{...s.session,objects:r,layers:a},undoStack:s.undoStack.slice(0,-1),redoStack:[t,...s.redoStack],isDirty:!0}}case"REDO":{if(s.redoStack.length===0)return s;const t=s.redoStack[0];let{objects:i,layers:r}={objects:s.session.objects,layers:s.session.layers};for(const a of t)({objects:i,layers:r}=ct(i,r,a));return{...s,session:{...s.session,objects:i,layers:r},undoStack:[...s.undoStack,t],redoStack:s.redoStack.slice(1),isDirty:!0}}case"SET_SELECTION":return{...s,selectedObjectIds:e.ids};case"SET_DRAWING":return{...s,isDrawing:e.value};case"SET_PANNING":return{...s,isPanning:e.value};case"UPDATE_CURSOR":{const{userId:t,x:i,y:r}=e,a=s.session.collaborators[t];return a?{...s,session:{...s.session,collaborators:{...s.session.collaborators,[t]:{...a,cursorX:i,cursorY:r,lastSeenAt:new Date}}}}:s}case"REMOVE_COLLABORATOR":{const t={...s.session.collaborators};return delete t[e.userId],{...s,session:{...s.session,collaborators:t}}}case"SET_VIEWPORT":return{...s,session:{...s.session,viewport:e.viewport}};case"MARK_SAVED":return{...s,isDirty:!1,lastSavedAt:new Date};default:return s}}function Ct(s){const{session:e,currentUser:t,onOperation:i,remoteOperations:r=[],readonly:a=!1,storageConfig:o,autoSaveMs:c=3e4}=s,[p,u]=l.useReducer(Jt,{session:e,activeTool:a?"select":"pen",selectedObjectIds:[],undoStack:[],redoStack:[],isDrawing:!1,isPanning:!1,isDirty:!1}),m=l.useRef(0),f=l.useRef(null),y=l.useRef(null);l.useEffect(()=>{o&&(y.current=jt(`wb_${e.id}`,o),y.current.loadWhiteboardSnapshot(e.id).then(P=>{P&&u({type:"LOAD_SESSION",session:P})}))},[e.id,o]),l.useEffect(()=>{if(!c||!y.current||!p.isDirty)return;const P=setTimeout(()=>{var O;(O=y.current)==null||O.saveWhiteboardSnapshot(p.session.id,p.session).then(()=>{u({type:"MARK_SAVED"})})},c);return()=>clearTimeout(P)},[p.isDirty,p.session,c]);const h=l.useRef(new Set);l.useEffect(()=>{for(const P of r)if(!h.current.has(P.id)&&P.userId!==t.id)if(h.current.add(P.id),P.type==="cursor:move"){const{x:O,y:_}=P.payload;u({type:"UPDATE_CURSOR",userId:P.userId,x:O,y:_})}else P.type==="viewport:sync"||u({type:"APPLY_OP",op:P,local:!1})},[r,t.id]);function S(P,O){return{id:`${t.id}_${++m.current}_${Date.now()}`,sessionId:p.session.id,type:P,userId:t.id,timestamp:new Date,payload:O}}const C=l.useCallback(P=>{a||u({type:"SET_TOOL",tool:P})},[a]),d=l.useCallback(P=>{if(a)return;const O=S("object:add",P);u({type:"APPLY_OP",op:O,local:!0}),i==null||i(O)},[a,i,p.session.id]),R=l.useCallback(P=>{if(a)return;const O=S("object:update",P);u({type:"APPLY_OP",op:O,local:!0}),i==null||i(O)},[a,i,p.session.id]),T=l.useCallback(P=>{if(!a){for(const O of P){const _=S("object:delete",{id:O});u({type:"APPLY_OP",op:_,local:!0}),i==null||i(_)}u({type:"SET_SELECTION",ids:[]})}},[a,i,p.session.id]),D=l.useCallback(P=>{if(!a)for(const{id:O,x:_,y:B}of P){const g=S("object:move",{id:O,x:_,y:B});u({type:"APPLY_OP",op:g,local:!0}),i==null||i(g)}},[a,i,p.session.id]),W=l.useCallback(P=>{u({type:"SET_SELECTION",ids:P})},[]),M=l.useCallback(()=>{a||u({type:"UNDO"})},[a]),F=l.useCallback(()=>{a||u({type:"REDO"})},[a]),U=l.useCallback(P=>{u({type:"SET_VIEWPORT",viewport:P});const O=S("viewport:sync",P);i==null||i(O)},[i,p.session.id]),N=l.useCallback((P,O)=>{if(f.current)return;f.current=setTimeout(()=>{f.current=null},50);const _=S("cursor:move",{x:P,y:O});i==null||i(_)},[i,p.session.id]),H=l.useCallback(P=>{if(a)return;const O={id:`layer_${Date.now()}`,name:P,visible:!0,locked:!1,objectIds:[]},_=S("layer:add",O);u({type:"APPLY_OP",op:_,local:!0}),i==null||i(_)},[a,i,p.session.id]),j=l.useCallback(P=>{if(a)return;const O=S("layer:update",P);u({type:"APPLY_OP",op:O,local:!0}),i==null||i(O)},[a,i,p.session.id]),b=l.useCallback(P=>{if(a)return;const O=S("layer:delete",{id:P});u({type:"APPLY_OP",op:O,local:!0}),i==null||i(O)},[a,i,p.session.id]),z=l.useCallback(P=>{const O={user:P,cursorX:0,cursorY:0,color:Xt(P.id),selectedObjectIds:[],activeTool:"pen",lastSeenAt:new Date};u({type:"APPLY_OP",op:S("cursor:move",O),local:!1})},[]),K=l.useCallback(P=>{u({type:"REMOVE_COLLABORATOR",userId:P})},[]),J=l.useCallback(async()=>{y.current&&(await y.current.saveWhiteboardSnapshot(p.session.id,p.session),u({type:"MARK_SAVED"}))},[p.session]);return{session:p.session,activeTool:p.activeTool,selectedObjectIds:p.selectedObjectIds,isDrawing:p.isDrawing,isPanning:p.isPanning,isDirty:p.isDirty,lastSavedAt:p.lastSavedAt,canUndo:p.undoStack.length>0,canRedo:p.redoStack.length>0,collaborators:Object.values(p.session.collaborators),objects:Object.values(p.session.objects),layers:p.session.layers,viewport:p.session.viewport,setTool:C,addObject:d,updateObject:R,deleteObjects:T,moveObjects:D,setSelection:W,undo:M,redo:F,setViewport:U,broadcastCursor:N,addLayer:H,updateLayer:j,deleteLayer:b,registerCollaborator:z,removeCollaborator:K,saveNow:J}}const Qt=[{id:"select",label:"Select",icon:"โ",group:"select"},{id:"laser",label:"Laser",icon:"๐ด",group:"select"},{id:"pen",label:"Pen",icon:"โ๏ธ",group:"draw"},{id:"highlighter",label:"Highlight",icon:"๐๏ธ",group:"draw"},{id:"eraser",label:"Eraser",icon:"โฌ",group:"draw"},{id:"line",label:"Line",icon:"โฑ",group:"shape"},{id:"arrow",label:"Arrow",icon:"โ",group:"shape"},{id:"rect",label:"Rectangle",icon:"โก",group:"shape"},{id:"ellipse",label:"Ellipse",icon:"โ",group:"shape"},{id:"triangle",label:"Triangle",icon:"โณ",group:"shape"},{id:"frame",label:"Frame",icon:"โฌ",group:"shape"},{id:"text",label:"Text",icon:"T",group:"insert"},{id:"sticky",label:"Sticky",icon:"๐",group:"insert"},{id:"image",label:"Image",icon:"๐ผ๏ธ",group:"insert"}];function Ee(){return`${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function _e(s,e,t){return{sx:s*t.scale+t.x,sy:e*t.scale+t.y}}function Zt(s,e,t){return{wx:(s-t.x)/t.scale,wy:(e-t.y)/t.scale}}function en(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function tn(s,e){if(!(e.points.length<2)){s.save(),s.globalAlpha=e.opacity,s.strokeStyle=e.color,s.lineWidth=e.strokeWidth,s.lineCap="round",s.lineJoin="round",e.tool==="highlighter"&&(s.globalCompositeOperation="multiply"),s.beginPath(),s.moveTo(e.points[0].x,e.points[0].y);for(let t=1;t<e.points.length;t++){const i={x:(e.points[t-1].x+e.points[t].x)/2,y:(e.points[t-1].y+e.points[t].y)/2};s.quadraticCurveTo(e.points[t-1].x,e.points[t-1].y,i.x,i.y)}s.stroke(),s.restore()}}function nn(s,e){switch(s.save(),s.globalAlpha=e.opacity,s.strokeStyle=e.strokeColor,s.lineWidth=e.strokeWidth,e.fillColor&&(s.fillStyle=e.fillColor),s.translate(e.x+e.width/2,e.y+e.height/2),s.rotate(e.rotation*Math.PI/180),s.beginPath(),e.shape){case"rect":s.rect(-e.width/2,-e.height/2,e.width,e.height);break;case"ellipse":s.ellipse(0,0,e.width/2,e.height/2,0,0,Math.PI*2);break;case"triangle":{const t=e.width/2,i=e.height/2;s.moveTo(0,-i),s.lineTo(t,i),s.lineTo(-t,i),s.closePath();break}case"diamond":{const t=e.width/2,i=e.height/2;s.moveTo(0,-i),s.lineTo(t,0),s.lineTo(0,i),s.lineTo(-t,0),s.closePath();break}}e.fillColor&&s.fill(),s.stroke(),s.restore()}function sn(s,e){if(s.save(),s.translate(e.x+e.width/2,e.y+e.height/2),s.rotate(e.rotation*Math.PI/180),s.font=`${e.fontStyle} ${e.fontWeight} ${e.fontSize}px ${e.fontFamily}`,s.fillStyle=e.color,s.textAlign=e.textAlign,s.textBaseline="middle",e.backgroundColor){const t=s.measureText(e.text),i=4;s.fillStyle=e.backgroundColor,s.fillRect(-t.width/2-i,-e.fontSize/2-i,t.width+i*2,e.fontSize+i*2),s.fillStyle=e.color}s.fillText(e.text,0,0),s.restore()}function rn(s,e){s.save(),s.translate(e.x,e.y),s.rotate(e.rotation*Math.PI/180),s.shadowColor="rgba(0,0,0,0.15)",s.shadowBlur=8,s.shadowOffsetY=3,s.fillStyle=e.backgroundColor,s.fillRect(0,0,e.width,e.height),s.shadowColor="transparent",s.fillStyle=e.textColor,s.font=`${e.fontSize}px sans-serif`,s.textAlign="left",s.textBaseline="top";const t=10,i=e.width-t*2,r=e.fontSize*1.4,a=e.text.split(" ");let o="",c=t;for(const p of a){const u=o?`${o} ${p}`:p;s.measureText(u).width>i&&o?(s.fillText(o,t,c),o=p,c+=r):o=u}o&&s.fillText(o,t,c),s.restore()}function an(s,e){if(!(e.points.length<2)){if(s.save(),s.strokeStyle=e.strokeColor,s.lineWidth=e.strokeWidth,s.lineCap="round",s.beginPath(),s.moveTo(e.points[0].x,e.points[0].y),e.curved&&e.points.length>2){for(let t=1;t<e.points.length-1;t++){const i=e.points[t],r={x:(i.x+e.points[t+1].x)/2,y:(i.y+e.points[t+1].y)/2};s.quadraticCurveTo(i.x,i.y,r.x,r.y)}s.lineTo(e.points[e.points.length-1].x,e.points[e.points.length-1].y)}else for(let t=1;t<e.points.length;t++)s.lineTo(e.points[t].x,e.points[t].y);if(s.stroke(),e.arrowEnd==="arrow"){const t=e.points[e.points.length-1],i=e.points[e.points.length-2],r=Math.atan2(t.y-i.y,t.x-i.x),a=12;s.beginPath(),s.moveTo(t.x,t.y),s.lineTo(t.x-a*Math.cos(r-Math.PI/6),t.y-a*Math.sin(r-Math.PI/6)),s.moveTo(t.x,t.y),s.lineTo(t.x-a*Math.cos(r+Math.PI/6),t.y-a*Math.sin(r+Math.PI/6)),s.stroke()}s.restore()}}function on(s,e){s.save(),s.strokeStyle=e.borderColor??"#aaa",s.lineWidth=2,s.setLineDash([8,4]),e.backgroundColor&&(s.fillStyle=e.backgroundColor,s.fillRect(e.x,e.y,e.width,e.height)),s.strokeRect(e.x,e.y,e.width,e.height),s.setLineDash([]),s.fillStyle="#555",s.font="bold 13px sans-serif",s.fillText(e.name,e.x+8,e.y-6),s.restore()}function ln(s,e){if(e.visible)switch(e.type){case"stroke":return tn(s,e);case"shape":return nn(s,e);case"text":return sn(s,e);case"sticky":return rn(s,e);case"connector":return an(s,e);case"frame":return on(s,e);case"image":{const t=e,i=new Image;i.src=t.dataUrl??t.url,s.save(),s.translate(t.x+t.width/2,t.y+t.height/2),s.rotate(t.rotation*Math.PI/180),s.drawImage(i,-t.width/2,-t.height/2,t.width,t.height),s.restore();break}}}function et({session:s,currentUser:e,onOperation:t,remoteOperations:i=[],readonly:r=!1,enableLayers:a=!0,enableExport:o=!0,enableLaserPointer:c=!0,enableVectorEditor:p=!1,enableDiagramEditor:u=!1,onExport:m,onSessionUpdate:f,storageConfig:y,className:h,style:S,"data-testid":C}){const d=Ct({session:s,currentUser:e,onOperation:t,remoteOperations:i,readonly:r,storageConfig:y,autoSaveMs:3e4}),R=l.useRef(null);l.useRef(null);const T=l.useRef(0),[D,W]=l.useState(!1),[M,F]=l.useState("#1a1a1a"),[U,N]=l.useState(3),[H,j]=l.useState(void 0),[b,z]=l.useState(18),[K,J]=l.useState("#fef08a"),[P,O]=l.useState(null),[_,B]=l.useState(null),g=l.useRef({active:!1,startX:0,startY:0,currentPoints:[],currentId:"",spaceDown:!1,panStart:null,laserPoints:[]}),w=l.useCallback((x,v,E,$)=>{if(!d.session.gridEnabled)return;const A=d.session.gridSize*v.scale,G=(v.x%A+A)%A,k=(v.y%A+A)%A;x.strokeStyle="rgba(180,180,200,0.35)",x.lineWidth=1,x.beginPath();for(let I=G;I<E;I+=A)x.moveTo(I,0),x.lineTo(I,$);for(let I=k;I<$;I+=A)x.moveTo(0,I),x.lineTo(E,I);x.stroke()},[d.session.gridEnabled,d.session.gridSize]),V=l.useCallback((x,v)=>{for(const E of d.collaborators){if(E.user.id===e.id)continue;const{sx:$,sy:A}=_e(E.cursorX,E.cursorY,v);x.save(),x.fillStyle=E.color,x.beginPath(),x.moveTo($,A),x.lineTo($+14,A+5),x.lineTo($+5,A+14),x.closePath(),x.fill(),x.fillStyle=E.color,x.font="bold 11px sans-serif",x.fillText(E.user.name,$+16,A+14),x.restore()}},[d.collaborators,e.id]),q=l.useCallback((x,v)=>{if(d.selectedObjectIds.length!==0)for(const E of d.selectedObjectIds){const $=d.session.objects[E];if(!$)continue;const{sx:A,sy:G}=_e($.x,$.y,v),k=$.width*v.scale,I=$.height*v.scale;x.strokeStyle="#4f8df9",x.lineWidth=1.5,x.setLineDash([4,2]),x.strokeRect(A-2,G-2,k+4,I+4),x.setLineDash([]);const ee=[[A-2,G-2],[A+k+2,G-2],[A-2,G+I+2],[A+k+2,G+I+2]];x.fillStyle="#fff",x.strokeStyle="#4f8df9",x.lineWidth=1.5;for(const[Z,ie]of ee)x.fillRect(Z-4,ie-4,8,8),x.strokeRect(Z-4,ie-4,8,8)}},[d.selectedObjectIds,d.session.objects]),Q=l.useCallback(()=>{const x=R.current;if(!x)return;const v=x.getContext("2d");if(!v)return;const{width:E,height:$}=x,A=d.viewport;v.clearRect(0,0,E,$),v.fillStyle=d.session.backgroundColor,v.fillRect(0,0,E,$),w(v,A,E,$),v.save();const G=Object.values(d.session.objects).filter(k=>k.visible).sort((k,I)=>k.zIndex-I.zIndex);v.translate(A.x,A.y),v.scale(A.scale,A.scale);for(const k of G)ln(v,k);if(g.current.active&&g.current.currentPoints.length>1){const k=g.current.currentPoints;v.strokeStyle=M,v.lineWidth=U,v.lineCap="round",v.lineJoin="round",v.beginPath(),v.moveTo(k[0].x,k[0].y);for(let I=1;I<k.length;I++)v.lineTo(k[I].x,k[I].y);v.stroke()}if(g.current.laserPoints.length>1&&d.activeTool==="laser"){const k=g.current.laserPoints;v.strokeStyle="#ff2c2c",v.lineWidth=3,v.globalAlpha=.7,v.beginPath(),v.moveTo(k[0].x,k[0].y);for(let I=1;I<k.length;I++)v.lineTo(k[I].x,k[I].y);v.stroke(),v.globalAlpha=1}v.restore(),q(v,A),V(v,A)},[d.session,d.viewport,d.activeTool,w,V,q,M,U]);l.useLayoutEffect(()=>{function x(){Q(),T.current=requestAnimationFrame(x)}return T.current=requestAnimationFrame(x),()=>cancelAnimationFrame(T.current)},[Q]),l.useEffect(()=>{const x=R.current;if(!x)return;const v=new ResizeObserver(()=>{x.width=x.offsetWidth,x.height=x.offsetHeight});return v.observe(x),x.width=x.offsetWidth,x.height=x.offsetHeight,()=>v.disconnect()},[]),l.useEffect(()=>{function x(v){if(v.target.tagName==="INPUT"||v.target.tagName==="TEXTAREA"||(v.code==="Space"&&(g.current.spaceDown=v.type==="keydown",v.preventDefault()),v.type!=="keydown"))return;(v.ctrlKey||v.metaKey)&&(v.key==="z"&&(v.preventDefault(),d.undo()),v.key==="y"&&(v.preventDefault(),d.redo()),v.key==="s"&&(v.preventDefault(),d.saveNow()),v.key==="a"&&(v.preventDefault(),d.setSelection(Object.keys(d.session.objects)))),(v.key==="Delete"||v.key==="Backspace")&&d.selectedObjectIds.length>0&&d.deleteObjects(d.selectedObjectIds);const E={v:"select",p:"pen",h:"highlighter",e:"eraser",r:"rect",c:"ellipse",t:"text",s:"sticky",i:"image",a:"arrow",l:"laser"};!v.ctrlKey&&!v.metaKey&&E[v.key]&&d.setTool(E[v.key])}return window.addEventListener("keydown",x),window.addEventListener("keyup",x),()=>{window.removeEventListener("keydown",x),window.removeEventListener("keyup",x)}},[d]);const Y=l.useCallback(x=>{const v=R.current.getBoundingClientRect(),E=x.clientX-v.left,$=x.clientY-v.top,{wx:A,wy:G}=Zt(E,$,d.viewport);return{x:A,y:G,pressure:x.pressure??.5}},[d.viewport]),re=l.useCallback(x=>{if(r)return;x.target.setPointerCapture(x.pointerId);const v=Y(x);if(x.button===1||g.current.spaceDown){g.current.panStart={x:x.clientX,y:x.clientY,vpX:d.viewport.x,vpY:d.viewport.y};return}const E=d.activeTool;if(g.current.active=!0,g.current.startX=v.x,g.current.startY=v.y,g.current.currentId=Ee(),E==="pen"||E==="highlighter")g.current.currentPoints=[v];else if(E==="laser")g.current.laserPoints=[v];else if(E==="select"){const $=Object.values(d.session.objects).filter(A=>A.visible&&A.x<=v.x&&A.y<=v.y&&A.x+A.width>=v.x&&A.y+A.height>=v.y).sort((A,G)=>G.zIndex-A.zIndex)[0];$?x.shiftKey?d.setSelection([...d.selectedObjectIds,$.id]):d.setSelection([$.id]):d.setSelection([])}},[r,Y,d]),ae=l.useCallback(x=>{const v=Y(x);if(d.broadcastCursor(v.x,v.y),g.current.panStart){const{x:$,y:A,vpX:G,vpY:k}=g.current.panStart;d.setViewport({...d.viewport,x:G+(x.clientX-$),y:k+(x.clientY-A)});return}if(!g.current.active)return;const E=d.activeTool;if(E==="pen"||E==="highlighter"){const $=g.current.currentPoints;($.length===0||en($[$.length-1],v)>2)&&(g.current.currentPoints=[...$,v])}else if(E==="laser"){const $=g.current.laserPoints;g.current.laserPoints=[...$.slice(-40),v]}else if(E==="select"&&d.selectedObjectIds.length>0){const $=v.x-g.current.startX,A=v.y-g.current.startY;g.current.startX=v.x,g.current.startY=v.y,d.moveObjects(d.selectedObjectIds.map(G=>{const k=d.session.objects[G];return{id:G,x:k.x+$,y:k.y+A}}))}},[Y,d]),pe=l.useCallback(x=>{if(g.current.panStart){g.current.panStart=null;return}if(!g.current.active)return;const v=Y(x),E=d.activeTool,$=g.current.startX,A=g.current.startY,G=g.current.currentId,k=new Date;switch(g.current.active=!1,E){case"pen":case"highlighter":{const I=g.current.currentPoints;if(I.length<2)break;const ee={id:G,type:"stroke",x:Math.min(...I.map(Z=>Z.x)),y:Math.min(...I.map(Z=>Z.y)),width:Math.max(...I.map(Z=>Z.x))-Math.min(...I.map(Z=>Z.x)),height:Math.max(...I.map(Z=>Z.y))-Math.min(...I.map(Z=>Z.y)),rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,points:I,color:M,strokeWidth:U,opacity:E==="highlighter"?.4:1,tool:E};d.addObject(ee),g.current.currentPoints=[];break}case"rect":case"ellipse":case"triangle":{const I=Math.min($,v.x),ee=Math.min(A,v.y),Z=Math.abs(v.x-$),ie=Math.abs(v.y-A);if(Z<5||ie<5)break;const ce={rect:"rect",ellipse:"ellipse",triangle:"triangle"},me={id:G,type:"shape",x:I,y:ee,width:Z,height:ie,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,shape:ce[E],fillColor:H,strokeColor:M,strokeWidth:U,opacity:1};d.addObject(me);break}case"arrow":case"line":{const I={id:G,type:"connector",x:Math.min($,v.x),y:Math.min(A,v.y),width:Math.abs(v.x-$),height:Math.abs(v.y-A),rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,points:[{x:$,y:A},{x:v.x,y:v.y}],strokeColor:M,strokeWidth:U,arrowStart:"none",arrowEnd:E==="arrow"?"arrow":"none",curved:!1};d.addObject(I);break}case"text":{const I={id:G,type:"text",x:v.x,y:v.y,width:200,height:b+10,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,text:"Click to edit",fontSize:b,fontFamily:"sans-serif",fontWeight:"normal",fontStyle:"normal",textAlign:"left",color:M};d.addObject(I),O(G);break}case"sticky":{const I={id:G,type:"sticky",x:v.x,y:v.y,width:180,height:150,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,text:"Note...",backgroundColor:K,textColor:"#333",fontSize:14,authorId:e.id};d.addObject(I),O(G);break}case"frame":{const I=Math.min($,v.x),ee=Math.min(A,v.y),Z=Math.abs(v.x-$),ie=Math.abs(v.y-A);if(Z<20||ie<20)break;const ce={id:G,type:"frame",x:I,y:ee,width:Z,height:ie,rotation:0,zIndex:0,locked:!1,visible:!0,createdBy:e.id,createdAt:k,name:`Frame ${Object.keys(d.session.objects).length+1}`,childIds:[],borderColor:"#8888"};d.addObject(ce);break}case"image":{const I=document.createElement("input");I.type="file",I.accept="image/*",I.onchange=()=>{var ie;const ee=(ie=I.files)==null?void 0:ie[0];if(!ee)return;const Z=new FileReader;Z.onload=ce=>{var Pe;const me=(Pe=ce.target)==null?void 0:Pe.result,fe=new Image;fe.onload=()=>{const Ae=400/fe.width,ye={id:Ee(),type:"image",x:v.x,y:v.y,width:fe.width*Ae,height:fe.height*Ae,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:me,dataUrl:me,originalWidth:fe.width,originalHeight:fe.height};d.addObject(ye)},fe.src=me},Z.readAsDataURL(ee)},I.click();break}}},[Y,d,e.id,M,U,H,b,K]),oe=l.useCallback(x=>{if(x.preventDefault(),!x.ctrlKey&&!x.metaKey){d.setViewport({...d.viewport,x:d.viewport.x-x.deltaX,y:d.viewport.y-x.deltaY});return}const v=R.current.getBoundingClientRect(),E=x.clientX-v.left,$=x.clientY-v.top,G=-x.deltaY>0?1.1:.9,k=Math.min(8,Math.max(.1,d.viewport.scale*G));d.setViewport({scale:k,x:E-(E-d.viewport.x)*(k/d.viewport.scale),y:$-($-d.viewport.y)*(k/d.viewport.scale)})},[d]),L=l.useCallback(x=>{if(x==="json"){const A=JSON.stringify(d.session,null,2);m==null||m("json",A);const G=document.createElement("a");G.href=URL.createObjectURL(new Blob([A],{type:"application/json"})),G.download=`${d.session.title}.json`,G.click();return}const v=R.current;if(!v)return;const E=v.toDataURL("image/png");m==null||m("png",E);const $=document.createElement("a");$.href=E,$.download=`${d.session.title}.png`,$.click()},[d.session,m]);l.useEffect(()=>{f==null||f(d.session)},[d.session,f]),l.useEffect(()=>{function x(v){if(v.clipboardData){for(const E of Array.from(v.clipboardData.items))if(E.type.startsWith("image/")){const $=E.getAsFile();if(!$)continue;const A=new FileReader;A.onload=G=>{var ee;const k=(ee=G.target)==null?void 0:ee.result,I=new Image;I.onload=()=>{const ie=400/I.width,ce={id:Ee(),type:"image",x:100,y:100,width:I.width*ie,height:I.height*ie,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:k,dataUrl:k,originalWidth:I.width,originalHeight:I.height};d.addObject(ce)},I.src=k},A.readAsDataURL($);break}}}return window.addEventListener("paste",x),()=>window.removeEventListener("paste",x)},[d,e.id]);const X=P?d.session.objects[P]:null,ne=l.useMemo(()=>X?_e(X.x,X.y,d.viewport):null,[X,d.viewport]),se=["#fef08a","#bfdbfe","#bbf7d0","#fecaca","#e9d5ff","#fed7aa"],le=l.useMemo(()=>{var v;const x={};for(const E of Qt)(x[v=E.group]??(x[v]=[])).push(E);return Object.values(x)},[]);return n.jsxs("div",{className:h,"data-testid":C,style:{position:"relative",display:"flex",flexDirection:"column",width:"100%",height:"100%",overflow:"hidden",background:"#f5f5f5",fontFamily:"system-ui, sans-serif",...S},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",background:"#fff",borderBottom:"1px solid #e5e7eb",flexShrink:0,flexWrap:"wrap"},children:[le.map((x,v)=>n.jsxs(l.Fragment,{children:[v>0&&n.jsx("div",{style:{width:1,height:24,background:"#e5e7eb",margin:"0 2px"}}),x.map(E=>n.jsx("button",{onClick:()=>d.setTool(E.id),title:`${E.label}`,style:{padding:"4px 7px",border:`1.5px solid ${d.activeTool===E.id?"#6366f1":"transparent"}`,borderRadius:6,background:d.activeTool===E.id?"#eef2ff":"transparent",cursor:"pointer",fontSize:15,minWidth:30,color:d.activeTool===E.id?"#4f46e5":"#374151"},children:E.icon},E.id))]},v)),n.jsx("div",{style:{width:1,height:24,background:"#e5e7eb",margin:"0 4px"}}),n.jsxs("label",{title:"Stroke color",style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[n.jsx("span",{style:{fontSize:11,color:"#6b7280"},children:"Color"}),n.jsx("input",{type:"color",value:M,onChange:x=>F(x.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}})]}),n.jsxs("label",{title:"Fill color",style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[n.jsx("span",{style:{fontSize:11,color:"#6b7280"},children:"Fill"}),n.jsx("input",{type:"color",value:H??"#ffffff",onChange:x=>j(x.target.value==="#ffffff"?void 0:x.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}}),n.jsx("button",{onClick:()=>j(void 0),style:{fontSize:11,padding:"1px 5px",border:"1px solid #e5e7eb",borderRadius:4,cursor:"pointer",background:H?"#fff":"#f3f4f6"},children:"No fill"})]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx("span",{style:{fontSize:11,color:"#6b7280"},children:"Width"}),n.jsx("input",{type:"range",min:1,max:24,step:1,value:U,onChange:x=>N(Number(x.target.value)),style:{width:70}}),n.jsx("span",{style:{fontSize:11,color:"#6b7280",minWidth:20},children:U})]}),d.activeTool==="sticky"&&n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{fontSize:11,color:"#6b7280"},children:"Note:"}),se.map(x=>n.jsx("button",{onClick:()=>J(x),style:{width:20,height:20,background:x,border:`2px solid ${K===x?"#6366f1":"#e5e7eb"}`,borderRadius:4,cursor:"pointer"}},x))]}),n.jsx("div",{style:{flex:1}}),n.jsx("button",{onClick:d.undo,disabled:!d.canUndo,title:"Undo (Ctrl+Z)",style:de(!d.canUndo),children:"โฉ"}),n.jsx("button",{onClick:d.redo,disabled:!d.canRedo,title:"Redo (Ctrl+Y)",style:de(!d.canRedo),children:"โช"}),n.jsx("div",{style:{width:1,height:24,background:"#e5e7eb"}}),n.jsxs("span",{style:{fontSize:11,color:"#6b7280",minWidth:42,textAlign:"center"},children:[Math.round(d.viewport.scale*100),"%"]}),n.jsx("button",{onClick:()=>d.setViewport({x:0,y:0,scale:1}),style:de(),title:"Reset zoom",children:"โ"}),a&&n.jsx("button",{onClick:()=>W(x=>!x),style:de(!1,D),title:"Layers",children:"โ"}),n.jsx("button",{onClick:()=>{const x={id:Ee(),sessionId:d.session.id,type:"object:update",userId:e.id,timestamp:new Date,payload:{...d.session,gridEnabled:!d.session.gridEnabled}};t==null||t(x)},style:de(!1,d.session.gridEnabled),title:"Toggle grid",children:"#"}),p&&n.jsx("button",{onClick:()=>B(x=>x==="vector"?null:"vector"),style:de(!1,_==="vector"),title:"Vector Editor panel",children:"Vฮต"}),u&&n.jsx("button",{onClick:()=>B(x=>x==="diagram"?null:"diagram"),style:de(!1,_==="diagram"),title:"Diagram Editor panel",children:"โ"}),n.jsx("button",{onClick:()=>void d.saveNow(),style:de(),title:"Save (Ctrl+S)",children:d.isDirty?"๐พ*":"๐พ"}),o&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>L("png"),style:de(),title:"Export PNG",children:"PNGโ"}),n.jsx("button",{onClick:()=>L("json"),style:de(),title:"Export JSON",children:"JSONโ"})]})]}),n.jsxs("div",{style:{display:"flex",flex:1,overflow:"hidden",position:"relative"},children:[n.jsx("canvas",{ref:R,style:{flex:1,display:"block",cursor:dn(d.activeTool,g.current.spaceDown)},onPointerDown:re,onPointerMove:ae,onPointerUp:pe,onWheel:oe,onContextMenu:x=>x.preventDefault()}),a&&D&&n.jsx(cn,{layers:d.layers,objects:d.session.objects,onAdd:()=>d.addLayer(`Layer ${d.layers.length+1}`),onUpdate:x=>d.updateLayer(x),onDelete:x=>d.deleteLayer(x)}),_&&n.jsxs("div",{style:{position:"absolute",right:D?220:0,top:0,bottom:0,width:360,background:"#fff",borderLeft:"1px solid #e5e7eb",padding:12,overflowY:"auto"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[n.jsx("strong",{style:{fontSize:13},children:_==="vector"?"Vector Editor":"Diagram Editor"}),n.jsx("button",{onClick:()=>B(null),style:{border:"none",background:"none",cursor:"pointer",fontSize:16},children:"โ"})]}),n.jsx("p",{style:{fontSize:12,color:"#6b7280"},children:_==="vector"?"Render the full @nice2dev/ui-graphics VectorEditor here. Pass the whiteboard's StorageConfig to persist edits and onOperation to broadcast strokes in real time.":"Render the full @nice2dev/ui-diagrams NiceDiagramEditor here. Pass the collaborativeDiagram YDoc to enable simultaneous multi-user editing."}),n.jsx("div",{id:`wb-integration-${_}`,style:{width:"100%",height:400}})]})]}),d.collaborators.length>1&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",background:"#fff",borderTop:"1px solid #f3f4f6",fontSize:11,color:"#6b7280",flexShrink:0},children:[n.jsx("span",{children:"Collaborators:"}),d.collaborators.map(x=>n.jsxs("span",{style:{display:"flex",alignItems:"center",gap:3},children:[n.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:x.color,display:"inline-block"}}),x.user.name]},x.user.id)),d.isDirty&&n.jsx("span",{style:{marginLeft:"auto",color:"#f59e0b"},children:"โ unsaved"}),d.lastSavedAt&&!d.isDirty&&n.jsxs("span",{style:{marginLeft:"auto",color:"#10b981"},children:["โ Saved ",d.lastSavedAt.toLocaleTimeString()]})]}),X&&ne&&n.jsx("textarea",{autoFocus:!0,defaultValue:X.text,onBlur:x=>{const v={...X,text:x.target.value,updatedAt:new Date,updatedBy:e.id};d.updateObject(v),O(null)},style:{position:"absolute",left:ne.sx,top:ne.sy,minWidth:X.width*d.viewport.scale,minHeight:X.height*d.viewport.scale,fontSize:(X.fontSize??14)*d.viewport.scale,fontFamily:"sans-serif",background:X.type==="sticky"?X.backgroundColor:"rgba(255,255,255,0.95)",border:"2px solid #6366f1",borderRadius:4,padding:6,resize:"both",zIndex:1e3,color:X.type==="sticky"?X.textColor:X.color}})]})}function cn({layers:s,objects:e,onAdd:t,onUpdate:i,onDelete:r}){return n.jsxs("div",{style:{width:200,borderLeft:"1px solid #e5e7eb",background:"#fff",display:"flex",flexDirection:"column",padding:8,gap:4,overflowY:"auto",flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[n.jsx("strong",{style:{fontSize:12,color:"#374151"},children:"Layers"}),n.jsx("button",{onClick:t,style:{fontSize:16,border:"none",background:"none",cursor:"pointer",color:"#6366f1"},title:"Add layer",children:"+"})]}),[...s].reverse().map(a=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",borderRadius:5,background:"#f9fafb",opacity:a.visible?1:.5},children:[n.jsx("button",{onClick:()=>i({id:a.id,visible:!a.visible}),title:"Toggle visibility",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,color:a.visible?"#374151":"#9ca3af"},children:a.visible?"๐":"๐ซ"}),n.jsx("button",{onClick:()=>i({id:a.id,locked:!a.locked}),title:"Toggle lock",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0},children:a.locked?"๐":"๐"}),n.jsx("span",{style:{flex:1,fontSize:11,color:"#374151",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.name}),n.jsx("span",{style:{fontSize:10,color:"#9ca3af"},children:a.objectIds.filter(o=>o in e).length}),s.length>1&&n.jsx("button",{onClick:()=>r(a.id),title:"Delete layer",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,color:"#ef4444"},children:"ร"})]},a.id))]})}function de(s=!1,e=!1){return{padding:"4px 8px",border:`1.5px solid ${e?"#6366f1":"#e5e7eb"}`,borderRadius:6,background:e?"#eef2ff":"#fff",cursor:s?"default":"pointer",opacity:s?.35:1,fontSize:13,color:e?"#4f46e5":"#374151",fontWeight:e?600:400}}function dn(s,e){if(e)return"grab";switch(s){case"pen":case"highlighter":return"crosshair";case"eraser":return"cell";case"select":return"default";case"text":return"text";case"laser":return"none";default:return"crosshair"}}function be({icon:s,label:e,active:t,badge:i,onClick:r}){return n.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[n.jsxs("button",{title:e,onClick:r,style:{width:44,height:44,borderRadius:10,border:"none",background:t?"rgba(255,255,255,0.2)":"transparent",color:"#fff",fontSize:20,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",position:"relative"},children:[s,i!=null&&i>0&&n.jsx("span",{style:{position:"absolute",top:4,right:4,background:"#ef4444",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700,lineHeight:1.4},children:i>99?"99+":i})]}),n.jsx("span",{style:{fontSize:9,color:"rgba(255,255,255,0.7)",letterSpacing:"0.03em"},children:e})]})}function un({team:s,activeChannelId:e,onSelectChannel:t}){var o;const[i,r]=l.useState(!1),a=s.channels.reduce((c,p)=>c+p.unreadCount,0);return n.jsxs("div",{className:"nice-workspace-team",children:[n.jsxs("button",{onClick:()=>r(c=>!c),style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",background:"none",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:"#374151",fontSize:13,fontWeight:600},children:[n.jsx("span",{style:{fontSize:10,color:"#9ca3af"},children:i?"โถ":"โผ"}),n.jsx("div",{style:{width:20,height:20,borderRadius:4,background:s.avatarUrl?`url(${s.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:9,flexShrink:0},children:!s.avatarUrl&&((o=s.name[0])==null?void 0:o.toUpperCase())}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.name}),!i&&a>0&&n.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:a})]}),!i&&s.channels.map(c=>n.jsxs("button",{onClick:()=>t(s.id,c.id),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 10px 5px 34px",background:c.id===e?"#ede9fe":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:c.unreadCount>0?"#111827":"#4b5563",fontSize:13,fontWeight:c.unreadCount>0?600:400},children:[n.jsx("span",{style:{color:"#9ca3af",fontSize:12},children:c.isPrivate?"๐":"#"}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.name}),c.mentionCount>0&&n.jsxs("span",{style:{background:"#ef4444",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:["@",c.mentionCount]}),c.unreadCount>0&&c.mentionCount===0&&n.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700},children:c.unreadCount})]},c.id))]})}function pn({conversation:s,partner:e,isActive:t,onClick:i}){var a;const r=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??s.name??"Group";return n.jsxs("button",{onClick:i,style:{display:"flex",alignItems:"center",gap:8,padding:"5px 10px",background:t?"#ede9fe":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:s.unreadCount>0?"#111827":"#4b5563",fontWeight:s.unreadCount>0?600:400,fontSize:13},children:[n.jsxs("div",{style:{position:"relative",flexShrink:0},children:[n.jsx("div",{style:{width:24,height:24,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:10},children:!(e!=null&&e.avatarUrl)&&((a=r[0])==null?void 0:a.toUpperCase())}),e&&n.jsx(ue,{status:e.presence.status,size:"xs",style:{position:"absolute",bottom:-1,right:-1}})]}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),s.unreadCount>0&&n.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700,flexShrink:0},children:s.unreadCount})]})}function It({currentUser:s,users:e,teams:t,conversations:i,messages:r,activeCall:a,incomingCall:o,meetings:c,transport:p,rtcConfig:u,enableCalls:m=!0,enableMeetings:f=!0,enableScreenSharing:y=!0,enableWhiteboard:h=!1,storageConfig:S,onSendMessage:C,onEditMessage:d,onDeleteMessage:R,onReactToMessage:T,onPinMessage:D,onLoadMoreMessages:W,onMarkAsRead:M,onStartCall:F,onAcceptCall:U,onDeclineCall:N,onEndCall:H,onMuteAudio:j,onMuteVideo:b,onStartScreenShare:z,onStopScreenShare:K,className:J,style:P,id:O,"data-testid":_}){var A,G;const[B,g]=l.useState("teams"),[w,V]=l.useState(null),[q,Q]=l.useState(""),[Y,re]=l.useState(null),ae=()=>{Y||re({id:`wb-workspace-${Date.now()}`,title:"Team Whiteboard",objects:{},layers:[{id:"layer-0",name:"Layer 1",visible:!0,locked:!1,objectIds:[]}],collaborators:{},viewport:{x:0,y:0,scale:1},width:4e3,height:3e3,backgroundColor:"#ffffff",gridEnabled:!0,gridSize:20,snapEnabled:!0,createdAt:new Date,updatedAt:new Date,ownerId:s.id,permissions:"edit"})},pe=l.useMemo(()=>{const k=new Map;return e.forEach(I=>k.set(I.id,I)),k},[e]),oe=l.useMemo(()=>Xe(i),[i]),L=l.useMemo(()=>i.reduce((k,I)=>k+I.mentionCount,0),[i]),X=l.useMemo(()=>{if(w!=null&&w.channelId)for(const k of t){const I=k.channels.find(ee=>ee.id===w.channelId);if(I)return I}},[t,w]),ne=l.useMemo(()=>{if(w!=null&&w.teamId)return t.find(k=>k.id===w.teamId)},[t,w]),se=l.useMemo(()=>i.find(k=>k.id===(w==null?void 0:w.conversationId))??null,[i,w]),le=l.useMemo(()=>{const k=(w==null?void 0:w.channelId)??(w==null?void 0:w.conversationId);return k?r[k]??[]:[]},[r,w]),x=!!o&&!a,v=!!a,E=l.useMemo(()=>i.filter(k=>k.type==="dm"||k.type==="group"),[i]),$=l.useMemo(()=>{if(!q)return E;const k=q.toLowerCase();return E.filter(I=>{var Z;const ee=pe.get(I.participantIds.find(ie=>ie!==s.id)??"");return(ee==null?void 0:ee.name.toLowerCase().includes(k))||((Z=I.name)==null?void 0:Z.toLowerCase().includes(k))})},[E,q,pe,s.id]);return n.jsxs("div",{id:O,"data-testid":_,className:`nice-teams-workspace${J?` ${J}`:""}`,style:{display:"flex",height:"100%",overflow:"hidden",background:"#fff",position:"relative",...P},children:[n.jsxs("div",{className:"nice-workspace-nav-rail",style:{width:64,flexShrink:0,background:"#4f46e5",display:"flex",flexDirection:"column",alignItems:"center",padding:"12px 0",gap:6},children:[n.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:s.avatarUrl?`url(${s.avatarUrl}) center/cover`:"#818cf8",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:14,marginBottom:8,flexShrink:0},children:!s.avatarUrl&&((A=s.name[0])==null?void 0:A.toUpperCase())}),n.jsx(be,{icon:"โก",label:"Activity",active:B==="activity",badge:L,onClick:()=>g("activity")}),n.jsx(be,{icon:"๐ฌ",label:"Chat",active:B==="chat",badge:oe,onClick:()=>g("chat")}),n.jsx(be,{icon:"๐ฅ",label:"Teams",active:B==="teams",onClick:()=>g("teams")}),m&&n.jsx(be,{icon:"๐",label:"Calls",active:B==="calls",onClick:()=>g("calls")}),f&&n.jsx(be,{icon:"๐
",label:"Meetings",active:B==="meetings",onClick:()=>g("meetings")}),n.jsx(be,{icon:"๐",label:"Files",active:B==="files",onClick:()=>g("files")}),h&&n.jsx(be,{icon:"๐๏ธ",label:"Board",active:B==="whiteboard",onClick:()=>{g("whiteboard"),ae()}})]}),n.jsxs("div",{className:"nice-workspace-sidebar",style:{width:240,flexShrink:0,borderRight:"1px solid #e5e7eb",display:"flex",flexDirection:"column",background:"#fafafa",overflow:"hidden"},children:[n.jsxs("div",{style:{padding:"12px 10px 8px",flexShrink:0},children:[n.jsx("div",{style:{fontWeight:700,fontSize:15,color:"#374151",marginBottom:8,textTransform:"capitalize"},children:B}),n.jsx("input",{type:"search",value:q,onChange:k=>Q(k.target.value),placeholder:`Search ${B}โฆ`,style:{width:"100%",padding:"5px 10px",border:"1px solid #e5e7eb",borderRadius:16,fontSize:12,outline:"none",boxSizing:"border-box",background:"#fff"}})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[B==="teams"&&n.jsx(n.Fragment,{children:t.map(k=>n.jsx(un,{team:k,activeChannelId:w==null?void 0:w.channelId,onSelectChannel:(I,ee)=>{V({type:"channel",teamId:I,channelId:ee}),M==null||M(ee)}},k.id))}),B==="chat"&&n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:"#9ca3af",fontWeight:600,letterSpacing:"0.05em"},children:"DIRECT MESSAGES"}),$.map(k=>{const I=pe.get(k.participantIds.find(ee=>ee!==s.id)??"");return n.jsx(pn,{conversation:k,partner:I,isActive:(w==null?void 0:w.conversationId)===k.id,onClick:()=>{V({type:k.type==="dm"?"dm":"group",conversationId:k.id}),M==null||M(k.id)}},k.id)})]}),B==="activity"&&n.jsxs("div",{style:{padding:12},children:[i.filter(k=>k.unreadCount>0).map(k=>n.jsxs("button",{onClick:()=>{g(k.type==="channel"?"teams":"chat"),V({type:k.type==="channel"?"channel":"dm",conversationId:k.id})},style:{display:"block",width:"100%",textAlign:"left",padding:"6px 0",background:"none",border:"none",cursor:"pointer",fontSize:13,color:"#374151"},children:[n.jsx("strong",{children:k.name??"Conversation"})," โ ",k.unreadCount," unread"]},k.id)),i.every(k=>k.unreadCount===0)&&n.jsx("p",{style:{color:"#9ca3af",fontSize:13,textAlign:"center",marginTop:24},children:"All caught up โ"})]}),B==="calls"&&n.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8},children:[n.jsx("button",{onClick:()=>F==null?void 0:F(e.map(k=>k.id).filter(k=>k!==s.id),"audio"),style:{background:"#6366f1",color:"#fff",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600},children:"๐ New audio call"}),n.jsx("button",{onClick:()=>F==null?void 0:F(e.map(k=>k.id).filter(k=>k!==s.id),"video"),style:{background:"#6366f1",color:"#fff",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600},children:"๐น New video call"})]}),B==="meetings"&&n.jsxs("div",{style:{padding:12},children:[(c??[]).map(k=>n.jsxs("div",{style:{padding:"8px 10px",border:"1px solid #e5e7eb",borderRadius:8,marginBottom:8},children:[n.jsx("div",{style:{fontWeight:600,fontSize:13},children:k.title}),n.jsx("div",{style:{fontSize:11,color:"#6b7280",marginTop:2},children:k.scheduledStart.toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}),n.jsx("button",{onClick:()=>{},style:{marginTop:6,background:"#6366f1",color:"#fff",border:"none",borderRadius:6,padding:"3px 10px",fontSize:12,cursor:"pointer"},children:"Join"})]},k.id)),(c??[]).length===0&&n.jsx("p",{style:{color:"#9ca3af",fontSize:13,textAlign:"center",marginTop:24},children:"No upcoming meetings"})]}),B==="files"&&n.jsx("div",{style:{padding:12},children:n.jsx("p",{style:{color:"#9ca3af",fontSize:13,textAlign:"center",marginTop:24},children:"No files shared yet"})}),B==="whiteboard"&&n.jsxs("div",{style:{padding:12},children:[n.jsxs("button",{onClick:()=>ae(),style:{width:"100%",background:"#6366f1",color:"#fff",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,marginBottom:8},children:["๐๏ธ ",Y?"Open whiteboard":"New whiteboard"]}),Y&&n.jsxs("div",{style:{padding:"6px 10px",border:"1px solid #e5e7eb",borderRadius:6,fontSize:12,color:"#374151"},children:[n.jsx("div",{style:{fontWeight:500},children:Y.title}),n.jsxs("div",{style:{color:"#9ca3af",marginTop:2},children:[Object.keys(Y.objects).length," objects"]})]})]})]})]}),n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[(w==null?void 0:w.type)==="channel"&&X?n.jsx(wt,{channel:X,messages:le,users:(ne==null?void 0:ne.members)??e,currentUser:s,team:ne,onSendMessage:C,onEditMessage:d,onDeleteMessage:R,onReactToMessage:T,onPinMessage:D,onLoadMoreMessages:W,onStartCall:m?F:void 0,style:{height:"100%"}}):((w==null?void 0:w.type)==="dm"||(w==null?void 0:w.type)==="group")&&se?n.jsx(Re,{conversation:se,messages:le,users:e,currentUser:s,onSendMessage:C,onEditMessage:d,onDeleteMessage:R,onReactToMessage:T,onPinMessage:D,onLoadMoreMessages:W,onStartCall:m?F:void 0,style:{height:"100%"}}):B==="whiteboard"&&Y?n.jsx(et,{session:Y,currentUser:s,storageConfig:S,onSessionUpdate:k=>re(k),style:{height:"100%"}}):n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"#9ca3af",gap:12},children:[n.jsx("span",{style:{fontSize:56},children:B==="teams"?"๐ฅ":B==="chat"?"๐ฌ":B==="calls"?"๐":B==="whiteboard"?"๐๏ธ":"โก"}),n.jsx("span",{style:{fontSize:17,fontWeight:500},children:B==="teams"?"Select a channel to get started":B==="chat"?"Select a conversation":B==="calls"?"Start or join a call":B==="whiteboard"?'Click "New whiteboard" to start':"Nothing selected"})]}),v&&a&&n.jsx("div",{style:{position:"absolute",inset:0,zIndex:50},children:a.participants.length>2?n.jsx(Qe,{session:a,currentUser:s,enableScreenSharing:y,onEndCall:H,onMuteAudio:j,onMuteVideo:b,onStartScreenShare:z,onStopScreenShare:K}):n.jsx(Je,{session:a,currentUser:s,enableScreenSharing:y,onEndCall:H,onMuteAudio:j,onMuteVideo:b,onStartScreenShare:z,onStopScreenShare:K})})]}),x&&o&&n.jsxs("div",{style:{position:"absolute",top:16,right:16,width:300,background:"#1f2937",borderRadius:12,padding:16,boxShadow:"0 8px 32px rgba(0,0,0,0.4)",zIndex:100,color:"#fff"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:12},children:[n.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:o.caller.avatarUrl?`url(${o.caller.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:16},children:!o.caller.avatarUrl&&((G=o.caller.name[0])==null?void 0:G.toUpperCase())}),n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:o.caller.displayName??o.caller.name}),n.jsxs("div",{style:{fontSize:12,color:"rgba(255,255,255,0.6)"},children:["Incoming ",o.callType," call"]})]})]}),n.jsxs("div",{style:{display:"flex",gap:8},children:[n.jsx("button",{onClick:()=>N==null?void 0:N(o.callId),style:{flex:1,background:"#ef4444",color:"#fff",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13},children:"๐ต Decline"}),n.jsx("button",{onClick:()=>U==null?void 0:U(o.callId),style:{flex:1,background:"#22c55e",color:"#fff",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13},children:"๐ Accept"})]})]})]})}const fn={"bottom-right":{bottom:24,right:24},"bottom-left":{bottom:24,left:24},"top-right":{top:24,right:24},"top-left":{top:24,left:24}};function hn({props:s,onExpand:e}){const[t,i]=l.useState(!1),{bubblePosition:r="bottom-right",bubbleLabel:a,currentUser:o,users:c,conversations:p=[],messages:u={},onSendMessage:m,onReactToMessage:f,onPinMessage:y,onDeleteMessage:h,onEditMessage:S,onLoadMoreMessages:C,onStartCall:d}=s,R=fn[r],T=p[0]??null,D=T?u[T.id]??[]:[];return n.jsxs("div",{style:{position:"fixed",zIndex:9999,...R},children:[t&&T&&n.jsxs("div",{style:{position:"absolute",bottom:r.startsWith("bottom")?64:void 0,top:r.startsWith("top")?64:void 0,right:r.endsWith("right")?0:void 0,left:r.endsWith("left")?0:void 0,width:360,height:500,background:"#fff",borderRadius:16,boxShadow:"0 8px 40px rgba(0,0,0,0.18)",overflow:"hidden",display:"flex",flexDirection:"column"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",background:"#6366f1",color:"#fff",flexShrink:0},children:[n.jsx("span",{style:{fontWeight:700,fontSize:15},children:a??"Chat"}),n.jsxs("div",{style:{display:"flex",gap:4},children:[n.jsx("button",{onClick:()=>e("messenger"),title:"Open full chat",style:{background:"rgba(255,255,255,0.15)",border:"none",borderRadius:6,padding:"3px 7px",color:"#fff",cursor:"pointer",fontSize:13},children:"โ"}),n.jsx("button",{onClick:()=>i(!1),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",fontSize:18},children:"ร"})]})]}),n.jsx(Re,{conversation:T,messages:D,users:c,currentUser:o,showHeader:!1,onSendMessage:m,onEditMessage:S,onDeleteMessage:h,onReactToMessage:f,onPinMessage:y,onLoadMoreMessages:C,onStartCall:d,style:{flex:1}})]}),n.jsx("button",{onClick:()=>i(W=>!W),style:{width:56,height:56,borderRadius:"50%",background:"#6366f1",border:"none",boxShadow:"0 4px 16px rgba(99,102,241,0.4)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:24,color:"#fff",transition:"transform 0.15s"},title:t?"Close chat":a??"Open chat",children:t?"โ":"๐ฌ"})]})}function gn({call:s,onAccept:e,onDecline:t}){return n.jsxs("div",{style:{position:"fixed",top:16,left:"50%",transform:"translateX(-50%)",zIndex:9998,background:"#1f2937",color:"#fff",borderRadius:12,padding:"12px 20px",boxShadow:"0 8px 32px rgba(0,0,0,0.4)",display:"flex",alignItems:"center",gap:16,minWidth:280},children:[n.jsx("div",{style:{fontSize:28},children:s.callType==="video"?"๐น":"๐"}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:600,fontSize:14},children:s.caller.displayName??s.caller.name}),n.jsxs("div",{style:{fontSize:12,color:"rgba(255,255,255,0.6)"},children:["Incoming ",s.callType," callโฆ"]})]}),n.jsx("button",{onClick:t,style:{background:"#ef4444",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",fontSize:18,color:"#fff"},title:"Decline",children:"๐ต"}),n.jsx("button",{onClick:e,style:{background:"#22c55e",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",fontSize:18,color:"#fff"},title:"Accept",children:"๐"})]})}function Tt(s){const{mode:e,currentUser:t,users:i,conversations:r=[],messages:a={},teams:o=[],meetings:c,activeCall:p,incomingCall:u,transport:m="webrtc",rtcConfig:f,onSendMessage:y,onEditMessage:h,onDeleteMessage:S,onReactToMessage:C,onPinMessage:d,onLoadMoreMessages:R,onMarkAsRead:T,onStartCall:D,onAcceptCall:W,onDeclineCall:M,onEndCall:F,onMuteAudio:U,onMuteVideo:N,onStartScreenShare:H,onStopScreenShare:j,onRaiseHand:b,onModeChange:z,enableScreenSharing:K=!0,enableMeetings:J=!0,enableWhiteboard:P=!1,storageConfig:O,encryptionConfig:_,className:B,style:g,id:w,"data-testid":V}=s,[q,Q]=l.useState(e),[Y,re]=l.useState(null),ae=l.useMemo(()=>({id:`wb-${t.id}-${Date.now()}`,title:"Whiteboard",objects:{},layers:[{id:"layer-0",name:"Layer 1",visible:!0,locked:!1,objectIds:[]}],collaborators:{},viewport:{x:0,y:0,scale:1},width:4e3,height:3e3,backgroundColor:"#ffffff",gridEnabled:!0,gridSize:20,snapEnabled:!0,createdAt:new Date,updatedAt:new Date,ownerId:t.id,permissions:"edit"}),[t.id]),[pe,oe]=l.useState(p??null),[L,X]=l.useState(u??null),ne=p??pe,se=u??L;l.useEffect(()=>{Q(e)},[e]),l.useEffect(()=>{p!==void 0&&oe(p)},[p]),l.useEffect(()=>{u!==void 0&&X(u)},[u]);const{state:le,startCall:x,acceptCall:v,declineCall:E,endCall:$,toggleMic:A,toggleCamera:G,startScreenShare:k,stopScreenShare:I}=vt({currentUser:t,transport:m,rtcConfig:f,onCallEnded:te=>{oe(null),F==null||F(te)},onIncomingCall:te=>{X(te)}}),ee=l.useCallback(te=>{Q(te),z==null||z(te)},[z]),Z=l.useCallback(async(te,rt)=>{if(D){await D(te,rt);return}const Lt=await x(te,rt);oe(Lt),Q(te.length>2?"conference":"call")},[D,x]),ie=l.useCallback(async()=>{var te;W&&se?await W(se.callId):await v(),X(null),Q((te=le.activeCall)!=null&&te.participants&&le.activeCall.participants.length>2?"conference":"call")},[W,se,v,le.activeCall]),ce=l.useCallback(()=>{M&&se?M(se.callId):E(),X(null)},[M,se,E]),me=l.useCallback(te=>{F?F(te):$(),oe(null),Q(e)},[F,$,e]),fe=l.useCallback(te=>{A(),U==null||U(te)},[A,U]),Pe=l.useCallback(te=>{G(),N==null||N(te)},[G,N]),st=l.useCallback(async()=>{await k(),await(H==null?void 0:H())},[k,H]),Ae=l.useCallback(()=>{I(),j==null||j()},[I,j]),ye={onSendMessage:y,onEditMessage:h,onDeleteMessage:S,onReactToMessage:C,onPinMessage:d,onLoadMoreMessages:R,onMarkAsRead:T,onStartCall:Z,onEndCall:me,onMuteAudio:fe,onMuteVideo:Pe,onStartScreenShare:st,onStopScreenShare:Ae,onRaiseHand:b},he=ne?ne.participants.length>2?"conference":"call":q,Ot={width:"100%",height:"100%",position:"relative",...g};return n.jsxs("div",{id:w,"data-testid":V,className:`nice-communication nice-communication--${he}${B?` ${B}`:""}`,style:Ot,children:[se&&he!=="workspace"&&n.jsx(gn,{call:se,onAccept:ie,onDecline:ce}),he==="bubble"&&n.jsx(hn,{props:s,onExpand:ee}),he==="chat"&&r.length>0&&n.jsx(Re,{conversation:r[0],messages:a[r[0].id]??[],users:i,currentUser:t,...ye,style:{height:"100%"}}),he==="messenger"&&n.jsx(St,{conversations:r,messages:a,users:i,currentUser:t,teams:o,...ye,onAcceptCall:W,onDeclineCall:M,style:{height:"100%"}}),he==="workspace"&&n.jsx(It,{currentUser:t,users:i,teams:o,conversations:r,messages:a,meetings:c,activeCall:ne??void 0,incomingCall:se??void 0,transport:m,rtcConfig:f,enableCalls:!0,enableMeetings:J,enableScreenSharing:K,...ye,onAcceptCall:ie,onDeclineCall:ce,style:{height:"100%"}}),he==="call"&&ne&&n.jsx(Je,{session:ne,currentUser:t,localStream:le.localStream??void 0,enableScreenSharing:K,...ye,style:{height:"100%"}}),he==="conference"&&ne&&n.jsx(Qe,{session:ne,currentUser:t,localStream:le.localStream??void 0,enableScreenSharing:K,...ye,style:{height:"100%"}}),he==="whiteboard"&&P&&n.jsx(et,{session:Y??ae,currentUser:t,storageConfig:O,onSessionUpdate:te=>re(te),style:{height:"100%"}})]})}const mn={messages:"Messages",attachments:"Attachments","whiteboard-snapshots":"Whiteboard snapshots",recordings:"Recordings",transcripts:"Transcripts",documents:"Documents","call-logs":"Call logs","audit-logs":"Audit logs"},dt={none:"No encryption","AES-GCM-128":"AES-GCM 128-bit","AES-GCM-256":"AES-GCM 256-bit (recommended)","ChaCha20-Poly1305":"ChaCha20-Poly1305","E2E-ECDH-P384":"End-to-End ECDH P-384"},yn={messages:"Messages",attachments:"Attachments",whiteboard:"Whiteboard",recordings:"Recordings",documents:"Documents",calls:"Calls (metadata)",presence:"Presence data",all:"Everything"},xn=["days","weeks","months","years","forever"];function ut(s){if(s===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],i=Math.floor(Math.log(s)/Math.log(e));return`${(s/Math.pow(e,i)).toFixed(1)} ${t[i]}`}function pt({value:s,onChange:e,disabled:t=!1}){return n.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[n.jsx("input",{type:"number",min:1,max:9999,value:s.unit==="forever"?"":s.value,disabled:t||s.unit==="forever",onChange:i=>e({...s,value:Math.max(1,Number(i.target.value))}),style:{width:60,padding:"3px 6px",border:"1px solid #d1d5db",borderRadius:5,fontSize:12}}),n.jsx("select",{value:s.unit,disabled:t,onChange:i=>e({...s,unit:i.target.value}),style:{padding:"3px 6px",border:"1px solid #d1d5db",borderRadius:5,fontSize:12},children:xn.map(i=>n.jsx("option",{value:i,children:i},i))})]})}function bn({config:s,onChange:e}){const t=s.retentionRules.length>0?s.retentionRules:Ze;function i(r,a){const o=t.map(c=>c.dataType===r?{...c,...a}:c);e({...s,retentionRules:o})}return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[n.jsx("p",{style:{fontSize:12,color:"#6b7280",margin:0},children:"Configure how long each data type is retained before archiving and eventual deletion. Legal-hold prevents deletion regardless of retention rules."}),n.jsxs("div",{style:je,children:[n.jsx("label",{style:Ce,children:"Storage provider"}),n.jsxs("select",{value:s.provider,onChange:r=>e({...s,provider:r.target.value}),style:ve,children:[n.jsx("option",{value:"indexeddb",children:"IndexedDB (browser)"}),n.jsx("option",{value:"localstorage",children:"LocalStorage (browser)"}),n.jsx("option",{value:"server",children:"Server"}),n.jsx("option",{value:"custom",children:"Custom adapter"})]})]}),s.provider==="server"&&n.jsxs("div",{style:je,children:[n.jsx("label",{style:Ce,children:"Server URL"}),n.jsx("input",{type:"url",value:s.serverUrl??"",onChange:r=>e({...s,serverUrl:r.target.value}),placeholder:"https://your-api.example.com/storage",style:ve})]}),n.jsx("hr",{style:{border:"none",borderTop:"1px solid #e5e7eb",margin:"4px 0"}}),n.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12},children:[n.jsx("thead",{children:n.jsxs("tr",{style:{background:"#f9fafb"},children:[n.jsx("th",{style:we,children:"Data type"}),n.jsx("th",{style:we,children:"Active period"}),n.jsx("th",{style:we,children:"Archive after"}),n.jsx("th",{style:we,children:"Auto-delete"}),n.jsx("th",{style:we,children:"User can delete"}),n.jsx("th",{style:we,children:"Legal hold"})]})}),n.jsx("tbody",{children:t.map(r=>n.jsxs("tr",{style:{borderBottom:"1px solid #f3f4f6"},children:[n.jsx("td",{style:{...ke,fontWeight:500,color:"#374151"},children:mn[r.dataType]}),n.jsx("td",{style:ke,children:n.jsx(pt,{value:r.activePeriod,onChange:a=>i(r.dataType,{activePeriod:a})})}),n.jsx("td",{style:ke,children:r.archivePeriod?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx(pt,{value:r.archivePeriod,onChange:a=>i(r.dataType,{archivePeriod:a})}),n.jsx("button",{onClick:()=>i(r.dataType,{archivePeriod:void 0}),style:{border:"none",background:"none",cursor:"pointer",color:"#ef4444",fontSize:14},title:"Remove archive period",children:"ร"})]}):n.jsx("button",{onClick:()=>i(r.dataType,{archivePeriod:{value:1,unit:"years"}}),style:{fontSize:11,padding:"2px 8px",border:"1px dashed #d1d5db",borderRadius:4,cursor:"pointer",background:"none",color:"#6b7280"},children:"+ Add"})}),n.jsx("td",{style:{...ke,textAlign:"center"},children:n.jsx("input",{type:"checkbox",checked:r.deleteAfterArchive,disabled:!r.archivePeriod,onChange:a=>i(r.dataType,{deleteAfterArchive:a.target.checked})})}),n.jsx("td",{style:{...ke,textAlign:"center"},children:n.jsx("input",{type:"checkbox",checked:r.userCanDelete,onChange:a=>i(r.dataType,{userCanDelete:a.target.checked})})}),n.jsx("td",{style:{...ke,textAlign:"center"},children:n.jsx("input",{type:"checkbox",checked:r.legalHoldEnabled??!1,onChange:a=>i(r.dataType,{legalHoldEnabled:a.target.checked})})})]},r.dataType))})]}),n.jsxs("div",{style:je,children:[n.jsx("label",{style:Ce,children:"Storage quota"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx("input",{type:"number",min:0,value:s.quota?Math.round(s.quota/1024/1024):0,onChange:r=>e({...s,quota:Number(r.target.value)*1024*1024}),style:{...ve,width:90},placeholder:"0"}),n.jsx("span",{style:{fontSize:12,color:"#6b7280"},children:"MB (0 = unlimited)"})]})]})]})}function vn({config:s,onChange:e}){const t=["messages","attachments","whiteboard","recordings","documents","calls","presence"];return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[n.jsx("p",{style:{fontSize:12,color:"#6b7280",margin:0},children:"Configure encryption at rest and in transit. E2E-ECDH ensures only participants can read conversations โ the server never sees plaintext."}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsxs("label",{style:{position:"relative",display:"inline-block",width:42,height:22},children:[n.jsx("input",{type:"checkbox",checked:s.enabled,onChange:i=>e({...s,enabled:i.target.checked}),style:{opacity:0,width:0,height:0}}),n.jsx("span",{style:{position:"absolute",inset:0,borderRadius:22,background:s.enabled?"#6366f1":"#d1d5db",transition:"background 0.2s",cursor:"pointer"},children:n.jsx("span",{style:{position:"absolute",width:16,height:16,top:3,left:s.enabled?23:3,background:"#fff",borderRadius:"50%",transition:"left 0.2s"}})})]}),n.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#374151"},children:s.enabled?"๐ Encryption enabled":"๐ Encryption disabled"})]}),s.enabled&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:je,children:[n.jsx("label",{style:Ce,children:"Default algorithm"}),n.jsx("select",{value:s.defaultAlgorithm,onChange:i=>e({...s,defaultAlgorithm:i.target.value}),style:ve,children:Object.entries(dt).map(([i,r])=>n.jsx("option",{value:i,children:r},i))})]}),s.defaultAlgorithm==="E2E-ECDH-P384"&&n.jsxs("div",{style:je,children:[n.jsx("label",{style:Ce,children:"Key exchange URL"}),n.jsx("input",{type:"url",value:s.keyExchangeUrl??"",onChange:i=>e({...s,keyExchangeUrl:i.target.value}),placeholder:"wss://your-server/e2e-key-exchange",style:ve}),n.jsx("span",{style:{fontSize:11,color:"#6b7280",marginTop:2},children:"WebSocket endpoint for ECDH public key exchange between participants."})]}),n.jsxs("div",{style:je,children:[n.jsx("label",{style:Ce,children:"External key (base64, optional)"}),n.jsx("input",{type:"password",value:s.keyMaterial??"",onChange:i=>e({...s,keyMaterial:i.target.value||void 0}),placeholder:"Leave empty to auto-generate",style:ve}),n.jsx("span",{style:{fontSize:11,color:"#6b7280",marginTop:2},children:"Provide a pre-shared key for symmetric algorithms. Leave empty for automatic key generation."})]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:s.showIndicator??!0,onChange:i=>e({...s,showIndicator:i.target.checked})}),n.jsx("span",{style:{fontSize:12,color:"#374151"},children:"Show lock indicator in messages"})]}),n.jsx("hr",{style:{border:"none",borderTop:"1px solid #e5e7eb",margin:"4px 0"}}),n.jsx("strong",{style:{fontSize:12,color:"#374151"},children:"Per-scope overrides"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:t.map(i=>{var c;const r=(c=s.scopeOverrides)==null?void 0:c.find(p=>p.scope===i),a=(r==null?void 0:r.enabled)??!1,o=(r==null?void 0:r.algorithm)??s.defaultAlgorithm;return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 8px",background:"#f9fafb",borderRadius:6},children:[n.jsx("input",{type:"checkbox",checked:a,onChange:p=>{const u=[...(s.scopeOverrides??[]).filter(m=>m.scope!==i),{scope:i,algorithm:o,enabled:p.target.checked}];e({...s,scopeOverrides:u})}}),n.jsx("span",{style:{minWidth:120,fontSize:12,color:"#374151"},children:yn[i]}),n.jsx("select",{value:o,disabled:!a,onChange:p=>{const u=[...(s.scopeOverrides??[]).filter(m=>m.scope!==i),{scope:i,algorithm:p.target.value,enabled:a}];e({...s,scopeOverrides:u})},style:{...ve,flex:1,opacity:a?1:.4},children:Object.entries(dt).map(([p,u])=>n.jsx("option",{value:p,children:u},p))})]},i)})})]})]})}function Sn({storageConfig:s,encryptionConfig:e,onStorageConfigChange:t,onEncryptionConfigChange:i,currentUsageBytes:r=0,showEncryption:a=!0,showRetention:o=!0,showQuota:c=!0,className:p,style:u,"data-testid":m}){const[f,y]=l.useState("retention"),h=e??{enabled:!1,defaultAlgorithm:"AES-GCM-256",showIndicator:!0},S={...s,retentionRules:s.retentionRules.length>0?s.retentionRules:Ze};return n.jsxs("div",{className:p,"data-testid":m,style:{display:"flex",flexDirection:"column",gap:16,padding:20,background:"#fff",borderRadius:10,border:"1px solid #e5e7eb",fontFamily:"system-ui, sans-serif",maxWidth:800,...u},children:[n.jsxs("div",{children:[n.jsx("h3",{style:{margin:0,fontSize:16,color:"#111827"},children:"Storage & Privacy"}),n.jsx("p",{style:{margin:"4px 0 0",fontSize:12,color:"#6b7280"},children:"Manage data retention, encryption, and storage settings."})]}),c&&s.quota&&s.quota>0&&n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:12,color:"#6b7280",marginBottom:4},children:[n.jsx("span",{children:"Storage used"}),n.jsxs("span",{children:[ut(r)," / ",ut(s.quota)]})]}),n.jsx("div",{style:{height:6,background:"#e5e7eb",borderRadius:3},children:n.jsx("div",{style:{width:`${Math.min(100,r/s.quota*100)}%`,height:"100%",background:r/s.quota>.9?"#ef4444":"#6366f1",borderRadius:3,transition:"width 0.3s"}})})]}),o&&a&&n.jsx("div",{style:{display:"flex",gap:0,borderBottom:"1px solid #e5e7eb"},children:["retention","encryption"].map(C=>n.jsx("button",{onClick:()=>y(C),style:{padding:"8px 18px",border:"none",borderBottom:`2px solid ${f===C?"#6366f1":"transparent"}`,background:"none",cursor:"pointer",fontSize:13,fontWeight:f===C?600:400,color:f===C?"#4f46e5":"#6b7280",marginBottom:-1},children:C==="retention"?"๐ฆ Retention":"๐ Encryption"},C))}),n.jsxs("div",{children:[(f==="retention"||!a)&&o&&n.jsx(bn,{config:S,onChange:t??(()=>{})}),(f==="encryption"||!o)&&a&&n.jsx(vn,{config:h,onChange:i??(()=>{})})]})]})}const je={display:"flex",flexDirection:"column",gap:4},Ce={fontSize:12,fontWeight:500,color:"#374151"},ve={padding:"6px 8px",border:"1px solid #d1d5db",borderRadius:6,fontSize:13,color:"#111827",background:"#fff"},we={padding:"6px 8px",textAlign:"left",fontSize:11,fontWeight:600,color:"#6b7280",borderBottom:"1px solid #e5e7eb"},ke={padding:"8px 8px",verticalAlign:"middle"};function Oe(s){const e=Math.floor(s/1e3),t=Math.floor(e/60),i=Math.floor(t/60);return i>0?`${i}:${String(t%60).padStart(2,"0")}:${String(e%60).padStart(2,"0")}`:`${String(t).padStart(2,"0")}:${String(e%60).padStart(2,"0")}`}function wn(s){if(s===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],i=Math.floor(Math.log(s)/Math.log(e));return`${(s/Math.pow(e,i)).toFixed(1)} ${t[i]}`}function kn(s){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(s))}const jn={idle:{label:"Idle",bg:"#f3f4f6",fg:"#6b7280"},recording:{label:"โ Recording",bg:"#fee2e2",fg:"#dc2626"},paused:{label:"โ Paused",bg:"#fef3c7",fg:"#d97706"},processing:{label:"โ Processing",bg:"#ede9fe",fg:"#7c3aed"},ready:{label:"โ Ready",bg:"#dcfce7",fg:"#16a34a"},failed:{label:"โ Failed",bg:"#fee2e2",fg:"#dc2626"}};function Cn({segments:s,onClose:e,currentTimeMs:t=0}){return n.jsx("div",{style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsxs("div",{style:{background:"#fff",borderRadius:12,width:"90%",maxWidth:640,maxHeight:"80vh",display:"flex",flexDirection:"column",boxShadow:"0 20px 40px rgba(0,0,0,0.2)",overflow:"hidden"},children:[n.jsxs("div",{style:{padding:"14px 18px",borderBottom:"1px solid #e5e7eb",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("strong",{style:{fontSize:14,color:"#111827"},children:"Transcript"}),n.jsx("button",{onClick:e,style:zn,children:"โ"})]}),n.jsx("div",{style:{flex:1,overflowY:"auto",padding:"12px 18px"},children:s.length===0?n.jsx("p",{style:{fontSize:13,color:"#9ca3af",textAlign:"center",padding:"32px 0"},children:"No transcript available."}):s.map(i=>{const r=t>=i.startMs&&t<i.endMs;return n.jsxs("div",{style:{marginBottom:12,padding:"8px 10px",borderRadius:6,background:r?"#eff6ff":"transparent",borderLeft:`3px solid ${r?"#3b82f6":"transparent"}`,transition:"background 0.2s"},children:[n.jsxs("div",{style:{display:"flex",gap:10,alignItems:"baseline",marginBottom:3},children:[n.jsx("span",{style:{fontSize:11,fontWeight:600,color:"#4f46e5"},children:i.speakerName}),n.jsxs("span",{style:{fontSize:10,color:"#9ca3af"},children:[Oe(i.startMs)," โ ",Oe(i.endMs)]}),n.jsxs("span",{style:{fontSize:10,color:"#d1d5db"},children:[Math.round(i.confidence*100),"% conf."]})]}),n.jsx("p",{style:{margin:0,fontSize:13,color:"#374151",lineHeight:1.5},children:i.text})]},i.id)})})]})})}function zt({startedAt:s}){const[e,t]=l.useState(0);return l.useEffect(()=>{const i=new Date(s).getTime(),r=setInterval(()=>t(Date.now()-i),500);return()=>clearInterval(r)},[s]),n.jsx(n.Fragment,{children:Oe(e)})}function In({rec:s,onDelete:e,onDownload:t}){const[i,r]=l.useState(!1),[a,o]=l.useState(0),c=l.useRef(null),p=jn[s.state],u=s.state==="recording"||s.state==="paused";return n.jsxs(n.Fragment,{children:[i&&s.transcript&&n.jsx(Cn,{segments:s.transcript,currentTimeMs:a,onClose:()=>r(!1)}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 12px",borderBottom:"1px solid #f3f4f6",flexWrap:"wrap"},children:[n.jsx("div",{style:{fontSize:20},children:s.sessionType==="call"?"๐":s.sessionType==="meeting"?"๐ฅ":s.sessionType==="whiteboard"?"๐ผ๏ธ":"๐ฅ๏ธ"}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.title??`Recording ${s.id.slice(0,8)}`}),n.jsxs("div",{style:{fontSize:11,color:"#9ca3af",marginTop:2,display:"flex",gap:8},children:[n.jsx("span",{children:kn(s.startedAt)}),n.jsx("span",{children:u?n.jsx(zt,{startedAt:s.startedAt}):s.durationMs!=null?Oe(s.durationMs):"โ"}),s.size!=null&&n.jsx("span",{children:wn(s.size)}),n.jsxs("span",{children:[s.participants.length," participants"]})]})]}),n.jsx("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:20,background:p.bg,color:p.fg,fontWeight:500,whiteSpace:"nowrap"},children:p.label}),s.url&&s.state==="ready"&&n.jsx("audio",{ref:c,src:s.url,controls:!0,onTimeUpdate:()=>{c.current&&o(c.current.currentTime*1e3)},style:{height:32,maxWidth:180}}),n.jsxs("div",{style:{display:"flex",gap:4},children:[s.transcript&&s.transcript.length>0&&n.jsx("button",{onClick:()=>r(!0),style:Be,title:"View transcript",children:"๐"}),s.state==="ready"&&n.jsx("button",{onClick:()=>t(s),style:Be,title:"Download",children:"โฌ"}),n.jsx("button",{onClick:()=>e(s.id),style:{...Be,color:"#ef4444"},title:"Delete",children:"๐"})]})]})]})}function Tn({recordings:s,onRecordingStart:e,onRecordingStop:t,onRecordingPause:i,onRecordingResume:r,onRecordingDelete:a,onRecordingDownload:o,activeRecordingId:c,sessionType:p="meeting",className:u,style:m,"data-testid":f}){const[y,h]=l.useState(s??[]),[S,C]=l.useState(""),[d,R]=l.useState("all");l.useEffect(()=>{s&&h(s)},[s]);const T=y.find(N=>N.id===c),D=(T==null?void 0:T.state)==="recording",W=(T==null?void 0:T.state)==="paused",M=y.filter(N=>{const H=d==="all"||N.sessionType===d,j=!S||(N.title??"").toLowerCase().includes(S.toLowerCase())||N.id.includes(S);return H&&j}),F=l.useCallback(N=>{h(H=>H.filter(j=>j.id!==N)),a==null||a(N)},[a]),U=l.useCallback(N=>{if(o){o(N.id);return}if(N.url){const H=document.createElement("a");H.href=N.url,H.download=`${N.title??N.id}.${N.mimeType.includes("mp4")?"mp4":"webm"}`,H.click()}else if(N.blob){const H=URL.createObjectURL(N.blob),j=document.createElement("a");j.href=H,j.download=`${N.title??N.id}.webm`,j.click(),setTimeout(()=>URL.revokeObjectURL(H),5e3)}},[o]);return n.jsxs("div",{className:u,"data-testid":f,style:{display:"flex",flexDirection:"column",background:"#fff",borderRadius:10,border:"1px solid #e5e7eb",fontFamily:"system-ui, sans-serif",overflow:"hidden",...m},children:[n.jsxs("div",{style:{padding:"14px 16px",borderBottom:"1px solid #e5e7eb",display:"flex",gap:8,alignItems:"center"},children:[n.jsx("span",{style:{fontSize:16},children:"๐๏ธ"}),n.jsx("strong",{style:{fontSize:14,color:"#111827",flex:1},children:"Recordings"}),n.jsxs("span",{style:{fontSize:12,color:"#9ca3af"},children:[y.length," total"]})]}),n.jsxs("div",{style:{padding:"12px 16px",borderBottom:"1px solid #f3f4f6",display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[n.jsxs("select",{value:p,disabled:D||W,onChange:()=>{},style:{...ft,flex:0},children:[n.jsx("option",{value:"call",children:"Call"}),n.jsx("option",{value:"meeting",children:"Meeting"}),n.jsx("option",{value:"whiteboard",children:"Whiteboard"}),n.jsx("option",{value:"screen",children:"Screen"})]}),!D&&!W?n.jsx("button",{onClick:e,style:{...De,background:"#ef4444",color:"#fff"},children:"โ Start recording"}):n.jsxs(n.Fragment,{children:[W?n.jsx("button",{onClick:r,style:{...De,background:"#6366f1",color:"#fff"},children:"โถ Resume"}):n.jsx("button",{onClick:i,style:{...De,background:"#f59e0b",color:"#fff"},children:"โ Pause"}),n.jsx("button",{onClick:t,style:{...De,background:"#374151",color:"#fff"},children:"โ Stop"}),T&&n.jsx("span",{style:{fontSize:12,color:"#9ca3af",marginLeft:4},children:n.jsx(zt,{startedAt:T.startedAt})})]})]}),n.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid #f3f4f6",display:"flex",gap:6,alignItems:"center"},children:[n.jsx("input",{type:"search",value:S,onChange:N=>C(N.target.value),placeholder:"Search recordingsโฆ",style:{flex:1,padding:"4px 8px",border:"1px solid #e5e7eb",borderRadius:6,fontSize:12}}),n.jsxs("select",{value:d,onChange:N=>R(N.target.value),style:ft,children:[n.jsx("option",{value:"all",children:"All types"}),n.jsx("option",{value:"call",children:"Calls"}),n.jsx("option",{value:"meeting",children:"Meetings"}),n.jsx("option",{value:"whiteboard",children:"Whiteboard"}),n.jsx("option",{value:"screen",children:"Screen"})]})]}),n.jsx("div",{style:{flex:1,overflowY:"auto"},children:M.length===0?n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:32,gap:8,color:"#9ca3af"},children:[n.jsx("span",{style:{fontSize:32},children:"๐๏ธ"}),n.jsx("span",{style:{fontSize:13},children:"No recordings found"}),n.jsx("span",{style:{fontSize:11},children:"Start a recording above or adjust your search filters."})]}):M.map(N=>n.jsx(In,{rec:N,onDelete:F,onDownload:U},N.id))})]})}const Be={border:"1px solid #e5e7eb",borderRadius:6,background:"#fff",cursor:"pointer",padding:"4px 8px",fontSize:14,lineHeight:1},De={border:"none",borderRadius:6,cursor:"pointer",padding:"6px 14px",fontSize:12,fontWeight:500},ft={padding:"4px 6px",border:"1px solid #e5e7eb",borderRadius:6,fontSize:12,color:"#374151",background:"#fff"},zn={border:"none",background:"none",cursor:"pointer",fontSize:16,color:"#9ca3af",lineHeight:1,padding:4};function ht({participant:s,isFollowing:e,onClick:t}){const i=s.user.displayName??s.user.name,r=i.split(" ").map(a=>a[0]).slice(0,2).join("").toUpperCase();return n.jsxs("button",{onClick:t,title:`${i}${e?" (following)":""} โ ${s.editingRegion??"viewing"}`,style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:"50%",background:s.color,color:"#fff",fontSize:11,fontWeight:600,border:`2px solid ${e?"#fff":s.color}`,boxShadow:e?`0 0 0 2px ${s.color}`:"none",cursor:"pointer",flexShrink:0,transition:"transform 0.15s",position:"relative",overflow:"visible"},children:[s.user.avatarUrl?n.jsx("img",{src:s.user.avatarUrl,alt:r,style:{width:"100%",height:"100%",borderRadius:"50%",objectFit:"cover"}}):r,s.isActive&&n.jsx("span",{style:{position:"absolute",bottom:-1,right:-1,width:9,height:9,borderRadius:"50%",background:"#22c55e",border:"2px solid #fff"}})]})}function Rn({participant:s,containerRect:e}){if(!s.cursorX||!s.cursorY||!e)return null;const t=s.cursorX,i=s.cursorY;return n.jsxs("div",{style:{position:"absolute",left:t,top:i,pointerEvents:"none",zIndex:9e3,transform:"translate(-2px, -2px)"},children:[n.jsx("svg",{width:16,height:20,style:{display:"block"},children:n.jsx("path",{d:"M2 2 L2 16 L6 12 L10 18 L12 17 L8 11 L14 11 Z",fill:s.color,stroke:"#fff",strokeWidth:1.5})}),n.jsx("div",{style:{background:s.color,color:"#fff",fontSize:10,padding:"1px 5px",borderRadius:3,whiteSpace:"nowrap",marginTop:-2,marginLeft:10},children:s.user.displayName??s.user.name})]})}function Pn({count:s}){return s===0?null:n.jsxs("div",{style:{position:"absolute",top:8,left:"50%",transform:"translateX(-50%)",zIndex:8e3,background:"#fef3c7",border:"1px solid #fbbf24",borderRadius:6,padding:"4px 12px",fontSize:12,color:"#92400e",display:"flex",alignItems:"center",gap:6,boxShadow:"0 2px 8px rgba(0,0,0,0.1)",pointerEvents:"none"},children:["โ ๏ธ ",s," edit conflict",s>1?"s":""," โ auto-mergingโฆ"]})}function An(){return n.jsx("div",{style:{position:"absolute",inset:0,zIndex:7e3,background:"rgba(0,0,0,0.03)",cursor:"not-allowed",display:"flex",alignItems:"flex-end",justifyContent:"center",paddingBottom:12,pointerEvents:"none"},children:n.jsx("div",{style:{background:"rgba(0,0,0,0.6)",color:"#fff",fontSize:12,padding:"4px 14px",borderRadius:20},children:"๐๏ธ View only"})})}function En({pending:s}){return s===0?n.jsx("span",{style:{fontSize:11,color:"#22c55e"},children:"โ Synced"}):n.jsxs("span",{style:{fontSize:11,color:"#f59e0b"},children:["โ ",s," pendingโฆ"]})}function Dn({participant:s,isFollowing:e,onClick:t}){return n.jsxs("button",{onClick:t,style:{fontSize:11,padding:"2px 8px",border:`1px solid ${e?s.color:"#e5e7eb"}`,borderRadius:20,background:e?s.color:"#fff",color:e?"#fff":"#6b7280",cursor:"pointer",display:"flex",alignItems:"center",gap:4},children:["๐ ",e?"Unfollow":`Follow ${(s.user.displayName??s.user.name).split(" ")[0]}`]})}function Mn({editorType:s,sessionId:e,currentUser:t,participants:i=[],onOperation:r,onParticipantJoin:a,onParticipantLeave:o,onCursorMove:c,isReadOnly:p=!1,showParticipants:u=!0,showCursors:m=!0,pendingOperations:f=0,conflictCount:y=0,className:h,style:S,children:C,"data-testid":d}){const R=l.useRef(null),[T,D]=l.useState(null),[W,M]=l.useState(null),[F,U]=l.useState(!1);l.useEffect(()=>{const b=R.current;if(!b)return;const z=new ResizeObserver(()=>D(b.getBoundingClientRect()));return z.observe(b),D(b.getBoundingClientRect()),()=>z.disconnect()},[]);const N=l.useCallback(b=>{if(!R.current||!c)return;const z=R.current.getBoundingClientRect();c(b.clientX-z.left,b.clientY-z.top)},[c]),H=l.useCallback(b=>{M(z=>z===b?null:b)},[]),j={vector:"โ๏ธ Vector",pixel:"๐ผ๏ธ Pixel",diagram:"๐ Diagram",document:"๐ Document",whiteboard:"๐๏ธ Whiteboard"};return n.jsxs("div",{className:h,"data-testid":d,style:{display:"flex",flexDirection:"column",background:"#fff",borderRadius:8,border:"1px solid #e5e7eb",overflow:"hidden",fontFamily:"system-ui, sans-serif",...S},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid #f3f4f6",background:"#f9fafb",minHeight:40},children:[n.jsx("span",{style:{fontSize:12,color:"#6b7280",fontWeight:500},children:j[s]}),n.jsx("span",{style:{flex:1}}),n.jsx(En,{pending:f}),u&&i.length>0&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:-4},children:[i.slice(0,5).map((b,z)=>n.jsx("div",{style:{marginLeft:z>0?-8:0,zIndex:10-z},children:n.jsx(ht,{participant:b,isFollowing:W===b.user.id,onClick:()=>{U(!0),H(b.user.id)}})},b.user.id)),i.length>5&&n.jsxs("button",{onClick:()=>U(!F),style:{marginLeft:-4,zIndex:5,width:30,height:30,borderRadius:"50%",background:"#e5e7eb",border:"2px solid #fff",fontSize:10,fontWeight:600,color:"#374151",cursor:"pointer"},children:["+",i.length-5]})]}),u&&i.length>0&&n.jsxs("button",{onClick:()=>U(!F),style:{border:"1px solid #e5e7eb",borderRadius:5,background:F?"#eff6ff":"#fff",padding:"3px 8px",cursor:"pointer",fontSize:11,color:F?"#3b82f6":"#6b7280"},children:[i.length," online"]})]}),n.jsxs("div",{style:{display:"flex",flex:1,overflow:"hidden",position:"relative"},children:[n.jsxs("div",{ref:R,onMouseMove:N,style:{flex:1,position:"relative",overflow:"hidden"},children:[C??n.jsxs("div",{id:`collab-editor-${s}-${e}`,style:{width:"100%",height:"100%",minHeight:400,display:"flex",alignItems:"center",justifyContent:"center",background:"#f9fafb",color:"#9ca3af",fontSize:13},children:["Drop your ",s," editor here or use the"," ",n.jsx("code",{style:{background:"#e5e7eb",padding:"1px 5px",borderRadius:3,margin:"0 4px"},children:`#collab-editor-${s}-${e}`})," ","mount point."]}),m&&i.filter(b=>b.user.id!==t.id&&b.cursorX!=null&&b.cursorY!=null).map(b=>n.jsx(Rn,{participant:b,containerRect:T},b.user.id)),n.jsx(Pn,{count:y}),p&&n.jsx(An,{})]}),F&&i.length>0&&n.jsxs("div",{style:{width:220,borderLeft:"1px solid #e5e7eb",background:"#f9fafb",overflowY:"auto",padding:10,display:"flex",flexDirection:"column",gap:8},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[n.jsx("strong",{style:{fontSize:12,color:"#374151"},children:"Participants"}),n.jsx("button",{onClick:()=>U(!1),style:{border:"none",background:"none",cursor:"pointer",color:"#9ca3af",fontSize:14},children:"โ"})]}),i.map(b=>n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"8px",borderRadius:6,background:"#fff",border:"1px solid #f3f4f6"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx(ht,{participant:b,isFollowing:W===b.user.id,onClick:()=>H(b.user.id)}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontSize:12,fontWeight:500,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.user.displayName??b.user.name}),n.jsx("div",{style:{fontSize:10,color:"#9ca3af"},children:b.editingRegion??"viewing"})]})]}),b.user.id!==t.id&&n.jsx(Dn,{participant:b,isFollowing:W===b.user.id,onClick:()=>H(b.user.id)})]},b.user.id))]})]})]})}function tt(s){let e="";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return btoa(e)}function nt(s){const e=atob(s),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}function Nn(s){return new TextEncoder().encode(s)}function $n(s){return new TextDecoder().decode(s)}async function On(s){return crypto.subtle.generateKey({name:"AES-GCM",length:s},!0,["encrypt","decrypt"])}async function Ln(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-384"},!0,["deriveKey"])}async function Wn(s,e){return crypto.subtle.deriveKey({name:"ECDH",public:e},s,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Fn(s,e){const t=crypto.getRandomValues(new Uint8Array(12)),i=Nn(e),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},s,i),a=new Uint8Array(r),o=new Uint8Array(12+a.length);return o.set(t,0),o.set(a,12),tt(o)}async function _n(s,e){const t=nt(e),i=t.slice(0,12),r=t.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},s,r);return $n(new Uint8Array(a))}async function gt(s,e){const t=nt(s);return crypto.subtle.importKey("raw",t,{name:"AES-GCM",length:e},!1,["encrypt","decrypt"])}async function Bn(s){const e=await crypto.subtle.exportKey("raw",s);return tt(new Uint8Array(e))}async function Un(s){const e=await crypto.subtle.exportKey("spki",s);return tt(new Uint8Array(e))}async function Hn(s){const e=nt(s);return crypto.subtle.importKey("spki",e,{name:"ECDH",namedCurve:"P-384"},!0,[])}class Rt{constructor(e){this.keys={},this.ready=!1,this.config=e}async init(){if(!this.config.enabled){this.ready=!0;return}const e=this.config.defaultAlgorithm;if(this.config.keyMaterial)e==="AES-GCM-128"?this.keys.aes128=await gt(this.config.keyMaterial,128):this.keys.aes256=await gt(this.config.keyMaterial,256);else if(e==="AES-GCM-256"||e==="AES-GCM-128"){const t=e==="AES-GCM-256"?256:128,i=await On(t);t===128?this.keys.aes128=i:this.keys.aes256=i}else if(e==="E2E-ECDH-P384"){const t=await Ln();this.keys.ecdhPrivate=t.privateKey,this.keys.ecdhPublic=t.publicKey,this.keys.ecdhSessionKeys=new Map}this.ready=!0}async getPublicKeyForPeer(){return this.keys.ecdhPublic?Un(this.keys.ecdhPublic):null}async registerPeerPublicKey(e,t){var a;if(!this.keys.ecdhPrivate)return;const i=await Hn(t),r=await Wn(this.keys.ecdhPrivate,i);(a=this.keys.ecdhSessionKeys)==null||a.set(e,r)}resolveAlgorithm(e){if(e&&this.config.scopeOverrides){const t=this.config.scopeOverrides.find(i=>(i.scope===e||i.scope==="all")&&i.enabled);if(t)return t.algorithm}return this.config.defaultAlgorithm}getKey(e,t){var i;switch(e){case"AES-GCM-256":return this.keys.aes256??null;case"AES-GCM-128":return this.keys.aes128??null;case"E2E-ECDH-P384":return t?((i=this.keys.ecdhSessionKeys)==null?void 0:i.get(t))??null:null;default:return null}}async encrypt(e,t,i){if(!this.config.enabled)return e;if(!this.ready)throw new Error("EncryptionService not initialised โ call init() first");const r=this.resolveAlgorithm(t);if(r==="none")return e;const a=this.getKey(r,i);return a?Fn(a,e):(console.warn(`EncryptionService: no key found for algorithm "${r}" โ returning plaintext`),e)}async decrypt(e,t,i){if(!this.config.enabled)return e;if(!this.ready)throw new Error("EncryptionService not initialised โ call init() first");const r=this.resolveAlgorithm(t);if(r==="none")return e;const a=this.getKey(r,i);return a?_n(a,e):(console.warn(`EncryptionService: no key found for algorithm "${r}" โ returning as-is`),e)}async exportSymmetricKey(e){const t=e??this.config.defaultAlgorithm,i=this.getKey(t);return i?Bn(i):null}isEnabled(){return this.config.enabled}getConfig(){return this.config}updateConfig(e){this.config=e,this.ready=!1}}const Ne=new Map;function Kn(s,e){return Ne.has(s)||Ne.set(s,new Rt(e)),Ne.get(s)}function Yn(s){Ne.delete(s)}class Pt{constructor(e={}){this.recorder=null,this.chunks=[],this.session=null,this.recognition=null,this.segmentCounter=0,this.callbacks=e}start(e,t){var c,p,u;if(((c=this.recorder)==null?void 0:c.state)==="recording")throw new Error("Recording already in progress");const i=t.mimeType??this.chooseMimeType(),r=new MediaRecorder(e,{mimeType:i});this.chunks=[];const a=new Date,o=`rec_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return this.session={id:o,sessionType:t.sessionType,startedAt:a,state:"recording",mimeType:i,participants:[t.speakerId??"unknown"],title:t.title??`Recording ${a.toLocaleString()}`},r.ondataavailable=m=>{m.data&&m.data.size>0&&this.chunks.push(m.data)},r.onstop=()=>{var f,y,h,S;const m=new Blob(this.chunks,{type:i});this.session&&(this.session.blob=m,this.session.endedAt=new Date,this.session.durationMs=this.session.endedAt.getTime()-this.session.startedAt.getTime(),this.session.size=m.size,this.session.state="ready"),(y=(f=this.callbacks).onDataAvailable)==null||y.call(f,m),(S=(h=this.callbacks).onStateChange)==null||S.call(h,"ready")},r.onerror=m=>{var f,y,h,S;(y=(f=this.callbacks).onError)==null||y.call(f,new Error(String(m))),this.session&&(this.session.state="failed"),(S=(h=this.callbacks).onStateChange)==null||S.call(h,"failed")},r.start(t.timesliceMs??1e3),this.recorder=r,t.transcribe&&this.startTranscription(t.speakerId??"unknown",t.speakerName??"Participant"),(u=(p=this.callbacks).onStateChange)==null||u.call(p,"recording"),this.session}pause(){var e,t,i;((e=this.recorder)==null?void 0:e.state)==="recording"&&(this.recorder.pause(),this.session&&(this.session.state="paused"),(i=(t=this.callbacks).onStateChange)==null||i.call(t,"paused"))}resume(){var e,t,i;((e=this.recorder)==null?void 0:e.state)==="paused"&&(this.recorder.resume(),this.session&&(this.session.state="recording"),(i=(t=this.callbacks).onStateChange)==null||i.call(t,"recording"))}stop(){var e,t;return this.stopTranscription(),this.recorder&&this.recorder.state!=="inactive"&&(this.recorder.stop(),this.session&&(this.session.state="processing"),(t=(e=this.callbacks).onStateChange)==null||t.call(e,"processing")),this.session}startTranscription(e,t){const i=window.SpeechRecognition??window.webkitSpeechRecognition;if(!i)return;const r=new i;r.continuous=!0,r.interimResults=!1,r.lang="en-US";const a=Date.now();r.onresult=o=>{var p,u;const c=o.results;for(let m=o.resultIndex;m<c.length;m++){const f=c[m];if(!f.isFinal)continue;const y=f[0],h=Date.now(),S={id:`seg_${++this.segmentCounter}`,speakerId:e,speakerName:t,text:y.transcript.trim(),startMs:h-a-1500,endMs:h-a,confidence:y.confidence??.9};this.session&&(this.session.transcript=[...this.session.transcript??[],S]),(u=(p=this.callbacks).onTranscriptSegment)==null||u.call(p,S)}},r.onerror=()=>{};try{r.start(),this.recognition=r}catch{}}stopTranscription(){var e;try{(e=this.recognition)==null||e.stop()}catch{}this.recognition=null}chooseMimeType(){const e=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm","audio/webm;codecs=opus","audio/ogg;codecs=opus"];for(const t of e)if(MediaRecorder.isTypeSupported(t))return t;return""}getState(){var e;return((e=this.session)==null?void 0:e.state)??"idle"}getSession(){return this.session}download(e){var a,o;const t=(a=this.session)==null?void 0:a.blob;if(!t)return;const i=URL.createObjectURL(t),r=document.createElement("a");r.href=i,r.download=e??`${((o=this.session)==null?void 0:o.title)??"recording"}.webm`,r.click(),setTimeout(()=>URL.revokeObjectURL(i),3e4)}}const $e=new Map;function Gn(s,e){return $e.has(s)||$e.set(s,new Pt(e)),$e.get(s)}function qn(s){$e.delete(s)}class At{constructor(e){this.events=[],this.eventListeners=new Map,this.config={serverUrl:e.serverUrl,apiKey:e.apiKey??"",anonymizeIp:e.anonymizeIp??!0,enableGeoLocation:e.enableGeoLocation??!1,pixelPath:e.pixelPath??"/pixel",redirectPath:e.redirectPath??"/redirect",hashAlgorithm:e.hashAlgorithm??"sha256"}}generateTrackingPixel(e){const t=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,metadata:e.metadata}),i=e.width??1,r=e.height??1,a=`${this.config.serverUrl}${this.config.pixelPath}?${t}`;return`<img src="${this.escapeHtml(a)}" width="${i}" height="${r}" alt="" style="display:block;width:${i}px;height:${r}px;border:0;" />`}generateTrackingPixelUrl(e){const t=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,metadata:e.metadata});return`${this.config.serverUrl}${this.config.pixelPath}?${t}`}wrapLink(e){const t=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,url:e.url,linkName:e.linkName});return`${this.config.serverUrl}${this.config.redirectPath}?${t}`}wrapLinksForTracking(e,t){const i=t.excludePatterns??[/^mailto:/i,/^tel:/i,/^#/,/unsubscribe/i],r=/<a\s+([^>]*?)href=["']([^"']+)["']([^>]*?)>/gi;return e.replace(r,(a,o,c,p)=>{if(i.some(y=>y.test(c)))return a;const m=this.extractLinkName(o+p)??c,f=this.wrapLink({url:c,messageId:t.messageId,recipientId:t.recipientId,campaignId:t.campaignId,linkName:m});return`<a ${o}href="${this.escapeHtml(f)}"${p}>`})}recordEvent(e){const t={...e,id:this.generateEventId(),timestamp:new Date,ipAddress:this.config.anonymizeIp?this.anonymizeIpAddress(e.ipAddress):e.ipAddress};return this.events.push(t),this.notifyListeners(t),t}parseTrackingParams(e){const t=e.get("mid"),i=e.get("rid");if(!t||!i)return null;const r={};return e.forEach((a,o)=>{o.startsWith("m_")&&(r[o.substring(2)]=a)}),{messageId:t,recipientHash:i,campaignId:e.get("cid")??void 0,url:e.get("url")??void 0,linkName:e.get("ln")??void 0,metadata:Object.keys(r).length>0?r:void 0}}getStats(e){let t=this.events;e&&(t=this.events.filter(y=>!(e.campaignId&&y.campaignId!==e.campaignId||e.messageId&&y.messageId!==e.messageId||e.startDate&&y.timestamp<e.startDate||e.endDate&&y.timestamp>e.endDate)));const i=new Set(t.map(y=>y.recipientHash)),r=t.filter(y=>y.type==="open"),a=t.filter(y=>y.type==="click"),o=t.filter(y=>y.type==="bounce"),c=t.filter(y=>y.type==="unsubscribe"),p=t.filter(y=>y.type==="complaint"),u=new Set(r.map(y=>y.recipientHash)).size,m=new Set(a.map(y=>y.recipientHash)).size,f=i.size;return{sent:f+o.length,delivered:f,opens:r.length,uniqueOpens:u,clicks:a.length,uniqueClicks:m,bounces:o.length,unsubscribes:c.length,complaints:p.length,openRate:f>0?u/f:0,clickRate:f>0?m/f:0,clickToOpenRate:u>0?m/u:0,bounceRate:f>0?o.length/(f+o.length):0}}getLinkStats(e){let t=this.events.filter(o=>o.type==="click"&&o.url);e&&(t=t.filter(o=>!(e.campaignId&&o.campaignId!==e.campaignId||e.messageId&&o.messageId!==e.messageId)));const i=new Map;for(const o of t){const c=o.url;i.has(c)||i.set(c,{url:c,linkName:void 0,total:0,unique:new Set});const p=i.get(c);p.total++,p.unique.add(o.recipientHash)}const r=t.length,a=[];for(const[,o]of i)a.push({url:o.url,linkName:o.linkName,totalClicks:o.total,uniqueClicks:o.unique.size,clickShare:r>0?o.total/r:0});return a.sort((o,c)=>c.totalClicks-o.totalClicks)}getDeviceStats(e){let t=this.events.filter(r=>r.type==="open");e!=null&&e.campaignId&&(t=t.filter(r=>r.campaignId===e.campaignId));const i={desktop:0,mobile:0,tablet:0,unknown:0};for(const r of t){const a=r.device??"unknown";i[a]=(i[a]??0)+1}return i}on(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t),()=>{var i;(i=this.eventListeners.get(e))==null||i.delete(t)}}onAny(e){const t=["open","click","bounce","unsubscribe","complaint"].map(i=>this.on(i,e));return()=>{t.forEach(i=>i())}}generateUnsubscribeLink(e){const t=new URLSearchParams;return t.set("rid",this.hashRecipientId(e.recipientId)),e.listId&&t.set("lid",e.listId),t.set("action","unsubscribe"),`${this.config.serverUrl}/unsubscribe?${t.toString()}`}generateListUnsubscribeHeader(e){return`<${this.generateUnsubscribeLink(e)}>`}clearEvents(){this.events=[]}exportEvents(e){return e!=null&&e.anonymize?this.events.map(t=>({...t,recipientHash:"anonymized",ipAddress:void 0,userAgent:void 0})):[...this.events]}buildTrackingParams(e){const t=new URLSearchParams;if(t.set("mid",e.messageId),t.set("rid",this.hashRecipientId(e.recipientId)),e.campaignId&&t.set("cid",e.campaignId),e.url&&t.set("url",e.url),e.linkName&&t.set("ln",e.linkName),e.metadata)for(const[i,r]of Object.entries(e.metadata))t.set(`m_${i}`,r);return t.toString()}hashRecipientId(e){let t=0;for(let i=0;i<e.length;i++){const r=e.charCodeAt(i);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(36)}anonymizeIpAddress(e){if(e){if(e.includes(".")){const t=e.split(".");return t[3]="0",t.join(".")}return e.includes(":")?e.split(":").slice(0,3).join(":")+"::":e}}extractLinkName(e){const t=e.match(/title=["']([^"']+)["']/i);if(t)return t[1];const i=e.match(/data-link-name=["']([^"']+)["']/i);if(i)return i[1]}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}generateEventId(){return`evt_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}notifyListeners(e){const t=this.eventListeners.get(e.type);if(t)for(const i of t)try{i(e)}catch(r){console.error("Tracking event listener error:",r)}}}let ge=null;function Ye(s){if(!ge&&s&&(ge=new At(s)),!ge)throw new Error("EmailTrackingService not initialized. Call with config first.");return ge}function Vn(){ge==null||ge.clearEvents(),ge=null}function Xn(s){const{config:e,campaignId:t,autoRefreshInterval:i}=s,r=l.useMemo(()=>{if(e)return Ye(e);try{return Ye()}catch{return null}},[e]),[a,o]=l.useState(null),[c,p]=l.useState([]),u=l.useCallback(()=>{r&&(o(r.getStats({campaignId:t})),p(r.getLinkStats({campaignId:t})))},[r,t]);l.useEffect(()=>{if(u(),i&&r){const h=setInterval(u,i);return()=>clearInterval(h)}},[u,i,r]),l.useEffect(()=>{if(r)return r.onAny(()=>{u()})},[r,u]);const m=l.useCallback((h,S)=>r?r.generateTrackingPixel({messageId:h,recipientId:S,campaignId:t}):"",[r,t]),f=l.useCallback((h,S,C)=>r?r.wrapLinksForTracking(h,{messageId:S,recipientId:C,campaignId:t}):h,[r,t]),y=l.useCallback(h=>{r==null||r.recordEvent(h)},[r]);return{generatePixel:m,wrapLinks:f,stats:a,linkStats:c,recordEvent:y,refreshStats:u}}class Et{constructor(e){this.templates=new Map,this.campaigns=new Map,this.abortControllers=new Map,this.config={sendEmail:e.sendEmail,rateLimit:e.rateLimit??60,batchSize:e.batchSize??10,retryOnFail:e.retryOnFail??!0,maxRetries:e.maxRetries??3,dateFormatter:e.dateFormatter??this.defaultDateFormatter,numberFormatter:e.numberFormatter??this.defaultNumberFormatter,currencyFormatter:e.currencyFormatter??this.defaultCurrencyFormatter}}createTemplate(e){const t={...e,id:this.generateId("tpl"),createdAt:new Date,updatedAt:new Date};return this.templates.set(t.id,t),t}updateTemplate(e,t){const i=this.templates.get(e);if(!i)throw new Error(`Template not found: ${e}`);const r={...i,...t,updatedAt:new Date};return this.templates.set(e,r),r}getTemplate(e){return this.templates.get(e)}deleteTemplate(e){return this.templates.delete(e)}listTemplates(){return Array.from(this.templates.values())}extractFields(e){const t=/\{\{([^}]+)\}\}/g,i=new Set;let r;for(;(r=t.exec(e))!==null;){const a=r[1].trim();if(a.startsWith("#if "))i.add(a.substring(4).trim());else if(a.startsWith("#unless "))i.add(a.substring(8).trim());else if(a.startsWith("#each "))i.add(a.substring(6).trim());else if(!a.startsWith("/")&&!a.startsWith("else")){const[o]=a.split("|");i.add(o.trim())}}return Array.from(i)}createCampaign(e){if(!this.templates.has(e.templateId))throw new Error(`Template not found: ${e.templateId}`);const t={...e,id:this.generateId("cmp"),status:"draft",recipients:e.recipients.map(i=>({...i,status:"pending"})),createdAt:new Date};return this.campaigns.set(t.id,t),t}getCampaign(e){return this.campaigns.get(e)}updateCampaign(e,t){const i=this.campaigns.get(e);if(!i)throw new Error(`Campaign not found: ${e}`);if(i.status==="sending")throw new Error("Cannot update campaign while sending");const r={...i,...t};return this.campaigns.set(e,r),r}addRecipients(e,t){const i=this.campaigns.get(e);if(!i)throw new Error(`Campaign not found: ${e}`);if(i.status==="sending")throw new Error("Cannot add recipients while sending");const r=t.map(a=>({...a,status:"pending"}));i.recipients.push(...r),this.campaigns.set(e,i)}removeRecipient(e,t){const i=this.campaigns.get(e);if(!i)return!1;const r=i.recipients.findIndex(a=>a.id===t);return r===-1?!1:(i.recipients.splice(r,1),!0)}listCampaigns(){return Array.from(this.campaigns.values())}validateCampaign(e){const t=this.campaigns.get(e);if(!t)return{isValid:!1,errors:[{type:"syntax_error",message:"Campaign not found"}],warnings:[],missingFields:new Map};const i=this.templates.get(t.templateId);if(!i)return{isValid:!1,errors:[{type:"syntax_error",message:"Template not found"}],warnings:[],missingFields:new Map};const r=[],a=[],o=new Map;t.recipients.length===0&&r.push({type:"empty_recipient",message:"No recipients in campaign"});for(const u of t.recipients){if(!u.email){r.push({type:"empty_recipient",recipientId:u.id,message:`Recipient ${u.id} has no email address`});continue}const m=[];for(const f of i.fields)f.required&&!(f.name in u.data)&&(m.push(f.name),r.push({type:"missing_field",field:f.name,recipientId:u.id,message:`Required field "${f.name}" missing for ${u.email}`}));m.length>0&&o.set(u.id,m)}const c=this.extractFields(i.subject+i.htmlBody+(i.textBody??"")),p=i.fields.map(u=>u.name);for(const u of c)p.includes(u)||a.push({type:"unused_field",field:u,message:`Field "${u}" used in template but not defined`});return{isValid:r.length===0,errors:r,warnings:a,missingFields:o}}previewMerge(e,t){const i=this.templates.get(e);if(!i)throw new Error(`Template not found: ${e}`);return{subject:this.processTemplate(i.subject,t,i.fields),html:this.processTemplate(i.htmlBody,t,i.fields),text:i.textBody?this.processTemplate(i.textBody,t,i.fields):void 0}}async*sendCampaign(e){const t=this.campaigns.get(e);if(!t)throw new Error(`Campaign not found: ${e}`);const i=this.templates.get(t.templateId);if(!i)throw new Error(`Template not found: ${t.templateId}`);const r=this.validateCampaign(e);if(!r.isValid)throw new Error(`Campaign validation failed: ${r.errors.map(y=>y.message).join(", ")}`);t.status="sending",t.startedAt=new Date,this.campaigns.set(e,t);const a=new AbortController;this.abortControllers.set(e,a);const o=t.recipients.filter(y=>y.status==="pending"),c=o.length;let p=0,u=0;const m=Date.now(),f=60*1e3/(t.rateLimit??this.config.rateLimit);try{for(let y=0;y<o.length;y++){if(a.signal.aborted){t.status="paused";break}const h=o[y];try{const D=this.previewMerge(i.id,h.data),W=await this.config.sendEmail({to:h.email,cc:h.cc,bcc:h.bcc,from:t.fromEmail,fromName:t.fromName,replyTo:t.replyTo,subject:h.subjectOverride??D.subject,html:D.html,text:D.text});W.success?(h.status="sent",p++):(h.status="failed",h.error=W.error,u++)}catch(D){h.status="failed",h.error=D instanceof Error?D.message:"Unknown error",u++}const S=p+u,C=Date.now()-m,d=S>0?C/S:f,R=c-S,T=Math.round(R*d/1e3);yield{campaignId:e,total:c,sent:p,failed:u,pending:c-S,current:h.email,percentage:Math.round(S/c*100),estimatedTimeRemaining:T,isComplete:!1},y<o.length-1&&await this.delay(f)}t.status="completed",t.completedAt=new Date,this.campaigns.set(e,t),yield{campaignId:e,total:c,sent:p,failed:u,pending:0,percentage:100,isComplete:!0}}finally{this.abortControllers.delete(e)}}pauseCampaign(e){const t=this.abortControllers.get(e);t&&t.abort();const i=this.campaigns.get(e);i&&i.status==="sending"&&(i.status="paused",this.campaigns.set(e,i))}async*resumeCampaign(e){const t=this.campaigns.get(e);if(!t)throw new Error(`Campaign not found: ${e}`);if(t.status!=="paused")throw new Error("Campaign is not paused");t.status="draft",this.campaigns.set(e,t),yield*this.sendCampaign(e)}cancelCampaign(e){this.pauseCampaign(e);const t=this.campaigns.get(e);t&&(t.status="cancelled",this.campaigns.set(e,t))}async*retryFailed(e){const t=this.campaigns.get(e);if(!t)throw new Error(`Campaign not found: ${e}`);for(const i of t.recipients)i.status==="failed"&&(i.status="pending",i.error=void 0);t.status="draft",this.campaigns.set(e,t),yield*this.sendCampaign(e)}processTemplate(e,t,i){const r=new Map(i.map(a=>[a.name,a]));return e=this.processConditionals(e,t),e=this.processLoops(e,t),e=e.replace(/\{\{([^}#/]+)\}\}/g,(a,o)=>{const[c,...p]=o.trim().split("|").map(f=>f.trim());let u=this.getNestedValue(t,c);const m=r.get(c);u==null&&(u=(m==null?void 0:m.defaultValue)??""),m&&u!==""&&(u=this.formatValue(u,m));for(const f of p)u=this.applyFormatter(u,f);return String(u)}),e}processConditionals(e,t){const i=/\{\{#if\s+([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g;return e.replace(i,(r,a,o,c="")=>{const p=this.getNestedValue(t,a.trim());return this.isTruthy(p)?o:c})}processLoops(e,t){const i=/\{\{#each\s+([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g;return e.replace(i,(r,a,o)=>{const c=this.getNestedValue(t,a.trim());return Array.isArray(c)?c.map((p,u)=>{let m=o;return typeof p!="object"&&(m=m.replace(/\{\{this\}\}/g,String(p))),m=m.replace(/\{\{this\.([^}]+)\}\}/g,(f,y)=>String(this.getNestedValue(p,y)??"")),m=m.replace(/\{\{@index\}\}/g,String(u)),m=m.replace(/\{\{@first\}\}/g,String(u===0)),m=m.replace(/\{\{@last\}\}/g,String(u===c.length-1)),m}).join(""):""})}formatValue(e,t){switch(t.type){case"date":return e instanceof Date?this.config.dateFormatter(e,t.format??"short"):typeof e=="string"||typeof e=="number"?this.config.dateFormatter(new Date(e),t.format??"short"):String(e);case"number":return typeof e=="number"?this.config.numberFormatter(e,t.format??""):String(e);case"currency":if(typeof e=="number"){const[i="USD",r="en-US"]=(t.format??"USD|en-US").split("|");return this.config.currencyFormatter(e,i,r)}return String(e);case"boolean":return e?"Yes":"No";case"list":return Array.isArray(e)?e.join(t.format??", "):String(e);default:return String(e)}}applyFormatter(e,t){const i=String(e);switch(t.toLowerCase()){case"uppercase":return i.toUpperCase();case"lowercase":return i.toLowerCase();case"capitalize":return i.charAt(0).toUpperCase()+i.slice(1).toLowerCase();case"titlecase":return i.replace(/\b\w/g,r=>r.toUpperCase());case"trim":return i.trim();case"escape":return this.escapeHtml(i);default:return i}}getNestedValue(e,t){const i=t.split(".");let r=e;for(const a of i){if(r==null)return;r=r[a]}return r}isTruthy(e){return e==null?!1:typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"||Array.isArray(e)?e.length>0:!0}defaultDateFormatter(e,t){const i={};switch(t){case"short":i.dateStyle="short";break;case"medium":i.dateStyle="medium";break;case"long":i.dateStyle="long";break;case"full":i.dateStyle="full";break;case"iso":return e.toISOString();default:i.dateStyle="medium"}return new Intl.DateTimeFormat("en-US",i).format(e)}defaultNumberFormatter(e,t){if(!t)return new Intl.NumberFormat().format(e);const i=parseInt(t,10);return isNaN(i)?String(e):new Intl.NumberFormat("en-US",{minimumFractionDigits:i,maximumFractionDigits:i}).format(e)}defaultCurrencyFormatter(e,t,i){return new Intl.NumberFormat(i,{style:"currency",currency:t}).format(e)}generateId(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}delay(e){return new Promise(t=>setTimeout(t,e))}}let Te=null;function Ge(s){if(!Te&&s&&(Te=new Et(s)),!Te)throw new Error("MailMergeService not initialized. Call with config first.");return Te}function Jn(){Te=null}function Qn(s={}){const{config:e}=s,t=l.useMemo(()=>{if(e)return Ge(e);try{return Ge()}catch{return null}},[e]),[i,r]=l.useState(null),[a,o]=l.useState(!1),[c,p]=l.useState([]),[u,m]=l.useState([]),f=l.useCallback(()=>{t&&(p(t.listTemplates()),m(t.listCampaigns()))},[t]),y=l.useCallback(T=>{if(!t)throw new Error("Service not initialized");const D=t.createTemplate(T);return f(),D},[t,f]),h=l.useCallback(T=>{if(!t)throw new Error("Service not initialized");const D=t.createCampaign(T);return f(),D},[t,f]),S=l.useCallback((T,D)=>{if(!t)throw new Error("Service not initialized");return t.previewMerge(T,D)},[t]),C=l.useCallback(T=>{if(!t)throw new Error("Service not initialized");return t.validateCampaign(T)},[t]),d=l.useCallback(async function*(T){if(!t)throw new Error("Service not initialized");o(!0);try{for await(const D of t.sendCampaign(T))r(D),yield D}finally{o(!1),f()}},[t,f]),R=l.useCallback(T=>{t==null||t.pauseCampaign(T),o(!1),f()},[t,f]);return{createTemplate:y,createCampaign:h,preview:S,validate:C,send:d,pause:R,progress:i,isSending:a,templates:c,campaigns:u}}class Dt{constructor(e){this.abortController=null,this.mapping={users:new Map,channels:new Map,files:new Map},this.config=e}async parseSlackExport(e){const t=await this.extractZipContents(e),i=t.get("users.json"),r=i?JSON.parse(i):[],a=t.get("channels.json"),o=a?JSON.parse(a):[],c=t.get("groups.json");if(c){const m=JSON.parse(c);o.push(...m.map(f=>({...f,is_private:!0})))}const p=t.get("dms.json");if(p){const m=JSON.parse(p);o.push(...m.map(f=>({...f,is_im:!0})))}const u=new Map;for(const m of o){const f=[],y=m.name;for(const[h,S]of t)if(h.startsWith(y+"/")&&h.endsWith(".json"))try{const C=JSON.parse(S);f.push(...C)}catch(C){console.warn(`Failed to parse messages from ${h}:`,C)}f.length>0&&u.set(m.id,f)}return{users:r,channels:o,messages:u}}parseSlackExportFromJson(e){return{users:e.users??[],channels:e.channels??[],messages:new Map(Object.entries(e.messages??{})),files:e.files}}previewImport(e,t={}){const i=e.users.filter(f=>t.importUsers!==!1&&!f.deleted),r=i.map(f=>this.mapUser(f)),a=e.channels.filter(f=>!(t.skipArchived&&f.is_archived||t.skipDirectMessages&&(f.is_im||f.is_mpim)||t.channelFilter&&!t.channelFilter.includes(f.id)&&!t.channelFilter.includes(f.name))),o=a.map(f=>this.mapChannel(f,new Map));let c=0;const p=new Map;for(const[f,y]of e.messages){const h=e.channels.find(d=>d.id===f);if(!h||!a.some(d=>d.id===f))continue;const C=this.filterMessages(y,t);p.set(h.name,C.length),c+=C.length}let u=0,m=0;for(const f of e.messages.values())for(const y of f)y.files&&(u+=y.files.length,m+=y.files.reduce((h,S)=>h+(S.size||0),0));return{users:{total:e.users.length,filtered:i.length,items:r},channels:{total:e.channels.length,filtered:a.length,items:o},messages:{total:c,perChannel:p},files:{total:u,totalSize:m}}}async*import(e,t={}){this.abortController=new AbortController,this.mapping={users:new Map,channels:new Map,files:new Map};const i=[],r={usersImported:0,channelsImported:0,messagesImported:0,filesImported:0,reactionsImported:0,threadsImported:0},a=new Date,c=1e3/(this.config.rateLimit??10);try{if(t.importUsers!==!1){const u=e.users.filter(f=>!f.deleted);let m=0;for(const f of u){if(this.abortController.signal.aborted)break;const y=this.mapUser(f),h=await this.config.createUser(y);h.success&&h.id?(this.mapping.users.set(f.id,h.id),r.usersImported++):i.push({phase:"users",itemId:f.id,itemType:"user",message:h.error??"Failed to create user"}),m++,yield{phase:"users",total:u.length,processed:m,failed:i.filter(S=>S.phase==="users").length,current:f.name,percentage:Math.round(m/u.length*100),isComplete:!1,errors:i},await this.delay(c)}}if(t.importChannels!==!1){const u=e.channels.filter(f=>{var y;return t.skipArchived&&f.is_archived||t.skipDirectMessages&&(f.is_im||f.is_mpim)?!1:(y=t.channelFilter)!=null&&y.length?t.channelFilter.includes(f.id)||t.channelFilter.includes(f.name):!0});let m=0;for(const f of u){if(this.abortController.signal.aborted)break;const y=this.mapChannel(f,this.mapping.users),h=await this.config.createChannel(y);h.success&&h.id?(this.mapping.channels.set(f.id,h.id),r.channelsImported++):i.push({phase:"channels",itemId:f.id,itemType:"channel",message:h.error??"Failed to create channel"}),m++,yield{phase:"channels",total:u.length,processed:m,failed:i.filter(S=>S.phase==="channels").length,current:f.name,percentage:Math.round(m/u.length*100),isComplete:!1,errors:i},await this.delay(c)}}if(t.importMessages!==!1){const u=[];for(const[y,h]of e.messages){if(!this.mapping.channels.has(y))continue;const S=this.filterMessages(h,t);for(const C of S)u.push({channelId:y,message:C})}u.sort((y,h)=>parseFloat(y.message.ts)-parseFloat(h.message.ts));const m=new Map;let f=0;for(const{channelId:y,message:h}of u){if(this.abortController.signal.aborted)break;const S=this.mapMessage(h,y,this.mapping,m),C=await this.config.createMessage(S);C.success&&C.id?((!h.thread_ts||h.thread_ts===h.ts)&&m.set(h.ts,C.id),r.messagesImported++,S.isThreadReply&&r.threadsImported++,r.reactionsImported+=S.reactions.length):i.push({phase:"messages",itemId:h.ts,itemType:"message",message:C.error??"Failed to create message"}),f++,yield{phase:"messages",total:u.length,processed:f,failed:i.filter(d=>d.phase==="messages").length,current:`${f}/${u.length}`,percentage:Math.round(f/u.length*100),isComplete:!1,errors:i},await this.delay(c)}}if(t.importFiles&&t.downloadFiles&&this.config.uploadFile&&this.config.downloadFile){const u=[];for(const f of e.messages.values())for(const y of f)y.files&&u.push(...y.files);let m=0;for(const f of u){if(this.abortController.signal.aborted)break;try{const y=f.url_private_download??f.url_private;if(y&&this.config.slackToken){const h=await this.config.downloadFile(y,this.config.slackToken),S=await this.config.uploadFile(f,h);S.success&&S.url?(this.mapping.files.set(f.id,S.url),r.filesImported++):i.push({phase:"files",itemId:f.id,itemType:"file",message:S.error??"Failed to upload file"})}}catch(y){i.push({phase:"files",itemId:f.id,itemType:"file",message:y instanceof Error?y.message:"File download failed"})}m++,yield{phase:"files",total:u.length,processed:m,failed:i.filter(y=>y.phase==="files").length,current:f.name,percentage:Math.round(m/u.length*100),isComplete:!1,errors:i},await this.delay(c)}}const p=new Date;return yield{phase:"complete",total:0,processed:0,failed:i.length,percentage:100,isComplete:!0,errors:i},{status:(i.length>0,"completed"),stats:r,mapping:this.mapping,errors:i,startedAt:a,completedAt:p,duration:p.getTime()-a.getTime()}}finally{this.abortController=null}}cancel(){var e;(e=this.abortController)==null||e.abort()}mapUser(e){var t,i,r,a,o;return{slackId:e.id,email:e.email,displayName:((t=e.profile)==null?void 0:t.display_name)||e.name,realName:e.real_name,avatarUrl:((i=e.profile)==null?void 0:i.image_192)||((r=e.profile)==null?void 0:r.image_72),title:(a=e.profile)==null?void 0:a.title,phone:(o=e.profile)==null?void 0:o.phone,timezone:e.tz,isAdmin:e.is_admin??!1,isBot:e.is_bot??!1,isDeactivated:e.deleted??!1}}mapChannel(e,t){var r,a;let i="public";return e.is_private&&(i="private"),e.is_im&&(i="dm"),e.is_mpim&&(i="mpim"),{slackId:e.id,name:e.name,type:i,description:(r=e.purpose)==null?void 0:r.value,topic:(a=e.topic)==null?void 0:a.value,isArchived:e.is_archived??!1,creatorId:e.creator?t.get(e.creator):void 0,memberIds:(e.members??[]).map(o=>t.get(o)).filter(o=>!!o),createdAt:e.created?new Date(e.created*1e3):void 0}}mapMessage(e,t,i,r){const a=i.channels.get(t)??t,o=e.user?i.users.get(e.user):void 0,{text:c,html:p}=this.convertSlackMessage(e.text,i.users),u=e.thread_ts!==void 0&&e.thread_ts!==e.ts,m=e.thread_ts?r.get(e.thread_ts):void 0,f=[];if(e.files)for(const h of e.files)f.push({type:h.mimetype.startsWith("image/")?"image":"file",url:i.files.get(h.id)??h.url_private,name:h.name,size:h.size});if(e.attachments)for(const h of e.attachments)h.image_url?f.push({type:"image",url:h.image_url}):h.title_link&&f.push({type:"link",url:h.title_link,name:h.title});const y=(e.reactions??[]).map(h=>({emoji:h.name,userIds:h.users.map(S=>i.users.get(S)).filter(S=>!!S),count:h.count}));return{channelId:a,senderId:o,content:c,htmlContent:p,threadId:m,isThreadReply:u,attachments:f,reactions:y,createdAt:e.ts?new Date(parseFloat(e.ts)*1e3):void 0,editedAt:e.edited?new Date(parseFloat(e.edited.ts)*1e3):void 0}}convertSlackMessage(e,t){let i=e,r=this.escapeHtml(e);const a=/<@([A-Z0-9]+)(?:\|([^>]+))?>/g;return i=i.replace(a,(o,c,p)=>p?`@${p}`:"@user"),r=r.replace(/<@([A-Z0-9]+)(?:\|([^&]+))?>/g,(o,c,p)=>`<span class="mention" data-user-id="${t.get(c)??c}">@${p??"user"}</span>`),i=i.replace(/<#([A-Z0-9]+)\|([^>]+)>/g,"#$2"),r=r.replace(/<#([A-Z0-9]+)\|([^&]+)>/g,'<span class="channel-mention">#$2</span>'),i=i.replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)"),i=i.replace(/<(https?:\/\/[^>]+)>/g,"$1"),r=r.replace(/<(https?:\/\/[^|&]+)\|([^&]+)>/g,'<a href="$1">$2</a>'),r=r.replace(/<(https?:\/\/[^&]+)>/g,'<a href="$1">$1</a>'),i=this.convertEmoji(i),r=this.convertEmoji(r),r=r.replace(/\*([^*]+)\*/g,"<strong>$1</strong>"),r=r.replace(/\b_([^_]+)_\b/g,"<em>$1</em>"),r=r.replace(/~([^~]+)~/g,"<del>$1</del>"),r=r.replace(/`([^`]+)`/g,"<code>$1</code>"),r=r.replace(/```([^`]+)```/g,"<pre>$1</pre>"),r=r.replace(/\n/g,"<br>"),{text:i,html:r}}convertEmoji(e){const t={":smile:":"๐",":laughing:":"๐",":blush:":"๐",":heart_eyes:":"๐",":heart:":"โค๏ธ",":thumbsup:":"๐",":thumbsdown:":"๐",":wave:":"๐",":clap:":"๐",":fire:":"๐ฅ",":rocket:":"๐",":star:":"โญ",":sparkles:":"โจ",":tada:":"๐",":100:":"๐ฏ",":thinking_face:":"๐ค",":eyes:":"๐",":pray:":"๐",":muscle:":"๐ช",":ok_hand:":"๐",":white_check_mark:":"โ
",":x:":"โ",":warning:":"โ ๏ธ",":question:":"โ",":exclamation:":"โ",":point_right:":"๐",":point_left:":"๐",":point_up:":"๐",":point_down:":"๐"};return e.replace(/:([a-z0-9_+-]+):/g,(i,r)=>t[i]??i)}filterMessages(e,t){return e.filter(i=>i.subtype==="bot_message"?!0:!(t.messagesAfter&&new Date(parseFloat(i.ts)*1e3)<t.messagesAfter||t.messagesBefore&&new Date(parseFloat(i.ts)*1e3)>t.messagesBefore||!t.importThreads&&i.thread_ts&&i.thread_ts!==i.ts))}async extractZipContents(e){return console.warn("ZIP extraction requires JSZip library. Use parseSlackExportFromJson() for JSON input."),new Map}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}delay(e){return new Promise(t=>setTimeout(t,e))}}let ze=null;function qe(s){if(!ze&&s&&(ze=new Dt(s)),!ze)throw new Error("SlackImportService not initialized. Call with config first.");return ze}function Zn(){ze=null}function ei(s={}){const{config:e}=s,t=l.useMemo(()=>{if(e)return qe(e);try{return qe()}catch{return null}},[e]),[i,r]=l.useState(null),[a,o]=l.useState(!1),[c,p]=l.useState(null),u=l.useCallback(h=>{if(!t)throw new Error("Service not initialized");return t.parseSlackExportFromJson(h)},[t]),m=l.useCallback((h,S)=>{if(!t)throw new Error("Service not initialized");return t.previewImport(h,S)},[t]),f=l.useCallback(async function*(h,S){var C,d;if(!t)throw new Error("Service not initialized");o(!0),p(null);try{let R;for await(const W of t.import(h,S))r(W),yield W;const T=t.import(h,S);let D;for await(const W of T)D=W;return R=(d=(C=T.next)==null?void 0:C.call(T))==null?void 0:d.value,R&&p(R),R}finally{o(!1)}},[t]),y=l.useCallback(()=>{t==null||t.cancel(),o(!1)},[t]);return{parseJson:u,preview:m,import:f,cancel:y,progress:i,isImporting:a,result:c}}const Mt={toggleMute:"*6",raiseHand:"*9",leave:"#",help:"*0",hostMuteAll:"*1",hostUnmuteAll:"*2",hostEndMeeting:"*#"},Nt={welcome:"Welcome to the conference. ",enterPin:"Please enter your meeting PIN followed by the pound key.",invalidPin:"Invalid PIN. Please try again.",joined:"You have joined the meeting.",muted:"You are now muted. Press star 6 to unmute.",unmuted:"You are now unmuted.",onHold:"Please hold. The meeting host will be with you shortly.",goodbye:"Goodbye."},Ve={US:"+1",CA:"+1",UK:"+44",DE:"+49",FR:"+33",PL:"+48",ES:"+34",IT:"+39",AU:"+61",JP:"+81",IN:"+91",BR:"+55",MX:"+52"};class it{constructor(e={}){this.eventHandlers={},this.participants=new Map,this.meetingDialIns=new Map,this.connectionStatus="disconnected",this.config={provider:"twilio",accountSid:"",authToken:"",sipDomain:"",defaultRegion:"US",enabledRegions:["US","UK","DE","PL"],maxParticipants:100,recordingMode:"none",...e},this.dtmfCommands=Mt,this.ivrText={...Nt,...e.ivrText}}on(e,t){this.eventHandlers[e]=t}off(e){delete this.eventHandlers[e]}emit(e,...t){const i=this.eventHandlers[e];i&&i(...t)}generateDialInInfo(e,t){const i=this.getAvailableNumbers(),r=this.generateAccessPin(),a=this.generateAccessPin(8),o={meetingId:e,dialInNumbers:i,accessPin:r,hostPin:a,meetingTitle:t,expiresAt:Date.now()+24*60*60*1e3};return this.meetingDialIns.set(e,o),o}getDialInInfo(e){return this.meetingDialIns.get(e)}getAvailableNumbers(){return this.config.enabledRegions.map(e=>({number:this.generatePhoneNumber(e),region:e,displayNumber:this.formatPhoneNumber(e),tollFree:e==="US"||e==="UK",type:e==="US"||e==="UK"?"toll-free":"local",sipUri:`sip:conference@${this.config.sipDomain}`}))}generatePhoneNumber(e){const t=Ve[e],i=Math.floor(1e9+Math.random()*9e9).toString();return`${t}${i}`}formatPhoneNumber(e){const t=Ve[e],i=this.generatePhoneNumber(e).slice(t.length);return e==="US"||e==="CA"?`${t} (${i.slice(0,3)}) ${i.slice(3,6)}-${i.slice(6)}`:`${t} ${i}`}generateAccessPin(e=6){return Math.floor(Math.random()*Math.pow(10,e)).toString().padStart(e,"0")}async handleIncomingCall(e,t,i){const r={callId:e,callerNumber:t,callerName:i,state:"connecting",joinedAt:Date.now(),audioStats:{volume:0,isMuted:!1,packetLoss:0,quality:5},isHost:!1,isModerator:!1};return this.participants.set(e,r),this.updateParticipantState(e,"waiting-pin"),await this.playIvr(e,"welcome"),await this.playIvr(e,"enterPin"),r}async validatePinAndJoin(e,t,i){const r=this.participants.get(e);if(!r)return{success:!1,isHost:!1};const a=this.meetingDialIns.get(t);if(!a)return await this.playIvr(e,"invalidPin"),{success:!1,isHost:!1};const o=i===a.hostPin;return i===a.accessPin||o?(r.isHost=o,r.isModerator=o,this.updateParticipantState(e,"joined"),await this.playIvr(e,"joined"),this.emit("onParticipantJoined",{...r}),{success:!0,isHost:o}):(await this.playIvr(e,"invalidPin"),{success:!1,isHost:!1})}getParticipant(e){return this.participants.get(e)}getParticipants(){return Array.from(this.participants.values())}updateParticipantState(e,t){const i=this.participants.get(e);if(!i)return;const r=i.state;i.state=t,this.emit("onParticipantStateChanged",{...i},r)}async muteParticipant(e){const t=this.participants.get(e);t&&(t.audioStats.isMuted=!0,this.updateParticipantState(e,"muted"),await this.playIvr(e,"muted"))}async unmuteParticipant(e){const t=this.participants.get(e);t&&(t.audioStats.isMuted=!1,this.updateParticipantState(e,"joined"),await this.playIvr(e,"unmuted"))}async toggleMute(e){const t=this.participants.get(e);return t?t.audioStats.isMuted?(await this.unmuteParticipant(e),!1):(await this.muteParticipant(e),!0):!1}async putOnHold(e){this.participants.get(e)&&(this.updateParticipantState(e,"on-hold"),await this.playIvr(e,"onHold"))}async removeFromHold(e){this.participants.get(e)&&(this.updateParticipantState(e,"joined"),await this.playIvr(e,"joined"))}async muteAll(e=!0){for(const t of this.participants.values())e&&(t.isHost||t.isModerator)||await this.muteParticipant(t.callId)}async unmuteAll(){for(const e of this.participants.values())await this.unmuteParticipant(e.callId)}async handleDtmf(e,t){const i=this.participants.get(e);i&&(this.emit("onDtmfReceived",{...i},t),t===this.dtmfCommands.toggleMute?await this.toggleMute(e):t===this.dtmfCommands.raiseHand?console.log(`Participant ${e} raised hand`):t===this.dtmfCommands.leave?await this.disconnectParticipant(e):t===this.dtmfCommands.help?await this.playHelp(e):(i.isHost||i.isModerator)&&(t===this.dtmfCommands.hostMuteAll?await this.muteAll():t===this.dtmfCommands.hostUnmuteAll?await this.unmuteAll():t===this.dtmfCommands.hostEndMeeting&&await this.endMeeting()))}setDtmfCommands(e){this.dtmfCommands={...this.dtmfCommands,...e}}async playIvr(e,t){const i=this.ivrText[t];console.log(`[IVR -> ${e}] ${i}`),await new Promise(r=>setTimeout(r,i.length*50))}async playCustomMessage(e,t){console.log(`[TTS -> ${e}] ${t}`),await new Promise(i=>setTimeout(i,t.length*50))}async playHelp(e){await this.playCustomMessage(e,`
|
|
6
|
+
`})]})}function Se({icon:s,label:e,onClick:t,active:i,style:r}){return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[n.jsx("button",{onClick:t,title:e,style:{width:44,height:44,borderRadius:"50%",border:"none",background:i?"rgba(255,255,255,0.15)":"rgba(255,255,255,0.08)",color:"#fff",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.2s",...r},children:s}),n.jsx("span",{style:{fontSize:9,color:"rgba(255,255,255,0.5)",textAlign:"center",maxWidth:50},children:e})]})}const Kt=["๐","โค๏ธ","๐","๐ฎ","๐ข","๐"];function Le({message:s,author:e,isMine:t,showAvatar:i,enableReactions:r,onReact:a,onReply:o,onEdit:c,onDelete:p,onPin:u,onOpenThread:m}){var z,P,D,W;const[f,y]=l.useState(!1),[h,S]=l.useState(!1),C=s.isDeleted,d=s.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.jsxs("div",{className:`nice-chat-message${t?" nice-chat-message--mine":""}${s.isPinned?" nice-chat-message--pinned":""}`,onMouseEnter:()=>y(!0),onMouseLeave:()=>{y(!1),S(!1)},style:{display:"flex",flexDirection:t?"row-reverse":"row",alignItems:"flex-end",gap:8,padding:"2px 16px",position:"relative"},children:[i&&!t&&n.jsxs("div",{style:{position:"relative",flexShrink:0},children:[n.jsx("div",{className:"nice-chat-avatar",style:{width:32,height:32,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontSize:13,fontWeight:600,flexShrink:0},children:!(e!=null&&e.avatarUrl)&&(((P=(z=e==null?void 0:e.name)==null?void 0:z[0])==null?void 0:P.toUpperCase())??"?")}),n.jsx(ue,{status:((D=e==null?void 0:e.presence)==null?void 0:D.status)??"unknown",size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),n.jsxs("div",{style:{maxWidth:"70%",display:"flex",flexDirection:"column",alignItems:t?"flex-end":"flex-start"},children:[!t&&e&&n.jsx("span",{style:{fontSize:11,color:"#6b7280",marginBottom:2,paddingLeft:2},children:e.displayName??e.name}),s.replyTo&&n.jsx("div",{className:"nice-chat-reply-preview",style:{borderLeft:"3px solid #6366f1",paddingLeft:6,fontSize:12,color:"#6b7280",marginBottom:4,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.replyTo.content}),n.jsx("div",{className:`nice-chat-bubble${t?" nice-chat-bubble--mine":""}`,style:{padding:"8px 12px",borderRadius:t?"18px 18px 4px 18px":"18px 18px 18px 4px",background:t?"#6366f1":"#f3f4f6",color:t?"#fff":"#111827",fontSize:14,lineHeight:1.5,wordBreak:"break-word"},children:C?n.jsx("span",{style:{fontStyle:"italic",opacity:.6},children:"This message was deleted"}):s.contentType==="image"&&((W=s.attachments)!=null&&W[0])?n.jsx("img",{src:s.attachments[0].url,alt:s.attachments[0].name,style:{maxWidth:280,maxHeight:280,borderRadius:8,display:"block"}}):n.jsx("span",{children:s.content})}),!C&&s.attachments&&s.attachments.length>0&&s.contentType!=="image"&&n.jsx("div",{className:"nice-chat-attachments",style:{marginTop:4},children:s.attachments.map(M=>n.jsxs("a",{href:M.url,target:"_blank",rel:"noreferrer",className:"nice-chat-attachment",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:12,color:t?"rgba(255,255,255,0.85)":"#6366f1",textDecoration:"none",background:t?"rgba(255,255,255,0.15)":"#e0e7ff",borderRadius:6,padding:"3px 8px",marginTop:2},children:["๐ ",M.name]},M.id))}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:2},children:[n.jsx("span",{style:{fontSize:11,color:"#9ca3af"},children:d}),s.editedAt&&n.jsx("span",{style:{fontSize:11,color:"#9ca3af"},children:"(edited)"}),t&&n.jsx("span",{style:{fontSize:11,color:s.status==="read"?"#6366f1":"#9ca3af"},children:s.status==="sending"?"โ":s.status==="sent"?"โ":(s.status==="delivered","โโ")})]}),s.reactions&&s.reactions.length>0&&n.jsx("div",{className:"nice-chat-reactions",style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:s.reactions.map(M=>n.jsxs("button",{onClick:()=>a(s.id,M.emoji),style:{background:M.mine?"#e0e7ff":"#f3f4f6",border:M.mine?"1px solid #6366f1":"1px solid transparent",borderRadius:12,padding:"2px 7px",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",gap:3},children:[M.emoji," ",M.count]},M.emoji))}),(s.threadCount??0)>0&&n.jsxs("button",{className:"nice-chat-thread-btn",onClick:()=>m==null?void 0:m(s),style:{background:"none",border:"none",color:"#6366f1",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:2},children:["๐ฌ ",s.threadCount," repl",s.threadCount===1?"y":"ies"]})]}),f&&!C&&n.jsxs("div",{className:"nice-chat-actions",style:{position:"absolute",top:-16,[t?"left":"right"]:16,display:"flex",gap:2,background:"#fff",borderRadius:8,boxShadow:"0 2px 8px rgba(0,0,0,0.12)",padding:"3px 6px",zIndex:10},children:[r&&n.jsxs("div",{style:{position:"relative"},children:[n.jsx("button",{title:"React",onClick:()=>S(M=>!M),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"๐"}),h&&n.jsx("div",{style:{position:"absolute",bottom:"100%",left:0,display:"flex",gap:4,background:"#fff",borderRadius:8,boxShadow:"0 2px 8px rgba(0,0,0,0.15)",padding:"6px 8px",zIndex:20},children:Kt.map(M=>n.jsx("button",{onClick:()=>{a(s.id,M),S(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:M},M))})]}),n.jsx("button",{title:"Reply",onClick:()=>o(s),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"โฉ"}),t&&c&&n.jsx("button",{title:"Edit",onClick:()=>c(s),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"โ๏ธ"}),u&&n.jsx("button",{title:s.isPinned?"Unpin":"Pin",onClick:()=>u(s),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"๐"}),t&&p&&n.jsx("button",{title:"Delete",onClick:()=>p(s),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px",color:"#ef4444"},children:"๐"})]})]})}function at({placeholder:s="Type a messageโฆ",maxLength:e,replyTo:t,onCancelReply:i,onSend:r,onAttach:a,disabled:o}){const[c,p]=l.useState(""),u=l.useRef(null);l.useEffect(()=>{t&&u.current&&u.current.focus()},[t]);const m=h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),f())},f=()=>{const h=c.trim();h&&(r(h),p(""),u.current&&(u.current.style.height="auto"))},y=h=>{p(h.target.value),h.target.style.height="auto",h.target.style.height=`${Math.min(h.target.scrollHeight,120)}px`};return n.jsxs("div",{className:"nice-chat-input-area",style:{padding:"8px 12px",borderTop:"1px solid #e5e7eb",background:"#fff"},children:[t&&n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",background:"#f3f4f6",borderLeft:"3px solid #6366f1",padding:"4px 8px",marginBottom:6,borderRadius:"0 4px 4px 0",fontSize:12,color:"#6b7280"},children:[n.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Replying: ",t.content]}),n.jsx("button",{onClick:i,style:{background:"none",border:"none",cursor:"pointer",fontSize:16,color:"#9ca3af",marginLeft:8},children:"ร"})]}),n.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:8},children:[a&&n.jsx("button",{onClick:a,title:"Attach file",style:{background:"none",border:"none",cursor:"pointer",fontSize:18,color:"#9ca3af",padding:"4px",flexShrink:0},children:"๐"}),n.jsx("textarea",{ref:u,value:c,onChange:y,onKeyDown:m,placeholder:s,maxLength:e,disabled:o,rows:1,style:{flex:1,resize:"none",border:"1px solid #e5e7eb",borderRadius:20,padding:"8px 14px",fontSize:14,outline:"none",fontFamily:"inherit",lineHeight:1.5,overflow:"hidden"}}),n.jsx("button",{onClick:f,disabled:!c.trim()||o,style:{background:c.trim()?"#6366f1":"#e5e7eb",border:"none",borderRadius:"50%",width:36,height:36,cursor:c.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:16,transition:"background 0.15s"},children:"โค"})]}),e&&c.length>e*.8&&n.jsxs("div",{style:{textAlign:"right",fontSize:11,color:c.length>=e?"#ef4444":"#9ca3af",marginTop:2},children:[c.length,"/",e]})]})}function Re({conversation:s,messages:e,users:t,currentUser:i,isLoading:r=!1,hasMore:a=!1,showHeader:o=!0,showUserAvatars:c=!0,enableReactions:p=!0,enableThreads:u=!0,enableAttachments:m=!0,placeholder:f,maxMessageLength:y,onSendMessage:h,onEditMessage:S,onDeleteMessage:C,onReactToMessage:d,onPinMessage:z,onLoadMoreMessages:P,onStartCall:D,className:W,style:M,id:F,"data-testid":U}){var B,g;const N=l.useRef(null),H=l.useRef(null),[j,b]=l.useState(null),[T,K]=l.useState(null),J=l.useMemo(()=>{const w=new Map;return t.forEach(V=>w.set(V.id,V)),w},[t]);l.useEffect(()=>{var w;(w=N.current)==null||w.scrollIntoView({behavior:"smooth"})},[e]);const R=l.useCallback(()=>{const w=H.current;!w||!a||r||w.scrollTop===0&&e.length>0&&(P==null||P(s.id,e[0].id))},[a,r,e,s.id,P]),O=l.useCallback(w=>{h==null||h(s.id,w,"text"),b(null)},[s.id,h]),_=s.type==="dm"?J.get(s.participantIds.find(w=>w!==i.id)??""):void 0;return n.jsxs("div",{id:F,"data-testid":U,className:`nice-chat-window${W?` ${W}`:""}`,style:{display:"flex",flexDirection:"column",height:"100%",background:"#fff",...M},children:[o&&n.jsxs("div",{className:"nice-chat-header",style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid #e5e7eb",flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:(_??s).avatarUrl?`url(${(_??s).avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:15,flexShrink:0},children:!(_??s).avatarUrl&&((B=((_==null?void 0:_.name)??s.name??"?")[0])==null?void 0:B.toUpperCase())}),n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600,fontSize:15},children:(_==null?void 0:_.displayName)??(_==null?void 0:_.name)??s.name??"Chat"}),_&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:1},children:[n.jsx(ue,{status:_.presence.status,size:"xs"}),n.jsx("span",{style:{fontSize:12,color:"#6b7280"},children:_.presence.statusMessage??_.presence.status})]}),s.type!=="dm"&&n.jsxs("span",{style:{fontSize:12,color:"#6b7280"},children:[s.participantIds.length," members"]})]})]}),s.type==="dm"&&D&&_&&n.jsxs("div",{style:{display:"flex",gap:4},children:[n.jsx("button",{onClick:()=>D([_.id],"audio"),title:"Audio call",style:{background:"none",border:"1px solid #e5e7eb",borderRadius:6,padding:"5px 8px",cursor:"pointer",fontSize:16},children:"๐"}),n.jsx("button",{onClick:()=>D([_.id],"video"),title:"Video call",style:{background:"none",border:"1px solid #e5e7eb",borderRadius:6,padding:"5px 8px",cursor:"pointer",fontSize:16},children:"๐น"})]})]}),n.jsxs("div",{ref:H,className:"nice-chat-messages",onScroll:R,style:{flex:1,overflowY:"auto",padding:"8px 0",display:"flex",flexDirection:"column"},children:[a&&n.jsx("button",{onClick:()=>e.length>0&&(P==null?void 0:P(s.id,e[0].id)),disabled:r,style:{display:"block",margin:"8px auto",background:"none",border:"1px solid #e5e7eb",borderRadius:16,padding:"4px 16px",fontSize:12,color:"#6b7280",cursor:"pointer"},children:r?"Loadingโฆ":"Load older messages"}),e.map((w,V)=>{const q=e[V-1],Q=c&&(!q||q.authorId!==w.authorId);return n.jsx(Le,{message:w,author:J.get(w.authorId),isMine:w.authorId===i.id,showAvatar:Q,enableReactions:p,onReact:(Y,re)=>d==null?void 0:d(Y,re),onReply:Y=>b(Y),onEdit:S?Y=>S(Y.id,Y.content):void 0,onDelete:C?Y=>C(Y.id):void 0,onPin:z?Y=>z(Y.id):void 0,onOpenThread:u?Y=>K(Y):void 0},w.id)}),n.jsx("div",{ref:N})]}),T&&n.jsxs("div",{className:"nice-chat-thread-panel",style:{position:"absolute",right:0,top:o?57:0,bottom:0,width:320,background:"#fff",borderLeft:"1px solid #e5e7eb",display:"flex",flexDirection:"column",zIndex:5},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid #e5e7eb"},children:[n.jsx("span",{style:{fontWeight:600,fontSize:14},children:"Thread"}),n.jsx("button",{onClick:()=>K(null),style:{background:"none",border:"none",cursor:"pointer",fontSize:18,color:"#9ca3af"},children:"ร"})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[n.jsx(Le,{message:T,author:J.get(T.authorId),isMine:T.authorId===i.id,showAvatar:!0,enableReactions:p,onReact:(w,V)=>d==null?void 0:d(w,V),onReply:()=>{}}),(g=T.thread)==null?void 0:g.map(w=>n.jsx(Le,{message:w,author:J.get(w.authorId),isMine:w.authorId===i.id,showAvatar:!0,enableReactions:p,onReact:(V,q)=>d==null?void 0:d(V,q),onReply:()=>{}},w.id))]}),n.jsx(at,{placeholder:"Reply in threadโฆ",onSend:w=>h==null?void 0:h(s.id,w,"text")})]}),n.jsx(at,{placeholder:f,maxLength:y,replyTo:j,onCancelReply:()=>b(null),onSend:O,onAttach:m?()=>{}:void 0})]})}function Yt({conversation:s,partner:e,isActive:t,lastMessage:i,onClick:r}){var m;const a=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??s.name??"Group",o=((m=a[0])==null?void 0:m.toUpperCase())??"?",c=(e==null?void 0:e.avatarUrl)??s.avatarUrl,p=i?i.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"",u=i?i.isDeleted?"Message deleted":i.content.slice(0,50):"";return n.jsxs("button",{className:`nice-messenger-conv-item${t?" nice-messenger-conv-item--active":""}`,onClick:r,style:{display:"flex",alignItems:"center",gap:10,padding:"10px 14px",background:t?"#ede9fe":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",position:"relative"},children:[n.jsxs("div",{style:{position:"relative",flexShrink:0},children:[n.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:c?`url(${c}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:16},children:!c&&o}),e&&n.jsx(ue,{status:e.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}}),s.type!=="dm"&&n.jsx("span",{style:{position:"absolute",bottom:-2,right:-2,background:"#f3f4f6",border:"1px solid #e5e7eb",borderRadius:4,fontSize:9,padding:"0 3px",color:"#6b7280"},children:"#"})]}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline"},children:[n.jsx("span",{style:{fontWeight:s.unreadCount>0?700:500,fontSize:14,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),n.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0,marginLeft:4},children:p})]}),n.jsx("div",{style:{fontSize:12,color:"#6b7280",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:u})]}),(s.unreadCount>0||s.mentionCount>0)&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,alignItems:"flex-end",flexShrink:0},children:[s.mentionCount>0&&n.jsxs("span",{style:{background:"#ef4444",color:"#fff",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:["@",s.mentionCount]}),s.unreadCount>0&&n.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:s.unreadCount>99?"99+":s.unreadCount})]}),s.isMuted&&n.jsx("span",{style:{position:"absolute",bottom:8,right:8,fontSize:10,color:"#9ca3af"},children:"๐"})]})}function St({conversations:s,messages:e,users:t,currentUser:i,activeConversationId:r,teams:a,enableGroupConversations:o=!0,showPresence:c=!0,enableSearch:p=!0,onSendMessage:u,onEditMessage:m,onDeleteMessage:f,onReactToMessage:y,onPinMessage:h,onLoadMoreMessages:S,onMarkAsRead:C,onStartCall:d,onCreateConversation:z,className:P,style:D,id:W,"data-testid":M}){var B;const[F,U]=l.useState(r??null),[N,H]=l.useState(""),[j,b]=l.useState("all");l.useMemo(()=>{const g=new Map;return t.forEach(w=>g.set(w.id,w)),g},[t]);const T=l.useMemo(()=>{let g=s;if(j==="unread"&&(g=g.filter(w=>w.unreadCount>0)),j==="groups"&&(g=g.filter(w=>w.type!=="dm")),N.trim()){const w=N.toLowerCase();g=g.filter(V=>{var Q,Y;const q=He(V,i.id,t);return(q==null?void 0:q.name.toLowerCase().includes(w))||((Q=V.name)==null?void 0:Q.toLowerCase().includes(w))||((Y=V.lastMessage)==null?void 0:Y.content.toLowerCase().includes(w))})}return[...g].sort((w,V)=>{var Y,re;if(w.isPinned!==V.isPinned)return w.isPinned?-1:1;const q=((Y=w.lastMessage)==null?void 0:Y.timestamp.getTime())??w.updatedAt.getTime();return(((re=V.lastMessage)==null?void 0:re.timestamp.getTime())??V.updatedAt.getTime())-q})},[s,j,N,i.id,t]),K=l.useMemo(()=>s.find(g=>g.id===F)??null,[s,F]),J=l.useMemo(()=>F?e[F]??[]:[],[e,F]),R=l.useCallback(g=>{U(g),C==null||C(g)},[C]),O=l.useMemo(()=>Xe(s),[s]),_=a??[];return n.jsxs("div",{id:W,"data-testid":M,className:`nice-messenger${P?` ${P}`:""}`,style:{display:"flex",height:"100%",background:"#fff",overflow:"hidden",...D},children:[n.jsxs("div",{className:"nice-messenger-sidebar",style:{width:280,flexShrink:0,borderRight:"1px solid #e5e7eb",display:"flex",flexDirection:"column",background:"#fafafa"},children:[n.jsxs("div",{style:{padding:"14px 14px 8px",borderBottom:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("span",{style:{fontWeight:700,fontSize:16},children:["Messages"," ",O>0&&n.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:10,padding:"1px 6px",fontWeight:700,marginLeft:4},children:O})]}),o&&z&&n.jsx("button",{onClick:()=>z([],"group"),title:"New conversation",style:{background:"#6366f1",border:"none",borderRadius:6,padding:"5px 8px",cursor:"pointer",color:"#fff",fontSize:13},children:"+"})]}),p&&n.jsx("input",{type:"search",value:N,onChange:g=>H(g.target.value),placeholder:"Search conversationsโฆ",style:{width:"100%",marginTop:8,padding:"6px 10px",border:"1px solid #e5e7eb",borderRadius:16,fontSize:13,outline:"none",boxSizing:"border-box",background:"#fff"}}),n.jsx("div",{style:{display:"flex",gap:2,marginTop:8},children:["all","unread","groups"].map(g=>n.jsx("button",{onClick:()=>b(g),style:{flex:1,padding:"4px 0",border:"none",borderRadius:6,background:j===g?"#6366f1":"transparent",color:j===g?"#fff":"#6b7280",cursor:"pointer",fontSize:12,textTransform:"capitalize",fontWeight:j===g?600:400},children:g},g))})]}),c&&n.jsxs("div",{style:{padding:"8px 14px",borderBottom:"1px solid #f3f4f6",overflowX:"auto"},children:[n.jsx("div",{style:{fontSize:11,color:"#9ca3af",marginBottom:6},children:"ONLINE NOW"}),n.jsx("div",{style:{display:"flex",gap:10},children:t.filter(g=>g.id!==i.id&&g.presence.status==="online").slice(0,6).map(g=>{var w;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:3},children:[n.jsxs("div",{style:{position:"relative"},children:[n.jsx("div",{style:{width:34,height:34,borderRadius:"50%",background:g.avatarUrl?`url(${g.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer"},title:g.name,children:!g.avatarUrl&&((w=g.name[0])==null?void 0:w.toUpperCase())}),n.jsx(ue,{status:g.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),n.jsx("span",{style:{fontSize:10,color:"#6b7280",maxWidth:36,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.displayName??g.name.split(" ")[0]})]},g.id)})})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[_.length>0&&j==="all"&&n.jsx("div",{style:{padding:"8px 14px 4px",fontSize:11,color:"#9ca3af",fontWeight:600,letterSpacing:"0.05em"},children:"DIRECT MESSAGES"}),T.length===0?n.jsx("div",{style:{padding:24,textAlign:"center",color:"#9ca3af",fontSize:13},children:"No conversations"}):T.map(g=>n.jsx(Yt,{conversation:g,partner:He(g,i.id,t),isActive:g.id===F,lastMessage:g.lastMessage,onClick:()=>R(g.id)},g.id))]}),n.jsxs("div",{style:{padding:"10px 14px",borderTop:"1px solid #e5e7eb",display:"flex",alignItems:"center",gap:8},children:[n.jsxs("div",{style:{position:"relative"},children:[n.jsx("div",{style:{width:32,height:32,borderRadius:"50%",background:i.avatarUrl?`url(${i.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:13},children:!i.avatarUrl&&((B=i.name[0])==null?void 0:B.toUpperCase())}),n.jsx(ue,{status:i.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontWeight:600,fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.displayName??i.name}),n.jsx("div",{style:{fontSize:11,color:"#9ca3af",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.presence.statusMessage??i.presence.status})]})]})]}),n.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:K?n.jsx(Re,{conversation:K,messages:J,users:t,currentUser:i,onSendMessage:u,onEditMessage:m,onDeleteMessage:f,onReactToMessage:y,onPinMessage:h,onLoadMoreMessages:S,onStartCall:d,style:{height:"100%"}}):n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"#9ca3af",gap:12},children:[n.jsx("span",{style:{fontSize:48},children:"๐ฌ"}),n.jsx("span",{style:{fontSize:15},children:"Select a conversation to start messaging"})]})})]})}const Gt=["๐","โค๏ธ","๐","๐","๐ฎ","๐ข"];function We({message:s,author:e,isMine:t,enableReactions:i,enableThreads:r,onReact:a,onOpenThread:o,onReply:c}){var S,C,d;const[p,u]=l.useState(!1),[m,f]=l.useState(!1),y=s.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),h=s.timestamp.toLocaleDateString([],{month:"short",day:"numeric"});return n.jsxs("div",{className:`nice-channel-msg${p?" nice-channel-msg--hovered":""}${t?" nice-channel-msg--mine":""}`,onMouseEnter:()=>u(!0),onMouseLeave:()=>{u(!1),f(!1)},style:{display:"flex",gap:10,padding:"4px 16px",position:"relative",background:p?"rgba(99,102,241,0.04)":"transparent"},children:[n.jsx("div",{style:{width:36,flexShrink:0},children:n.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:14},children:!(e!=null&&e.avatarUrl)&&(((C=(S=e==null?void 0:e.name)==null?void 0:S[0])==null?void 0:C.toUpperCase())??"?")})}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:2},children:[n.jsx("span",{style:{fontWeight:600,fontSize:14,color:"#111827"},children:(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??"Unknown"}),e&&n.jsx(ue,{status:e.presence.status,size:"xs"}),n.jsxs("span",{style:{fontSize:11,color:"#9ca3af"},children:[h," ",y]}),s.editedAt&&n.jsx("span",{style:{fontSize:11,color:"#9ca3af"},children:"(edited)"}),s.isPinned&&n.jsx("span",{style:{fontSize:11,color:"#6366f1"},children:"๐ Pinned"})]}),s.isDeleted?n.jsx("span",{style:{fontStyle:"italic",color:"#9ca3af",fontSize:14},children:"This message was deleted"}):n.jsx("div",{style:{fontSize:14,lineHeight:1.6,color:"#1f2937",wordBreak:"break-word"},children:s.contentType==="image"&&((d=s.attachments)!=null&&d[0])?n.jsx("img",{src:s.attachments[0].url,alt:s.attachments[0].name,style:{maxWidth:400,maxHeight:300,borderRadius:8,display:"block",marginTop:4}}):s.content}),!s.isDeleted&&s.attachments&&s.attachments.length>0&&s.contentType!=="image"&&n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:4},children:s.attachments.map(z=>n.jsxs("a",{href:z.url,target:"_blank",rel:"noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:12,color:"#6366f1",background:"#ede9fe",borderRadius:6,padding:"3px 8px",textDecoration:"none"},children:["๐ ",z.name]},z.id))}),s.reactions&&s.reactions.length>0&&n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:s.reactions.map(z=>n.jsxs("button",{onClick:()=>a(s.id,z.emoji),style:{background:z.mine?"#ede9fe":"#f3f4f6",border:z.mine?"1px solid #6366f1":"1px solid transparent",borderRadius:12,padding:"2px 7px",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",gap:3},children:[z.emoji," ",z.count]},z.emoji))}),r&&(s.threadCount??0)>0&&n.jsxs("button",{onClick:()=>o(s),style:{background:"none",border:"none",color:"#6366f1",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:3},children:["๐ฌ ",s.threadCount," repl",s.threadCount===1?"y":"ies"," โ"]})]}),p&&!s.isDeleted&&n.jsxs("div",{style:{position:"absolute",top:-16,right:16,display:"flex",gap:2,background:"#fff",borderRadius:8,boxShadow:"0 2px 8px rgba(0,0,0,0.12)",padding:"3px 6px",zIndex:10},children:[i&&n.jsxs("div",{style:{position:"relative"},children:[n.jsx("button",{onClick:()=>f(z=>!z),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"๐"}),m&&n.jsx("div",{style:{position:"absolute",bottom:"100%",right:0,display:"flex",gap:4,background:"#fff",borderRadius:8,boxShadow:"0 2px 8px rgba(0,0,0,0.15)",padding:"6px 8px",zIndex:20},children:Gt.map(z=>n.jsx("button",{onClick:()=>{a(s.id,z),f(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:z},z))})]}),n.jsx("button",{onClick:()=>c(s),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},title:"Reply",children:"โฉ"}),r&&n.jsx("button",{onClick:()=>o(s),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},title:"Open thread",children:"๐ฌ"})]})]})}function wt({channel:s,messages:e,users:t,currentUser:i,team:r,isLoading:a=!1,hasMore:o=!1,enableThreads:c=!0,enableReactions:p=!0,enableAttachments:u=!0,onSendMessage:m,onEditMessage:f,onDeleteMessage:y,onReactToMessage:h,onPinMessage:S,onLoadMoreMessages:C,onStartCall:d,className:z,style:P,id:D,"data-testid":W}){var B;const M=l.useRef(null),F=l.useRef(null),[U,N]=l.useState(""),[H,j]=l.useState(null),[b,T]=l.useState(null),K=l.useMemo(()=>{const g=new Map;return t.forEach(w=>g.set(w.id,w)),g},[t]);l.useEffect(()=>{var g;(g=M.current)==null||g.scrollIntoView({behavior:"smooth"})},[e]);const J=l.useCallback(()=>{const g=F.current;!g||!o||a||g.scrollTop===0&&e.length>0&&(C==null||C(s.id,e[0].id))},[o,a,e,s.id,C]),R=l.useCallback(()=>{const g=U.trim();g&&(m==null||m(s.id,g,"text"),N(""),j(null))},[U,s.id,m]),O=g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),R())},_=t.filter(g=>g.presence.status==="online").length;return n.jsxs("div",{id:D,"data-testid":W,className:`nice-channel-view${z?` ${z}`:""}`,style:{display:"flex",height:"100%",background:"#fff",overflow:"hidden",...P},children:[n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid #e5e7eb",flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsx("span",{style:{fontSize:20,color:"#6b7280"},children:"#"}),n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:700,fontSize:16},children:s.name}),s.description&&n.jsx("div",{style:{fontSize:12,color:"#6b7280",marginTop:1},children:s.description})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsxs("span",{style:{fontSize:12,color:"#6b7280"},children:[n.jsx("span",{style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:"#22c55e",marginRight:4,verticalAlign:"middle"}}),_," online"]}),d&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>d(t.map(g=>g.id),"audio"),style:{background:"none",border:"1px solid #e5e7eb",borderRadius:6,padding:"5px 8px",cursor:"pointer",fontSize:15},title:"Audio call",children:"๐"}),n.jsx("button",{onClick:()=>d(t.map(g=>g.id),"video"),style:{background:"none",border:"1px solid #e5e7eb",borderRadius:6,padding:"5px 8px",cursor:"pointer",fontSize:15},title:"Video meet",children:"๐น"})]})]})]}),n.jsxs("div",{ref:F,onScroll:J,style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[o&&n.jsx("button",{onClick:()=>e.length>0&&(C==null?void 0:C(s.id,e[0].id)),disabled:a,style:{display:"block",margin:"8px auto",background:"none",border:"1px solid #e5e7eb",borderRadius:16,padding:"4px 16px",fontSize:12,color:"#6b7280",cursor:"pointer"},children:a?"Loadingโฆ":"Load older messages"}),e.map(g=>n.jsx(We,{message:g,author:K.get(g.authorId),isMine:g.authorId===i.id,enableReactions:p,enableThreads:c,onReact:(w,V)=>h==null?void 0:h(w,V),onOpenThread:w=>T(w),onReply:w=>j(w)},g.id)),n.jsx("div",{ref:M})]}),n.jsxs("div",{style:{padding:"8px 16px",borderTop:"1px solid #e5e7eb",flexShrink:0},children:[H&&n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",background:"#f3f4f6",borderLeft:"3px solid #6366f1",padding:"3px 8px",marginBottom:6,borderRadius:"0 4px 4px 0",fontSize:12,color:"#6b7280"},children:[n.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Replying to: ",H.content]}),n.jsx("button",{onClick:()=>j(null),style:{background:"none",border:"none",cursor:"pointer",fontSize:16,color:"#9ca3af"},children:"ร"})]}),n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-end"},children:[u&&n.jsx("button",{title:"Attach",style:{background:"none",border:"none",cursor:"pointer",fontSize:18,color:"#9ca3af",padding:"6px 4px"},children:"๐"}),n.jsx("textarea",{value:U,onChange:g=>N(g.target.value),onKeyDown:O,placeholder:`Message #${s.name}`,rows:1,style:{flex:1,resize:"none",border:"1px solid #e5e7eb",borderRadius:8,padding:"8px 12px",fontSize:14,outline:"none",fontFamily:"inherit",lineHeight:1.5,overflow:"hidden",maxHeight:100}}),n.jsx("button",{onClick:R,disabled:!U.trim(),style:{background:U.trim()?"#6366f1":"#e5e7eb",border:"none",borderRadius:"50%",width:36,height:36,cursor:U.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:15,transition:"background 0.15s"},children:"โค"})]})]})]}),b&&n.jsxs("div",{style:{width:340,flexShrink:0,borderLeft:"1px solid #e5e7eb",display:"flex",flexDirection:"column",overflow:"hidden"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid #e5e7eb",flexShrink:0},children:[n.jsx("span",{style:{fontWeight:600,fontSize:14},children:"Thread"}),n.jsx("button",{onClick:()=>T(null),style:{background:"none",border:"none",cursor:"pointer",fontSize:18,color:"#9ca3af"},children:"ร"})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[n.jsx(We,{message:b,author:K.get(b.authorId),isMine:b.authorId===i.id,enableReactions:p,enableThreads:!1,onReact:(g,w)=>h==null?void 0:h(g,w),onOpenThread:()=>{},onReply:()=>{}}),n.jsxs("div",{style:{padding:"6px 14px",color:"#9ca3af",fontSize:12,borderTop:"1px solid #f3f4f6"},children:[b.threadCount??0," repl",b.threadCount===1?"y":"ies"]}),(B=b.thread)==null?void 0:B.map(g=>n.jsx(We,{message:g,author:K.get(g.authorId),isMine:g.authorId===i.id,enableReactions:p,enableThreads:!1,onReact:(w,V)=>h==null?void 0:h(w,V),onOpenThread:()=>{},onReply:()=>{}},g.id))]}),n.jsx("div",{style:{padding:"8px 12px",borderTop:"1px solid #e5e7eb"},children:n.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-end"},children:[n.jsx("textarea",{placeholder:"Reply in threadโฆ",rows:1,onKeyDown:g=>{if(g.key==="Enter"&&!g.shiftKey){g.preventDefault();const w=g.target.value.trim();w&&(m==null||m(s.id,w,"text"),g.target.value="")}},style:{flex:1,resize:"none",border:"1px solid #e5e7eb",borderRadius:8,padding:"7px 10px",fontSize:13,outline:"none",fontFamily:"inherit",overflow:"hidden"}}),n.jsx("button",{style:{background:"#6366f1",border:"none",borderRadius:"50%",width:32,height:32,cursor:"pointer",color:"#fff",fontSize:14,display:"flex",alignItems:"center",justifyContent:"center"},children:"โค"})]})})]})]})}function Fe({participant:s,isLocal:e,isPinned:t,onPin:i,size:r="medium"}){var C;const a=l.useRef(null),{user:o,isMuted:c,isCameraOff:p,isScreenSharing:u,isSpeaking:m,isHandRaised:f,stream:y,screenStream:h}=s;l.useEffect(()=>{if(!a.current)return;const d=u?h:y;d&&(a.current.srcObject=d)},[y,h,u]);const S=!p&&!!y;return n.jsxs("div",{className:`nice-conference-tile${m?" nice-conference-tile--speaking":""}${t?" nice-conference-tile--pinned":""}`,style:{position:"relative",background:"#1f2937",borderRadius:10,overflow:"hidden",border:m?"2px solid #22c55e":t?"2px solid #6366f1":"2px solid transparent",display:"flex",alignItems:"center",justifyContent:"center",aspectRatio:"16/9"},children:[S?n.jsx("video",{ref:a,autoPlay:!0,muted:e,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"cover",transform:e&&!u?"scaleX(-1)":"none"}}):n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:8},children:[n.jsx("div",{style:{width:r==="large"?64:r==="small"?28:44,height:r==="large"?64:r==="small"?28:44,borderRadius:"50%",background:o.avatarUrl?`url(${o.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:r==="large"?28:r==="small"?12:18},children:!o.avatarUrl&&((C=o.name[0])==null?void 0:C.toUpperCase())}),r!=="small"&&n.jsx("span",{style:{color:"#fff",fontSize:12},children:o.displayName??o.name})]}),n.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, rgba(0,0,0,0.6))",padding:"6px 8px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("span",{style:{color:"#fff",fontSize:11,fontWeight:500},children:[o.displayName??o.name,e&&" (You)"]}),n.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[f&&n.jsx("span",{style:{fontSize:13},children:"โ"}),c&&n.jsx("span",{style:{fontSize:12},children:"๐"}),u&&n.jsx("span",{style:{fontSize:12},children:"๐ฅ"}),r!=="small"&&n.jsx("div",{style:{width:6,height:6,borderRadius:"50%",background:m?"#22c55e":"transparent",border:"1px solid rgba(255,255,255,0.3)"}})]})]}),r!=="small"&&n.jsx("button",{onClick:i,style:{position:"absolute",top:6,right:6,background:"rgba(0,0,0,0.4)",border:"none",borderRadius:4,padding:"2px 5px",color:t?"#6366f1":"rgba(255,255,255,0.6)",cursor:"pointer",fontSize:12},title:t?"Unpin":"Pin",children:"๐"}),s.connectionQuality!=="none"&&r!=="small"&&n.jsx("div",{style:{position:"absolute",top:6,left:6,width:14,height:10,display:"flex",gap:2,alignItems:"flex-end"},children:[1,2,3].map(d=>n.jsx("div",{style:{flex:1,background:s.connectionQuality==="excellent"||s.connectionQuality==="good"&&d<=2||s.connectionQuality==="fair"&&d<=1?"#22c55e":"rgba(255,255,255,0.3)",height:`${d*30}%`,borderRadius:1}},d))})]})}function Qe({session:s,currentUser:e,localStream:t,enableScreenSharing:i=!0,enableRecording:r=!1,enableTranscription:a=!1,enableRaiseHand:o=!0,maxGridCols:c=4,onEndCall:p,onMuteAudio:u,onMuteVideo:m,onStartScreenShare:f,onStopScreenShare:y,onRaiseHand:h,className:S,style:C,id:d,"data-testid":z}){const[P,D]=l.useState(!1),[W,M]=l.useState(!1),[F,U]=l.useState(!1),[N,H]=l.useState(!1),[j,b]=l.useState(s.pinnedParticipantId??null),[T,K]=l.useState(s.layout==="sidebar"?"grid":s.layout??"grid"),[J,R]=l.useState(0),[O,_]=l.useState(!1);l.useEffect(()=>{if(s.status!=="active")return;const L=setInterval(()=>R(X=>X+1),1e3);return()=>clearInterval(L)},[s.status]);const B=L=>{const X=Math.floor(L/3600),ne=Math.floor(L%3600/60),se=L%60;return X>0?`${X}:${String(ne).padStart(2,"0")}:${String(se).padStart(2,"0")}`:`${String(ne).padStart(2,"0")}:${String(se).padStart(2,"0")}`},g=()=>{const L=!P;D(L),u==null||u(L)},w=()=>{const L=!W;M(L),m==null||m(L)},V=async()=>{F?(U(!1),y==null||y()):(U(!0),await(f==null?void 0:f()))},q=()=>{const L=!N;H(L),h==null||h(L)},Q=[{user:e,isMuted:P,isCameraOff:W,isScreenSharing:F,isSpeaking:!1,isHandRaised:N,stream:t,connectionQuality:"excellent"},...s.participants],Y=j?Q.find(L=>L.user.id===j):null,re=Q.filter(L=>L.user.id!==j),ae=Q.length,pe=Math.min(c,ae<=1?1:ae<=2||ae<=4?2:ae<=9?3:4),oe=T==="spotlight"||Y!=null;return n.jsxs("div",{id:d,"data-testid":z,className:`nice-video-conference${S?` ${S}`:""}`,style:{position:"relative",width:"100%",height:"100%",background:"#111827",display:"flex",flexDirection:"column",overflow:"hidden",...C},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 16px",flexShrink:0,color:"#fff"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[n.jsxs("span",{style:{fontSize:15,fontWeight:600},children:[s.id.slice(0,8),"โฆ"]}),n.jsx("span",{style:{fontSize:12,color:"rgba(255,255,255,0.6)"},children:B(J)}),s.isRecording&&n.jsx("span",{style:{fontSize:11,color:"#ef4444",display:"flex",alignItems:"center",gap:4},children:"โ Recording"})]}),n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[n.jsx("button",{onClick:()=>K(T==="grid"?"spotlight":"grid"),style:{background:"rgba(255,255,255,0.1)",border:"none",borderRadius:6,padding:"4px 10px",color:"#fff",cursor:"pointer",fontSize:12},children:T==="grid"?"โ Grid":"โก Spotlight"}),n.jsxs("button",{onClick:()=>_(L=>!L),style:{background:O?"#6366f1":"rgba(255,255,255,0.1)",border:"none",borderRadius:6,padding:"4px 10px",color:"#fff",cursor:"pointer",fontSize:12},children:["๐ฅ ",Q.length]})]})]}),n.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden",gap:4,padding:"0 8px 8px"},children:[n.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:4,overflow:"hidden"},children:oe&&Y?n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{flex:1},children:n.jsx(Fe,{participant:Y,isLocal:Y.user.id===e.id,isPinned:!0,onPin:()=>b(null),size:"large"})}),n.jsx("div",{style:{display:"flex",gap:4,height:90,flexShrink:0,overflowX:"auto"},children:re.map(L=>n.jsx("div",{style:{width:140,flexShrink:0},children:n.jsx(Fe,{participant:L,isLocal:L.user.id===e.id,isPinned:!1,onPin:()=>b(L.user.id),size:"small"})},L.user.id))})]}):n.jsx("div",{style:{flex:1,display:"grid",gridTemplateColumns:`repeat(${pe}, 1fr)`,gap:6,overflow:"hidden"},children:Q.map(L=>n.jsx(Fe,{participant:L,isLocal:L.user.id===e.id,isPinned:L.user.id===j,onPin:()=>b(X=>X===L.user.id?null:L.user.id),size:ae<=4?"large":"medium"},L.user.id))})}),O&&n.jsxs("div",{style:{width:220,flexShrink:0,background:"rgba(255,255,255,0.05)",borderRadius:10,display:"flex",flexDirection:"column",overflow:"hidden"},children:[n.jsxs("div",{style:{padding:"10px 12px",fontWeight:600,fontSize:13,color:"#fff",borderBottom:"1px solid rgba(255,255,255,0.1)"},children:["Participants (",Q.length,")"]}),n.jsx("div",{style:{flex:1,overflowY:"auto",padding:8},children:Q.map(L=>{var X;return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px"},children:[n.jsx("div",{style:{width:28,height:28,borderRadius:"50%",background:L.user.avatarUrl?`url(${L.user.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontSize:11,fontWeight:700},children:!L.user.avatarUrl&&((X=L.user.name[0])==null?void 0:X.toUpperCase())}),n.jsx("div",{style:{flex:1,minWidth:0},children:n.jsxs("div",{style:{color:"#fff",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[L.user.displayName??L.user.name,L.user.id===e.id&&" (You)"]})}),n.jsxs("div",{style:{display:"flex",gap:3},children:[L.isHandRaised&&n.jsx("span",{style:{fontSize:11},children:"โ"}),L.isMuted&&n.jsx("span",{style:{fontSize:11},children:"๐"}),n.jsx(ue,{status:L.user.presence.status,size:"xs"})]})]},L.user.id)})})]})]}),n.jsxs("div",{className:"nice-conference-controls",style:{display:"flex",justifyContent:"center",gap:10,padding:"10px 16px",flexShrink:0,background:"rgba(0,0,0,0.3)"},children:[n.jsx(xe,{icon:P?"๐":"๐ค",label:P?"Unmute":"Mute",onClick:g,danger:P}),n.jsx(xe,{icon:W?"๐ท":"๐น",label:W?"Start video":"Stop video",onClick:w,danger:W}),i&&n.jsx(xe,{icon:"๐ฅ",label:F?"Stop share":"Share",onClick:()=>{V()},active:F}),o&&n.jsx(xe,{icon:"โ",label:"Raise hand",onClick:q,active:N}),r&&n.jsx(xe,{icon:"โบ",label:s.isRecording?"Stop rec":"Record",onClick:()=>{},active:s.isRecording,danger:s.isRecording}),a&&n.jsx(xe,{icon:"๐",label:s.isTranscribing?"Stop captions":"Captions",onClick:()=>{},active:s.isTranscribing}),n.jsx(xe,{icon:"๐ต",label:"Leave",onClick:()=>p==null?void 0:p(s.id),end:!0})]})]})}function xe({icon:s,label:e,onClick:t,active:i,danger:r,end:a}){return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[n.jsx("button",{title:e,onClick:t,style:{width:46,height:46,borderRadius:"50%",border:"none",background:a?"#ef4444":r?"#450a0a":i?"#6366f1":"rgba(255,255,255,0.12)",color:"#fff",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.15s"},children:s}),n.jsx("span",{style:{fontSize:9,color:"rgba(255,255,255,0.5)",textAlign:"center",maxWidth:52},children:e})]})}function Ke(s){const e={days:864e5,weeks:6048e5,months:2592e6,years:31536e6,forever:Number.MAX_SAFE_INTEGER};return s.unit==="forever"?e.forever:e[s.unit]*s.value}function Ie(s,e=new Date){if(s.unit!=="forever")return new Date(e.getTime()+Ke(s))}class ot{constructor(e="nice2dev-communication"){this.storeName="nice_comm_store",this.db=null,this.dbName=e}async openDb(){return this.db?this.db:new Promise((e,t)=>{const i=indexedDB.open(this.dbName,1);i.onupgradeneeded=r=>{const a=r.target.result;a.objectStoreNames.contains(this.storeName)||a.createObjectStore(this.storeName,{keyPath:"key"})},i.onsuccess=r=>{this.db=r.target.result,e(this.db)},i.onerror=()=>t(i.error)})}async save(e,t,i){const r=await this.openDb();return new Promise((a,o)=>{const u=r.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:e,data:t,expiresAt:i==null?void 0:i.toISOString()});u.onsuccess=()=>a(),u.onerror=()=>o(u.error)})}async load(e){const t=await this.openDb();return new Promise((i,r)=>{const c=t.transaction(this.storeName,"readonly").objectStore(this.storeName).get(e);c.onsuccess=()=>{const p=c.result;if(!p){i(void 0);return}if(p.expiresAt&&new Date(p.expiresAt)<new Date){this.delete(e),i(void 0);return}i(p.data)},c.onerror=()=>r(c.error)})}async delete(e){const t=await this.openDb();return new Promise((i,r)=>{const c=t.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(e);c.onsuccess=()=>i(),c.onerror=()=>r(c.error)})}async list(e){const t=await this.openDb();return new Promise((i,r)=>{const c=t.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();c.onsuccess=()=>i((c.result??[]).filter(p=>p.startsWith(e))),c.onerror=()=>r(c.error)})}async clear(e){if(!e){const i=await this.openDb();return new Promise((r,a)=>{const p=i.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();p.onsuccess=()=>r(),p.onerror=()=>a(p.error)})}const t=await this.list(e);await Promise.all(t.map(i=>this.delete(i)))}}class qt{constructor(e="nice_comm__"){this.prefix=e}async save(e,t,i){const r={data:t,expiresAt:i==null?void 0:i.toISOString()};localStorage.setItem(this.prefix+e,JSON.stringify(r))}async load(e){const t=localStorage.getItem(this.prefix+e);if(t)try{const i=JSON.parse(t);if(i.expiresAt&&new Date(i.expiresAt)<new Date){await this.delete(e);return}return i.data}catch{return}}async delete(e){localStorage.removeItem(this.prefix+e)}async list(e){const t=[];for(let i=0;i<localStorage.length;i++){const r=localStorage.key(i);r&&r.startsWith(this.prefix+e)&&t.push(r.slice(this.prefix.length))}return t}async clear(e){(await this.list(e??"")).forEach(i=>localStorage.removeItem(this.prefix+i))}}class kt{constructor(e,t){this.config=e,this.encryption=t,this.adapter=this.buildAdapter()}buildAdapter(){switch(this.config.provider){case"localstorage":return new qt;case"custom":return this.config.customAdapter??new ot;default:return new ot}}getRuleFor(e){return this.config.retentionRules.find(t=>t.dataType===e)}async encode(e){var i;const t=JSON.stringify(e);return(i=this.encryption)!=null&&i.isEnabled()?this.encryption.encrypt(t,"messages"):t}async decode(e){var t;if(typeof e!="string")return e;if(!((t=this.encryption)!=null&&t.isEnabled()))try{return JSON.parse(e)}catch{return e}try{const i=await this.encryption.decrypt(e,"messages");return JSON.parse(i)}catch{return e}}async saveMessages(e,t){const i=this.getRuleFor("messages"),r=i?Ie(i.activePeriod):void 0,a=await this.encode(t);await this.adapter.save(`msg:${e}`,a,r)}async loadMessages(e){const t=await this.adapter.load(`msg:${e}`);if(!t)return[];const i=await this.decode(t);return Array.isArray(i)?i:[]}async appendMessage(e,t){const i=await this.loadMessages(e);await this.saveMessages(e,[...i,t])}async saveWhiteboardSnapshot(e,t){const i=this.getRuleFor("whiteboard-snapshots"),r=i?Ie(i.activePeriod):void 0,a=await this.encode(t);await this.adapter.save(`wb:${e}`,a,r)}async loadWhiteboardSnapshot(e){const t=await this.adapter.load(`wb:${e}`);return t?await this.decode(t):null}async saveRecordingMeta(e){const t=this.getRuleFor("recordings"),i=t?Ie(t.activePeriod):void 0,r=await this.encode(e);await this.adapter.save(`rec:${e.id}`,r,i)}async loadRecordingMeta(e){const t=await this.adapter.load(`rec:${e}`);return t?await this.decode(t):null}async listRecordings(){const e=await this.adapter.list("rec:");return(await Promise.all(e.map(i=>this.loadRecordingMeta(i.slice(4))))).filter(Boolean)}async deleteRecording(e){await this.adapter.delete(`rec:${e}`)}async saveDocument(e,t){const i=this.getRuleFor("documents"),r=i?Ie(i.activePeriod):void 0,a=await this.encode(t);await this.adapter.save(`doc:${e}`,a,r)}async loadDocument(e){const t=await this.adapter.load(`doc:${e}`);return t?this.decode(t):null}async enforceRetention(){let e=0,t=0;const i=new Date,r=[{prefix:"msg:",type:"messages"},{prefix:"wb:",type:"whiteboard-snapshots"},{prefix:"rec:",type:"recordings"},{prefix:"doc:",type:"documents"}];for(const{prefix:a,type:o}of r){const c=this.getRuleFor(o);if(!c)continue;const p=await this.adapter.list(a);for(const u of p){const m=await this.adapter.load(u);if(m){if(Ke(c.activePeriod),c.archivePeriod){const f=`archive:${u}`,y=Ie(c.archivePeriod,i);await this.adapter.save(f,m,y),e++}if(c.deleteAfterArchive&&c.archivePeriod){const f=Ke(c.archivePeriod);new Date(i.getTime()+f)<i&&(await this.adapter.delete(`archive:${u}`),t++)}}}}return{archived:e,deleted:t}}async estimateUsageBytes(){return typeof window<"u"&&"storage"in navigator&&"estimate"in navigator.storage?(await navigator.storage.estimate()).usage??0:0}updateConfig(e){this.config=e,this.adapter=this.buildAdapter()}getConfig(){return this.config}}const Ze=[{dataType:"messages",activePeriod:{value:1,unit:"years"},archivePeriod:{value:2,unit:"years"},deleteAfterArchive:!0,userCanDelete:!0},{dataType:"attachments",activePeriod:{value:6,unit:"months"},archivePeriod:{value:1,unit:"years"},deleteAfterArchive:!0,userCanDelete:!0},{dataType:"recordings",activePeriod:{value:3,unit:"months"},archivePeriod:{value:6,unit:"months"},deleteAfterArchive:!0,userCanDelete:!0},{dataType:"whiteboard-snapshots",activePeriod:{value:1,unit:"years"},deleteAfterArchive:!1,userCanDelete:!0},{dataType:"transcripts",activePeriod:{value:1,unit:"years"},archivePeriod:{value:2,unit:"years"},deleteAfterArchive:!0,userCanDelete:!0},{dataType:"documents",activePeriod:{value:3,unit:"years"},deleteAfterArchive:!1,userCanDelete:!0},{dataType:"call-logs",activePeriod:{value:90,unit:"days"},deleteAfterArchive:!0,userCanDelete:!1},{dataType:"audit-logs",activePeriod:{value:2,unit:"years"},deleteAfterArchive:!1,userCanDelete:!1,legalHoldEnabled:!0}],Me=new Map;function jt(s,e,t){return Me.has(s)||Me.set(s,new kt(e,t)),Me.get(s)}function Vt(s){Me.delete(s)}const lt=["#e91e63","#9c27b0","#3f51b5","#2196f3","#00bcd4","#4caf50","#ff9800","#ff5722","#795548","#607d8b"];function Xt(s){let e=0;for(let t=0;t<s.length;t++)e=e*31+s.charCodeAt(t)>>>0;return lt[e%lt.length]}function ct(s,e,t){const i={...s},r=[...e];switch(t.type){case"object:add":case"object:update":{const a=t.payload;if(i[a.id]=a,r.length>0&&!r[0].objectIds.includes(a.id)){const o=a.layerId?r.find(c=>c.id===a.layerId)??r[0]:r[0];o.objectIds=[...o.objectIds,a.id]}break}case"object:delete":{const{id:a}=t.payload;delete i[a],r.forEach(o=>{o.objectIds=o.objectIds.filter(c=>c!==a)});break}case"object:move":{const{id:a,x:o,y:c}=t.payload;i[a]&&(i[a]={...i[a],x:o,y:c,updatedAt:t.timestamp});break}case"layer:add":{const a=t.payload;r.find(o=>o.id===a.id)||r.push(a);break}case"layer:update":{const a=t.payload,o=r.findIndex(c=>c.id===a.id);o!==-1&&(r[o]={...r[o],...a});break}case"layer:delete":{const{id:a}=t.payload,o=r.findIndex(c=>c.id===a);o!==-1&&r.splice(o,1);break}}return{objects:i,layers:r}}function Jt(s,e){switch(e.type){case"LOAD_SESSION":return{...s,session:e.session,undoStack:[],redoStack:[],isDirty:!1};case"SET_TOOL":return{...s,activeTool:e.tool};case"APPLY_OP":{const{op:t,local:i}=e,{objects:r,layers:a}=ct(s.session.objects,s.session.layers,t),o={...s.session,objects:r,layers:a,updatedAt:t.timestamp},p=i&&["object:add","object:update","object:delete","object:move","layer:add","layer:update","layer:delete"].includes(t.type)?[...s.undoStack,[t]]:s.undoStack;return{...s,session:o,undoStack:p,redoStack:i?[]:s.redoStack,isDirty:!0}}case"UNDO":{if(s.undoStack.length===0)return s;const t=s.undoStack[s.undoStack.length-1],i=t.filter(o=>o.type==="object:add").map(o=>o.payload.id),r={...s.session.objects};i.forEach(o=>delete r[o]);const a=s.session.layers.map(o=>({...o,objectIds:o.objectIds.filter(c=>!i.includes(c))}));return{...s,session:{...s.session,objects:r,layers:a},undoStack:s.undoStack.slice(0,-1),redoStack:[t,...s.redoStack],isDirty:!0}}case"REDO":{if(s.redoStack.length===0)return s;const t=s.redoStack[0];let{objects:i,layers:r}={objects:s.session.objects,layers:s.session.layers};for(const a of t)({objects:i,layers:r}=ct(i,r,a));return{...s,session:{...s.session,objects:i,layers:r},undoStack:[...s.undoStack,t],redoStack:s.redoStack.slice(1),isDirty:!0}}case"SET_SELECTION":return{...s,selectedObjectIds:e.ids};case"SET_DRAWING":return{...s,isDrawing:e.value};case"SET_PANNING":return{...s,isPanning:e.value};case"UPDATE_CURSOR":{const{userId:t,x:i,y:r}=e,a=s.session.collaborators[t];return a?{...s,session:{...s.session,collaborators:{...s.session.collaborators,[t]:{...a,cursorX:i,cursorY:r,lastSeenAt:new Date}}}}:s}case"REMOVE_COLLABORATOR":{const t={...s.session.collaborators};return delete t[e.userId],{...s,session:{...s.session,collaborators:t}}}case"SET_VIEWPORT":return{...s,session:{...s.session,viewport:e.viewport}};case"MARK_SAVED":return{...s,isDirty:!1,lastSavedAt:new Date};default:return s}}function Ct(s){const{session:e,currentUser:t,onOperation:i,remoteOperations:r=[],readonly:a=!1,storageConfig:o,autoSaveMs:c=3e4}=s,[p,u]=l.useReducer(Jt,{session:e,activeTool:a?"select":"pen",selectedObjectIds:[],undoStack:[],redoStack:[],isDrawing:!1,isPanning:!1,isDirty:!1}),m=l.useRef(0),f=l.useRef(null),y=l.useRef(null);l.useEffect(()=>{o&&(y.current=jt(`wb_${e.id}`,o),y.current.loadWhiteboardSnapshot(e.id).then(R=>{R&&u({type:"LOAD_SESSION",session:R})}))},[e.id,o]),l.useEffect(()=>{if(!c||!y.current||!p.isDirty)return;const R=setTimeout(()=>{var O;(O=y.current)==null||O.saveWhiteboardSnapshot(p.session.id,p.session).then(()=>{u({type:"MARK_SAVED"})})},c);return()=>clearTimeout(R)},[p.isDirty,p.session,c]);const h=l.useRef(new Set);l.useEffect(()=>{for(const R of r)if(!h.current.has(R.id)&&R.userId!==t.id)if(h.current.add(R.id),R.type==="cursor:move"){const{x:O,y:_}=R.payload;u({type:"UPDATE_CURSOR",userId:R.userId,x:O,y:_})}else R.type==="viewport:sync"||u({type:"APPLY_OP",op:R,local:!1})},[r,t.id]);function S(R,O){return{id:`${t.id}_${++m.current}_${Date.now()}`,sessionId:p.session.id,type:R,userId:t.id,timestamp:new Date,payload:O}}const C=l.useCallback(R=>{a||u({type:"SET_TOOL",tool:R})},[a]),d=l.useCallback(R=>{if(a)return;const O=S("object:add",R);u({type:"APPLY_OP",op:O,local:!0}),i==null||i(O)},[a,i,p.session.id]),z=l.useCallback(R=>{if(a)return;const O=S("object:update",R);u({type:"APPLY_OP",op:O,local:!0}),i==null||i(O)},[a,i,p.session.id]),P=l.useCallback(R=>{if(!a){for(const O of R){const _=S("object:delete",{id:O});u({type:"APPLY_OP",op:_,local:!0}),i==null||i(_)}u({type:"SET_SELECTION",ids:[]})}},[a,i,p.session.id]),D=l.useCallback(R=>{if(!a)for(const{id:O,x:_,y:B}of R){const g=S("object:move",{id:O,x:_,y:B});u({type:"APPLY_OP",op:g,local:!0}),i==null||i(g)}},[a,i,p.session.id]),W=l.useCallback(R=>{u({type:"SET_SELECTION",ids:R})},[]),M=l.useCallback(()=>{a||u({type:"UNDO"})},[a]),F=l.useCallback(()=>{a||u({type:"REDO"})},[a]),U=l.useCallback(R=>{u({type:"SET_VIEWPORT",viewport:R});const O=S("viewport:sync",R);i==null||i(O)},[i,p.session.id]),N=l.useCallback((R,O)=>{if(f.current)return;f.current=setTimeout(()=>{f.current=null},50);const _=S("cursor:move",{x:R,y:O});i==null||i(_)},[i,p.session.id]),H=l.useCallback(R=>{if(a)return;const O={id:`layer_${Date.now()}`,name:R,visible:!0,locked:!1,objectIds:[]},_=S("layer:add",O);u({type:"APPLY_OP",op:_,local:!0}),i==null||i(_)},[a,i,p.session.id]),j=l.useCallback(R=>{if(a)return;const O=S("layer:update",R);u({type:"APPLY_OP",op:O,local:!0}),i==null||i(O)},[a,i,p.session.id]),b=l.useCallback(R=>{if(a)return;const O=S("layer:delete",{id:R});u({type:"APPLY_OP",op:O,local:!0}),i==null||i(O)},[a,i,p.session.id]),T=l.useCallback(R=>{const O={user:R,cursorX:0,cursorY:0,color:Xt(R.id),selectedObjectIds:[],activeTool:"pen",lastSeenAt:new Date};u({type:"APPLY_OP",op:S("cursor:move",O),local:!1})},[]),K=l.useCallback(R=>{u({type:"REMOVE_COLLABORATOR",userId:R})},[]),J=l.useCallback(async()=>{y.current&&(await y.current.saveWhiteboardSnapshot(p.session.id,p.session),u({type:"MARK_SAVED"}))},[p.session]);return{session:p.session,activeTool:p.activeTool,selectedObjectIds:p.selectedObjectIds,isDrawing:p.isDrawing,isPanning:p.isPanning,isDirty:p.isDirty,lastSavedAt:p.lastSavedAt,canUndo:p.undoStack.length>0,canRedo:p.redoStack.length>0,collaborators:Object.values(p.session.collaborators),objects:Object.values(p.session.objects),layers:p.session.layers,viewport:p.session.viewport,setTool:C,addObject:d,updateObject:z,deleteObjects:P,moveObjects:D,setSelection:W,undo:M,redo:F,setViewport:U,broadcastCursor:N,addLayer:H,updateLayer:j,deleteLayer:b,registerCollaborator:T,removeCollaborator:K,saveNow:J}}const Qt=[{id:"select",label:"Select",icon:"โ",group:"select"},{id:"laser",label:"Laser",icon:"๐ด",group:"select"},{id:"pen",label:"Pen",icon:"โ๏ธ",group:"draw"},{id:"highlighter",label:"Highlight",icon:"๐๏ธ",group:"draw"},{id:"eraser",label:"Eraser",icon:"โฌ",group:"draw"},{id:"line",label:"Line",icon:"โฑ",group:"shape"},{id:"arrow",label:"Arrow",icon:"โ",group:"shape"},{id:"rect",label:"Rectangle",icon:"โก",group:"shape"},{id:"ellipse",label:"Ellipse",icon:"โ",group:"shape"},{id:"triangle",label:"Triangle",icon:"โณ",group:"shape"},{id:"frame",label:"Frame",icon:"โฌ",group:"shape"},{id:"text",label:"Text",icon:"T",group:"insert"},{id:"sticky",label:"Sticky",icon:"๐",group:"insert"},{id:"image",label:"Image",icon:"๐ผ๏ธ",group:"insert"}];function Ee(){return`${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function _e(s,e,t){return{sx:s*t.scale+t.x,sy:e*t.scale+t.y}}function Zt(s,e,t){return{wx:(s-t.x)/t.scale,wy:(e-t.y)/t.scale}}function en(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function tn(s,e){if(!(e.points.length<2)){s.save(),s.globalAlpha=e.opacity,s.strokeStyle=e.color,s.lineWidth=e.strokeWidth,s.lineCap="round",s.lineJoin="round",e.tool==="highlighter"&&(s.globalCompositeOperation="multiply"),s.beginPath(),s.moveTo(e.points[0].x,e.points[0].y);for(let t=1;t<e.points.length;t++){const i={x:(e.points[t-1].x+e.points[t].x)/2,y:(e.points[t-1].y+e.points[t].y)/2};s.quadraticCurveTo(e.points[t-1].x,e.points[t-1].y,i.x,i.y)}s.stroke(),s.restore()}}function nn(s,e){switch(s.save(),s.globalAlpha=e.opacity,s.strokeStyle=e.strokeColor,s.lineWidth=e.strokeWidth,e.fillColor&&(s.fillStyle=e.fillColor),s.translate(e.x+e.width/2,e.y+e.height/2),s.rotate(e.rotation*Math.PI/180),s.beginPath(),e.shape){case"rect":s.rect(-e.width/2,-e.height/2,e.width,e.height);break;case"ellipse":s.ellipse(0,0,e.width/2,e.height/2,0,0,Math.PI*2);break;case"triangle":{const t=e.width/2,i=e.height/2;s.moveTo(0,-i),s.lineTo(t,i),s.lineTo(-t,i),s.closePath();break}case"diamond":{const t=e.width/2,i=e.height/2;s.moveTo(0,-i),s.lineTo(t,0),s.lineTo(0,i),s.lineTo(-t,0),s.closePath();break}}e.fillColor&&s.fill(),s.stroke(),s.restore()}function sn(s,e){if(s.save(),s.translate(e.x+e.width/2,e.y+e.height/2),s.rotate(e.rotation*Math.PI/180),s.font=`${e.fontStyle} ${e.fontWeight} ${e.fontSize}px ${e.fontFamily}`,s.fillStyle=e.color,s.textAlign=e.textAlign,s.textBaseline="middle",e.backgroundColor){const t=s.measureText(e.text),i=4;s.fillStyle=e.backgroundColor,s.fillRect(-t.width/2-i,-e.fontSize/2-i,t.width+i*2,e.fontSize+i*2),s.fillStyle=e.color}s.fillText(e.text,0,0),s.restore()}function rn(s,e){s.save(),s.translate(e.x,e.y),s.rotate(e.rotation*Math.PI/180),s.shadowColor="rgba(0,0,0,0.15)",s.shadowBlur=8,s.shadowOffsetY=3,s.fillStyle=e.backgroundColor,s.fillRect(0,0,e.width,e.height),s.shadowColor="transparent",s.fillStyle=e.textColor,s.font=`${e.fontSize}px sans-serif`,s.textAlign="left",s.textBaseline="top";const t=10,i=e.width-t*2,r=e.fontSize*1.4,a=e.text.split(" ");let o="",c=t;for(const p of a){const u=o?`${o} ${p}`:p;s.measureText(u).width>i&&o?(s.fillText(o,t,c),o=p,c+=r):o=u}o&&s.fillText(o,t,c),s.restore()}function an(s,e){if(!(e.points.length<2)){if(s.save(),s.strokeStyle=e.strokeColor,s.lineWidth=e.strokeWidth,s.lineCap="round",s.beginPath(),s.moveTo(e.points[0].x,e.points[0].y),e.curved&&e.points.length>2){for(let t=1;t<e.points.length-1;t++){const i=e.points[t],r={x:(i.x+e.points[t+1].x)/2,y:(i.y+e.points[t+1].y)/2};s.quadraticCurveTo(i.x,i.y,r.x,r.y)}s.lineTo(e.points[e.points.length-1].x,e.points[e.points.length-1].y)}else for(let t=1;t<e.points.length;t++)s.lineTo(e.points[t].x,e.points[t].y);if(s.stroke(),e.arrowEnd==="arrow"){const t=e.points[e.points.length-1],i=e.points[e.points.length-2],r=Math.atan2(t.y-i.y,t.x-i.x),a=12;s.beginPath(),s.moveTo(t.x,t.y),s.lineTo(t.x-a*Math.cos(r-Math.PI/6),t.y-a*Math.sin(r-Math.PI/6)),s.moveTo(t.x,t.y),s.lineTo(t.x-a*Math.cos(r+Math.PI/6),t.y-a*Math.sin(r+Math.PI/6)),s.stroke()}s.restore()}}function on(s,e){s.save(),s.strokeStyle=e.borderColor??"#aaa",s.lineWidth=2,s.setLineDash([8,4]),e.backgroundColor&&(s.fillStyle=e.backgroundColor,s.fillRect(e.x,e.y,e.width,e.height)),s.strokeRect(e.x,e.y,e.width,e.height),s.setLineDash([]),s.fillStyle="#555",s.font="bold 13px sans-serif",s.fillText(e.name,e.x+8,e.y-6),s.restore()}function ln(s,e){if(e.visible)switch(e.type){case"stroke":return tn(s,e);case"shape":return nn(s,e);case"text":return sn(s,e);case"sticky":return rn(s,e);case"connector":return an(s,e);case"frame":return on(s,e);case"image":{const t=e,i=new Image;i.src=t.dataUrl??t.url,s.save(),s.translate(t.x+t.width/2,t.y+t.height/2),s.rotate(t.rotation*Math.PI/180),s.drawImage(i,-t.width/2,-t.height/2,t.width,t.height),s.restore();break}}}function et({session:s,currentUser:e,onOperation:t,remoteOperations:i=[],readonly:r=!1,enableLayers:a=!0,enableExport:o=!0,enableLaserPointer:c=!0,enableVectorEditor:p=!1,enableDiagramEditor:u=!1,onExport:m,onSessionUpdate:f,storageConfig:y,className:h,style:S,"data-testid":C}){const d=Ct({session:s,currentUser:e,onOperation:t,remoteOperations:i,readonly:r,storageConfig:y,autoSaveMs:3e4}),z=l.useRef(null);l.useRef(null);const P=l.useRef(0),[D,W]=l.useState(!1),[M,F]=l.useState("#1a1a1a"),[U,N]=l.useState(3),[H,j]=l.useState(void 0),[b,T]=l.useState(18),[K,J]=l.useState("#fef08a"),[R,O]=l.useState(null),[_,B]=l.useState(null),g=l.useRef({active:!1,startX:0,startY:0,currentPoints:[],currentId:"",spaceDown:!1,panStart:null,laserPoints:[]}),w=l.useCallback((x,v,E,$)=>{if(!d.session.gridEnabled)return;const A=d.session.gridSize*v.scale,G=(v.x%A+A)%A,k=(v.y%A+A)%A;x.strokeStyle="rgba(180,180,200,0.35)",x.lineWidth=1,x.beginPath();for(let I=G;I<E;I+=A)x.moveTo(I,0),x.lineTo(I,$);for(let I=k;I<$;I+=A)x.moveTo(0,I),x.lineTo(E,I);x.stroke()},[d.session.gridEnabled,d.session.gridSize]),V=l.useCallback((x,v)=>{for(const E of d.collaborators){if(E.user.id===e.id)continue;const{sx:$,sy:A}=_e(E.cursorX,E.cursorY,v);x.save(),x.fillStyle=E.color,x.beginPath(),x.moveTo($,A),x.lineTo($+14,A+5),x.lineTo($+5,A+14),x.closePath(),x.fill(),x.fillStyle=E.color,x.font="bold 11px sans-serif",x.fillText(E.user.name,$+16,A+14),x.restore()}},[d.collaborators,e.id]),q=l.useCallback((x,v)=>{if(d.selectedObjectIds.length!==0)for(const E of d.selectedObjectIds){const $=d.session.objects[E];if(!$)continue;const{sx:A,sy:G}=_e($.x,$.y,v),k=$.width*v.scale,I=$.height*v.scale;x.strokeStyle="#4f8df9",x.lineWidth=1.5,x.setLineDash([4,2]),x.strokeRect(A-2,G-2,k+4,I+4),x.setLineDash([]);const ee=[[A-2,G-2],[A+k+2,G-2],[A-2,G+I+2],[A+k+2,G+I+2]];x.fillStyle="#fff",x.strokeStyle="#4f8df9",x.lineWidth=1.5;for(const[Z,ie]of ee)x.fillRect(Z-4,ie-4,8,8),x.strokeRect(Z-4,ie-4,8,8)}},[d.selectedObjectIds,d.session.objects]),Q=l.useCallback(()=>{const x=z.current;if(!x)return;const v=x.getContext("2d");if(!v)return;const{width:E,height:$}=x,A=d.viewport;v.clearRect(0,0,E,$),v.fillStyle=d.session.backgroundColor,v.fillRect(0,0,E,$),w(v,A,E,$),v.save();const G=Object.values(d.session.objects).filter(k=>k.visible).sort((k,I)=>k.zIndex-I.zIndex);v.translate(A.x,A.y),v.scale(A.scale,A.scale);for(const k of G)ln(v,k);if(g.current.active&&g.current.currentPoints.length>1){const k=g.current.currentPoints;v.strokeStyle=M,v.lineWidth=U,v.lineCap="round",v.lineJoin="round",v.beginPath(),v.moveTo(k[0].x,k[0].y);for(let I=1;I<k.length;I++)v.lineTo(k[I].x,k[I].y);v.stroke()}if(g.current.laserPoints.length>1&&d.activeTool==="laser"){const k=g.current.laserPoints;v.strokeStyle="#ff2c2c",v.lineWidth=3,v.globalAlpha=.7,v.beginPath(),v.moveTo(k[0].x,k[0].y);for(let I=1;I<k.length;I++)v.lineTo(k[I].x,k[I].y);v.stroke(),v.globalAlpha=1}v.restore(),q(v,A),V(v,A)},[d.session,d.viewport,d.activeTool,w,V,q,M,U]);l.useLayoutEffect(()=>{function x(){Q(),P.current=requestAnimationFrame(x)}return P.current=requestAnimationFrame(x),()=>cancelAnimationFrame(P.current)},[Q]),l.useEffect(()=>{const x=z.current;if(!x)return;const v=new ResizeObserver(()=>{x.width=x.offsetWidth,x.height=x.offsetHeight});return v.observe(x),x.width=x.offsetWidth,x.height=x.offsetHeight,()=>v.disconnect()},[]),l.useEffect(()=>{function x(v){if(v.target.tagName==="INPUT"||v.target.tagName==="TEXTAREA"||(v.code==="Space"&&(g.current.spaceDown=v.type==="keydown",v.preventDefault()),v.type!=="keydown"))return;(v.ctrlKey||v.metaKey)&&(v.key==="z"&&(v.preventDefault(),d.undo()),v.key==="y"&&(v.preventDefault(),d.redo()),v.key==="s"&&(v.preventDefault(),d.saveNow()),v.key==="a"&&(v.preventDefault(),d.setSelection(Object.keys(d.session.objects)))),(v.key==="Delete"||v.key==="Backspace")&&d.selectedObjectIds.length>0&&d.deleteObjects(d.selectedObjectIds);const E={v:"select",p:"pen",h:"highlighter",e:"eraser",r:"rect",c:"ellipse",t:"text",s:"sticky",i:"image",a:"arrow",l:"laser"};!v.ctrlKey&&!v.metaKey&&E[v.key]&&d.setTool(E[v.key])}return window.addEventListener("keydown",x),window.addEventListener("keyup",x),()=>{window.removeEventListener("keydown",x),window.removeEventListener("keyup",x)}},[d]);const Y=l.useCallback(x=>{const v=z.current.getBoundingClientRect(),E=x.clientX-v.left,$=x.clientY-v.top,{wx:A,wy:G}=Zt(E,$,d.viewport);return{x:A,y:G,pressure:x.pressure??.5}},[d.viewport]),re=l.useCallback(x=>{if(r)return;x.target.setPointerCapture(x.pointerId);const v=Y(x);if(x.button===1||g.current.spaceDown){g.current.panStart={x:x.clientX,y:x.clientY,vpX:d.viewport.x,vpY:d.viewport.y};return}const E=d.activeTool;if(g.current.active=!0,g.current.startX=v.x,g.current.startY=v.y,g.current.currentId=Ee(),E==="pen"||E==="highlighter")g.current.currentPoints=[v];else if(E==="laser")g.current.laserPoints=[v];else if(E==="select"){const $=Object.values(d.session.objects).filter(A=>A.visible&&A.x<=v.x&&A.y<=v.y&&A.x+A.width>=v.x&&A.y+A.height>=v.y).sort((A,G)=>G.zIndex-A.zIndex)[0];$?x.shiftKey?d.setSelection([...d.selectedObjectIds,$.id]):d.setSelection([$.id]):d.setSelection([])}},[r,Y,d]),ae=l.useCallback(x=>{const v=Y(x);if(d.broadcastCursor(v.x,v.y),g.current.panStart){const{x:$,y:A,vpX:G,vpY:k}=g.current.panStart;d.setViewport({...d.viewport,x:G+(x.clientX-$),y:k+(x.clientY-A)});return}if(!g.current.active)return;const E=d.activeTool;if(E==="pen"||E==="highlighter"){const $=g.current.currentPoints;($.length===0||en($[$.length-1],v)>2)&&(g.current.currentPoints=[...$,v])}else if(E==="laser"){const $=g.current.laserPoints;g.current.laserPoints=[...$.slice(-40),v]}else if(E==="select"&&d.selectedObjectIds.length>0){const $=v.x-g.current.startX,A=v.y-g.current.startY;g.current.startX=v.x,g.current.startY=v.y,d.moveObjects(d.selectedObjectIds.map(G=>{const k=d.session.objects[G];return{id:G,x:k.x+$,y:k.y+A}}))}},[Y,d]),pe=l.useCallback(x=>{if(g.current.panStart){g.current.panStart=null;return}if(!g.current.active)return;const v=Y(x),E=d.activeTool,$=g.current.startX,A=g.current.startY,G=g.current.currentId,k=new Date;switch(g.current.active=!1,E){case"pen":case"highlighter":{const I=g.current.currentPoints;if(I.length<2)break;const ee={id:G,type:"stroke",x:Math.min(...I.map(Z=>Z.x)),y:Math.min(...I.map(Z=>Z.y)),width:Math.max(...I.map(Z=>Z.x))-Math.min(...I.map(Z=>Z.x)),height:Math.max(...I.map(Z=>Z.y))-Math.min(...I.map(Z=>Z.y)),rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,points:I,color:M,strokeWidth:U,opacity:E==="highlighter"?.4:1,tool:E};d.addObject(ee),g.current.currentPoints=[];break}case"rect":case"ellipse":case"triangle":{const I=Math.min($,v.x),ee=Math.min(A,v.y),Z=Math.abs(v.x-$),ie=Math.abs(v.y-A);if(Z<5||ie<5)break;const ce={rect:"rect",ellipse:"ellipse",triangle:"triangle"},me={id:G,type:"shape",x:I,y:ee,width:Z,height:ie,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,shape:ce[E],fillColor:H,strokeColor:M,strokeWidth:U,opacity:1};d.addObject(me);break}case"arrow":case"line":{const I={id:G,type:"connector",x:Math.min($,v.x),y:Math.min(A,v.y),width:Math.abs(v.x-$),height:Math.abs(v.y-A),rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,points:[{x:$,y:A},{x:v.x,y:v.y}],strokeColor:M,strokeWidth:U,arrowStart:"none",arrowEnd:E==="arrow"?"arrow":"none",curved:!1};d.addObject(I);break}case"text":{const I={id:G,type:"text",x:v.x,y:v.y,width:200,height:b+10,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,text:"Click to edit",fontSize:b,fontFamily:"sans-serif",fontWeight:"normal",fontStyle:"normal",textAlign:"left",color:M};d.addObject(I),O(G);break}case"sticky":{const I={id:G,type:"sticky",x:v.x,y:v.y,width:180,height:150,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,text:"Note...",backgroundColor:K,textColor:"#333",fontSize:14,authorId:e.id};d.addObject(I),O(G);break}case"frame":{const I=Math.min($,v.x),ee=Math.min(A,v.y),Z=Math.abs(v.x-$),ie=Math.abs(v.y-A);if(Z<20||ie<20)break;const ce={id:G,type:"frame",x:I,y:ee,width:Z,height:ie,rotation:0,zIndex:0,locked:!1,visible:!0,createdBy:e.id,createdAt:k,name:`Frame ${Object.keys(d.session.objects).length+1}`,childIds:[],borderColor:"#8888"};d.addObject(ce);break}case"image":{const I=document.createElement("input");I.type="file",I.accept="image/*",I.onchange=()=>{var ie;const ee=(ie=I.files)==null?void 0:ie[0];if(!ee)return;const Z=new FileReader;Z.onload=ce=>{var Pe;const me=(Pe=ce.target)==null?void 0:Pe.result,fe=new Image;fe.onload=()=>{const Ae=400/fe.width,ye={id:Ee(),type:"image",x:v.x,y:v.y,width:fe.width*Ae,height:fe.height*Ae,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:me,dataUrl:me,originalWidth:fe.width,originalHeight:fe.height};d.addObject(ye)},fe.src=me},Z.readAsDataURL(ee)},I.click();break}}},[Y,d,e.id,M,U,H,b,K]),oe=l.useCallback(x=>{if(x.preventDefault(),!x.ctrlKey&&!x.metaKey){d.setViewport({...d.viewport,x:d.viewport.x-x.deltaX,y:d.viewport.y-x.deltaY});return}const v=z.current.getBoundingClientRect(),E=x.clientX-v.left,$=x.clientY-v.top,G=-x.deltaY>0?1.1:.9,k=Math.min(8,Math.max(.1,d.viewport.scale*G));d.setViewport({scale:k,x:E-(E-d.viewport.x)*(k/d.viewport.scale),y:$-($-d.viewport.y)*(k/d.viewport.scale)})},[d]),L=l.useCallback(x=>{if(x==="json"){const A=JSON.stringify(d.session,null,2);m==null||m("json",A);const G=document.createElement("a");G.href=URL.createObjectURL(new Blob([A],{type:"application/json"})),G.download=`${d.session.title}.json`,G.click();return}const v=z.current;if(!v)return;const E=v.toDataURL("image/png");m==null||m("png",E);const $=document.createElement("a");$.href=E,$.download=`${d.session.title}.png`,$.click()},[d.session,m]);l.useEffect(()=>{f==null||f(d.session)},[d.session,f]),l.useEffect(()=>{function x(v){if(v.clipboardData){for(const E of Array.from(v.clipboardData.items))if(E.type.startsWith("image/")){const $=E.getAsFile();if(!$)continue;const A=new FileReader;A.onload=G=>{var ee;const k=(ee=G.target)==null?void 0:ee.result,I=new Image;I.onload=()=>{const ie=400/I.width,ce={id:Ee(),type:"image",x:100,y:100,width:I.width*ie,height:I.height*ie,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:k,dataUrl:k,originalWidth:I.width,originalHeight:I.height};d.addObject(ce)},I.src=k},A.readAsDataURL($);break}}}return window.addEventListener("paste",x),()=>window.removeEventListener("paste",x)},[d,e.id]);const X=R?d.session.objects[R]:null,ne=l.useMemo(()=>X?_e(X.x,X.y,d.viewport):null,[X,d.viewport]),se=["#fef08a","#bfdbfe","#bbf7d0","#fecaca","#e9d5ff","#fed7aa"],le=l.useMemo(()=>{var v;const x={};for(const E of Qt)(x[v=E.group]??(x[v]=[])).push(E);return Object.values(x)},[]);return n.jsxs("div",{className:h,"data-testid":C,style:{position:"relative",display:"flex",flexDirection:"column",width:"100%",height:"100%",overflow:"hidden",background:"#f5f5f5",fontFamily:"system-ui, sans-serif",...S},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",background:"#fff",borderBottom:"1px solid #e5e7eb",flexShrink:0,flexWrap:"wrap"},children:[le.map((x,v)=>n.jsxs(l.Fragment,{children:[v>0&&n.jsx("div",{style:{width:1,height:24,background:"#e5e7eb",margin:"0 2px"}}),x.map(E=>n.jsx("button",{onClick:()=>d.setTool(E.id),title:`${E.label}`,style:{padding:"4px 7px",border:`1.5px solid ${d.activeTool===E.id?"#6366f1":"transparent"}`,borderRadius:6,background:d.activeTool===E.id?"#eef2ff":"transparent",cursor:"pointer",fontSize:15,minWidth:30,color:d.activeTool===E.id?"#4f46e5":"#374151"},children:E.icon},E.id))]},v)),n.jsx("div",{style:{width:1,height:24,background:"#e5e7eb",margin:"0 4px"}}),n.jsxs("label",{title:"Stroke color",style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[n.jsx("span",{style:{fontSize:11,color:"#6b7280"},children:"Color"}),n.jsx("input",{type:"color",value:M,onChange:x=>F(x.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}})]}),n.jsxs("label",{title:"Fill color",style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[n.jsx("span",{style:{fontSize:11,color:"#6b7280"},children:"Fill"}),n.jsx("input",{type:"color",value:H??"#ffffff",onChange:x=>j(x.target.value==="#ffffff"?void 0:x.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}}),n.jsx("button",{onClick:()=>j(void 0),style:{fontSize:11,padding:"1px 5px",border:"1px solid #e5e7eb",borderRadius:4,cursor:"pointer",background:H?"#fff":"#f3f4f6"},children:"No fill"})]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx("span",{style:{fontSize:11,color:"#6b7280"},children:"Width"}),n.jsx("input",{type:"range",min:1,max:24,step:1,value:U,onChange:x=>N(Number(x.target.value)),style:{width:70}}),n.jsx("span",{style:{fontSize:11,color:"#6b7280",minWidth:20},children:U})]}),d.activeTool==="sticky"&&n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{fontSize:11,color:"#6b7280"},children:"Note:"}),se.map(x=>n.jsx("button",{onClick:()=>J(x),style:{width:20,height:20,background:x,border:`2px solid ${K===x?"#6366f1":"#e5e7eb"}`,borderRadius:4,cursor:"pointer"}},x))]}),n.jsx("div",{style:{flex:1}}),n.jsx("button",{onClick:d.undo,disabled:!d.canUndo,title:"Undo (Ctrl+Z)",style:de(!d.canUndo),children:"โฉ"}),n.jsx("button",{onClick:d.redo,disabled:!d.canRedo,title:"Redo (Ctrl+Y)",style:de(!d.canRedo),children:"โช"}),n.jsx("div",{style:{width:1,height:24,background:"#e5e7eb"}}),n.jsxs("span",{style:{fontSize:11,color:"#6b7280",minWidth:42,textAlign:"center"},children:[Math.round(d.viewport.scale*100),"%"]}),n.jsx("button",{onClick:()=>d.setViewport({x:0,y:0,scale:1}),style:de(),title:"Reset zoom",children:"โ"}),a&&n.jsx("button",{onClick:()=>W(x=>!x),style:de(!1,D),title:"Layers",children:"โ"}),n.jsx("button",{onClick:()=>{const x={id:Ee(),sessionId:d.session.id,type:"object:update",userId:e.id,timestamp:new Date,payload:{...d.session,gridEnabled:!d.session.gridEnabled}};t==null||t(x)},style:de(!1,d.session.gridEnabled),title:"Toggle grid",children:"#"}),p&&n.jsx("button",{onClick:()=>B(x=>x==="vector"?null:"vector"),style:de(!1,_==="vector"),title:"Vector Editor panel",children:"Vฮต"}),u&&n.jsx("button",{onClick:()=>B(x=>x==="diagram"?null:"diagram"),style:de(!1,_==="diagram"),title:"Diagram Editor panel",children:"โ"}),n.jsx("button",{onClick:()=>void d.saveNow(),style:de(),title:"Save (Ctrl+S)",children:d.isDirty?"๐พ*":"๐พ"}),o&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>L("png"),style:de(),title:"Export PNG",children:"PNGโ"}),n.jsx("button",{onClick:()=>L("json"),style:de(),title:"Export JSON",children:"JSONโ"})]})]}),n.jsxs("div",{style:{display:"flex",flex:1,overflow:"hidden",position:"relative"},children:[n.jsx("canvas",{ref:z,style:{flex:1,display:"block",cursor:dn(d.activeTool,g.current.spaceDown)},onPointerDown:re,onPointerMove:ae,onPointerUp:pe,onWheel:oe,onContextMenu:x=>x.preventDefault()}),a&&D&&n.jsx(cn,{layers:d.layers,objects:d.session.objects,onAdd:()=>d.addLayer(`Layer ${d.layers.length+1}`),onUpdate:x=>d.updateLayer(x),onDelete:x=>d.deleteLayer(x)}),_&&n.jsxs("div",{style:{position:"absolute",right:D?220:0,top:0,bottom:0,width:360,background:"#fff",borderLeft:"1px solid #e5e7eb",padding:12,overflowY:"auto"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[n.jsx("strong",{style:{fontSize:13},children:_==="vector"?"Vector Editor":"Diagram Editor"}),n.jsx("button",{onClick:()=>B(null),style:{border:"none",background:"none",cursor:"pointer",fontSize:16},children:"โ"})]}),n.jsx("p",{style:{fontSize:12,color:"#6b7280"},children:_==="vector"?"Render the full @nice2dev/ui-graphics VectorEditor here. Pass the whiteboard's StorageConfig to persist edits and onOperation to broadcast strokes in real time.":"Render the full @nice2dev/ui-diagrams NiceDiagramEditor here. Pass the collaborativeDiagram YDoc to enable simultaneous multi-user editing."}),n.jsx("div",{id:`wb-integration-${_}`,style:{width:"100%",height:400}})]})]}),d.collaborators.length>1&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",background:"#fff",borderTop:"1px solid #f3f4f6",fontSize:11,color:"#6b7280",flexShrink:0},children:[n.jsx("span",{children:"Collaborators:"}),d.collaborators.map(x=>n.jsxs("span",{style:{display:"flex",alignItems:"center",gap:3},children:[n.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:x.color,display:"inline-block"}}),x.user.name]},x.user.id)),d.isDirty&&n.jsx("span",{style:{marginLeft:"auto",color:"#f59e0b"},children:"โ unsaved"}),d.lastSavedAt&&!d.isDirty&&n.jsxs("span",{style:{marginLeft:"auto",color:"#10b981"},children:["โ Saved ",d.lastSavedAt.toLocaleTimeString()]})]}),X&&ne&&n.jsx("textarea",{autoFocus:!0,defaultValue:X.text,onBlur:x=>{const v={...X,text:x.target.value,updatedAt:new Date,updatedBy:e.id};d.updateObject(v),O(null)},style:{position:"absolute",left:ne.sx,top:ne.sy,minWidth:X.width*d.viewport.scale,minHeight:X.height*d.viewport.scale,fontSize:(X.fontSize??14)*d.viewport.scale,fontFamily:"sans-serif",background:X.type==="sticky"?X.backgroundColor:"rgba(255,255,255,0.95)",border:"2px solid #6366f1",borderRadius:4,padding:6,resize:"both",zIndex:1e3,color:X.type==="sticky"?X.textColor:X.color}})]})}function cn({layers:s,objects:e,onAdd:t,onUpdate:i,onDelete:r}){return n.jsxs("div",{style:{width:200,borderLeft:"1px solid #e5e7eb",background:"#fff",display:"flex",flexDirection:"column",padding:8,gap:4,overflowY:"auto",flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[n.jsx("strong",{style:{fontSize:12,color:"#374151"},children:"Layers"}),n.jsx("button",{onClick:t,style:{fontSize:16,border:"none",background:"none",cursor:"pointer",color:"#6366f1"},title:"Add layer",children:"+"})]}),[...s].reverse().map(a=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",borderRadius:5,background:"#f9fafb",opacity:a.visible?1:.5},children:[n.jsx("button",{onClick:()=>i({id:a.id,visible:!a.visible}),title:"Toggle visibility",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,color:a.visible?"#374151":"#9ca3af"},children:a.visible?"๐":"๐ซ"}),n.jsx("button",{onClick:()=>i({id:a.id,locked:!a.locked}),title:"Toggle lock",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0},children:a.locked?"๐":"๐"}),n.jsx("span",{style:{flex:1,fontSize:11,color:"#374151",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.name}),n.jsx("span",{style:{fontSize:10,color:"#9ca3af"},children:a.objectIds.filter(o=>o in e).length}),s.length>1&&n.jsx("button",{onClick:()=>r(a.id),title:"Delete layer",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,color:"#ef4444"},children:"ร"})]},a.id))]})}function de(s=!1,e=!1){return{padding:"4px 8px",border:`1.5px solid ${e?"#6366f1":"#e5e7eb"}`,borderRadius:6,background:e?"#eef2ff":"#fff",cursor:s?"default":"pointer",opacity:s?.35:1,fontSize:13,color:e?"#4f46e5":"#374151",fontWeight:e?600:400}}function dn(s,e){if(e)return"grab";switch(s){case"pen":case"highlighter":return"crosshair";case"eraser":return"cell";case"select":return"default";case"text":return"text";case"laser":return"none";default:return"crosshair"}}function be({icon:s,label:e,active:t,badge:i,onClick:r}){return n.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[n.jsxs("button",{title:e,onClick:r,style:{width:44,height:44,borderRadius:10,border:"none",background:t?"rgba(255,255,255,0.2)":"transparent",color:"#fff",fontSize:20,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",position:"relative"},children:[s,i!=null&&i>0&&n.jsx("span",{style:{position:"absolute",top:4,right:4,background:"#ef4444",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700,lineHeight:1.4},children:i>99?"99+":i})]}),n.jsx("span",{style:{fontSize:9,color:"rgba(255,255,255,0.7)",letterSpacing:"0.03em"},children:e})]})}function un({team:s,activeChannelId:e,onSelectChannel:t}){var o;const[i,r]=l.useState(!1),a=s.channels.reduce((c,p)=>c+p.unreadCount,0);return n.jsxs("div",{className:"nice-workspace-team",children:[n.jsxs("button",{onClick:()=>r(c=>!c),style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",background:"none",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:"#374151",fontSize:13,fontWeight:600},children:[n.jsx("span",{style:{fontSize:10,color:"#9ca3af"},children:i?"โถ":"โผ"}),n.jsx("div",{style:{width:20,height:20,borderRadius:4,background:s.avatarUrl?`url(${s.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:9,flexShrink:0},children:!s.avatarUrl&&((o=s.name[0])==null?void 0:o.toUpperCase())}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.name}),!i&&a>0&&n.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:a})]}),!i&&s.channels.map(c=>n.jsxs("button",{onClick:()=>t(s.id,c.id),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 10px 5px 34px",background:c.id===e?"#ede9fe":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:c.unreadCount>0?"#111827":"#4b5563",fontSize:13,fontWeight:c.unreadCount>0?600:400},children:[n.jsx("span",{style:{color:"#9ca3af",fontSize:12},children:c.isPrivate?"๐":"#"}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.name}),c.mentionCount>0&&n.jsxs("span",{style:{background:"#ef4444",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:["@",c.mentionCount]}),c.unreadCount>0&&c.mentionCount===0&&n.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700},children:c.unreadCount})]},c.id))]})}function pn({conversation:s,partner:e,isActive:t,onClick:i}){var a;const r=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??s.name??"Group";return n.jsxs("button",{onClick:i,style:{display:"flex",alignItems:"center",gap:8,padding:"5px 10px",background:t?"#ede9fe":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:s.unreadCount>0?"#111827":"#4b5563",fontWeight:s.unreadCount>0?600:400,fontSize:13},children:[n.jsxs("div",{style:{position:"relative",flexShrink:0},children:[n.jsx("div",{style:{width:24,height:24,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:10},children:!(e!=null&&e.avatarUrl)&&((a=r[0])==null?void 0:a.toUpperCase())}),e&&n.jsx(ue,{status:e.presence.status,size:"xs",style:{position:"absolute",bottom:-1,right:-1}})]}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),s.unreadCount>0&&n.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700,flexShrink:0},children:s.unreadCount})]})}function It({currentUser:s,users:e,teams:t,conversations:i,messages:r,activeCall:a,incomingCall:o,meetings:c,transport:p,rtcConfig:u,enableCalls:m=!0,enableMeetings:f=!0,enableScreenSharing:y=!0,enableWhiteboard:h=!1,storageConfig:S,onSendMessage:C,onEditMessage:d,onDeleteMessage:z,onReactToMessage:P,onPinMessage:D,onLoadMoreMessages:W,onMarkAsRead:M,onStartCall:F,onAcceptCall:U,onDeclineCall:N,onEndCall:H,onMuteAudio:j,onMuteVideo:b,onStartScreenShare:T,onStopScreenShare:K,className:J,style:R,id:O,"data-testid":_}){var A,G;const[B,g]=l.useState("teams"),[w,V]=l.useState(null),[q,Q]=l.useState(""),[Y,re]=l.useState(null),ae=()=>{Y||re({id:`wb-workspace-${Date.now()}`,title:"Team Whiteboard",objects:{},layers:[{id:"layer-0",name:"Layer 1",visible:!0,locked:!1,objectIds:[]}],collaborators:{},viewport:{x:0,y:0,scale:1},width:4e3,height:3e3,backgroundColor:"#ffffff",gridEnabled:!0,gridSize:20,snapEnabled:!0,createdAt:new Date,updatedAt:new Date,ownerId:s.id,permissions:"edit"})},pe=l.useMemo(()=>{const k=new Map;return e.forEach(I=>k.set(I.id,I)),k},[e]),oe=l.useMemo(()=>Xe(i),[i]),L=l.useMemo(()=>i.reduce((k,I)=>k+I.mentionCount,0),[i]),X=l.useMemo(()=>{if(w!=null&&w.channelId)for(const k of t){const I=k.channels.find(ee=>ee.id===w.channelId);if(I)return I}},[t,w]),ne=l.useMemo(()=>{if(w!=null&&w.teamId)return t.find(k=>k.id===w.teamId)},[t,w]),se=l.useMemo(()=>i.find(k=>k.id===(w==null?void 0:w.conversationId))??null,[i,w]),le=l.useMemo(()=>{const k=(w==null?void 0:w.channelId)??(w==null?void 0:w.conversationId);return k?r[k]??[]:[]},[r,w]),x=!!o&&!a,v=!!a,E=l.useMemo(()=>i.filter(k=>k.type==="dm"||k.type==="group"),[i]),$=l.useMemo(()=>{if(!q)return E;const k=q.toLowerCase();return E.filter(I=>{var Z;const ee=pe.get(I.participantIds.find(ie=>ie!==s.id)??"");return(ee==null?void 0:ee.name.toLowerCase().includes(k))||((Z=I.name)==null?void 0:Z.toLowerCase().includes(k))})},[E,q,pe,s.id]);return n.jsxs("div",{id:O,"data-testid":_,className:`nice-teams-workspace${J?` ${J}`:""}`,style:{display:"flex",height:"100%",overflow:"hidden",background:"#fff",position:"relative",...R},children:[n.jsxs("div",{className:"nice-workspace-nav-rail",style:{width:64,flexShrink:0,background:"#4f46e5",display:"flex",flexDirection:"column",alignItems:"center",padding:"12px 0",gap:6},children:[n.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:s.avatarUrl?`url(${s.avatarUrl}) center/cover`:"#818cf8",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:14,marginBottom:8,flexShrink:0},children:!s.avatarUrl&&((A=s.name[0])==null?void 0:A.toUpperCase())}),n.jsx(be,{icon:"โก",label:"Activity",active:B==="activity",badge:L,onClick:()=>g("activity")}),n.jsx(be,{icon:"๐ฌ",label:"Chat",active:B==="chat",badge:oe,onClick:()=>g("chat")}),n.jsx(be,{icon:"๐ฅ",label:"Teams",active:B==="teams",onClick:()=>g("teams")}),m&&n.jsx(be,{icon:"๐",label:"Calls",active:B==="calls",onClick:()=>g("calls")}),f&&n.jsx(be,{icon:"๐
",label:"Meetings",active:B==="meetings",onClick:()=>g("meetings")}),n.jsx(be,{icon:"๐",label:"Files",active:B==="files",onClick:()=>g("files")}),h&&n.jsx(be,{icon:"๐๏ธ",label:"Board",active:B==="whiteboard",onClick:()=>{g("whiteboard"),ae()}})]}),n.jsxs("div",{className:"nice-workspace-sidebar",style:{width:240,flexShrink:0,borderRight:"1px solid #e5e7eb",display:"flex",flexDirection:"column",background:"#fafafa",overflow:"hidden"},children:[n.jsxs("div",{style:{padding:"12px 10px 8px",flexShrink:0},children:[n.jsx("div",{style:{fontWeight:700,fontSize:15,color:"#374151",marginBottom:8,textTransform:"capitalize"},children:B}),n.jsx("input",{type:"search",value:q,onChange:k=>Q(k.target.value),placeholder:`Search ${B}โฆ`,style:{width:"100%",padding:"5px 10px",border:"1px solid #e5e7eb",borderRadius:16,fontSize:12,outline:"none",boxSizing:"border-box",background:"#fff"}})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[B==="teams"&&n.jsx(n.Fragment,{children:t.map(k=>n.jsx(un,{team:k,activeChannelId:w==null?void 0:w.channelId,onSelectChannel:(I,ee)=>{V({type:"channel",teamId:I,channelId:ee}),M==null||M(ee)}},k.id))}),B==="chat"&&n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:"#9ca3af",fontWeight:600,letterSpacing:"0.05em"},children:"DIRECT MESSAGES"}),$.map(k=>{const I=pe.get(k.participantIds.find(ee=>ee!==s.id)??"");return n.jsx(pn,{conversation:k,partner:I,isActive:(w==null?void 0:w.conversationId)===k.id,onClick:()=>{V({type:k.type==="dm"?"dm":"group",conversationId:k.id}),M==null||M(k.id)}},k.id)})]}),B==="activity"&&n.jsxs("div",{style:{padding:12},children:[i.filter(k=>k.unreadCount>0).map(k=>n.jsxs("button",{onClick:()=>{g(k.type==="channel"?"teams":"chat"),V({type:k.type==="channel"?"channel":"dm",conversationId:k.id})},style:{display:"block",width:"100%",textAlign:"left",padding:"6px 0",background:"none",border:"none",cursor:"pointer",fontSize:13,color:"#374151"},children:[n.jsx("strong",{children:k.name??"Conversation"})," โ ",k.unreadCount," unread"]},k.id)),i.every(k=>k.unreadCount===0)&&n.jsx("p",{style:{color:"#9ca3af",fontSize:13,textAlign:"center",marginTop:24},children:"All caught up โ"})]}),B==="calls"&&n.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8},children:[n.jsx("button",{onClick:()=>F==null?void 0:F(e.map(k=>k.id).filter(k=>k!==s.id),"audio"),style:{background:"#6366f1",color:"#fff",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600},children:"๐ New audio call"}),n.jsx("button",{onClick:()=>F==null?void 0:F(e.map(k=>k.id).filter(k=>k!==s.id),"video"),style:{background:"#6366f1",color:"#fff",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600},children:"๐น New video call"})]}),B==="meetings"&&n.jsxs("div",{style:{padding:12},children:[(c??[]).map(k=>n.jsxs("div",{style:{padding:"8px 10px",border:"1px solid #e5e7eb",borderRadius:8,marginBottom:8},children:[n.jsx("div",{style:{fontWeight:600,fontSize:13},children:k.title}),n.jsx("div",{style:{fontSize:11,color:"#6b7280",marginTop:2},children:k.scheduledStart.toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}),n.jsx("button",{onClick:()=>{},style:{marginTop:6,background:"#6366f1",color:"#fff",border:"none",borderRadius:6,padding:"3px 10px",fontSize:12,cursor:"pointer"},children:"Join"})]},k.id)),(c??[]).length===0&&n.jsx("p",{style:{color:"#9ca3af",fontSize:13,textAlign:"center",marginTop:24},children:"No upcoming meetings"})]}),B==="files"&&n.jsx("div",{style:{padding:12},children:n.jsx("p",{style:{color:"#9ca3af",fontSize:13,textAlign:"center",marginTop:24},children:"No files shared yet"})}),B==="whiteboard"&&n.jsxs("div",{style:{padding:12},children:[n.jsxs("button",{onClick:()=>ae(),style:{width:"100%",background:"#6366f1",color:"#fff",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,marginBottom:8},children:["๐๏ธ ",Y?"Open whiteboard":"New whiteboard"]}),Y&&n.jsxs("div",{style:{padding:"6px 10px",border:"1px solid #e5e7eb",borderRadius:6,fontSize:12,color:"#374151"},children:[n.jsx("div",{style:{fontWeight:500},children:Y.title}),n.jsxs("div",{style:{color:"#9ca3af",marginTop:2},children:[Object.keys(Y.objects).length," objects"]})]})]})]})]}),n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[(w==null?void 0:w.type)==="channel"&&X?n.jsx(wt,{channel:X,messages:le,users:(ne==null?void 0:ne.members)??e,currentUser:s,team:ne,onSendMessage:C,onEditMessage:d,onDeleteMessage:z,onReactToMessage:P,onPinMessage:D,onLoadMoreMessages:W,onStartCall:m?F:void 0,style:{height:"100%"}}):((w==null?void 0:w.type)==="dm"||(w==null?void 0:w.type)==="group")&&se?n.jsx(Re,{conversation:se,messages:le,users:e,currentUser:s,onSendMessage:C,onEditMessage:d,onDeleteMessage:z,onReactToMessage:P,onPinMessage:D,onLoadMoreMessages:W,onStartCall:m?F:void 0,style:{height:"100%"}}):B==="whiteboard"&&Y?n.jsx(et,{session:Y,currentUser:s,storageConfig:S,onSessionUpdate:k=>re(k),style:{height:"100%"}}):n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"#9ca3af",gap:12},children:[n.jsx("span",{style:{fontSize:56},children:B==="teams"?"๐ฅ":B==="chat"?"๐ฌ":B==="calls"?"๐":B==="whiteboard"?"๐๏ธ":"โก"}),n.jsx("span",{style:{fontSize:17,fontWeight:500},children:B==="teams"?"Select a channel to get started":B==="chat"?"Select a conversation":B==="calls"?"Start or join a call":B==="whiteboard"?'Click "New whiteboard" to start':"Nothing selected"})]}),v&&a&&n.jsx("div",{style:{position:"absolute",inset:0,zIndex:50},children:a.participants.length>2?n.jsx(Qe,{session:a,currentUser:s,enableScreenSharing:y,onEndCall:H,onMuteAudio:j,onMuteVideo:b,onStartScreenShare:T,onStopScreenShare:K}):n.jsx(Je,{session:a,currentUser:s,enableScreenSharing:y,onEndCall:H,onMuteAudio:j,onMuteVideo:b,onStartScreenShare:T,onStopScreenShare:K})})]}),x&&o&&n.jsxs("div",{style:{position:"absolute",top:16,right:16,width:300,background:"#1f2937",borderRadius:12,padding:16,boxShadow:"0 8px 32px rgba(0,0,0,0.4)",zIndex:100,color:"#fff"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:12},children:[n.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:o.caller.avatarUrl?`url(${o.caller.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:16},children:!o.caller.avatarUrl&&((G=o.caller.name[0])==null?void 0:G.toUpperCase())}),n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:o.caller.displayName??o.caller.name}),n.jsxs("div",{style:{fontSize:12,color:"rgba(255,255,255,0.6)"},children:["Incoming ",o.callType," call"]})]})]}),n.jsxs("div",{style:{display:"flex",gap:8},children:[n.jsx("button",{onClick:()=>N==null?void 0:N(o.callId),style:{flex:1,background:"#ef4444",color:"#fff",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13},children:"๐ต Decline"}),n.jsx("button",{onClick:()=>U==null?void 0:U(o.callId),style:{flex:1,background:"#22c55e",color:"#fff",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13},children:"๐ Accept"})]})]})]})}const fn={"bottom-right":{bottom:24,right:24},"bottom-left":{bottom:24,left:24},"top-right":{top:24,right:24},"top-left":{top:24,left:24}};function hn({props:s,onExpand:e}){const[t,i]=l.useState(!1),{bubblePosition:r="bottom-right",bubbleLabel:a,currentUser:o,users:c,conversations:p=[],messages:u={},onSendMessage:m,onReactToMessage:f,onPinMessage:y,onDeleteMessage:h,onEditMessage:S,onLoadMoreMessages:C,onStartCall:d}=s,z=fn[r],P=p[0]??null,D=P?u[P.id]??[]:[];return n.jsxs("div",{style:{position:"fixed",zIndex:9999,...z},children:[t&&P&&n.jsxs("div",{style:{position:"absolute",bottom:r.startsWith("bottom")?64:void 0,top:r.startsWith("top")?64:void 0,right:r.endsWith("right")?0:void 0,left:r.endsWith("left")?0:void 0,width:360,height:500,background:"#fff",borderRadius:16,boxShadow:"0 8px 40px rgba(0,0,0,0.18)",overflow:"hidden",display:"flex",flexDirection:"column"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",background:"#6366f1",color:"#fff",flexShrink:0},children:[n.jsx("span",{style:{fontWeight:700,fontSize:15},children:a??"Chat"}),n.jsxs("div",{style:{display:"flex",gap:4},children:[n.jsx("button",{onClick:()=>e("messenger"),title:"Open full chat",style:{background:"rgba(255,255,255,0.15)",border:"none",borderRadius:6,padding:"3px 7px",color:"#fff",cursor:"pointer",fontSize:13},children:"โ"}),n.jsx("button",{onClick:()=>i(!1),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",fontSize:18},children:"ร"})]})]}),n.jsx(Re,{conversation:P,messages:D,users:c,currentUser:o,showHeader:!1,onSendMessage:m,onEditMessage:S,onDeleteMessage:h,onReactToMessage:f,onPinMessage:y,onLoadMoreMessages:C,onStartCall:d,style:{flex:1}})]}),n.jsx("button",{onClick:()=>i(W=>!W),style:{width:56,height:56,borderRadius:"50%",background:"#6366f1",border:"none",boxShadow:"0 4px 16px rgba(99,102,241,0.4)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:24,color:"#fff",transition:"transform 0.15s"},title:t?"Close chat":a??"Open chat",children:t?"โ":"๐ฌ"})]})}function gn({call:s,onAccept:e,onDecline:t}){return n.jsxs("div",{style:{position:"fixed",top:16,left:"50%",transform:"translateX(-50%)",zIndex:9998,background:"#1f2937",color:"#fff",borderRadius:12,padding:"12px 20px",boxShadow:"0 8px 32px rgba(0,0,0,0.4)",display:"flex",alignItems:"center",gap:16,minWidth:280},children:[n.jsx("div",{style:{fontSize:28},children:s.callType==="video"?"๐น":"๐"}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:600,fontSize:14},children:s.caller.displayName??s.caller.name}),n.jsxs("div",{style:{fontSize:12,color:"rgba(255,255,255,0.6)"},children:["Incoming ",s.callType," callโฆ"]})]}),n.jsx("button",{onClick:t,style:{background:"#ef4444",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",fontSize:18,color:"#fff"},title:"Decline",children:"๐ต"}),n.jsx("button",{onClick:e,style:{background:"#22c55e",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",fontSize:18,color:"#fff"},title:"Accept",children:"๐"})]})}function Tt(s){const{mode:e,currentUser:t,users:i,conversations:r=[],messages:a={},teams:o=[],meetings:c,activeCall:p,incomingCall:u,transport:m="webrtc",rtcConfig:f,onSendMessage:y,onEditMessage:h,onDeleteMessage:S,onReactToMessage:C,onPinMessage:d,onLoadMoreMessages:z,onMarkAsRead:P,onStartCall:D,onAcceptCall:W,onDeclineCall:M,onEndCall:F,onMuteAudio:U,onMuteVideo:N,onStartScreenShare:H,onStopScreenShare:j,onRaiseHand:b,onModeChange:T,enableScreenSharing:K=!0,enableMeetings:J=!0,enableWhiteboard:R=!1,storageConfig:O,encryptionConfig:_,className:B,style:g,id:w,"data-testid":V}=s,[q,Q]=l.useState(e),[Y,re]=l.useState(null),ae=l.useMemo(()=>({id:`wb-${t.id}-${Date.now()}`,title:"Whiteboard",objects:{},layers:[{id:"layer-0",name:"Layer 1",visible:!0,locked:!1,objectIds:[]}],collaborators:{},viewport:{x:0,y:0,scale:1},width:4e3,height:3e3,backgroundColor:"#ffffff",gridEnabled:!0,gridSize:20,snapEnabled:!0,createdAt:new Date,updatedAt:new Date,ownerId:t.id,permissions:"edit"}),[t.id]),[pe,oe]=l.useState(p??null),[L,X]=l.useState(u??null),ne=p??pe,se=u??L;l.useEffect(()=>{Q(e)},[e]),l.useEffect(()=>{p!==void 0&&oe(p)},[p]),l.useEffect(()=>{u!==void 0&&X(u)},[u]);const{state:le,startCall:x,acceptCall:v,declineCall:E,endCall:$,toggleMic:A,toggleCamera:G,startScreenShare:k,stopScreenShare:I}=vt({currentUser:t,transport:m,rtcConfig:f,onCallEnded:te=>{oe(null),F==null||F(te)},onIncomingCall:te=>{X(te)}}),ee=l.useCallback(te=>{Q(te),T==null||T(te)},[T]),Z=l.useCallback(async(te,rt)=>{if(D){await D(te,rt);return}const Lt=await x(te,rt);oe(Lt),Q(te.length>2?"conference":"call")},[D,x]),ie=l.useCallback(async()=>{var te;W&&se?await W(se.callId):await v(),X(null),Q((te=le.activeCall)!=null&&te.participants&&le.activeCall.participants.length>2?"conference":"call")},[W,se,v,le.activeCall]),ce=l.useCallback(()=>{M&&se?M(se.callId):E(),X(null)},[M,se,E]),me=l.useCallback(te=>{F?F(te):$(),oe(null),Q(e)},[F,$,e]),fe=l.useCallback(te=>{A(),U==null||U(te)},[A,U]),Pe=l.useCallback(te=>{G(),N==null||N(te)},[G,N]),st=l.useCallback(async()=>{await k(),await(H==null?void 0:H())},[k,H]),Ae=l.useCallback(()=>{I(),j==null||j()},[I,j]),ye={onSendMessage:y,onEditMessage:h,onDeleteMessage:S,onReactToMessage:C,onPinMessage:d,onLoadMoreMessages:z,onMarkAsRead:P,onStartCall:Z,onEndCall:me,onMuteAudio:fe,onMuteVideo:Pe,onStartScreenShare:st,onStopScreenShare:Ae,onRaiseHand:b},he=ne?ne.participants.length>2?"conference":"call":q,Ot={width:"100%",height:"100%",position:"relative",...g};return n.jsxs("div",{id:w,"data-testid":V,className:`nice-communication nice-communication--${he}${B?` ${B}`:""}`,style:Ot,children:[se&&he!=="workspace"&&n.jsx(gn,{call:se,onAccept:ie,onDecline:ce}),he==="bubble"&&n.jsx(hn,{props:s,onExpand:ee}),he==="chat"&&r.length>0&&n.jsx(Re,{conversation:r[0],messages:a[r[0].id]??[],users:i,currentUser:t,...ye,style:{height:"100%"}}),he==="messenger"&&n.jsx(St,{conversations:r,messages:a,users:i,currentUser:t,teams:o,...ye,onAcceptCall:W,onDeclineCall:M,style:{height:"100%"}}),he==="workspace"&&n.jsx(It,{currentUser:t,users:i,teams:o,conversations:r,messages:a,meetings:c,activeCall:ne??void 0,incomingCall:se??void 0,transport:m,rtcConfig:f,enableCalls:!0,enableMeetings:J,enableScreenSharing:K,...ye,onAcceptCall:ie,onDeclineCall:ce,style:{height:"100%"}}),he==="call"&&ne&&n.jsx(Je,{session:ne,currentUser:t,localStream:le.localStream??void 0,enableScreenSharing:K,...ye,style:{height:"100%"}}),he==="conference"&&ne&&n.jsx(Qe,{session:ne,currentUser:t,localStream:le.localStream??void 0,enableScreenSharing:K,...ye,style:{height:"100%"}}),he==="whiteboard"&&R&&n.jsx(et,{session:Y??ae,currentUser:t,storageConfig:O,onSessionUpdate:te=>re(te),style:{height:"100%"}})]})}const mn={messages:"Messages",attachments:"Attachments","whiteboard-snapshots":"Whiteboard snapshots",recordings:"Recordings",transcripts:"Transcripts",documents:"Documents","call-logs":"Call logs","audit-logs":"Audit logs"},dt={none:"No encryption","AES-GCM-128":"AES-GCM 128-bit","AES-GCM-256":"AES-GCM 256-bit (recommended)","ChaCha20-Poly1305":"ChaCha20-Poly1305","E2E-ECDH-P384":"End-to-End ECDH P-384"},yn={messages:"Messages",attachments:"Attachments",whiteboard:"Whiteboard",recordings:"Recordings",documents:"Documents",calls:"Calls (metadata)",presence:"Presence data",all:"Everything"},xn=["days","weeks","months","years","forever"];function ut(s){if(s===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],i=Math.floor(Math.log(s)/Math.log(e));return`${(s/Math.pow(e,i)).toFixed(1)} ${t[i]}`}function pt({value:s,onChange:e,disabled:t=!1}){return n.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[n.jsx("input",{type:"number",min:1,max:9999,value:s.unit==="forever"?"":s.value,disabled:t||s.unit==="forever",onChange:i=>e({...s,value:Math.max(1,Number(i.target.value))}),style:{width:60,padding:"3px 6px",border:"1px solid #d1d5db",borderRadius:5,fontSize:12}}),n.jsx("select",{value:s.unit,disabled:t,onChange:i=>e({...s,unit:i.target.value}),style:{padding:"3px 6px",border:"1px solid #d1d5db",borderRadius:5,fontSize:12},children:xn.map(i=>n.jsx("option",{value:i,children:i},i))})]})}function bn({config:s,onChange:e}){const t=s.retentionRules.length>0?s.retentionRules:Ze;function i(r,a){const o=t.map(c=>c.dataType===r?{...c,...a}:c);e({...s,retentionRules:o})}return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[n.jsx("p",{style:{fontSize:12,color:"#6b7280",margin:0},children:"Configure how long each data type is retained before archiving and eventual deletion. Legal-hold prevents deletion regardless of retention rules."}),n.jsxs("div",{style:je,children:[n.jsx("label",{style:Ce,children:"Storage provider"}),n.jsxs("select",{value:s.provider,onChange:r=>e({...s,provider:r.target.value}),style:ve,children:[n.jsx("option",{value:"indexeddb",children:"IndexedDB (browser)"}),n.jsx("option",{value:"localstorage",children:"LocalStorage (browser)"}),n.jsx("option",{value:"server",children:"Server"}),n.jsx("option",{value:"custom",children:"Custom adapter"})]})]}),s.provider==="server"&&n.jsxs("div",{style:je,children:[n.jsx("label",{style:Ce,children:"Server URL"}),n.jsx("input",{type:"url",value:s.serverUrl??"",onChange:r=>e({...s,serverUrl:r.target.value}),placeholder:"https://your-api.example.com/storage",style:ve})]}),n.jsx("hr",{style:{border:"none",borderTop:"1px solid #e5e7eb",margin:"4px 0"}}),n.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12},children:[n.jsx("thead",{children:n.jsxs("tr",{style:{background:"#f9fafb"},children:[n.jsx("th",{style:we,children:"Data type"}),n.jsx("th",{style:we,children:"Active period"}),n.jsx("th",{style:we,children:"Archive after"}),n.jsx("th",{style:we,children:"Auto-delete"}),n.jsx("th",{style:we,children:"User can delete"}),n.jsx("th",{style:we,children:"Legal hold"})]})}),n.jsx("tbody",{children:t.map(r=>n.jsxs("tr",{style:{borderBottom:"1px solid #f3f4f6"},children:[n.jsx("td",{style:{...ke,fontWeight:500,color:"#374151"},children:mn[r.dataType]}),n.jsx("td",{style:ke,children:n.jsx(pt,{value:r.activePeriod,onChange:a=>i(r.dataType,{activePeriod:a})})}),n.jsx("td",{style:ke,children:r.archivePeriod?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx(pt,{value:r.archivePeriod,onChange:a=>i(r.dataType,{archivePeriod:a})}),n.jsx("button",{onClick:()=>i(r.dataType,{archivePeriod:void 0}),style:{border:"none",background:"none",cursor:"pointer",color:"#ef4444",fontSize:14},title:"Remove archive period",children:"ร"})]}):n.jsx("button",{onClick:()=>i(r.dataType,{archivePeriod:{value:1,unit:"years"}}),style:{fontSize:11,padding:"2px 8px",border:"1px dashed #d1d5db",borderRadius:4,cursor:"pointer",background:"none",color:"#6b7280"},children:"+ Add"})}),n.jsx("td",{style:{...ke,textAlign:"center"},children:n.jsx("input",{type:"checkbox",checked:r.deleteAfterArchive,disabled:!r.archivePeriod,onChange:a=>i(r.dataType,{deleteAfterArchive:a.target.checked})})}),n.jsx("td",{style:{...ke,textAlign:"center"},children:n.jsx("input",{type:"checkbox",checked:r.userCanDelete,onChange:a=>i(r.dataType,{userCanDelete:a.target.checked})})}),n.jsx("td",{style:{...ke,textAlign:"center"},children:n.jsx("input",{type:"checkbox",checked:r.legalHoldEnabled??!1,onChange:a=>i(r.dataType,{legalHoldEnabled:a.target.checked})})})]},r.dataType))})]}),n.jsxs("div",{style:je,children:[n.jsx("label",{style:Ce,children:"Storage quota"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx("input",{type:"number",min:0,value:s.quota?Math.round(s.quota/1024/1024):0,onChange:r=>e({...s,quota:Number(r.target.value)*1024*1024}),style:{...ve,width:90},placeholder:"0"}),n.jsx("span",{style:{fontSize:12,color:"#6b7280"},children:"MB (0 = unlimited)"})]})]})]})}function vn({config:s,onChange:e}){const t=["messages","attachments","whiteboard","recordings","documents","calls","presence"];return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[n.jsx("p",{style:{fontSize:12,color:"#6b7280",margin:0},children:"Configure encryption at rest and in transit. E2E-ECDH ensures only participants can read conversations โ the server never sees plaintext."}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsxs("label",{style:{position:"relative",display:"inline-block",width:42,height:22},children:[n.jsx("input",{type:"checkbox",checked:s.enabled,onChange:i=>e({...s,enabled:i.target.checked}),style:{opacity:0,width:0,height:0}}),n.jsx("span",{style:{position:"absolute",inset:0,borderRadius:22,background:s.enabled?"#6366f1":"#d1d5db",transition:"background 0.2s",cursor:"pointer"},children:n.jsx("span",{style:{position:"absolute",width:16,height:16,top:3,left:s.enabled?23:3,background:"#fff",borderRadius:"50%",transition:"left 0.2s"}})})]}),n.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#374151"},children:s.enabled?"๐ Encryption enabled":"๐ Encryption disabled"})]}),s.enabled&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:je,children:[n.jsx("label",{style:Ce,children:"Default algorithm"}),n.jsx("select",{value:s.defaultAlgorithm,onChange:i=>e({...s,defaultAlgorithm:i.target.value}),style:ve,children:Object.entries(dt).map(([i,r])=>n.jsx("option",{value:i,children:r},i))})]}),s.defaultAlgorithm==="E2E-ECDH-P384"&&n.jsxs("div",{style:je,children:[n.jsx("label",{style:Ce,children:"Key exchange URL"}),n.jsx("input",{type:"url",value:s.keyExchangeUrl??"",onChange:i=>e({...s,keyExchangeUrl:i.target.value}),placeholder:"wss://your-server/e2e-key-exchange",style:ve}),n.jsx("span",{style:{fontSize:11,color:"#6b7280",marginTop:2},children:"WebSocket endpoint for ECDH public key exchange between participants."})]}),n.jsxs("div",{style:je,children:[n.jsx("label",{style:Ce,children:"External key (base64, optional)"}),n.jsx("input",{type:"password",value:s.keyMaterial??"",onChange:i=>e({...s,keyMaterial:i.target.value||void 0}),placeholder:"Leave empty to auto-generate",style:ve}),n.jsx("span",{style:{fontSize:11,color:"#6b7280",marginTop:2},children:"Provide a pre-shared key for symmetric algorithms. Leave empty for automatic key generation."})]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:s.showIndicator??!0,onChange:i=>e({...s,showIndicator:i.target.checked})}),n.jsx("span",{style:{fontSize:12,color:"#374151"},children:"Show lock indicator in messages"})]}),n.jsx("hr",{style:{border:"none",borderTop:"1px solid #e5e7eb",margin:"4px 0"}}),n.jsx("strong",{style:{fontSize:12,color:"#374151"},children:"Per-scope overrides"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:t.map(i=>{var c;const r=(c=s.scopeOverrides)==null?void 0:c.find(p=>p.scope===i),a=(r==null?void 0:r.enabled)??!1,o=(r==null?void 0:r.algorithm)??s.defaultAlgorithm;return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 8px",background:"#f9fafb",borderRadius:6},children:[n.jsx("input",{type:"checkbox",checked:a,onChange:p=>{const u=[...(s.scopeOverrides??[]).filter(m=>m.scope!==i),{scope:i,algorithm:o,enabled:p.target.checked}];e({...s,scopeOverrides:u})}}),n.jsx("span",{style:{minWidth:120,fontSize:12,color:"#374151"},children:yn[i]}),n.jsx("select",{value:o,disabled:!a,onChange:p=>{const u=[...(s.scopeOverrides??[]).filter(m=>m.scope!==i),{scope:i,algorithm:p.target.value,enabled:a}];e({...s,scopeOverrides:u})},style:{...ve,flex:1,opacity:a?1:.4},children:Object.entries(dt).map(([p,u])=>n.jsx("option",{value:p,children:u},p))})]},i)})})]})]})}function Sn({storageConfig:s,encryptionConfig:e,onStorageConfigChange:t,onEncryptionConfigChange:i,currentUsageBytes:r=0,showEncryption:a=!0,showRetention:o=!0,showQuota:c=!0,className:p,style:u,"data-testid":m}){const[f,y]=l.useState("retention"),h=e??{enabled:!1,defaultAlgorithm:"AES-GCM-256",showIndicator:!0},S={...s,retentionRules:s.retentionRules.length>0?s.retentionRules:Ze};return n.jsxs("div",{className:p,"data-testid":m,style:{display:"flex",flexDirection:"column",gap:16,padding:20,background:"#fff",borderRadius:10,border:"1px solid #e5e7eb",fontFamily:"system-ui, sans-serif",maxWidth:800,...u},children:[n.jsxs("div",{children:[n.jsx("h3",{style:{margin:0,fontSize:16,color:"#111827"},children:"Storage & Privacy"}),n.jsx("p",{style:{margin:"4px 0 0",fontSize:12,color:"#6b7280"},children:"Manage data retention, encryption, and storage settings."})]}),c&&s.quota&&s.quota>0&&n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:12,color:"#6b7280",marginBottom:4},children:[n.jsx("span",{children:"Storage used"}),n.jsxs("span",{children:[ut(r)," / ",ut(s.quota)]})]}),n.jsx("div",{style:{height:6,background:"#e5e7eb",borderRadius:3},children:n.jsx("div",{style:{width:`${Math.min(100,r/s.quota*100)}%`,height:"100%",background:r/s.quota>.9?"#ef4444":"#6366f1",borderRadius:3,transition:"width 0.3s"}})})]}),o&&a&&n.jsx("div",{style:{display:"flex",gap:0,borderBottom:"1px solid #e5e7eb"},children:["retention","encryption"].map(C=>n.jsx("button",{onClick:()=>y(C),style:{padding:"8px 18px",border:"none",borderBottom:`2px solid ${f===C?"#6366f1":"transparent"}`,background:"none",cursor:"pointer",fontSize:13,fontWeight:f===C?600:400,color:f===C?"#4f46e5":"#6b7280",marginBottom:-1},children:C==="retention"?"๐ฆ Retention":"๐ Encryption"},C))}),n.jsxs("div",{children:[(f==="retention"||!a)&&o&&n.jsx(bn,{config:S,onChange:t??(()=>{})}),(f==="encryption"||!o)&&a&&n.jsx(vn,{config:h,onChange:i??(()=>{})})]})]})}const je={display:"flex",flexDirection:"column",gap:4},Ce={fontSize:12,fontWeight:500,color:"#374151"},ve={padding:"6px 8px",border:"1px solid #d1d5db",borderRadius:6,fontSize:13,color:"#111827",background:"#fff"},we={padding:"6px 8px",textAlign:"left",fontSize:11,fontWeight:600,color:"#6b7280",borderBottom:"1px solid #e5e7eb"},ke={padding:"8px 8px",verticalAlign:"middle"};function Oe(s){const e=Math.floor(s/1e3),t=Math.floor(e/60),i=Math.floor(t/60);return i>0?`${i}:${String(t%60).padStart(2,"0")}:${String(e%60).padStart(2,"0")}`:`${String(t).padStart(2,"0")}:${String(e%60).padStart(2,"0")}`}function wn(s){if(s===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],i=Math.floor(Math.log(s)/Math.log(e));return`${(s/Math.pow(e,i)).toFixed(1)} ${t[i]}`}function kn(s){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(s))}const jn={idle:{label:"Idle",bg:"#f3f4f6",fg:"#6b7280"},recording:{label:"โ Recording",bg:"#fee2e2",fg:"#dc2626"},paused:{label:"โ Paused",bg:"#fef3c7",fg:"#d97706"},processing:{label:"โ Processing",bg:"#ede9fe",fg:"#7c3aed"},ready:{label:"โ Ready",bg:"#dcfce7",fg:"#16a34a"},failed:{label:"โ Failed",bg:"#fee2e2",fg:"#dc2626"}};function Cn({segments:s,onClose:e,currentTimeMs:t=0}){return n.jsx("div",{style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsxs("div",{style:{background:"#fff",borderRadius:12,width:"90%",maxWidth:640,maxHeight:"80vh",display:"flex",flexDirection:"column",boxShadow:"0 20px 40px rgba(0,0,0,0.2)",overflow:"hidden"},children:[n.jsxs("div",{style:{padding:"14px 18px",borderBottom:"1px solid #e5e7eb",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("strong",{style:{fontSize:14,color:"#111827"},children:"Transcript"}),n.jsx("button",{onClick:e,style:zn,children:"โ"})]}),n.jsx("div",{style:{flex:1,overflowY:"auto",padding:"12px 18px"},children:s.length===0?n.jsx("p",{style:{fontSize:13,color:"#9ca3af",textAlign:"center",padding:"32px 0"},children:"No transcript available."}):s.map(i=>{const r=t>=i.startMs&&t<i.endMs;return n.jsxs("div",{style:{marginBottom:12,padding:"8px 10px",borderRadius:6,background:r?"#eff6ff":"transparent",borderLeft:`3px solid ${r?"#3b82f6":"transparent"}`,transition:"background 0.2s"},children:[n.jsxs("div",{style:{display:"flex",gap:10,alignItems:"baseline",marginBottom:3},children:[n.jsx("span",{style:{fontSize:11,fontWeight:600,color:"#4f46e5"},children:i.speakerName}),n.jsxs("span",{style:{fontSize:10,color:"#9ca3af"},children:[Oe(i.startMs)," โ ",Oe(i.endMs)]}),n.jsxs("span",{style:{fontSize:10,color:"#d1d5db"},children:[Math.round(i.confidence*100),"% conf."]})]}),n.jsx("p",{style:{margin:0,fontSize:13,color:"#374151",lineHeight:1.5},children:i.text})]},i.id)})})]})})}function zt({startedAt:s}){const[e,t]=l.useState(0);return l.useEffect(()=>{const i=new Date(s).getTime(),r=setInterval(()=>t(Date.now()-i),500);return()=>clearInterval(r)},[s]),n.jsx(n.Fragment,{children:Oe(e)})}function In({rec:s,onDelete:e,onDownload:t}){const[i,r]=l.useState(!1),[a,o]=l.useState(0),c=l.useRef(null),p=jn[s.state],u=s.state==="recording"||s.state==="paused";return n.jsxs(n.Fragment,{children:[i&&s.transcript&&n.jsx(Cn,{segments:s.transcript,currentTimeMs:a,onClose:()=>r(!1)}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 12px",borderBottom:"1px solid #f3f4f6",flexWrap:"wrap"},children:[n.jsx("div",{style:{fontSize:20},children:s.sessionType==="call"?"๐":s.sessionType==="meeting"?"๐ฅ":s.sessionType==="whiteboard"?"๐ผ๏ธ":"๐ฅ๏ธ"}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.title??`Recording ${s.id.slice(0,8)}`}),n.jsxs("div",{style:{fontSize:11,color:"#9ca3af",marginTop:2,display:"flex",gap:8},children:[n.jsx("span",{children:kn(s.startedAt)}),n.jsx("span",{children:u?n.jsx(zt,{startedAt:s.startedAt}):s.durationMs!=null?Oe(s.durationMs):"โ"}),s.size!=null&&n.jsx("span",{children:wn(s.size)}),n.jsxs("span",{children:[s.participants.length," participants"]})]})]}),n.jsx("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:20,background:p.bg,color:p.fg,fontWeight:500,whiteSpace:"nowrap"},children:p.label}),s.url&&s.state==="ready"&&n.jsx("audio",{ref:c,src:s.url,controls:!0,onTimeUpdate:()=>{c.current&&o(c.current.currentTime*1e3)},style:{height:32,maxWidth:180}}),n.jsxs("div",{style:{display:"flex",gap:4},children:[s.transcript&&s.transcript.length>0&&n.jsx("button",{onClick:()=>r(!0),style:Be,title:"View transcript",children:"๐"}),s.state==="ready"&&n.jsx("button",{onClick:()=>t(s),style:Be,title:"Download",children:"โฌ"}),n.jsx("button",{onClick:()=>e(s.id),style:{...Be,color:"#ef4444"},title:"Delete",children:"๐"})]})]})]})}function Tn({recordings:s,onRecordingStart:e,onRecordingStop:t,onRecordingPause:i,onRecordingResume:r,onRecordingDelete:a,onRecordingDownload:o,activeRecordingId:c,sessionType:p="meeting",className:u,style:m,"data-testid":f}){const[y,h]=l.useState(s??[]),[S,C]=l.useState(""),[d,z]=l.useState("all");l.useEffect(()=>{s&&h(s)},[s]);const P=y.find(N=>N.id===c),D=(P==null?void 0:P.state)==="recording",W=(P==null?void 0:P.state)==="paused",M=y.filter(N=>{const H=d==="all"||N.sessionType===d,j=!S||(N.title??"").toLowerCase().includes(S.toLowerCase())||N.id.includes(S);return H&&j}),F=l.useCallback(N=>{h(H=>H.filter(j=>j.id!==N)),a==null||a(N)},[a]),U=l.useCallback(N=>{if(o){o(N.id);return}if(N.url){const H=document.createElement("a");H.href=N.url,H.download=`${N.title??N.id}.${N.mimeType.includes("mp4")?"mp4":"webm"}`,H.click()}else if(N.blob){const H=URL.createObjectURL(N.blob),j=document.createElement("a");j.href=H,j.download=`${N.title??N.id}.webm`,j.click(),setTimeout(()=>URL.revokeObjectURL(H),5e3)}},[o]);return n.jsxs("div",{className:u,"data-testid":f,style:{display:"flex",flexDirection:"column",background:"#fff",borderRadius:10,border:"1px solid #e5e7eb",fontFamily:"system-ui, sans-serif",overflow:"hidden",...m},children:[n.jsxs("div",{style:{padding:"14px 16px",borderBottom:"1px solid #e5e7eb",display:"flex",gap:8,alignItems:"center"},children:[n.jsx("span",{style:{fontSize:16},children:"๐๏ธ"}),n.jsx("strong",{style:{fontSize:14,color:"#111827",flex:1},children:"Recordings"}),n.jsxs("span",{style:{fontSize:12,color:"#9ca3af"},children:[y.length," total"]})]}),n.jsxs("div",{style:{padding:"12px 16px",borderBottom:"1px solid #f3f4f6",display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[n.jsxs("select",{value:p,disabled:D||W,onChange:()=>{},style:{...ft,flex:0},children:[n.jsx("option",{value:"call",children:"Call"}),n.jsx("option",{value:"meeting",children:"Meeting"}),n.jsx("option",{value:"whiteboard",children:"Whiteboard"}),n.jsx("option",{value:"screen",children:"Screen"})]}),!D&&!W?n.jsx("button",{onClick:e,style:{...De,background:"#ef4444",color:"#fff"},children:"โ Start recording"}):n.jsxs(n.Fragment,{children:[W?n.jsx("button",{onClick:r,style:{...De,background:"#6366f1",color:"#fff"},children:"โถ Resume"}):n.jsx("button",{onClick:i,style:{...De,background:"#f59e0b",color:"#fff"},children:"โ Pause"}),n.jsx("button",{onClick:t,style:{...De,background:"#374151",color:"#fff"},children:"โ Stop"}),P&&n.jsx("span",{style:{fontSize:12,color:"#9ca3af",marginLeft:4},children:n.jsx(zt,{startedAt:P.startedAt})})]})]}),n.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid #f3f4f6",display:"flex",gap:6,alignItems:"center"},children:[n.jsx("input",{type:"search",value:S,onChange:N=>C(N.target.value),placeholder:"Search recordingsโฆ",style:{flex:1,padding:"4px 8px",border:"1px solid #e5e7eb",borderRadius:6,fontSize:12}}),n.jsxs("select",{value:d,onChange:N=>z(N.target.value),style:ft,children:[n.jsx("option",{value:"all",children:"All types"}),n.jsx("option",{value:"call",children:"Calls"}),n.jsx("option",{value:"meeting",children:"Meetings"}),n.jsx("option",{value:"whiteboard",children:"Whiteboard"}),n.jsx("option",{value:"screen",children:"Screen"})]})]}),n.jsx("div",{style:{flex:1,overflowY:"auto"},children:M.length===0?n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:32,gap:8,color:"#9ca3af"},children:[n.jsx("span",{style:{fontSize:32},children:"๐๏ธ"}),n.jsx("span",{style:{fontSize:13},children:"No recordings found"}),n.jsx("span",{style:{fontSize:11},children:"Start a recording above or adjust your search filters."})]}):M.map(N=>n.jsx(In,{rec:N,onDelete:F,onDownload:U},N.id))})]})}const Be={border:"1px solid #e5e7eb",borderRadius:6,background:"#fff",cursor:"pointer",padding:"4px 8px",fontSize:14,lineHeight:1},De={border:"none",borderRadius:6,cursor:"pointer",padding:"6px 14px",fontSize:12,fontWeight:500},ft={padding:"4px 6px",border:"1px solid #e5e7eb",borderRadius:6,fontSize:12,color:"#374151",background:"#fff"},zn={border:"none",background:"none",cursor:"pointer",fontSize:16,color:"#9ca3af",lineHeight:1,padding:4};function ht({participant:s,isFollowing:e,onClick:t}){const i=s.user.displayName??s.user.name,r=i.split(" ").map(a=>a[0]).slice(0,2).join("").toUpperCase();return n.jsxs("button",{onClick:t,title:`${i}${e?" (following)":""} โ ${s.editingRegion??"viewing"}`,style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:"50%",background:s.color,color:"#fff",fontSize:11,fontWeight:600,border:`2px solid ${e?"#fff":s.color}`,boxShadow:e?`0 0 0 2px ${s.color}`:"none",cursor:"pointer",flexShrink:0,transition:"transform 0.15s",position:"relative",overflow:"visible"},children:[s.user.avatarUrl?n.jsx("img",{src:s.user.avatarUrl,alt:r,style:{width:"100%",height:"100%",borderRadius:"50%",objectFit:"cover"}}):r,s.isActive&&n.jsx("span",{style:{position:"absolute",bottom:-1,right:-1,width:9,height:9,borderRadius:"50%",background:"#22c55e",border:"2px solid #fff"}})]})}function Rn({participant:s,containerRect:e}){if(!s.cursorX||!s.cursorY||!e)return null;const t=s.cursorX,i=s.cursorY;return n.jsxs("div",{style:{position:"absolute",left:t,top:i,pointerEvents:"none",zIndex:9e3,transform:"translate(-2px, -2px)"},children:[n.jsx("svg",{width:16,height:20,style:{display:"block"},children:n.jsx("path",{d:"M2 2 L2 16 L6 12 L10 18 L12 17 L8 11 L14 11 Z",fill:s.color,stroke:"#fff",strokeWidth:1.5})}),n.jsx("div",{style:{background:s.color,color:"#fff",fontSize:10,padding:"1px 5px",borderRadius:3,whiteSpace:"nowrap",marginTop:-2,marginLeft:10},children:s.user.displayName??s.user.name})]})}function Pn({count:s}){return s===0?null:n.jsxs("div",{style:{position:"absolute",top:8,left:"50%",transform:"translateX(-50%)",zIndex:8e3,background:"#fef3c7",border:"1px solid #fbbf24",borderRadius:6,padding:"4px 12px",fontSize:12,color:"#92400e",display:"flex",alignItems:"center",gap:6,boxShadow:"0 2px 8px rgba(0,0,0,0.1)",pointerEvents:"none"},children:["โ ๏ธ ",s," edit conflict",s>1?"s":""," โ auto-mergingโฆ"]})}function An(){return n.jsx("div",{style:{position:"absolute",inset:0,zIndex:7e3,background:"rgba(0,0,0,0.03)",cursor:"not-allowed",display:"flex",alignItems:"flex-end",justifyContent:"center",paddingBottom:12,pointerEvents:"none"},children:n.jsx("div",{style:{background:"rgba(0,0,0,0.6)",color:"#fff",fontSize:12,padding:"4px 14px",borderRadius:20},children:"๐๏ธ View only"})})}function En({pending:s}){return s===0?n.jsx("span",{style:{fontSize:11,color:"#22c55e"},children:"โ Synced"}):n.jsxs("span",{style:{fontSize:11,color:"#f59e0b"},children:["โ ",s," pendingโฆ"]})}function Dn({participant:s,isFollowing:e,onClick:t}){return n.jsxs("button",{onClick:t,style:{fontSize:11,padding:"2px 8px",border:`1px solid ${e?s.color:"#e5e7eb"}`,borderRadius:20,background:e?s.color:"#fff",color:e?"#fff":"#6b7280",cursor:"pointer",display:"flex",alignItems:"center",gap:4},children:["๐"," ",e?"Unfollow":`Follow ${(s.user.displayName??s.user.name).split(" ")[0]}`]})}function Mn({editorType:s,sessionId:e,currentUser:t,participants:i=[],onOperation:r,onParticipantJoin:a,onParticipantLeave:o,onCursorMove:c,isReadOnly:p=!1,showParticipants:u=!0,showCursors:m=!0,pendingOperations:f=0,conflictCount:y=0,className:h,style:S,children:C,"data-testid":d}){const z=l.useRef(null),[P,D]=l.useState(null),[W,M]=l.useState(null),[F,U]=l.useState(!1);l.useEffect(()=>{const b=z.current;if(!b)return;const T=new ResizeObserver(()=>D(b.getBoundingClientRect()));return T.observe(b),D(b.getBoundingClientRect()),()=>T.disconnect()},[]);const N=l.useCallback(b=>{if(!z.current||!c)return;const T=z.current.getBoundingClientRect();c(b.clientX-T.left,b.clientY-T.top)},[c]),H=l.useCallback(b=>{M(T=>T===b?null:b)},[]),j={vector:"โ๏ธ Vector",pixel:"๐ผ๏ธ Pixel",diagram:"๐ Diagram",document:"๐ Document",whiteboard:"๐๏ธ Whiteboard"};return n.jsxs("div",{className:h,"data-testid":d,style:{display:"flex",flexDirection:"column",background:"#fff",borderRadius:8,border:"1px solid #e5e7eb",overflow:"hidden",fontFamily:"system-ui, sans-serif",...S},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid #f3f4f6",background:"#f9fafb",minHeight:40},children:[n.jsx("span",{style:{fontSize:12,color:"#6b7280",fontWeight:500},children:j[s]}),n.jsx("span",{style:{flex:1}}),n.jsx(En,{pending:f}),u&&i.length>0&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:-4},children:[i.slice(0,5).map((b,T)=>n.jsx("div",{style:{marginLeft:T>0?-8:0,zIndex:10-T},children:n.jsx(ht,{participant:b,isFollowing:W===b.user.id,onClick:()=>{U(!0),H(b.user.id)}})},b.user.id)),i.length>5&&n.jsxs("button",{onClick:()=>U(!F),style:{marginLeft:-4,zIndex:5,width:30,height:30,borderRadius:"50%",background:"#e5e7eb",border:"2px solid #fff",fontSize:10,fontWeight:600,color:"#374151",cursor:"pointer"},children:["+",i.length-5]})]}),u&&i.length>0&&n.jsxs("button",{onClick:()=>U(!F),style:{border:"1px solid #e5e7eb",borderRadius:5,background:F?"#eff6ff":"#fff",padding:"3px 8px",cursor:"pointer",fontSize:11,color:F?"#3b82f6":"#6b7280"},children:[i.length," online"]})]}),n.jsxs("div",{style:{display:"flex",flex:1,overflow:"hidden",position:"relative"},children:[n.jsxs("div",{ref:z,onMouseMove:N,style:{flex:1,position:"relative",overflow:"hidden"},children:[C??n.jsxs("div",{id:`collab-editor-${s}-${e}`,style:{width:"100%",height:"100%",minHeight:400,display:"flex",alignItems:"center",justifyContent:"center",background:"#f9fafb",color:"#9ca3af",fontSize:13},children:["Drop your ",s," editor here or use the"," ",n.jsx("code",{style:{background:"#e5e7eb",padding:"1px 5px",borderRadius:3,margin:"0 4px"},children:`#collab-editor-${s}-${e}`})," ","mount point."]}),m&&i.filter(b=>b.user.id!==t.id&&b.cursorX!=null&&b.cursorY!=null).map(b=>n.jsx(Rn,{participant:b,containerRect:P},b.user.id)),n.jsx(Pn,{count:y}),p&&n.jsx(An,{})]}),F&&i.length>0&&n.jsxs("div",{style:{width:220,borderLeft:"1px solid #e5e7eb",background:"#f9fafb",overflowY:"auto",padding:10,display:"flex",flexDirection:"column",gap:8},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[n.jsx("strong",{style:{fontSize:12,color:"#374151"},children:"Participants"}),n.jsx("button",{onClick:()=>U(!1),style:{border:"none",background:"none",cursor:"pointer",color:"#9ca3af",fontSize:14},children:"โ"})]}),i.map(b=>n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"8px",borderRadius:6,background:"#fff",border:"1px solid #f3f4f6"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx(ht,{participant:b,isFollowing:W===b.user.id,onClick:()=>H(b.user.id)}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontSize:12,fontWeight:500,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.user.displayName??b.user.name}),n.jsx("div",{style:{fontSize:10,color:"#9ca3af"},children:b.editingRegion??"viewing"})]})]}),b.user.id!==t.id&&n.jsx(Dn,{participant:b,isFollowing:W===b.user.id,onClick:()=>H(b.user.id)})]},b.user.id))]})]})]})}function tt(s){let e="";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return btoa(e)}function nt(s){const e=atob(s),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}function Nn(s){return new TextEncoder().encode(s)}function $n(s){return new TextDecoder().decode(s)}async function On(s){return crypto.subtle.generateKey({name:"AES-GCM",length:s},!0,["encrypt","decrypt"])}async function Ln(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-384"},!0,["deriveKey"])}async function Wn(s,e){return crypto.subtle.deriveKey({name:"ECDH",public:e},s,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Fn(s,e){const t=crypto.getRandomValues(new Uint8Array(12)),i=Nn(e),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},s,i),a=new Uint8Array(r),o=new Uint8Array(12+a.length);return o.set(t,0),o.set(a,12),tt(o)}async function _n(s,e){const t=nt(e),i=t.slice(0,12),r=t.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},s,r);return $n(new Uint8Array(a))}async function gt(s,e){const t=nt(s);return crypto.subtle.importKey("raw",t,{name:"AES-GCM",length:e},!1,["encrypt","decrypt"])}async function Bn(s){const e=await crypto.subtle.exportKey("raw",s);return tt(new Uint8Array(e))}async function Un(s){const e=await crypto.subtle.exportKey("spki",s);return tt(new Uint8Array(e))}async function Hn(s){const e=nt(s);return crypto.subtle.importKey("spki",e,{name:"ECDH",namedCurve:"P-384"},!0,[])}class Rt{constructor(e){this.keys={},this.ready=!1,this.config=e}async init(){if(!this.config.enabled){this.ready=!0;return}const e=this.config.defaultAlgorithm;if(this.config.keyMaterial)e==="AES-GCM-128"?this.keys.aes128=await gt(this.config.keyMaterial,128):this.keys.aes256=await gt(this.config.keyMaterial,256);else if(e==="AES-GCM-256"||e==="AES-GCM-128"){const t=e==="AES-GCM-256"?256:128,i=await On(t);t===128?this.keys.aes128=i:this.keys.aes256=i}else if(e==="E2E-ECDH-P384"){const t=await Ln();this.keys.ecdhPrivate=t.privateKey,this.keys.ecdhPublic=t.publicKey,this.keys.ecdhSessionKeys=new Map}this.ready=!0}async getPublicKeyForPeer(){return this.keys.ecdhPublic?Un(this.keys.ecdhPublic):null}async registerPeerPublicKey(e,t){var a;if(!this.keys.ecdhPrivate)return;const i=await Hn(t),r=await Wn(this.keys.ecdhPrivate,i);(a=this.keys.ecdhSessionKeys)==null||a.set(e,r)}resolveAlgorithm(e){if(e&&this.config.scopeOverrides){const t=this.config.scopeOverrides.find(i=>(i.scope===e||i.scope==="all")&&i.enabled);if(t)return t.algorithm}return this.config.defaultAlgorithm}getKey(e,t){var i;switch(e){case"AES-GCM-256":return this.keys.aes256??null;case"AES-GCM-128":return this.keys.aes128??null;case"E2E-ECDH-P384":return t?((i=this.keys.ecdhSessionKeys)==null?void 0:i.get(t))??null:null;default:return null}}async encrypt(e,t,i){if(!this.config.enabled)return e;if(!this.ready)throw new Error("EncryptionService not initialised โ call init() first");const r=this.resolveAlgorithm(t);if(r==="none")return e;const a=this.getKey(r,i);return a?Fn(a,e):(console.warn(`EncryptionService: no key found for algorithm "${r}" โ returning plaintext`),e)}async decrypt(e,t,i){if(!this.config.enabled)return e;if(!this.ready)throw new Error("EncryptionService not initialised โ call init() first");const r=this.resolveAlgorithm(t);if(r==="none")return e;const a=this.getKey(r,i);return a?_n(a,e):(console.warn(`EncryptionService: no key found for algorithm "${r}" โ returning as-is`),e)}async exportSymmetricKey(e){const t=e??this.config.defaultAlgorithm,i=this.getKey(t);return i?Bn(i):null}isEnabled(){return this.config.enabled}getConfig(){return this.config}updateConfig(e){this.config=e,this.ready=!1}}const Ne=new Map;function Kn(s,e){return Ne.has(s)||Ne.set(s,new Rt(e)),Ne.get(s)}function Yn(s){Ne.delete(s)}class Pt{constructor(e={}){this.recorder=null,this.chunks=[],this.session=null,this.recognition=null,this.segmentCounter=0,this.callbacks=e}start(e,t){var c,p,u;if(((c=this.recorder)==null?void 0:c.state)==="recording")throw new Error("Recording already in progress");const i=t.mimeType??this.chooseMimeType(),r=new MediaRecorder(e,{mimeType:i});this.chunks=[];const a=new Date,o=`rec_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return this.session={id:o,sessionType:t.sessionType,startedAt:a,state:"recording",mimeType:i,participants:[t.speakerId??"unknown"],title:t.title??`Recording ${a.toLocaleString()}`},r.ondataavailable=m=>{m.data&&m.data.size>0&&this.chunks.push(m.data)},r.onstop=()=>{var f,y,h,S;const m=new Blob(this.chunks,{type:i});this.session&&(this.session.blob=m,this.session.endedAt=new Date,this.session.durationMs=this.session.endedAt.getTime()-this.session.startedAt.getTime(),this.session.size=m.size,this.session.state="ready"),(y=(f=this.callbacks).onDataAvailable)==null||y.call(f,m),(S=(h=this.callbacks).onStateChange)==null||S.call(h,"ready")},r.onerror=m=>{var f,y,h,S;(y=(f=this.callbacks).onError)==null||y.call(f,new Error(String(m))),this.session&&(this.session.state="failed"),(S=(h=this.callbacks).onStateChange)==null||S.call(h,"failed")},r.start(t.timesliceMs??1e3),this.recorder=r,t.transcribe&&this.startTranscription(t.speakerId??"unknown",t.speakerName??"Participant"),(u=(p=this.callbacks).onStateChange)==null||u.call(p,"recording"),this.session}pause(){var e,t,i;((e=this.recorder)==null?void 0:e.state)==="recording"&&(this.recorder.pause(),this.session&&(this.session.state="paused"),(i=(t=this.callbacks).onStateChange)==null||i.call(t,"paused"))}resume(){var e,t,i;((e=this.recorder)==null?void 0:e.state)==="paused"&&(this.recorder.resume(),this.session&&(this.session.state="recording"),(i=(t=this.callbacks).onStateChange)==null||i.call(t,"recording"))}stop(){var e,t;return this.stopTranscription(),this.recorder&&this.recorder.state!=="inactive"&&(this.recorder.stop(),this.session&&(this.session.state="processing"),(t=(e=this.callbacks).onStateChange)==null||t.call(e,"processing")),this.session}startTranscription(e,t){const i=window,r=i.SpeechRecognition??i.webkitSpeechRecognition;if(!r)return;const a=new r;a.continuous=!0,a.interimResults=!1,a.lang="en-US";const o=Date.now();a.onresult=c=>{var u,m;const p=c.results;for(let f=c.resultIndex;f<p.length;f++){const y=p[f];if(!y.isFinal)continue;const h=y[0],S=Date.now(),C={id:`seg_${++this.segmentCounter}`,speakerId:e,speakerName:t,text:h.transcript.trim(),startMs:S-o-1500,endMs:S-o,confidence:h.confidence??.9};this.session&&(this.session.transcript=[...this.session.transcript??[],C]),(m=(u=this.callbacks).onTranscriptSegment)==null||m.call(u,C)}},a.onerror=()=>{};try{a.start(),this.recognition=a}catch{}}stopTranscription(){var e;try{(e=this.recognition)==null||e.stop()}catch{}this.recognition=null}chooseMimeType(){const e=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm","audio/webm;codecs=opus","audio/ogg;codecs=opus"];for(const t of e)if(MediaRecorder.isTypeSupported(t))return t;return""}getState(){var e;return((e=this.session)==null?void 0:e.state)??"idle"}getSession(){return this.session}download(e){var a,o;const t=(a=this.session)==null?void 0:a.blob;if(!t)return;const i=URL.createObjectURL(t),r=document.createElement("a");r.href=i,r.download=e??`${((o=this.session)==null?void 0:o.title)??"recording"}.webm`,r.click(),setTimeout(()=>URL.revokeObjectURL(i),3e4)}}const $e=new Map;function Gn(s,e){return $e.has(s)||$e.set(s,new Pt(e)),$e.get(s)}function qn(s){$e.delete(s)}class At{constructor(e){this.events=[],this.eventListeners=new Map,this.config={serverUrl:e.serverUrl,apiKey:e.apiKey??"",anonymizeIp:e.anonymizeIp??!0,enableGeoLocation:e.enableGeoLocation??!1,pixelPath:e.pixelPath??"/pixel",redirectPath:e.redirectPath??"/redirect",hashAlgorithm:e.hashAlgorithm??"sha256"}}generateTrackingPixel(e){const t=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,metadata:e.metadata}),i=e.width??1,r=e.height??1,a=`${this.config.serverUrl}${this.config.pixelPath}?${t}`;return`<img src="${this.escapeHtml(a)}" width="${i}" height="${r}" alt="" style="display:block;width:${i}px;height:${r}px;border:0;" />`}generateTrackingPixelUrl(e){const t=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,metadata:e.metadata});return`${this.config.serverUrl}${this.config.pixelPath}?${t}`}wrapLink(e){const t=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,url:e.url,linkName:e.linkName});return`${this.config.serverUrl}${this.config.redirectPath}?${t}`}wrapLinksForTracking(e,t){const i=t.excludePatterns??[/^mailto:/i,/^tel:/i,/^#/,/unsubscribe/i],r=/<a\s+([^>]*?)href=["']([^"']+)["']([^>]*?)>/gi;return e.replace(r,(a,o,c,p)=>{if(i.some(y=>y.test(c)))return a;const m=this.extractLinkName(o+p)??c,f=this.wrapLink({url:c,messageId:t.messageId,recipientId:t.recipientId,campaignId:t.campaignId,linkName:m});return`<a ${o}href="${this.escapeHtml(f)}"${p}>`})}recordEvent(e){const t={...e,id:this.generateEventId(),timestamp:new Date,ipAddress:this.config.anonymizeIp?this.anonymizeIpAddress(e.ipAddress):e.ipAddress};return this.events.push(t),this.notifyListeners(t),t}parseTrackingParams(e){const t=e.get("mid"),i=e.get("rid");if(!t||!i)return null;const r={};return e.forEach((a,o)=>{o.startsWith("m_")&&(r[o.substring(2)]=a)}),{messageId:t,recipientHash:i,campaignId:e.get("cid")??void 0,url:e.get("url")??void 0,linkName:e.get("ln")??void 0,metadata:Object.keys(r).length>0?r:void 0}}getStats(e){let t=this.events;e&&(t=this.events.filter(y=>!(e.campaignId&&y.campaignId!==e.campaignId||e.messageId&&y.messageId!==e.messageId||e.startDate&&y.timestamp<e.startDate||e.endDate&&y.timestamp>e.endDate)));const i=new Set(t.map(y=>y.recipientHash)),r=t.filter(y=>y.type==="open"),a=t.filter(y=>y.type==="click"),o=t.filter(y=>y.type==="bounce"),c=t.filter(y=>y.type==="unsubscribe"),p=t.filter(y=>y.type==="complaint"),u=new Set(r.map(y=>y.recipientHash)).size,m=new Set(a.map(y=>y.recipientHash)).size,f=i.size;return{sent:f+o.length,delivered:f,opens:r.length,uniqueOpens:u,clicks:a.length,uniqueClicks:m,bounces:o.length,unsubscribes:c.length,complaints:p.length,openRate:f>0?u/f:0,clickRate:f>0?m/f:0,clickToOpenRate:u>0?m/u:0,bounceRate:f>0?o.length/(f+o.length):0}}getLinkStats(e){let t=this.events.filter(o=>o.type==="click"&&o.url);e&&(t=t.filter(o=>!(e.campaignId&&o.campaignId!==e.campaignId||e.messageId&&o.messageId!==e.messageId)));const i=new Map;for(const o of t){const c=o.url;i.has(c)||i.set(c,{url:c,linkName:void 0,total:0,unique:new Set});const p=i.get(c);p.total++,p.unique.add(o.recipientHash)}const r=t.length,a=[];for(const[,o]of i)a.push({url:o.url,linkName:o.linkName,totalClicks:o.total,uniqueClicks:o.unique.size,clickShare:r>0?o.total/r:0});return a.sort((o,c)=>c.totalClicks-o.totalClicks)}getDeviceStats(e){let t=this.events.filter(r=>r.type==="open");e!=null&&e.campaignId&&(t=t.filter(r=>r.campaignId===e.campaignId));const i={desktop:0,mobile:0,tablet:0,unknown:0};for(const r of t){const a=r.device??"unknown";i[a]=(i[a]??0)+1}return i}on(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t),()=>{var i;(i=this.eventListeners.get(e))==null||i.delete(t)}}onAny(e){const t=["open","click","bounce","unsubscribe","complaint"].map(i=>this.on(i,e));return()=>{t.forEach(i=>i())}}generateUnsubscribeLink(e){const t=new URLSearchParams;return t.set("rid",this.hashRecipientId(e.recipientId)),e.listId&&t.set("lid",e.listId),t.set("action","unsubscribe"),`${this.config.serverUrl}/unsubscribe?${t.toString()}`}generateListUnsubscribeHeader(e){return`<${this.generateUnsubscribeLink(e)}>`}clearEvents(){this.events=[]}exportEvents(e){return e!=null&&e.anonymize?this.events.map(t=>({...t,recipientHash:"anonymized",ipAddress:void 0,userAgent:void 0})):[...this.events]}buildTrackingParams(e){const t=new URLSearchParams;if(t.set("mid",e.messageId),t.set("rid",this.hashRecipientId(e.recipientId)),e.campaignId&&t.set("cid",e.campaignId),e.url&&t.set("url",e.url),e.linkName&&t.set("ln",e.linkName),e.metadata)for(const[i,r]of Object.entries(e.metadata))t.set(`m_${i}`,r);return t.toString()}hashRecipientId(e){let t=0;for(let i=0;i<e.length;i++){const r=e.charCodeAt(i);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(36)}anonymizeIpAddress(e){if(e){if(e.includes(".")){const t=e.split(".");return t[3]="0",t.join(".")}return e.includes(":")?e.split(":").slice(0,3).join(":")+"::":e}}extractLinkName(e){const t=e.match(/title=["']([^"']+)["']/i);if(t)return t[1];const i=e.match(/data-link-name=["']([^"']+)["']/i);if(i)return i[1]}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}generateEventId(){return`evt_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}notifyListeners(e){const t=this.eventListeners.get(e.type);if(t)for(const i of t)try{i(e)}catch(r){console.error("Tracking event listener error:",r)}}}let ge=null;function Ye(s){if(!ge&&s&&(ge=new At(s)),!ge)throw new Error("EmailTrackingService not initialized. Call with config first.");return ge}function Vn(){ge==null||ge.clearEvents(),ge=null}function Xn(s){const{config:e,campaignId:t,autoRefreshInterval:i}=s,r=l.useMemo(()=>{if(e)return Ye(e);try{return Ye()}catch{return null}},[e]),[a,o]=l.useState(null),[c,p]=l.useState([]),u=l.useCallback(()=>{r&&(o(r.getStats({campaignId:t})),p(r.getLinkStats({campaignId:t})))},[r,t]);l.useEffect(()=>{if(u(),i&&r){const h=setInterval(u,i);return()=>clearInterval(h)}},[u,i,r]),l.useEffect(()=>{if(r)return r.onAny(()=>{u()})},[r,u]);const m=l.useCallback((h,S)=>r?r.generateTrackingPixel({messageId:h,recipientId:S,campaignId:t}):"",[r,t]),f=l.useCallback((h,S,C)=>r?r.wrapLinksForTracking(h,{messageId:S,recipientId:C,campaignId:t}):h,[r,t]),y=l.useCallback(h=>{r==null||r.recordEvent(h)},[r]);return{generatePixel:m,wrapLinks:f,stats:a,linkStats:c,recordEvent:y,refreshStats:u}}class Et{constructor(e){this.templates=new Map,this.campaigns=new Map,this.abortControllers=new Map,this.config={sendEmail:e.sendEmail,rateLimit:e.rateLimit??60,batchSize:e.batchSize??10,retryOnFail:e.retryOnFail??!0,maxRetries:e.maxRetries??3,dateFormatter:e.dateFormatter??this.defaultDateFormatter,numberFormatter:e.numberFormatter??this.defaultNumberFormatter,currencyFormatter:e.currencyFormatter??this.defaultCurrencyFormatter}}createTemplate(e){const t={...e,id:this.generateId("tpl"),createdAt:new Date,updatedAt:new Date};return this.templates.set(t.id,t),t}updateTemplate(e,t){const i=this.templates.get(e);if(!i)throw new Error(`Template not found: ${e}`);const r={...i,...t,updatedAt:new Date};return this.templates.set(e,r),r}getTemplate(e){return this.templates.get(e)}deleteTemplate(e){return this.templates.delete(e)}listTemplates(){return Array.from(this.templates.values())}extractFields(e){const t=/\{\{([^}]+)\}\}/g,i=new Set;let r;for(;(r=t.exec(e))!==null;){const a=r[1].trim();if(a.startsWith("#if "))i.add(a.substring(4).trim());else if(a.startsWith("#unless "))i.add(a.substring(8).trim());else if(a.startsWith("#each "))i.add(a.substring(6).trim());else if(!a.startsWith("/")&&!a.startsWith("else")){const[o]=a.split("|");i.add(o.trim())}}return Array.from(i)}createCampaign(e){if(!this.templates.has(e.templateId))throw new Error(`Template not found: ${e.templateId}`);const t={...e,id:this.generateId("cmp"),status:"draft",recipients:e.recipients.map(i=>({...i,status:"pending"})),createdAt:new Date};return this.campaigns.set(t.id,t),t}getCampaign(e){return this.campaigns.get(e)}updateCampaign(e,t){const i=this.campaigns.get(e);if(!i)throw new Error(`Campaign not found: ${e}`);if(i.status==="sending")throw new Error("Cannot update campaign while sending");const r={...i,...t};return this.campaigns.set(e,r),r}addRecipients(e,t){const i=this.campaigns.get(e);if(!i)throw new Error(`Campaign not found: ${e}`);if(i.status==="sending")throw new Error("Cannot add recipients while sending");const r=t.map(a=>({...a,status:"pending"}));i.recipients.push(...r),this.campaigns.set(e,i)}removeRecipient(e,t){const i=this.campaigns.get(e);if(!i)return!1;const r=i.recipients.findIndex(a=>a.id===t);return r===-1?!1:(i.recipients.splice(r,1),!0)}listCampaigns(){return Array.from(this.campaigns.values())}validateCampaign(e){const t=this.campaigns.get(e);if(!t)return{isValid:!1,errors:[{type:"syntax_error",message:"Campaign not found"}],warnings:[],missingFields:new Map};const i=this.templates.get(t.templateId);if(!i)return{isValid:!1,errors:[{type:"syntax_error",message:"Template not found"}],warnings:[],missingFields:new Map};const r=[],a=[],o=new Map;t.recipients.length===0&&r.push({type:"empty_recipient",message:"No recipients in campaign"});for(const u of t.recipients){if(!u.email){r.push({type:"empty_recipient",recipientId:u.id,message:`Recipient ${u.id} has no email address`});continue}const m=[];for(const f of i.fields)f.required&&!(f.name in u.data)&&(m.push(f.name),r.push({type:"missing_field",field:f.name,recipientId:u.id,message:`Required field "${f.name}" missing for ${u.email}`}));m.length>0&&o.set(u.id,m)}const c=this.extractFields(i.subject+i.htmlBody+(i.textBody??"")),p=i.fields.map(u=>u.name);for(const u of c)p.includes(u)||a.push({type:"unused_field",field:u,message:`Field "${u}" used in template but not defined`});return{isValid:r.length===0,errors:r,warnings:a,missingFields:o}}previewMerge(e,t){const i=this.templates.get(e);if(!i)throw new Error(`Template not found: ${e}`);return{subject:this.processTemplate(i.subject,t,i.fields),html:this.processTemplate(i.htmlBody,t,i.fields),text:i.textBody?this.processTemplate(i.textBody,t,i.fields):void 0}}async*sendCampaign(e){const t=this.campaigns.get(e);if(!t)throw new Error(`Campaign not found: ${e}`);const i=this.templates.get(t.templateId);if(!i)throw new Error(`Template not found: ${t.templateId}`);const r=this.validateCampaign(e);if(!r.isValid)throw new Error(`Campaign validation failed: ${r.errors.map(y=>y.message).join(", ")}`);t.status="sending",t.startedAt=new Date,this.campaigns.set(e,t);const a=new AbortController;this.abortControllers.set(e,a);const o=t.recipients.filter(y=>y.status==="pending"),c=o.length;let p=0,u=0;const m=Date.now(),f=60*1e3/(t.rateLimit??this.config.rateLimit);try{for(let y=0;y<o.length;y++){if(a.signal.aborted){t.status="paused";break}const h=o[y];try{const D=this.previewMerge(i.id,h.data),W=await this.config.sendEmail({to:h.email,cc:h.cc,bcc:h.bcc,from:t.fromEmail,fromName:t.fromName,replyTo:t.replyTo,subject:h.subjectOverride??D.subject,html:D.html,text:D.text});W.success?(h.status="sent",p++):(h.status="failed",h.error=W.error,u++)}catch(D){h.status="failed",h.error=D instanceof Error?D.message:"Unknown error",u++}const S=p+u,C=Date.now()-m,d=S>0?C/S:f,z=c-S,P=Math.round(z*d/1e3);yield{campaignId:e,total:c,sent:p,failed:u,pending:c-S,current:h.email,percentage:Math.round(S/c*100),estimatedTimeRemaining:P,isComplete:!1},y<o.length-1&&await this.delay(f)}t.status="completed",t.completedAt=new Date,this.campaigns.set(e,t),yield{campaignId:e,total:c,sent:p,failed:u,pending:0,percentage:100,isComplete:!0}}finally{this.abortControllers.delete(e)}}pauseCampaign(e){const t=this.abortControllers.get(e);t&&t.abort();const i=this.campaigns.get(e);i&&i.status==="sending"&&(i.status="paused",this.campaigns.set(e,i))}async*resumeCampaign(e){const t=this.campaigns.get(e);if(!t)throw new Error(`Campaign not found: ${e}`);if(t.status!=="paused")throw new Error("Campaign is not paused");t.status="draft",this.campaigns.set(e,t),yield*this.sendCampaign(e)}cancelCampaign(e){this.pauseCampaign(e);const t=this.campaigns.get(e);t&&(t.status="cancelled",this.campaigns.set(e,t))}async*retryFailed(e){const t=this.campaigns.get(e);if(!t)throw new Error(`Campaign not found: ${e}`);for(const i of t.recipients)i.status==="failed"&&(i.status="pending",i.error=void 0);t.status="draft",this.campaigns.set(e,t),yield*this.sendCampaign(e)}processTemplate(e,t,i){const r=new Map(i.map(a=>[a.name,a]));return e=this.processConditionals(e,t),e=this.processLoops(e,t),e=e.replace(/\{\{([^}#/]+)\}\}/g,(a,o)=>{const[c,...p]=o.trim().split("|").map(f=>f.trim());let u=this.getNestedValue(t,c);const m=r.get(c);u==null&&(u=(m==null?void 0:m.defaultValue)??""),m&&u!==""&&(u=this.formatValue(u,m));for(const f of p)u=this.applyFormatter(u,f);return String(u)}),e}processConditionals(e,t){const i=/\{\{#if\s+([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g;return e.replace(i,(r,a,o,c="")=>{const p=this.getNestedValue(t,a.trim());return this.isTruthy(p)?o:c})}processLoops(e,t){const i=/\{\{#each\s+([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g;return e.replace(i,(r,a,o)=>{const c=this.getNestedValue(t,a.trim());return Array.isArray(c)?c.map((p,u)=>{let m=o;return typeof p!="object"&&(m=m.replace(/\{\{this\}\}/g,String(p))),m=m.replace(/\{\{this\.([^}]+)\}\}/g,(f,y)=>String(this.getNestedValue(p,y)??"")),m=m.replace(/\{\{@index\}\}/g,String(u)),m=m.replace(/\{\{@first\}\}/g,String(u===0)),m=m.replace(/\{\{@last\}\}/g,String(u===c.length-1)),m}).join(""):""})}formatValue(e,t){switch(t.type){case"date":return e instanceof Date?this.config.dateFormatter(e,t.format??"short"):typeof e=="string"||typeof e=="number"?this.config.dateFormatter(new Date(e),t.format??"short"):String(e);case"number":return typeof e=="number"?this.config.numberFormatter(e,t.format??""):String(e);case"currency":if(typeof e=="number"){const[i="USD",r="en-US"]=(t.format??"USD|en-US").split("|");return this.config.currencyFormatter(e,i,r)}return String(e);case"boolean":return e?"Yes":"No";case"list":return Array.isArray(e)?e.join(t.format??", "):String(e);default:return String(e)}}applyFormatter(e,t){const i=String(e);switch(t.toLowerCase()){case"uppercase":return i.toUpperCase();case"lowercase":return i.toLowerCase();case"capitalize":return i.charAt(0).toUpperCase()+i.slice(1).toLowerCase();case"titlecase":return i.replace(/\b\w/g,r=>r.toUpperCase());case"trim":return i.trim();case"escape":return this.escapeHtml(i);default:return i}}getNestedValue(e,t){const i=t.split(".");let r=e;for(const a of i){if(r==null)return;r=r[a]}return r}isTruthy(e){return e==null?!1:typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"||Array.isArray(e)?e.length>0:!0}defaultDateFormatter(e,t){const i={};switch(t){case"short":i.dateStyle="short";break;case"medium":i.dateStyle="medium";break;case"long":i.dateStyle="long";break;case"full":i.dateStyle="full";break;case"iso":return e.toISOString();default:i.dateStyle="medium"}return new Intl.DateTimeFormat("en-US",i).format(e)}defaultNumberFormatter(e,t){if(!t)return new Intl.NumberFormat().format(e);const i=parseInt(t,10);return isNaN(i)?String(e):new Intl.NumberFormat("en-US",{minimumFractionDigits:i,maximumFractionDigits:i}).format(e)}defaultCurrencyFormatter(e,t,i){return new Intl.NumberFormat(i,{style:"currency",currency:t}).format(e)}generateId(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}delay(e){return new Promise(t=>setTimeout(t,e))}}let Te=null;function Ge(s){if(!Te&&s&&(Te=new Et(s)),!Te)throw new Error("MailMergeService not initialized. Call with config first.");return Te}function Jn(){Te=null}function Qn(s={}){const{config:e}=s,t=l.useMemo(()=>{if(e)return Ge(e);try{return Ge()}catch{return null}},[e]),[i,r]=l.useState(null),[a,o]=l.useState(!1),[c,p]=l.useState([]),[u,m]=l.useState([]),f=l.useCallback(()=>{t&&(p(t.listTemplates()),m(t.listCampaigns()))},[t]),y=l.useCallback(P=>{if(!t)throw new Error("Service not initialized");const D=t.createTemplate(P);return f(),D},[t,f]),h=l.useCallback(P=>{if(!t)throw new Error("Service not initialized");const D=t.createCampaign(P);return f(),D},[t,f]),S=l.useCallback((P,D)=>{if(!t)throw new Error("Service not initialized");return t.previewMerge(P,D)},[t]),C=l.useCallback(P=>{if(!t)throw new Error("Service not initialized");return t.validateCampaign(P)},[t]),d=l.useCallback(async function*(P){if(!t)throw new Error("Service not initialized");o(!0);try{for await(const D of t.sendCampaign(P))r(D),yield D}finally{o(!1),f()}},[t,f]),z=l.useCallback(P=>{t==null||t.pauseCampaign(P),o(!1),f()},[t,f]);return{createTemplate:y,createCampaign:h,preview:S,validate:C,send:d,pause:z,progress:i,isSending:a,templates:c,campaigns:u}}class Dt{constructor(e){this.abortController=null,this.mapping={users:new Map,channels:new Map,files:new Map},this.config=e}async parseSlackExport(e){const t=await this.extractZipContents(e),i=t.get("users.json"),r=i?JSON.parse(i):[],a=t.get("channels.json"),o=a?JSON.parse(a):[],c=t.get("groups.json");if(c){const m=JSON.parse(c);o.push(...m.map(f=>({...f,is_private:!0})))}const p=t.get("dms.json");if(p){const m=JSON.parse(p);o.push(...m.map(f=>({...f,is_im:!0})))}const u=new Map;for(const m of o){const f=[],y=m.name;for(const[h,S]of t)if(h.startsWith(y+"/")&&h.endsWith(".json"))try{const C=JSON.parse(S);f.push(...C)}catch(C){console.warn(`Failed to parse messages from ${h}:`,C)}f.length>0&&u.set(m.id,f)}return{users:r,channels:o,messages:u}}parseSlackExportFromJson(e){return{users:e.users??[],channels:e.channels??[],messages:new Map(Object.entries(e.messages??{})),files:e.files}}previewImport(e,t={}){const i=e.users.filter(f=>t.importUsers!==!1&&!f.deleted),r=i.map(f=>this.mapUser(f)),a=e.channels.filter(f=>!(t.skipArchived&&f.is_archived||t.skipDirectMessages&&(f.is_im||f.is_mpim)||t.channelFilter&&!t.channelFilter.includes(f.id)&&!t.channelFilter.includes(f.name))),o=a.map(f=>this.mapChannel(f,new Map));let c=0;const p=new Map;for(const[f,y]of e.messages){const h=e.channels.find(d=>d.id===f);if(!h||!a.some(d=>d.id===f))continue;const C=this.filterMessages(y,t);p.set(h.name,C.length),c+=C.length}let u=0,m=0;for(const f of e.messages.values())for(const y of f)y.files&&(u+=y.files.length,m+=y.files.reduce((h,S)=>h+(S.size||0),0));return{users:{total:e.users.length,filtered:i.length,items:r},channels:{total:e.channels.length,filtered:a.length,items:o},messages:{total:c,perChannel:p},files:{total:u,totalSize:m}}}async*import(e,t={}){this.abortController=new AbortController,this.mapping={users:new Map,channels:new Map,files:new Map};const i=[],r={usersImported:0,channelsImported:0,messagesImported:0,filesImported:0,reactionsImported:0,threadsImported:0},a=new Date,c=1e3/(this.config.rateLimit??10);try{if(t.importUsers!==!1){const u=e.users.filter(f=>!f.deleted);let m=0;for(const f of u){if(this.abortController.signal.aborted)break;const y=this.mapUser(f),h=await this.config.createUser(y);h.success&&h.id?(this.mapping.users.set(f.id,h.id),r.usersImported++):i.push({phase:"users",itemId:f.id,itemType:"user",message:h.error??"Failed to create user"}),m++,yield{phase:"users",total:u.length,processed:m,failed:i.filter(S=>S.phase==="users").length,current:f.name,percentage:Math.round(m/u.length*100),isComplete:!1,errors:i},await this.delay(c)}}if(t.importChannels!==!1){const u=e.channels.filter(f=>{var y;return t.skipArchived&&f.is_archived||t.skipDirectMessages&&(f.is_im||f.is_mpim)?!1:(y=t.channelFilter)!=null&&y.length?t.channelFilter.includes(f.id)||t.channelFilter.includes(f.name):!0});let m=0;for(const f of u){if(this.abortController.signal.aborted)break;const y=this.mapChannel(f,this.mapping.users),h=await this.config.createChannel(y);h.success&&h.id?(this.mapping.channels.set(f.id,h.id),r.channelsImported++):i.push({phase:"channels",itemId:f.id,itemType:"channel",message:h.error??"Failed to create channel"}),m++,yield{phase:"channels",total:u.length,processed:m,failed:i.filter(S=>S.phase==="channels").length,current:f.name,percentage:Math.round(m/u.length*100),isComplete:!1,errors:i},await this.delay(c)}}if(t.importMessages!==!1){const u=[];for(const[y,h]of e.messages){if(!this.mapping.channels.has(y))continue;const S=this.filterMessages(h,t);for(const C of S)u.push({channelId:y,message:C})}u.sort((y,h)=>parseFloat(y.message.ts)-parseFloat(h.message.ts));const m=new Map;let f=0;for(const{channelId:y,message:h}of u){if(this.abortController.signal.aborted)break;const S=this.mapMessage(h,y,this.mapping,m),C=await this.config.createMessage(S);C.success&&C.id?((!h.thread_ts||h.thread_ts===h.ts)&&m.set(h.ts,C.id),r.messagesImported++,S.isThreadReply&&r.threadsImported++,r.reactionsImported+=S.reactions.length):i.push({phase:"messages",itemId:h.ts,itemType:"message",message:C.error??"Failed to create message"}),f++,yield{phase:"messages",total:u.length,processed:f,failed:i.filter(d=>d.phase==="messages").length,current:`${f}/${u.length}`,percentage:Math.round(f/u.length*100),isComplete:!1,errors:i},await this.delay(c)}}if(t.importFiles&&t.downloadFiles&&this.config.uploadFile&&this.config.downloadFile){const u=[];for(const f of e.messages.values())for(const y of f)y.files&&u.push(...y.files);let m=0;for(const f of u){if(this.abortController.signal.aborted)break;try{const y=f.url_private_download??f.url_private;if(y&&this.config.slackToken){const h=await this.config.downloadFile(y,this.config.slackToken),S=await this.config.uploadFile(f,h);S.success&&S.url?(this.mapping.files.set(f.id,S.url),r.filesImported++):i.push({phase:"files",itemId:f.id,itemType:"file",message:S.error??"Failed to upload file"})}}catch(y){i.push({phase:"files",itemId:f.id,itemType:"file",message:y instanceof Error?y.message:"File download failed"})}m++,yield{phase:"files",total:u.length,processed:m,failed:i.filter(y=>y.phase==="files").length,current:f.name,percentage:Math.round(m/u.length*100),isComplete:!1,errors:i},await this.delay(c)}}const p=new Date;return yield{phase:"complete",total:0,processed:0,failed:i.length,percentage:100,isComplete:!0,errors:i},{status:(i.length>0,"completed"),stats:r,mapping:this.mapping,errors:i,startedAt:a,completedAt:p,duration:p.getTime()-a.getTime()}}finally{this.abortController=null}}cancel(){var e;(e=this.abortController)==null||e.abort()}mapUser(e){var t,i,r,a,o;return{slackId:e.id,email:e.email,displayName:((t=e.profile)==null?void 0:t.display_name)||e.name,realName:e.real_name,avatarUrl:((i=e.profile)==null?void 0:i.image_192)||((r=e.profile)==null?void 0:r.image_72),title:(a=e.profile)==null?void 0:a.title,phone:(o=e.profile)==null?void 0:o.phone,timezone:e.tz,isAdmin:e.is_admin??!1,isBot:e.is_bot??!1,isDeactivated:e.deleted??!1}}mapChannel(e,t){var r,a;let i="public";return e.is_private&&(i="private"),e.is_im&&(i="dm"),e.is_mpim&&(i="mpim"),{slackId:e.id,name:e.name,type:i,description:(r=e.purpose)==null?void 0:r.value,topic:(a=e.topic)==null?void 0:a.value,isArchived:e.is_archived??!1,creatorId:e.creator?t.get(e.creator):void 0,memberIds:(e.members??[]).map(o=>t.get(o)).filter(o=>!!o),createdAt:e.created?new Date(e.created*1e3):void 0}}mapMessage(e,t,i,r){const a=i.channels.get(t)??t,o=e.user?i.users.get(e.user):void 0,{text:c,html:p}=this.convertSlackMessage(e.text,i.users),u=e.thread_ts!==void 0&&e.thread_ts!==e.ts,m=e.thread_ts?r.get(e.thread_ts):void 0,f=[];if(e.files)for(const h of e.files)f.push({type:h.mimetype.startsWith("image/")?"image":"file",url:i.files.get(h.id)??h.url_private,name:h.name,size:h.size});if(e.attachments)for(const h of e.attachments)h.image_url?f.push({type:"image",url:h.image_url}):h.title_link&&f.push({type:"link",url:h.title_link,name:h.title});const y=(e.reactions??[]).map(h=>({emoji:h.name,userIds:h.users.map(S=>i.users.get(S)).filter(S=>!!S),count:h.count}));return{channelId:a,senderId:o,content:c,htmlContent:p,threadId:m,isThreadReply:u,attachments:f,reactions:y,createdAt:e.ts?new Date(parseFloat(e.ts)*1e3):void 0,editedAt:e.edited?new Date(parseFloat(e.edited.ts)*1e3):void 0}}convertSlackMessage(e,t){let i=e,r=this.escapeHtml(e);const a=/<@([A-Z0-9]+)(?:\|([^>]+))?>/g;return i=i.replace(a,(o,c,p)=>p?`@${p}`:"@user"),r=r.replace(/<@([A-Z0-9]+)(?:\|([^&]+))?>/g,(o,c,p)=>`<span class="mention" data-user-id="${t.get(c)??c}">@${p??"user"}</span>`),i=i.replace(/<#([A-Z0-9]+)\|([^>]+)>/g,"#$2"),r=r.replace(/<#([A-Z0-9]+)\|([^&]+)>/g,'<span class="channel-mention">#$2</span>'),i=i.replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)"),i=i.replace(/<(https?:\/\/[^>]+)>/g,"$1"),r=r.replace(/<(https?:\/\/[^|&]+)\|([^&]+)>/g,'<a href="$1">$2</a>'),r=r.replace(/<(https?:\/\/[^&]+)>/g,'<a href="$1">$1</a>'),i=this.convertEmoji(i),r=this.convertEmoji(r),r=r.replace(/\*([^*]+)\*/g,"<strong>$1</strong>"),r=r.replace(/\b_([^_]+)_\b/g,"<em>$1</em>"),r=r.replace(/~([^~]+)~/g,"<del>$1</del>"),r=r.replace(/`([^`]+)`/g,"<code>$1</code>"),r=r.replace(/```([^`]+)```/g,"<pre>$1</pre>"),r=r.replace(/\n/g,"<br>"),{text:i,html:r}}convertEmoji(e){const t={":smile:":"๐",":laughing:":"๐",":blush:":"๐",":heart_eyes:":"๐",":heart:":"โค๏ธ",":thumbsup:":"๐",":thumbsdown:":"๐",":wave:":"๐",":clap:":"๐",":fire:":"๐ฅ",":rocket:":"๐",":star:":"โญ",":sparkles:":"โจ",":tada:":"๐",":100:":"๐ฏ",":thinking_face:":"๐ค",":eyes:":"๐",":pray:":"๐",":muscle:":"๐ช",":ok_hand:":"๐",":white_check_mark:":"โ
",":x:":"โ",":warning:":"โ ๏ธ",":question:":"โ",":exclamation:":"โ",":point_right:":"๐",":point_left:":"๐",":point_up:":"๐",":point_down:":"๐"};return e.replace(/:([a-z0-9_+-]+):/g,(i,r)=>t[i]??i)}filterMessages(e,t){return e.filter(i=>i.subtype==="bot_message"?!0:!(t.messagesAfter&&new Date(parseFloat(i.ts)*1e3)<t.messagesAfter||t.messagesBefore&&new Date(parseFloat(i.ts)*1e3)>t.messagesBefore||!t.importThreads&&i.thread_ts&&i.thread_ts!==i.ts))}async extractZipContents(e){return console.warn("ZIP extraction requires JSZip library. Use parseSlackExportFromJson() for JSON input."),new Map}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}delay(e){return new Promise(t=>setTimeout(t,e))}}let ze=null;function qe(s){if(!ze&&s&&(ze=new Dt(s)),!ze)throw new Error("SlackImportService not initialized. Call with config first.");return ze}function Zn(){ze=null}function ei(s={}){const{config:e}=s,t=l.useMemo(()=>{if(e)return qe(e);try{return qe()}catch{return null}},[e]),[i,r]=l.useState(null),[a,o]=l.useState(!1),[c,p]=l.useState(null),u=l.useCallback(h=>{if(!t)throw new Error("Service not initialized");return t.parseSlackExportFromJson(h)},[t]),m=l.useCallback((h,S)=>{if(!t)throw new Error("Service not initialized");return t.previewImport(h,S)},[t]),f=l.useCallback(async function*(h,S){var C,d;if(!t)throw new Error("Service not initialized");o(!0),p(null);try{for await(const W of t.import(h,S))r(W),yield W;const z=t.import(h,S);let P;for await(const W of z)P=W;const D=(d=(C=z.next)==null?void 0:C.call(z))==null?void 0:d.value;return D&&p(D),D}finally{o(!1)}},[t]),y=l.useCallback(()=>{t==null||t.cancel(),o(!1)},[t]);return{parseJson:u,preview:m,import:f,cancel:y,progress:i,isImporting:a,result:c}}const Mt={toggleMute:"*6",raiseHand:"*9",leave:"#",help:"*0",hostMuteAll:"*1",hostUnmuteAll:"*2",hostEndMeeting:"*#"},Nt={welcome:"Welcome to the conference. ",enterPin:"Please enter your meeting PIN followed by the pound key.",invalidPin:"Invalid PIN. Please try again.",joined:"You have joined the meeting.",muted:"You are now muted. Press star 6 to unmute.",unmuted:"You are now unmuted.",onHold:"Please hold. The meeting host will be with you shortly.",goodbye:"Goodbye."},Ve={US:"+1",CA:"+1",UK:"+44",DE:"+49",FR:"+33",PL:"+48",ES:"+34",IT:"+39",AU:"+61",JP:"+81",IN:"+91",BR:"+55",MX:"+52"};class it{constructor(e={}){this.eventHandlers={},this.participants=new Map,this.meetingDialIns=new Map,this.connectionStatus="disconnected",this.config={provider:"twilio",accountSid:"",authToken:"",sipDomain:"",defaultRegion:"US",enabledRegions:["US","UK","DE","PL"],maxParticipants:100,recordingMode:"none",...e},this.dtmfCommands=Mt,this.ivrText={...Nt,...e.ivrText}}on(e,t){this.eventHandlers[e]=t}off(e){delete this.eventHandlers[e]}emit(e,...t){const i=this.eventHandlers[e];i&&i(...t)}generateDialInInfo(e,t){const i=this.getAvailableNumbers(),r=this.generateAccessPin(),a=this.generateAccessPin(8),o={meetingId:e,dialInNumbers:i,accessPin:r,hostPin:a,meetingTitle:t,expiresAt:Date.now()+24*60*60*1e3};return this.meetingDialIns.set(e,o),o}getDialInInfo(e){return this.meetingDialIns.get(e)}getAvailableNumbers(){return this.config.enabledRegions.map(e=>({number:this.generatePhoneNumber(e),region:e,displayNumber:this.formatPhoneNumber(e),tollFree:e==="US"||e==="UK",type:e==="US"||e==="UK"?"toll-free":"local",sipUri:`sip:conference@${this.config.sipDomain}`}))}generatePhoneNumber(e){const t=Ve[e],i=Math.floor(1e9+Math.random()*9e9).toString();return`${t}${i}`}formatPhoneNumber(e){const t=Ve[e],i=this.generatePhoneNumber(e).slice(t.length);return e==="US"||e==="CA"?`${t} (${i.slice(0,3)}) ${i.slice(3,6)}-${i.slice(6)}`:`${t} ${i}`}generateAccessPin(e=6){return Math.floor(Math.random()*Math.pow(10,e)).toString().padStart(e,"0")}async handleIncomingCall(e,t,i){const r={callId:e,callerNumber:t,callerName:i,state:"connecting",joinedAt:Date.now(),audioStats:{volume:0,isMuted:!1,packetLoss:0,quality:5},isHost:!1,isModerator:!1};return this.participants.set(e,r),this.updateParticipantState(e,"waiting-pin"),await this.playIvr(e,"welcome"),await this.playIvr(e,"enterPin"),r}async validatePinAndJoin(e,t,i){const r=this.participants.get(e);if(!r)return{success:!1,isHost:!1};const a=this.meetingDialIns.get(t);if(!a)return await this.playIvr(e,"invalidPin"),{success:!1,isHost:!1};const o=i===a.hostPin;return i===a.accessPin||o?(r.isHost=o,r.isModerator=o,this.updateParticipantState(e,"joined"),await this.playIvr(e,"joined"),this.emit("onParticipantJoined",{...r}),{success:!0,isHost:o}):(await this.playIvr(e,"invalidPin"),{success:!1,isHost:!1})}getParticipant(e){return this.participants.get(e)}getParticipants(){return Array.from(this.participants.values())}updateParticipantState(e,t){const i=this.participants.get(e);if(!i)return;const r=i.state;i.state=t,this.emit("onParticipantStateChanged",{...i},r)}async muteParticipant(e){const t=this.participants.get(e);t&&(t.audioStats.isMuted=!0,this.updateParticipantState(e,"muted"),await this.playIvr(e,"muted"))}async unmuteParticipant(e){const t=this.participants.get(e);t&&(t.audioStats.isMuted=!1,this.updateParticipantState(e,"joined"),await this.playIvr(e,"unmuted"))}async toggleMute(e){const t=this.participants.get(e);return t?t.audioStats.isMuted?(await this.unmuteParticipant(e),!1):(await this.muteParticipant(e),!0):!1}async putOnHold(e){this.participants.get(e)&&(this.updateParticipantState(e,"on-hold"),await this.playIvr(e,"onHold"))}async removeFromHold(e){this.participants.get(e)&&(this.updateParticipantState(e,"joined"),await this.playIvr(e,"joined"))}async muteAll(e=!0){for(const t of this.participants.values())e&&(t.isHost||t.isModerator)||await this.muteParticipant(t.callId)}async unmuteAll(){for(const e of this.participants.values())await this.unmuteParticipant(e.callId)}async handleDtmf(e,t){const i=this.participants.get(e);i&&(this.emit("onDtmfReceived",{...i},t),t===this.dtmfCommands.toggleMute?await this.toggleMute(e):t===this.dtmfCommands.raiseHand?console.log(`Participant ${e} raised hand`):t===this.dtmfCommands.leave?await this.disconnectParticipant(e):t===this.dtmfCommands.help?await this.playHelp(e):(i.isHost||i.isModerator)&&(t===this.dtmfCommands.hostMuteAll?await this.muteAll():t===this.dtmfCommands.hostUnmuteAll?await this.unmuteAll():t===this.dtmfCommands.hostEndMeeting&&await this.endMeeting()))}setDtmfCommands(e){this.dtmfCommands={...this.dtmfCommands,...e}}async playIvr(e,t){const i=this.ivrText[t];console.log(`[IVR -> ${e}] ${i}`),await new Promise(r=>setTimeout(r,i.length*50))}async playCustomMessage(e,t){console.log(`[TTS -> ${e}] ${t}`),await new Promise(i=>setTimeout(i,t.length*50))}async playHelp(e){await this.playCustomMessage(e,`
|
|
7
7
|
To mute or unmute yourself, press star 6.
|
|
8
8
|
To raise your hand, press star 9.
|
|
9
9
|
To leave the meeting, press pound.
|