@nice2dev/ui-communication 1.0.5 โ 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +17 -2
- package/dist/index.d.ts +9 -1
- package/dist/index.mjs +4665 -2939
- package/dist/services/emailTrackingService.d.ts +279 -0
- package/dist/services/mailMergeService.d.ts +365 -0
- package/dist/services/pstnGatewayService.d.ts +341 -0
- package/dist/services/slackImportService.d.ts +426 -0
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),a=require("react");class lt{constructor(){this.listeners=new Map}on(t,i){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(i)}off(t,i){var s;(s=this.listeners.get(t))==null||s.delete(i)}emit(t,i){var s;(s=this.listeners.get(t))==null||s.forEach(r=>r(i))}removeAll(){this.listeners.clear()}}class at extends lt{constructor(t={}){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"}],...t}}async connect(t,i){return this.userId=i,new Promise((s,r)=>{const o=new WebSocket(t);o.onopen=()=>{this.signalingWs=o,this.connected=!0,o.send(JSON.stringify({type:"register",userId:i})),this.emit("transport:connected",{}),s()},o.onerror=c=>{r(new Error(`Signaling WebSocket error: ${String(c)}`))},o.onclose=c=>{this.connected=!1,this.emit("transport:disconnected",{reason:c.reason})},o.onmessage=c=>{try{const f=JSON.parse(String(c.data));this.handleSignalingMessage(f).catch(console.error)}catch{}}})}disconnect(){var t;this.releaseLocalStream();for(const[,i]of this.peers)i.close();this.peers.clear(),(t=this.signalingWs)==null||t.close(),this.signalingWs=null,this.connected=!1,this.removeAll()}isConnected(){return this.connected}async getLocalStream(t){return this.localStream?this.localStream:(this.localStream=await navigator.mediaDevices.getUserMedia(t),this.localStream)}releaseLocalStream(){this.localStream&&(this.localStream.getTracks().forEach(t=>t.stop()),this.localStream=null),this.screenStream&&(this.screenStream.getTracks().forEach(t=>t.stop()),this.screenStream=null)}async startCall(t,i){const s=crypto.randomUUID();return this.sendSignal({type:"call:request",callId:s,callType:i,from:this.userId,to:t}),{id:s,type:i,participants:[],status:"ringing",isRecording:!1,isTranscribing:!1,layout:"grid"}}async acceptCall(t){this.sendSignal({type:"call:accept",callId:t,from:this.userId})}declineCall(t){this.sendSignal({type:"call:decline",callId:t,from:this.userId})}endCall(t){this.sendSignal({type:"call:end",callId:t,from:this.userId});for(const[i,s]of this.peers)s.close(),this.peers.delete(i)}muteAudio(t){var i;(i=this.localStream)==null||i.getAudioTracks().forEach(s=>{s.enabled=!t}),this.sendSignal({type:"peer:mute",from:this.userId,audio:t,video:!1})}muteVideo(t){var i;(i=this.localStream)==null||i.getVideoTracks().forEach(s=>{s.enabled=!t}),this.sendSignal({type:"peer:mute",from:this.userId,audio:!1,video:t})}async setAudioDevice(t){var s;const i=(s=this.localStream)==null?void 0:s.getAudioTracks()[0];i&&await i.applyConstraints({deviceId:{exact:t}})}async setVideoDevice(t){var s;const i=(s=this.localStream)==null?void 0:s.getVideoTracks()[0];i&&await i.applyConstraints({deviceId:{exact:t}})}async startScreenShare(){this.screenStream=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:15},audio:!0});const[t]=this.screenStream.getVideoTracks();t.addEventListener("ended",()=>this.stopScreenShare());for(const[,i]of this.peers)this.screenStream.getTracks().forEach(s=>i.addTrack(s,this.screenStream));return this.sendSignal({type:"screen:started",from:this.userId}),this.screenStream}stopScreenShare(){this.screenStream&&(this.screenStream.getTracks().forEach(t=>t.stop()),this.screenStream=null,this.sendSignal({type:"screen:stopped",from:this.userId}),this.emit("screen:stopped",{participantId:this.userId}))}sendSignal(t){var i;((i=this.signalingWs)==null?void 0:i.readyState)===WebSocket.OPEN&&this.signalingWs.send(JSON.stringify(t))}async handleSignalingMessage(t){var i;switch(t.type){case"call:request":this.emit("call:incoming",{callId:t.callId,callType:t.callType??"audio",callerId:t.from});break;case"call:accept":await this.createPeerConnection(t.from),this.emit("call:accepted",{callId:t.callId,participantId:t.from});break;case"call:decline":this.emit("call:declined",{callId:t.callId,participantId:t.from});break;case"call:end":(i=this.peers.get(t.from))==null||i.close(),this.peers.delete(t.from),this.emit("call:ended",{callId:t.callId,reason:"remote-ended"});break;case"offer":{const s=await this.getOrCreatePeer(t.from);await s.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:t.sdp}));const r=await s.createAnswer();await s.setLocalDescription(r),this.sendSignal({type:"answer",to:t.from,from:this.userId,sdp:r.sdp});break}case"answer":{const s=this.peers.get(t.from);s&&await s.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:t.sdp}));break}case"ice-candidate":{const s=this.peers.get(t.from);s&&t.candidate&&await s.addIceCandidate(new RTCIceCandidate(t.candidate));break}case"peer:mute":this.emit("peer:muted",{participantId:t.from,audio:t.audio??!1,video:t.video??!1});break;case"screen:started":break;case"screen:stopped":this.emit("screen:stopped",{participantId:t.from});break}}async getOrCreatePeer(t){return this.peers.has(t)?this.peers.get(t):this.createPeerConnection(t)}async createPeerConnection(t){var r,o;const i=new RTCPeerConnection({iceServers:(r=this.config.iceServers)==null?void 0:r.map(c=>({urls:c.urls,username:c.username,credential:c.credential})),iceTransportPolicy:this.config.iceTransportPolicy});if(this.peers.set(t,i),(o=this.localStream)==null||o.getTracks().forEach(c=>i.addTrack(c,this.localStream)),i.onicecandidate=c=>{c.candidate&&this.sendSignal({type:"ice-candidate",to:t,from:this.userId,candidate:c.candidate})},i.ontrack=c=>{const f=c.streams[0];f&&this.emit("stream:added",{participantId:t,stream:f})},i.onconnectionstatechange=()=>{(i.connectionState==="failed"||i.connectionState==="disconnected")&&this.emit("stream:removed",{participantId:t})},this.config.maxBitrate){const c=i.getSenders();for(const f of c){if(!f.track)continue;const u=f.getParameters();u.encodings||(u.encodings=[{}]),f.track.kind==="audio"&&this.config.maxBitrate.audio?u.encodings[0].maxBitrate=this.config.maxBitrate.audio:f.track.kind==="video"&&this.config.maxBitrate.video&&(u.encodings[0].maxBitrate=this.config.maxBitrate.video),await f.setParameters(u)}}const s=await i.createOffer();return await i.setLocalDescription(s),this.sendSignal({type:"offer",to:t,from:this.userId,sdp:s.sdp}),i}}class ct extends lt{constructor(){super(...arguments),this.type="mock",this.connected=!1,this.localStream=null}async connect(t,i){this.connected=!0,this.emit("transport:connected",{})}disconnect(){this.releaseLocalStream(),this.connected=!1,this.removeAll()}isConnected(){return this.connected}async getLocalStream(t){const i=new AudioContext,s=i.createMediaStreamDestination();i.createOscillator().connect(s);const o=s.stream,c=document.createElement("canvas");c.width=640,c.height=480;const f=c.captureStream(15),u=[...o.getTracks(),...f.getTracks()];return this.localStream=new MediaStream(u),this.localStream}releaseLocalStream(){var t;(t=this.localStream)==null||t.getTracks().forEach(i=>i.stop()),this.localStream=null}async startCall(t,i){const s={id:crypto.randomUUID(),type:i,participants:[],status:"connecting",startedAt:new Date,isRecording:!1,isTranscribing:!1,layout:t.length>2?"grid":"spotlight"};return setTimeout(()=>this.emit("call:accepted",{callId:s.id,participantId:t[0]??"mock"}),800),s}async acceptCall(t){this.emit("call:accepted",{callId:t,participantId:"mock-remote"})}declineCall(t){this.emit("call:declined",{callId:t,participantId:"mock-remote"})}endCall(t){this.emit("call:ended",{callId:t,reason:"local-ended"})}muteAudio(t){}muteVideo(t){}async setAudioDevice(t){}async setVideoDevice(t){}async startScreenShare(){const t=document.createElement("canvas");return t.width=1920,t.height=1080,t.captureStream(15)}stopScreenShare(){this.emit("screen:stopped",{participantId:"local"})}}function dt(n,t){switch(n){case"mock":return new ct;case"webrtc":case"sfu":default:return new at(t)}}function ft(n){const{currentUser:t,transport:i="webrtc",rtcConfig:s,signalingUrl:r,autoConnect:o=!1,onCallEnded:c,onIncomingCall:f,onStreamAdded:u,onStreamRemoved:x,onError:m}=n,j=a.useRef(null),[C,v]=a.useState({isConnected:!1,activeCall:null,incomingCall:null,localStream:null,isMicMuted:!1,isCameraMuted:!1,isScreenSharing:!1,screenStream:null,isHandRaised:!1,connectionError:null}),R=a.useCallback(()=>{if(j.current)return j.current;const S=dt(i,s);return S.on("transport:connected",()=>v(h=>({...h,isConnected:!0,connectionError:null}))),S.on("transport:disconnected",()=>v(h=>({...h,isConnected:!1}))),S.on("transport:error",h=>{const{error:k}=h;v(F=>({...F,connectionError:k.message})),m==null||m(k)}),S.on("call:incoming",h=>{const{callId:k,callType:F,callerId:J}=h,I={callId:k,callType:F,caller:{id:J,name:J,presence:{status:"online"}},startedAt:new Date};v(W=>({...W,incomingCall:I})),f==null||f(I)}),S.on("call:ended",h=>{const{callId:k}=h;v(F=>{var J;return{...F,activeCall:((J=F.activeCall)==null?void 0:J.id)===k?null:F.activeCall,localStream:null}}),c==null||c(k)}),S.on("stream:added",h=>{const{participantId:k,stream:F}=h;u==null||u(k,F)}),S.on("stream:removed",h=>{const{participantId:k}=h;x==null||x(k)}),j.current=S,S},[i,s,c,f,u,x,m]);a.useEffect(()=>!o||!r?void 0:(R().connect(r,t.id).catch(h=>{const k=h instanceof Error?h:new Error(String(h));v(F=>({...F,connectionError:k.message})),m==null||m(k)}),()=>{var h;(h=j.current)==null||h.disconnect(),j.current=null}),[o,r,t.id,R,m]);const O=a.useCallback(async S=>{await R().connect(S,t.id)},[R,t.id]),l=a.useCallback(()=>{var S;(S=j.current)==null||S.disconnect(),j.current=null,v(h=>({...h,isConnected:!1}))},[]),A=a.useCallback(async(S,h="video")=>{const k=j.current??R(),F=h==="video"?{audio:!0,video:{width:1280,height:720}}:{audio:!0,video:!1},J=await k.getLocalStream(F),I=await k.startCall(S,h);return v(W=>({...W,activeCall:I,localStream:J})),I},[R]),N=a.useCallback(async()=>{const S=j.current,{incomingCall:h}=C;if(!S||!h)return;const k=h.callType==="video"?{audio:!0,video:{width:1280,height:720}}:{audio:!0,video:!1},F=await S.getLocalStream(k);await S.acceptCall(h.callId);const J={id:h.callId,type:h.callType,participants:[],status:"active",startedAt:new Date,isRecording:!1,isTranscribing:!1,layout:"spotlight"};v(I=>({...I,activeCall:J,incomingCall:null,localStream:F}))},[C]),Y=a.useCallback(()=>{var h;const{incomingCall:S}=C;S&&((h=j.current)==null||h.declineCall(S.callId),v(k=>({...k,incomingCall:null})))},[C]),H=a.useCallback(()=>{var h,k;const{activeCall:S}=C;S&&((h=j.current)==null||h.endCall(S.id),(k=j.current)==null||k.releaseLocalStream(),v(F=>({...F,activeCall:null,localStream:null,isScreenSharing:!1,screenStream:null})))},[C]),D=a.useCallback(()=>{var h;const S=!C.isMicMuted;(h=j.current)==null||h.muteAudio(S),v(k=>({...k,isMicMuted:S}))},[C.isMicMuted]),$=a.useCallback(()=>{var h;const S=!C.isCameraMuted;(h=j.current)==null||h.muteVideo(S),v(k=>({...k,isCameraMuted:S}))},[C.isCameraMuted]),U=a.useCallback(async()=>{const S=j.current;if(!S)return;const h=await S.startScreenShare();v(k=>({...k,isScreenSharing:!0,screenStream:h}))},[]),E=a.useCallback(()=>{var S;(S=j.current)==null||S.stopScreenShare(),v(h=>({...h,isScreenSharing:!1,screenStream:null}))},[]),_=a.useCallback(()=>{v(S=>({...S,isHandRaised:!S.isHandRaised}))},[]);return{state:C,connect:O,disconnect:l,startCall:A,acceptCall:N,declineCall:Y,endCall:H,toggleMic:D,toggleCamera:$,startScreenShare:U,stopScreenShare:E,toggleHand:_,transport:j}}function kt(n,t,i,s="text"){return{id:`optimistic-${crypto.randomUUID()}`,conversationId:n,authorId:t,content:i,contentType:s,timestamp:new Date,status:"sending",reactions:[],attachments:[],mentions:[],isPinned:!1}}function Me(n,t,i){if(n.type!=="dm")return;const s=n.participantIds.find(r=>r!==t);return i.find(r=>r.id===s)}function _e(n){return n.reduce((t,i)=>t+i.unreadCount,0)}function Ct(n){return n.reduce((t,i)=>t+i.mentionCount,0)}function It(n,t){return n?"workspace":t?"messenger":"bubble"}const zt={online:"Online",away:"Away",busy:"Busy",dnd:"Do not disturb",offline:"Offline",invisible:"Invisible",unknown:"Unknown"},Rt={online:"#22c55e",away:"#f59e0b",busy:"#ef4444",dnd:"#ef4444",offline:"#9ca3af",invisible:"#9ca3af",unknown:"#d1d5db"},Tt={xs:6,sm:8,md:10,lg:14};function fe({status:n,size:t="sm",showLabel:i=!1,showTooltip:s=!1,className:r,style:o,id:c,"data-testid":f}){const u=Tt[t],x=Rt[n],m=zt[n],j=e.jsx("span",{className:`nice-presence-dot nice-presence-dot--${n} nice-presence-dot--${t}`,title:s?m:void 0,"aria-label":m,role:"img",style:{display:"inline-block",width:u,height:u,borderRadius:"50%",backgroundColor:x,flexShrink:0,border:n==="offline"||n==="invisible"?"1.5px solid #9ca3af":"none",boxSizing:"border-box"}});return i?e.jsxs("span",{id:c,"data-testid":f,className:`nice-presence-indicator nice-presence-indicator--with-label${r?` ${r}`:""}`,style:{display:"inline-flex",alignItems:"center",gap:6,...o},children:[j,e.jsx("span",{className:"nice-presence-label",style:{fontSize:u+4,color:x},children:m})]}):e.jsx("span",{id:c,"data-testid":f,className:`nice-presence-indicator${r?` ${r}`:""}`,style:o,children:j})}const At=["๐","โค๏ธ","๐","๐ฎ","๐ข","๐"];function We({message:n,author:t,isMine:i,showAvatar:s,enableReactions:r,onReact:o,onReply:c,onEdit:f,onDelete:u,onPin:x,onOpenThread:m}){var A,N,Y,H;const[j,C]=a.useState(!1),[v,R]=a.useState(!1),O=n.isDeleted,l=n.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return e.jsxs("div",{className:`nice-chat-message${i?" nice-chat-message--mine":""}${n.isPinned?" nice-chat-message--pinned":""}`,onMouseEnter:()=>C(!0),onMouseLeave:()=>{C(!1),R(!1)},style:{display:"flex",flexDirection:i?"row-reverse":"row",alignItems:"flex-end",gap:8,padding:"2px 16px",position:"relative"},children:[s&&!i&&e.jsxs("div",{style:{position:"relative",flexShrink:0},children:[e.jsx("div",{className:"nice-chat-avatar",style:{width:32,height:32,borderRadius:"50%",background:t!=null&&t.avatarUrl?`url(${t.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontSize:13,fontWeight:600,flexShrink:0},children:!(t!=null&&t.avatarUrl)&&(((N=(A=t==null?void 0:t.name)==null?void 0:A[0])==null?void 0:N.toUpperCase())??"?")}),e.jsx(fe,{status:((Y=t==null?void 0:t.presence)==null?void 0:Y.status)??"unknown",size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),e.jsxs("div",{style:{maxWidth:"70%",display:"flex",flexDirection:"column",alignItems:i?"flex-end":"flex-start"},children:[!i&&t&&e.jsx("span",{style:{fontSize:11,color:"#6b7280",marginBottom:2,paddingLeft:2},children:t.displayName??t.name}),n.replyTo&&e.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:n.replyTo.content}),e.jsx("div",{className:`nice-chat-bubble${i?" nice-chat-bubble--mine":""}`,style:{padding:"8px 12px",borderRadius:i?"18px 18px 4px 18px":"18px 18px 18px 4px",background:i?"#6366f1":"#f3f4f6",color:i?"#fff":"#111827",fontSize:14,lineHeight:1.5,wordBreak:"break-word"},children:O?e.jsx("span",{style:{fontStyle:"italic",opacity:.6},children:"This message was deleted"}):n.contentType==="image"&&((H=n.attachments)!=null&&H[0])?e.jsx("img",{src:n.attachments[0].url,alt:n.attachments[0].name,style:{maxWidth:280,maxHeight:280,borderRadius:8,display:"block"}}):e.jsx("span",{children:n.content})}),!O&&n.attachments&&n.attachments.length>0&&n.contentType!=="image"&&e.jsx("div",{className:"nice-chat-attachments",style:{marginTop:4},children:n.attachments.map(D=>e.jsxs("a",{href:D.url,target:"_blank",rel:"noreferrer",className:"nice-chat-attachment",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:12,color:i?"rgba(255,255,255,0.85)":"#6366f1",textDecoration:"none",background:i?"rgba(255,255,255,0.15)":"#e0e7ff",borderRadius:6,padding:"3px 8px",marginTop:2},children:["๐ ",D.name]},D.id))}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:2},children:[e.jsx("span",{style:{fontSize:11,color:"#9ca3af"},children:l}),n.editedAt&&e.jsx("span",{style:{fontSize:11,color:"#9ca3af"},children:"(edited)"}),i&&e.jsx("span",{style:{fontSize:11,color:n.status==="read"?"#6366f1":"#9ca3af"},children:n.status==="sending"?"โ":n.status==="sent"?"โ":(n.status==="delivered","โโ")})]}),n.reactions&&n.reactions.length>0&&e.jsx("div",{className:"nice-chat-reactions",style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:n.reactions.map(D=>e.jsxs("button",{onClick:()=>o(n.id,D.emoji),style:{background:D.mine?"#e0e7ff":"#f3f4f6",border:D.mine?"1px solid #6366f1":"1px solid transparent",borderRadius:12,padding:"2px 7px",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",gap:3},children:[D.emoji," ",D.count]},D.emoji))}),(n.threadCount??0)>0&&e.jsxs("button",{className:"nice-chat-thread-btn",onClick:()=>m==null?void 0:m(n),style:{background:"none",border:"none",color:"#6366f1",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:2},children:["๐ฌ ",n.threadCount," repl",n.threadCount===1?"y":"ies"]})]}),j&&!O&&e.jsxs("div",{className:"nice-chat-actions",style:{position:"absolute",top:-16,[i?"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&&e.jsxs("div",{style:{position:"relative"},children:[e.jsx("button",{title:"React",onClick:()=>R(D=>!D),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"๐"}),v&&e.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:At.map(D=>e.jsx("button",{onClick:()=>{o(n.id,D),R(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:D},D))})]}),e.jsx("button",{title:"Reply",onClick:()=>c(n),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"โฉ"}),i&&f&&e.jsx("button",{title:"Edit",onClick:()=>f(n),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"โ๏ธ"}),x&&e.jsx("button",{title:n.isPinned?"Unpin":"Pin",onClick:()=>x(n),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"๐"}),i&&u&&e.jsx("button",{title:"Delete",onClick:()=>u(n),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px",color:"#ef4444"},children:"๐"})]})]})}function Je({placeholder:n="Type a messageโฆ",maxLength:t,replyTo:i,onCancelReply:s,onSend:r,onAttach:o,disabled:c}){const[f,u]=a.useState(""),x=a.useRef(null);a.useEffect(()=>{i&&x.current&&x.current.focus()},[i]);const m=v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),j())},j=()=>{const v=f.trim();v&&(r(v),u(""),x.current&&(x.current.style.height="auto"))},C=v=>{u(v.target.value),v.target.style.height="auto",v.target.style.height=`${Math.min(v.target.scrollHeight,120)}px`};return e.jsxs("div",{className:"nice-chat-input-area",style:{padding:"8px 12px",borderTop:"1px solid #e5e7eb",background:"#fff"},children:[i&&e.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:[e.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Replying: ",i.content]}),e.jsx("button",{onClick:s,style:{background:"none",border:"none",cursor:"pointer",fontSize:16,color:"#9ca3af",marginLeft:8},children:"ร"})]}),e.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:8},children:[o&&e.jsx("button",{onClick:o,title:"Attach file",style:{background:"none",border:"none",cursor:"pointer",fontSize:18,color:"#9ca3af",padding:"4px",flexShrink:0},children:"๐"}),e.jsx("textarea",{ref:x,value:f,onChange:C,onKeyDown:m,placeholder:n,maxLength:t,disabled:c,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"}}),e.jsx("button",{onClick:j,disabled:!f.trim()||c,style:{background:f.trim()?"#6366f1":"#e5e7eb",border:"none",borderRadius:"50%",width:36,height:36,cursor:f.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:16,transition:"background 0.15s"},children:"โค"})]}),t&&f.length>t*.8&&e.jsxs("div",{style:{textAlign:"right",fontSize:11,color:f.length>=t?"#ef4444":"#9ca3af",marginTop:2},children:[f.length,"/",t]})]})}function Ie({conversation:n,messages:t,users:i,currentUser:s,isLoading:r=!1,hasMore:o=!1,showHeader:c=!0,showUserAvatars:f=!0,enableReactions:u=!0,enableThreads:x=!0,enableAttachments:m=!0,placeholder:j,maxMessageLength:C,onSendMessage:v,onEditMessage:R,onDeleteMessage:O,onReactToMessage:l,onPinMessage:A,onLoadMoreMessages:N,onStartCall:Y,className:H,style:D,id:$,"data-testid":U}){var M,d;const E=a.useRef(null),_=a.useRef(null),[S,h]=a.useState(null),[k,F]=a.useState(null),J=a.useMemo(()=>{const y=new Map;return i.forEach(q=>y.set(q.id,q)),y},[i]);a.useEffect(()=>{var y;(y=E.current)==null||y.scrollIntoView({behavior:"smooth"})},[t]);const I=a.useCallback(()=>{const y=_.current;!y||!o||r||y.scrollTop===0&&t.length>0&&(N==null||N(n.id,t[0].id))},[o,r,t,n.id,N]),W=a.useCallback(y=>{v==null||v(n.id,y,"text"),h(null)},[n.id,v]),B=n.type==="dm"?J.get(n.participantIds.find(y=>y!==s.id)??""):void 0;return e.jsxs("div",{id:$,"data-testid":U,className:`nice-chat-window${H?` ${H}`:""}`,style:{display:"flex",flexDirection:"column",height:"100%",background:"#fff",...D},children:[c&&e.jsxs("div",{className:"nice-chat-header",style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid #e5e7eb",flexShrink:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[e.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:(B??n).avatarUrl?`url(${(B??n).avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:15,flexShrink:0},children:!(B??n).avatarUrl&&((M=((B==null?void 0:B.name)??n.name??"?")[0])==null?void 0:M.toUpperCase())}),e.jsxs("div",{children:[e.jsx("div",{style:{fontWeight:600,fontSize:15},children:(B==null?void 0:B.displayName)??(B==null?void 0:B.name)??n.name??"Chat"}),B&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:1},children:[e.jsx(fe,{status:B.presence.status,size:"xs"}),e.jsx("span",{style:{fontSize:12,color:"#6b7280"},children:B.presence.statusMessage??B.presence.status})]}),n.type!=="dm"&&e.jsxs("span",{style:{fontSize:12,color:"#6b7280"},children:[n.participantIds.length," members"]})]})]}),n.type==="dm"&&Y&&B&&e.jsxs("div",{style:{display:"flex",gap:4},children:[e.jsx("button",{onClick:()=>Y([B.id],"audio"),title:"Audio call",style:{background:"none",border:"1px solid #e5e7eb",borderRadius:6,padding:"5px 8px",cursor:"pointer",fontSize:16},children:"๐"}),e.jsx("button",{onClick:()=>Y([B.id],"video"),title:"Video call",style:{background:"none",border:"1px solid #e5e7eb",borderRadius:6,padding:"5px 8px",cursor:"pointer",fontSize:16},children:"๐น"})]})]}),e.jsxs("div",{ref:_,className:"nice-chat-messages",onScroll:I,style:{flex:1,overflowY:"auto",padding:"8px 0",display:"flex",flexDirection:"column"},children:[o&&e.jsx("button",{onClick:()=>t.length>0&&(N==null?void 0:N(n.id,t[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"}),t.map((y,q)=>{const X=t[q-1],Q=f&&(!X||X.authorId!==y.authorId);return e.jsx(We,{message:y,author:J.get(y.authorId),isMine:y.authorId===s.id,showAvatar:Q,enableReactions:u,onReact:(K,re)=>l==null?void 0:l(K,re),onReply:K=>h(K),onEdit:R?K=>R(K.id,K.content):void 0,onDelete:O?K=>O(K.id):void 0,onPin:A?K=>A(K.id):void 0,onOpenThread:x?K=>F(K):void 0},y.id)}),e.jsx("div",{ref:E})]}),k&&e.jsxs("div",{className:"nice-chat-thread-panel",style:{position:"absolute",right:0,top:c?57:0,bottom:0,width:320,background:"#fff",borderLeft:"1px solid #e5e7eb",display:"flex",flexDirection:"column",zIndex:5},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid #e5e7eb"},children:[e.jsx("span",{style:{fontWeight:600,fontSize:14},children:"Thread"}),e.jsx("button",{onClick:()=>F(null),style:{background:"none",border:"none",cursor:"pointer",fontSize:18,color:"#9ca3af"},children:"ร"})]}),e.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[e.jsx(We,{message:k,author:J.get(k.authorId),isMine:k.authorId===s.id,showAvatar:!0,enableReactions:u,onReact:(y,q)=>l==null?void 0:l(y,q),onReply:()=>{}}),(d=k.thread)==null?void 0:d.map(y=>e.jsx(We,{message:y,author:J.get(y.authorId),isMine:y.authorId===s.id,showAvatar:!0,enableReactions:u,onReact:(q,X)=>l==null?void 0:l(q,X),onReply:()=>{}},y.id))]}),e.jsx(Je,{placeholder:"Reply in threadโฆ",onSend:y=>v==null?void 0:v(n.id,y,"text")})]}),e.jsx(Je,{placeholder:j,maxLength:C,replyTo:S,onCancelReply:()=>h(null),onSend:W,onAttach:m?()=>{}:void 0})]})}function Dt({conversation:n,partner:t,isActive:i,lastMessage:s,onClick:r}){var m;const o=(t==null?void 0:t.displayName)??(t==null?void 0:t.name)??n.name??"Group",c=((m=o[0])==null?void 0:m.toUpperCase())??"?",f=(t==null?void 0:t.avatarUrl)??n.avatarUrl,u=s?s.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"",x=s?s.isDeleted?"Message deleted":s.content.slice(0,50):"";return e.jsxs("button",{className:`nice-messenger-conv-item${i?" nice-messenger-conv-item--active":""}`,onClick:r,style:{display:"flex",alignItems:"center",gap:10,padding:"10px 14px",background:i?"#ede9fe":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",position:"relative"},children:[e.jsxs("div",{style:{position:"relative",flexShrink:0},children:[e.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:f?`url(${f}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:16},children:!f&&c}),t&&e.jsx(fe,{status:t.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}}),n.type!=="dm"&&e.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:"#"})]}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline"},children:[e.jsx("span",{style:{fontWeight:n.unreadCount>0?700:500,fontSize:14,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o}),e.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0,marginLeft:4},children:u})]}),e.jsx("div",{style:{fontSize:12,color:"#6b7280",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:x})]}),(n.unreadCount>0||n.mentionCount>0)&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,alignItems:"flex-end",flexShrink:0},children:[n.mentionCount>0&&e.jsxs("span",{style:{background:"#ef4444",color:"#fff",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:["@",n.mentionCount]}),n.unreadCount>0&&e.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:n.unreadCount>99?"99+":n.unreadCount})]}),n.isMuted&&e.jsx("span",{style:{position:"absolute",bottom:8,right:8,fontSize:10,color:"#9ca3af"},children:"๐"})]})}function ut({conversations:n,messages:t,users:i,currentUser:s,activeConversationId:r,teams:o,enableGroupConversations:c=!0,showPresence:f=!0,enableSearch:u=!0,onSendMessage:x,onEditMessage:m,onDeleteMessage:j,onReactToMessage:C,onPinMessage:v,onLoadMoreMessages:R,onMarkAsRead:O,onStartCall:l,onCreateConversation:A,className:N,style:Y,id:H,"data-testid":D}){var M;const[$,U]=a.useState(r??null),[E,_]=a.useState(""),[S,h]=a.useState("all");a.useMemo(()=>{const d=new Map;return i.forEach(y=>d.set(y.id,y)),d},[i]);const k=a.useMemo(()=>{let d=n;if(S==="unread"&&(d=d.filter(y=>y.unreadCount>0)),S==="groups"&&(d=d.filter(y=>y.type!=="dm")),E.trim()){const y=E.toLowerCase();d=d.filter(q=>{var Q,K;const X=Me(q,s.id,i);return(X==null?void 0:X.name.toLowerCase().includes(y))||((Q=q.name)==null?void 0:Q.toLowerCase().includes(y))||((K=q.lastMessage)==null?void 0:K.content.toLowerCase().includes(y))})}return[...d].sort((y,q)=>{var K,re;if(y.isPinned!==q.isPinned)return y.isPinned?-1:1;const X=((K=y.lastMessage)==null?void 0:K.timestamp.getTime())??y.updatedAt.getTime();return(((re=q.lastMessage)==null?void 0:re.timestamp.getTime())??q.updatedAt.getTime())-X})},[n,S,E,s.id,i]),F=a.useMemo(()=>n.find(d=>d.id===$)??null,[n,$]),J=a.useMemo(()=>$?t[$]??[]:[],[t,$]),I=a.useCallback(d=>{U(d),O==null||O(d)},[O]),W=a.useMemo(()=>_e(n),[n]),B=o??[];return e.jsxs("div",{id:H,"data-testid":D,className:`nice-messenger${N?` ${N}`:""}`,style:{display:"flex",height:"100%",background:"#fff",overflow:"hidden",...Y},children:[e.jsxs("div",{className:"nice-messenger-sidebar",style:{width:280,flexShrink:0,borderRight:"1px solid #e5e7eb",display:"flex",flexDirection:"column",background:"#fafafa"},children:[e.jsxs("div",{style:{padding:"14px 14px 8px",borderBottom:"1px solid #e5e7eb"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("span",{style:{fontWeight:700,fontSize:16},children:["Messages ",W>0&&e.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:10,padding:"1px 6px",fontWeight:700,marginLeft:4},children:W})]}),c&&A&&e.jsx("button",{onClick:()=>A([],"group"),title:"New conversation",style:{background:"#6366f1",border:"none",borderRadius:6,padding:"5px 8px",cursor:"pointer",color:"#fff",fontSize:13},children:"+"})]}),u&&e.jsx("input",{type:"search",value:E,onChange:d=>_(d.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"}}),e.jsx("div",{style:{display:"flex",gap:2,marginTop:8},children:["all","unread","groups"].map(d=>e.jsx("button",{onClick:()=>h(d),style:{flex:1,padding:"4px 0",border:"none",borderRadius:6,background:S===d?"#6366f1":"transparent",color:S===d?"#fff":"#6b7280",cursor:"pointer",fontSize:12,textTransform:"capitalize",fontWeight:S===d?600:400},children:d},d))})]}),f&&e.jsxs("div",{style:{padding:"8px 14px",borderBottom:"1px solid #f3f4f6",overflowX:"auto"},children:[e.jsx("div",{style:{fontSize:11,color:"#9ca3af",marginBottom:6},children:"ONLINE NOW"}),e.jsx("div",{style:{display:"flex",gap:10},children:i.filter(d=>d.id!==s.id&&d.presence.status==="online").slice(0,6).map(d=>{var y;return e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:3},children:[e.jsxs("div",{style:{position:"relative"},children:[e.jsx("div",{style:{width:34,height:34,borderRadius:"50%",background:d.avatarUrl?`url(${d.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer"},title:d.name,children:!d.avatarUrl&&((y=d.name[0])==null?void 0:y.toUpperCase())}),e.jsx(fe,{status:d.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),e.jsx("span",{style:{fontSize:10,color:"#6b7280",maxWidth:36,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d.displayName??d.name.split(" ")[0]})]},d.id)})})]}),e.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[B.length>0&&S==="all"&&e.jsx("div",{style:{padding:"8px 14px 4px",fontSize:11,color:"#9ca3af",fontWeight:600,letterSpacing:"0.05em"},children:"DIRECT MESSAGES"}),k.length===0?e.jsx("div",{style:{padding:24,textAlign:"center",color:"#9ca3af",fontSize:13},children:"No conversations"}):k.map(d=>e.jsx(Dt,{conversation:d,partner:Me(d,s.id,i),isActive:d.id===$,lastMessage:d.lastMessage,onClick:()=>I(d.id)},d.id))]}),e.jsxs("div",{style:{padding:"10px 14px",borderTop:"1px solid #e5e7eb",display:"flex",alignItems:"center",gap:8},children:[e.jsxs("div",{style:{position:"relative"},children:[e.jsx("div",{style:{width:32,height:32,borderRadius:"50%",background:s.avatarUrl?`url(${s.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:13},children:!s.avatarUrl&&((M=s.name[0])==null?void 0:M.toUpperCase())}),e.jsx(fe,{status:s.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontWeight:600,fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.displayName??s.name}),e.jsx("div",{style:{fontSize:11,color:"#9ca3af",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.presence.statusMessage??s.presence.status})]})]})]}),e.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:F?e.jsx(Ie,{conversation:F,messages:J,users:i,currentUser:s,onSendMessage:x,onEditMessage:m,onDeleteMessage:j,onReactToMessage:C,onPinMessage:v,onLoadMoreMessages:R,onStartCall:l,style:{height:"100%"}}):e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"#9ca3af",gap:12},children:[e.jsx("span",{style:{fontSize:48},children:"๐ฌ"}),e.jsx("span",{style:{fontSize:15},children:"Select a conversation to start messaging"})]})})]})}const Et=["๐","โค๏ธ","๐","๐","๐ฎ","๐ข"];function Ne({message:n,author:t,isMine:i,enableReactions:s,enableThreads:r,onReact:o,onOpenThread:c,onReply:f}){var R,O,l;const[u,x]=a.useState(!1),[m,j]=a.useState(!1),C=n.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),v=n.timestamp.toLocaleDateString([],{month:"short",day:"numeric"});return e.jsxs("div",{className:`nice-channel-msg${u?" nice-channel-msg--hovered":""}${i?" nice-channel-msg--mine":""}`,onMouseEnter:()=>x(!0),onMouseLeave:()=>{x(!1),j(!1)},style:{display:"flex",gap:10,padding:"4px 16px",position:"relative",background:u?"rgba(99,102,241,0.04)":"transparent"},children:[e.jsx("div",{style:{width:36,flexShrink:0},children:e.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:t!=null&&t.avatarUrl?`url(${t.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:14},children:!(t!=null&&t.avatarUrl)&&(((O=(R=t==null?void 0:t.name)==null?void 0:R[0])==null?void 0:O.toUpperCase())??"?")})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:2},children:[e.jsx("span",{style:{fontWeight:600,fontSize:14,color:"#111827"},children:(t==null?void 0:t.displayName)??(t==null?void 0:t.name)??"Unknown"}),t&&e.jsx(fe,{status:t.presence.status,size:"xs"}),e.jsxs("span",{style:{fontSize:11,color:"#9ca3af"},children:[v," ",C]}),n.editedAt&&e.jsx("span",{style:{fontSize:11,color:"#9ca3af"},children:"(edited)"}),n.isPinned&&e.jsx("span",{style:{fontSize:11,color:"#6366f1"},children:"๐ Pinned"})]}),n.isDeleted?e.jsx("span",{style:{fontStyle:"italic",color:"#9ca3af",fontSize:14},children:"This message was deleted"}):e.jsx("div",{style:{fontSize:14,lineHeight:1.6,color:"#1f2937",wordBreak:"break-word"},children:n.contentType==="image"&&((l=n.attachments)!=null&&l[0])?e.jsx("img",{src:n.attachments[0].url,alt:n.attachments[0].name,style:{maxWidth:400,maxHeight:300,borderRadius:8,display:"block",marginTop:4}}):n.content}),!n.isDeleted&&n.attachments&&n.attachments.length>0&&n.contentType!=="image"&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:4},children:n.attachments.map(A=>e.jsxs("a",{href:A.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:["๐ ",A.name]},A.id))}),n.reactions&&n.reactions.length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:n.reactions.map(A=>e.jsxs("button",{onClick:()=>o(n.id,A.emoji),style:{background:A.mine?"#ede9fe":"#f3f4f6",border:A.mine?"1px solid #6366f1":"1px solid transparent",borderRadius:12,padding:"2px 7px",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",gap:3},children:[A.emoji," ",A.count]},A.emoji))}),r&&(n.threadCount??0)>0&&e.jsxs("button",{onClick:()=>c(n),style:{background:"none",border:"none",color:"#6366f1",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:3},children:["๐ฌ ",n.threadCount," repl",n.threadCount===1?"y":"ies"," โ"]})]}),u&&!n.isDeleted&&e.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:[s&&e.jsxs("div",{style:{position:"relative"},children:[e.jsx("button",{onClick:()=>j(A=>!A),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},children:"๐"}),m&&e.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:Et.map(A=>e.jsx("button",{onClick:()=>{o(n.id,A),j(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:A},A))})]}),e.jsx("button",{onClick:()=>f(n),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},title:"Reply",children:"โฉ"}),r&&e.jsx("button",{onClick:()=>c(n),style:{background:"none",border:"none",cursor:"pointer",fontSize:14,padding:"2px 4px"},title:"Open thread",children:"๐ฌ"})]})]})}function pt({channel:n,messages:t,users:i,currentUser:s,team:r,isLoading:o=!1,hasMore:c=!1,enableThreads:f=!0,enableReactions:u=!0,enableAttachments:x=!0,onSendMessage:m,onEditMessage:j,onDeleteMessage:C,onReactToMessage:v,onPinMessage:R,onLoadMoreMessages:O,onStartCall:l,className:A,style:N,id:Y,"data-testid":H}){var M;const D=a.useRef(null),$=a.useRef(null),[U,E]=a.useState(""),[_,S]=a.useState(null),[h,k]=a.useState(null),F=a.useMemo(()=>{const d=new Map;return i.forEach(y=>d.set(y.id,y)),d},[i]);a.useEffect(()=>{var d;(d=D.current)==null||d.scrollIntoView({behavior:"smooth"})},[t]);const J=a.useCallback(()=>{const d=$.current;!d||!c||o||d.scrollTop===0&&t.length>0&&(O==null||O(n.id,t[0].id))},[c,o,t,n.id,O]),I=a.useCallback(()=>{const d=U.trim();d&&(m==null||m(n.id,d,"text"),E(""),S(null))},[U,n.id,m]),W=d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),I())},B=i.filter(d=>d.presence.status==="online").length;return e.jsxs("div",{id:Y,"data-testid":H,className:`nice-channel-view${A?` ${A}`:""}`,style:{display:"flex",height:"100%",background:"#fff",overflow:"hidden",...N},children:[e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid #e5e7eb",flexShrink:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[e.jsx("span",{style:{fontSize:20,color:"#6b7280"},children:"#"}),e.jsxs("div",{children:[e.jsx("div",{style:{fontWeight:700,fontSize:16},children:n.name}),n.description&&e.jsx("div",{style:{fontSize:12,color:"#6b7280",marginTop:1},children:n.description})]})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsxs("span",{style:{fontSize:12,color:"#6b7280"},children:[e.jsx("span",{style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:"#22c55e",marginRight:4,verticalAlign:"middle"}}),B," online"]}),l&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>l(i.map(d=>d.id),"audio"),style:{background:"none",border:"1px solid #e5e7eb",borderRadius:6,padding:"5px 8px",cursor:"pointer",fontSize:15},title:"Audio call",children:"๐"}),e.jsx("button",{onClick:()=>l(i.map(d=>d.id),"video"),style:{background:"none",border:"1px solid #e5e7eb",borderRadius:6,padding:"5px 8px",cursor:"pointer",fontSize:15},title:"Video meet",children:"๐น"})]})]})]}),e.jsxs("div",{ref:$,onScroll:J,style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[c&&e.jsx("button",{onClick:()=>t.length>0&&(O==null?void 0:O(n.id,t[0].id)),disabled:o,style:{display:"block",margin:"8px auto",background:"none",border:"1px solid #e5e7eb",borderRadius:16,padding:"4px 16px",fontSize:12,color:"#6b7280",cursor:"pointer"},children:o?"Loadingโฆ":"Load older messages"}),t.map(d=>e.jsx(Ne,{message:d,author:F.get(d.authorId),isMine:d.authorId===s.id,enableReactions:u,enableThreads:f,onReact:(y,q)=>v==null?void 0:v(y,q),onOpenThread:y=>k(y),onReply:y=>S(y)},d.id)),e.jsx("div",{ref:D})]}),e.jsxs("div",{style:{padding:"8px 16px",borderTop:"1px solid #e5e7eb",flexShrink:0},children:[_&&e.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:[e.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Replying to: ",_.content]}),e.jsx("button",{onClick:()=>S(null),style:{background:"none",border:"none",cursor:"pointer",fontSize:16,color:"#9ca3af"},children:"ร"})]}),e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-end"},children:[x&&e.jsx("button",{title:"Attach",style:{background:"none",border:"none",cursor:"pointer",fontSize:18,color:"#9ca3af",padding:"6px 4px"},children:"๐"}),e.jsx("textarea",{value:U,onChange:d=>E(d.target.value),onKeyDown:W,placeholder:`Message #${n.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}}),e.jsx("button",{onClick:I,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:"โค"})]})]})]}),h&&e.jsxs("div",{style:{width:340,flexShrink:0,borderLeft:"1px solid #e5e7eb",display:"flex",flexDirection:"column",overflow:"hidden"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid #e5e7eb",flexShrink:0},children:[e.jsx("span",{style:{fontWeight:600,fontSize:14},children:"Thread"}),e.jsx("button",{onClick:()=>k(null),style:{background:"none",border:"none",cursor:"pointer",fontSize:18,color:"#9ca3af"},children:"ร"})]}),e.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[e.jsx(Ne,{message:h,author:F.get(h.authorId),isMine:h.authorId===s.id,enableReactions:u,enableThreads:!1,onReact:(d,y)=>v==null?void 0:v(d,y),onOpenThread:()=>{},onReply:()=>{}}),e.jsxs("div",{style:{padding:"6px 14px",color:"#9ca3af",fontSize:12,borderTop:"1px solid #f3f4f6"},children:[h.threadCount??0," repl",h.threadCount===1?"y":"ies"]}),(M=h.thread)==null?void 0:M.map(d=>e.jsx(Ne,{message:d,author:F.get(d.authorId),isMine:d.authorId===s.id,enableReactions:u,enableThreads:!1,onReact:(y,q)=>v==null?void 0:v(y,q),onOpenThread:()=>{},onReply:()=>{}},d.id))]}),e.jsx("div",{style:{padding:"8px 12px",borderTop:"1px solid #e5e7eb"},children:e.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-end"},children:[e.jsx("textarea",{placeholder:"Reply in threadโฆ",rows:1,onKeyDown:d=>{if(d.key==="Enter"&&!d.shiftKey){d.preventDefault();const y=d.target.value.trim();y&&(m==null||m(n.id,y,"text"),d.target.value="")}},style:{flex:1,resize:"none",border:"1px solid #e5e7eb",borderRadius:8,padding:"7px 10px",fontSize:13,outline:"none",fontFamily:"inherit",overflow:"hidden"}}),e.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({session:n,currentUser:t,localStream:i,enableScreenSharing:s=!0,enableRecording:r=!1,onEndCall:o,onMuteAudio:c,onMuteVideo:f,onStartScreenShare:u,onStopScreenShare:x,onRaiseHand:m,className:j,style:C,id:v,"data-testid":R}){var y,q;const O=a.useRef(null),l=a.useRef(null),[A,N]=a.useState(!1),[Y,H]=a.useState(n.type==="audio"),[D,$]=a.useState(!1),[U,E]=a.useState(0),[_,S]=a.useState(!1),h=n.participants.find(X=>X.user.id!==t.id);a.useEffect(()=>{O.current&&i&&(O.current.srcObject=i)},[i]),a.useEffect(()=>{l.current&&(h!=null&&h.stream)&&(l.current.srcObject=h.stream)},[h==null?void 0:h.stream]),a.useEffect(()=>{if(n.status!=="active")return;const X=setInterval(()=>E(Q=>Q+1),1e3);return()=>clearInterval(X)},[n.status]);const k=X=>{const Q=Math.floor(X/3600),K=Math.floor(X%3600/60),re=X%60;return Q>0?`${Q}:${String(K).padStart(2,"0")}:${String(re).padStart(2,"0")}`:`${String(K).padStart(2,"0")}:${String(re).padStart(2,"0")}`},F=()=>{const X=!A;N(X),c==null||c(X)},J=()=>{const X=!Y;H(X),f==null||f(X)},I=async()=>{D?($(!1),x==null||x()):($(!0),await(u==null?void 0:u()))},W=()=>{o==null||o(n.id)},B={position:"relative",width:"100%",height:"100%",background:"#111827",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",overflow:"hidden",...C},M=n.status==="ringing"||n.status==="connecting",d=h==null?void 0:h.user;return e.jsxs("div",{id:v,"data-testid":R,className:`nice-call-screen${j?` ${j}`:""}`,style:B,children:[n.type==="video"&&(h!=null&&h.stream)&&!h.isCameraOff?e.jsx("video",{ref:l,autoPlay:!0,playsInline:!0,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}):e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[e.jsx("div",{style:{width:120,height:120,borderRadius:"50%",background:d!=null&&d.avatarUrl?`url(${d.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:48,boxShadow:M?"0 0 0 12px rgba(99,102,241,0.3)":void 0,animation:M?"nice-call-pulse 1.5s ease-in-out infinite":void 0},children:!(d!=null&&d.avatarUrl)&&(((q=(y=d==null?void 0:d.name)==null?void 0:y[0])==null?void 0:q.toUpperCase())??"?")}),e.jsx("span",{style:{color:"#fff",fontSize:22,fontWeight:600},children:(d==null?void 0:d.displayName)??(d==null?void 0:d.name)??"Callingโฆ"}),d&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx(fe,{status:d.presence.status,size:"sm"}),e.jsx("span",{style:{color:"rgba(255,255,255,0.6)",fontSize:13},children:M?n.status==="ringing"?"Callingโฆ":"Connectingโฆ":k(U)})]})]}),n.status==="active"&&e.jsxs("div",{style:{position:"absolute",top:16,left:"50%",transform:"translateX(-50%)",color:"rgba(255,255,255,0.7)",fontSize:13},children:[k(U),n.isRecording&&e.jsx("span",{style:{marginLeft:8,color:"#ef4444"},children:"โ REC"})]}),(h==null?void 0:h.isMuted)&&e.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:["๐ ",d==null?void 0:d.name," is muted"]}),e.jsx("button",{onClick:()=>S(X=>!X),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:_?"Exit fullscreen":"Fullscreen",children:_?"โก":"โ"}),n.type==="video"&&!Y&&i&&e.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:e.jsx("video",{ref:O,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"cover",transform:"scaleX(-1)"}})}),e.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:[e.jsx(ve,{icon:A?"๐":"๐ค",label:A?"Unmute":"Mute",onClick:F,active:!A,style:{background:A?"#ef4444":void 0}}),n.type==="video"&&e.jsx(ve,{icon:Y?"๐ท":"๐น",label:Y?"Turn on camera":"Turn off camera",onClick:J,active:!Y,style:{background:Y?"#ef4444":void 0}}),s&&e.jsx(ve,{icon:"๐ฅ",label:D?"Stop sharing":"Share screen",onClick:()=>{I()},active:D,style:{background:D?"#22c55e":void 0}}),m&&e.jsx(ve,{icon:"โ",label:"Raise hand",onClick:()=>m(!0),active:!1}),r&&e.jsx(ve,{icon:"โบ",label:n.isRecording?"Stop recording":"Start recording",onClick:()=>{},active:n.isRecording,style:{background:n.isRecording?"#ef4444":void 0}}),e.jsx(ve,{icon:"๐ต",label:"End call",onClick:W,active:!1,style:{background:"#ef4444",color:"#fff"}})]}),e.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: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:`
|
|
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 ve({icon:n,label:t,onClick:i,active:s,style:r}){return e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[e.jsx("button",{onClick:i,title:t,style:{width:44,height:44,borderRadius:"50%",border:"none",background:s?"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:n}),e.jsx("span",{style:{fontSize:9,color:"rgba(255,255,255,0.5)",textAlign:"center",maxWidth:50},children:t})]})}function Le({participant:n,isLocal:t,isPinned:i,onPin:s,size:r="medium"}){var O;const o=a.useRef(null),{user:c,isMuted:f,isCameraOff:u,isScreenSharing:x,isSpeaking:m,isHandRaised:j,stream:C,screenStream:v}=n;a.useEffect(()=>{if(!o.current)return;const l=x?v:C;l&&(o.current.srcObject=l)},[C,v,x]);const R=!u&&!!C;return e.jsxs("div",{className:`nice-conference-tile${m?" nice-conference-tile--speaking":""}${i?" nice-conference-tile--pinned":""}`,style:{position:"relative",background:"#1f2937",borderRadius:10,overflow:"hidden",border:m?"2px solid #22c55e":i?"2px solid #6366f1":"2px solid transparent",display:"flex",alignItems:"center",justifyContent:"center",aspectRatio:"16/9"},children:[R?e.jsx("video",{ref:o,autoPlay:!0,muted:t,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"cover",transform:t&&!x?"scaleX(-1)":"none"}}):e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:8},children:[e.jsx("div",{style:{width:r==="large"?64:r==="small"?28:44,height:r==="large"?64:r==="small"?28:44,borderRadius:"50%",background:c.avatarUrl?`url(${c.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:r==="large"?28:r==="small"?12:18},children:!c.avatarUrl&&((O=c.name[0])==null?void 0:O.toUpperCase())}),r!=="small"&&e.jsx("span",{style:{color:"#fff",fontSize:12},children:c.displayName??c.name})]}),e.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:[e.jsxs("span",{style:{color:"#fff",fontSize:11,fontWeight:500},children:[c.displayName??c.name,t&&" (You)"]}),e.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[j&&e.jsx("span",{style:{fontSize:13},children:"โ"}),f&&e.jsx("span",{style:{fontSize:12},children:"๐"}),x&&e.jsx("span",{style:{fontSize:12},children:"๐ฅ"}),r!=="small"&&e.jsx("div",{style:{width:6,height:6,borderRadius:"50%",background:m?"#22c55e":"transparent",border:"1px solid rgba(255,255,255,0.3)"}})]})]}),r!=="small"&&e.jsx("button",{onClick:s,style:{position:"absolute",top:6,right:6,background:"rgba(0,0,0,0.4)",border:"none",borderRadius:4,padding:"2px 5px",color:i?"#6366f1":"rgba(255,255,255,0.6)",cursor:"pointer",fontSize:12},title:i?"Unpin":"Pin",children:"๐"}),n.connectionQuality!=="none"&&r!=="small"&&e.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(l=>e.jsx("div",{style:{flex:1,background:n.connectionQuality==="excellent"||n.connectionQuality==="good"&&l<=2||n.connectionQuality==="fair"&&l<=1?"#22c55e":"rgba(255,255,255,0.3)",height:`${l*30}%`,borderRadius:1}},l))})]})}function Ke({session:n,currentUser:t,localStream:i,enableScreenSharing:s=!0,enableRecording:r=!1,enableTranscription:o=!1,enableRaiseHand:c=!0,maxGridCols:f=4,onEndCall:u,onMuteAudio:x,onMuteVideo:m,onStartScreenShare:j,onStopScreenShare:C,onRaiseHand:v,className:R,style:O,id:l,"data-testid":A}){const[N,Y]=a.useState(!1),[H,D]=a.useState(!1),[$,U]=a.useState(!1),[E,_]=a.useState(!1),[S,h]=a.useState(n.pinnedParticipantId??null),[k,F]=a.useState(n.layout==="sidebar"?"grid":n.layout??"grid"),[J,I]=a.useState(0),[W,B]=a.useState(!1);a.useEffect(()=>{if(n.status!=="active")return;const L=setInterval(()=>I(V=>V+1),1e3);return()=>clearInterval(L)},[n.status]);const M=L=>{const V=Math.floor(L/3600),ne=Math.floor(L%3600/60),se=L%60;return V>0?`${V}:${String(ne).padStart(2,"0")}:${String(se).padStart(2,"0")}`:`${String(ne).padStart(2,"0")}:${String(se).padStart(2,"0")}`},d=()=>{const L=!N;Y(L),x==null||x(L)},y=()=>{const L=!H;D(L),m==null||m(L)},q=async()=>{$?(U(!1),C==null||C()):(U(!0),await(j==null?void 0:j()))},X=()=>{const L=!E;_(L),v==null||v(L)},Q=[{user:t,isMuted:N,isCameraOff:H,isScreenSharing:$,isSpeaking:!1,isHandRaised:E,stream:i,connectionQuality:"excellent"},...n.participants],K=S?Q.find(L=>L.user.id===S):null,re=Q.filter(L=>L.user.id!==S),oe=Q.length,ue=Math.min(f,oe<=1?1:oe<=2||oe<=4?2:oe<=9?3:4),le=k==="spotlight"||K!=null;return e.jsxs("div",{id:l,"data-testid":A,className:`nice-video-conference${R?` ${R}`:""}`,style:{position:"relative",width:"100%",height:"100%",background:"#111827",display:"flex",flexDirection:"column",overflow:"hidden",...O},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 16px",flexShrink:0,color:"#fff"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[e.jsxs("span",{style:{fontSize:15,fontWeight:600},children:[n.id.slice(0,8),"โฆ"]}),e.jsx("span",{style:{fontSize:12,color:"rgba(255,255,255,0.6)"},children:M(J)}),n.isRecording&&e.jsx("span",{style:{fontSize:11,color:"#ef4444",display:"flex",alignItems:"center",gap:4},children:"โ Recording"})]}),e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[e.jsx("button",{onClick:()=>F(k==="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:k==="grid"?"โ Grid":"โก Spotlight"}),e.jsxs("button",{onClick:()=>B(L=>!L),style:{background:W?"#6366f1":"rgba(255,255,255,0.1)",border:"none",borderRadius:6,padding:"4px 10px",color:"#fff",cursor:"pointer",fontSize:12},children:["๐ฅ ",Q.length]})]})]}),e.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden",gap:4,padding:"0 8px 8px"},children:[e.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:4,overflow:"hidden"},children:le&&K?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{flex:1},children:e.jsx(Le,{participant:K,isLocal:K.user.id===t.id,isPinned:!0,onPin:()=>h(null),size:"large"})}),e.jsx("div",{style:{display:"flex",gap:4,height:90,flexShrink:0,overflowX:"auto"},children:re.map(L=>e.jsx("div",{style:{width:140,flexShrink:0},children:e.jsx(Le,{participant:L,isLocal:L.user.id===t.id,isPinned:!1,onPin:()=>h(L.user.id),size:"small"})},L.user.id))})]}):e.jsx("div",{style:{flex:1,display:"grid",gridTemplateColumns:`repeat(${ue}, 1fr)`,gap:6,overflow:"hidden"},children:Q.map(L=>e.jsx(Le,{participant:L,isLocal:L.user.id===t.id,isPinned:L.user.id===S,onPin:()=>h(V=>V===L.user.id?null:L.user.id),size:oe<=4?"large":"medium"},L.user.id))})}),W&&e.jsxs("div",{style:{width:220,flexShrink:0,background:"rgba(255,255,255,0.05)",borderRadius:10,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e.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,")"]}),e.jsx("div",{style:{flex:1,overflowY:"auto",padding:8},children:Q.map(L=>{var V;return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px"},children:[e.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&&((V=L.user.name[0])==null?void 0:V.toUpperCase())}),e.jsx("div",{style:{flex:1,minWidth:0},children:e.jsxs("div",{style:{color:"#fff",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[L.user.displayName??L.user.name,L.user.id===t.id&&" (You)"]})}),e.jsxs("div",{style:{display:"flex",gap:3},children:[L.isHandRaised&&e.jsx("span",{style:{fontSize:11},children:"โ"}),L.isMuted&&e.jsx("span",{style:{fontSize:11},children:"๐"}),e.jsx(fe,{status:L.user.presence.status,size:"xs"})]})]},L.user.id)})})]})]}),e.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:[e.jsx(xe,{icon:N?"๐":"๐ค",label:N?"Unmute":"Mute",onClick:d,danger:N}),e.jsx(xe,{icon:H?"๐ท":"๐น",label:H?"Start video":"Stop video",onClick:y,danger:H}),s&&e.jsx(xe,{icon:"๐ฅ",label:$?"Stop share":"Share",onClick:()=>{q()},active:$}),c&&e.jsx(xe,{icon:"โ",label:"Raise hand",onClick:X,active:E}),r&&e.jsx(xe,{icon:"โบ",label:n.isRecording?"Stop rec":"Record",onClick:()=>{},active:n.isRecording,danger:n.isRecording}),o&&e.jsx(xe,{icon:"๐",label:n.isTranscribing?"Stop captions":"Captions",onClick:()=>{},active:n.isTranscribing}),e.jsx(xe,{icon:"๐ต",label:"Leave",onClick:()=>u==null?void 0:u(n.id),end:!0})]})]})}function xe({icon:n,label:t,onClick:i,active:s,danger:r,end:o}){return e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[e.jsx("button",{title:t,onClick:i,style:{width:46,height:46,borderRadius:"50%",border:"none",background:o?"#ef4444":r?"#450a0a":s?"#6366f1":"rgba(255,255,255,0.12)",color:"#fff",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.15s"},children:n}),e.jsx("span",{style:{fontSize:9,color:"rgba(255,255,255,0.5)",textAlign:"center",maxWidth:52},children:t})]})}function Ue(n){const t={days:864e5,weeks:6048e5,months:2592e6,years:31536e6,forever:Number.MAX_SAFE_INTEGER};return n.unit==="forever"?t.forever:t[n.unit]*n.value}function Ce(n,t=new Date){if(n.unit!=="forever")return new Date(t.getTime()+Ue(n))}class Qe{constructor(t="nice2dev-communication"){this.storeName="nice_comm_store",this.db=null,this.dbName=t}async openDb(){return this.db?this.db:new Promise((t,i)=>{const s=indexedDB.open(this.dbName,1);s.onupgradeneeded=r=>{const o=r.target.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"key"})},s.onsuccess=r=>{this.db=r.target.result,t(this.db)},s.onerror=()=>i(s.error)})}async save(t,i,s){const r=await this.openDb();return new Promise((o,c)=>{const x=r.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:t,data:i,expiresAt:s==null?void 0:s.toISOString()});x.onsuccess=()=>o(),x.onerror=()=>c(x.error)})}async load(t){const i=await this.openDb();return new Promise((s,r)=>{const f=i.transaction(this.storeName,"readonly").objectStore(this.storeName).get(t);f.onsuccess=()=>{const u=f.result;if(!u){s(void 0);return}if(u.expiresAt&&new Date(u.expiresAt)<new Date){this.delete(t),s(void 0);return}s(u.data)},f.onerror=()=>r(f.error)})}async delete(t){const i=await this.openDb();return new Promise((s,r)=>{const f=i.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(t);f.onsuccess=()=>s(),f.onerror=()=>r(f.error)})}async list(t){const i=await this.openDb();return new Promise((s,r)=>{const f=i.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();f.onsuccess=()=>s((f.result??[]).filter(u=>u.startsWith(t))),f.onerror=()=>r(f.error)})}async clear(t){if(!t){const s=await this.openDb();return new Promise((r,o)=>{const u=s.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();u.onsuccess=()=>r(),u.onerror=()=>o(u.error)})}const i=await this.list(t);await Promise.all(i.map(s=>this.delete(s)))}}class Pt{constructor(t="nice_comm__"){this.prefix=t}async save(t,i,s){const r={data:i,expiresAt:s==null?void 0:s.toISOString()};localStorage.setItem(this.prefix+t,JSON.stringify(r))}async load(t){const i=localStorage.getItem(this.prefix+t);if(i)try{const s=JSON.parse(i);if(s.expiresAt&&new Date(s.expiresAt)<new Date){await this.delete(t);return}return s.data}catch{return}}async delete(t){localStorage.removeItem(this.prefix+t)}async list(t){const i=[];for(let s=0;s<localStorage.length;s++){const r=localStorage.key(s);r&&r.startsWith(this.prefix+t)&&i.push(r.slice(this.prefix.length))}return i}async clear(t){(await this.list(t??"")).forEach(s=>localStorage.removeItem(this.prefix+s))}}class ht{constructor(t,i){this.config=t,this.encryption=i,this.adapter=this.buildAdapter()}buildAdapter(){switch(this.config.provider){case"localstorage":return new Pt;case"custom":return this.config.customAdapter??new Qe;default:return new Qe}}getRuleFor(t){return this.config.retentionRules.find(i=>i.dataType===t)}async encode(t){var s;const i=JSON.stringify(t);return(s=this.encryption)!=null&&s.isEnabled()?this.encryption.encrypt(i,"messages"):i}async decode(t){var i;if(typeof t!="string")return t;if(!((i=this.encryption)!=null&&i.isEnabled()))try{return JSON.parse(t)}catch{return t}try{const s=await this.encryption.decrypt(t,"messages");return JSON.parse(s)}catch{return t}}async saveMessages(t,i){const s=this.getRuleFor("messages"),r=s?Ce(s.activePeriod):void 0,o=await this.encode(i);await this.adapter.save(`msg:${t}`,o,r)}async loadMessages(t){const i=await this.adapter.load(`msg:${t}`);if(!i)return[];const s=await this.decode(i);return Array.isArray(s)?s:[]}async appendMessage(t,i){const s=await this.loadMessages(t);await this.saveMessages(t,[...s,i])}async saveWhiteboardSnapshot(t,i){const s=this.getRuleFor("whiteboard-snapshots"),r=s?Ce(s.activePeriod):void 0,o=await this.encode(i);await this.adapter.save(`wb:${t}`,o,r)}async loadWhiteboardSnapshot(t){const i=await this.adapter.load(`wb:${t}`);return i?await this.decode(i):null}async saveRecordingMeta(t){const i=this.getRuleFor("recordings"),s=i?Ce(i.activePeriod):void 0,r=await this.encode(t);await this.adapter.save(`rec:${t.id}`,r,s)}async loadRecordingMeta(t){const i=await this.adapter.load(`rec:${t}`);return i?await this.decode(i):null}async listRecordings(){const t=await this.adapter.list("rec:");return(await Promise.all(t.map(s=>this.loadRecordingMeta(s.slice(4))))).filter(Boolean)}async deleteRecording(t){await this.adapter.delete(`rec:${t}`)}async saveDocument(t,i){const s=this.getRuleFor("documents"),r=s?Ce(s.activePeriod):void 0,o=await this.encode(i);await this.adapter.save(`doc:${t}`,o,r)}async loadDocument(t){const i=await this.adapter.load(`doc:${t}`);return i?this.decode(i):null}async enforceRetention(){let t=0,i=0;const s=new Date,r=[{prefix:"msg:",type:"messages"},{prefix:"wb:",type:"whiteboard-snapshots"},{prefix:"rec:",type:"recordings"},{prefix:"doc:",type:"documents"}];for(const{prefix:o,type:c}of r){const f=this.getRuleFor(c);if(!f)continue;const u=await this.adapter.list(o);for(const x of u){const m=await this.adapter.load(x);if(m){if(Ue(f.activePeriod),f.archivePeriod){const j=`archive:${x}`,C=Ce(f.archivePeriod,s);await this.adapter.save(j,m,C),t++}if(f.deleteAfterArchive&&f.archivePeriod){const j=Ue(f.archivePeriod);new Date(s.getTime()+j)<s&&(await this.adapter.delete(`archive:${x}`),i++)}}}}return{archived:t,deleted:i}}async estimateUsageBytes(){return typeof window<"u"&&"storage"in navigator&&"estimate"in navigator.storage?(await navigator.storage.estimate()).usage??0:0}updateConfig(t){this.config=t,this.adapter=this.buildAdapter()}getConfig(){return this.config}}const Ye=[{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}],De=new Map;function gt(n,t,i){return De.has(n)||De.set(n,new ht(t,i)),De.get(n)}function Ot(n){De.delete(n)}const Ze=["#e91e63","#9c27b0","#3f51b5","#2196f3","#00bcd4","#4caf50","#ff9800","#ff5722","#795548","#607d8b"];function Wt(n){let t=0;for(let i=0;i<n.length;i++)t=t*31+n.charCodeAt(i)>>>0;return Ze[t%Ze.length]}function et(n,t,i){const s={...n},r=[...t];switch(i.type){case"object:add":case"object:update":{const o=i.payload;if(s[o.id]=o,r.length>0&&!r[0].objectIds.includes(o.id)){const c=o.layerId?r.find(f=>f.id===o.layerId)??r[0]:r[0];c.objectIds=[...c.objectIds,o.id]}break}case"object:delete":{const{id:o}=i.payload;delete s[o],r.forEach(c=>{c.objectIds=c.objectIds.filter(f=>f!==o)});break}case"object:move":{const{id:o,x:c,y:f}=i.payload;s[o]&&(s[o]={...s[o],x:c,y:f,updatedAt:i.timestamp});break}case"layer:add":{const o=i.payload;r.find(c=>c.id===o.id)||r.push(o);break}case"layer:update":{const o=i.payload,c=r.findIndex(f=>f.id===o.id);c!==-1&&(r[c]={...r[c],...o});break}case"layer:delete":{const{id:o}=i.payload,c=r.findIndex(f=>f.id===o);c!==-1&&r.splice(c,1);break}}return{objects:s,layers:r}}function Nt(n,t){switch(t.type){case"LOAD_SESSION":return{...n,session:t.session,undoStack:[],redoStack:[],isDirty:!1};case"SET_TOOL":return{...n,activeTool:t.tool};case"APPLY_OP":{const{op:i,local:s}=t,{objects:r,layers:o}=et(n.session.objects,n.session.layers,i),c={...n.session,objects:r,layers:o,updatedAt:i.timestamp},u=s&&["object:add","object:update","object:delete","object:move","layer:add","layer:update","layer:delete"].includes(i.type)?[...n.undoStack,[i]]:n.undoStack;return{...n,session:c,undoStack:u,redoStack:s?[]:n.redoStack,isDirty:!0}}case"UNDO":{if(n.undoStack.length===0)return n;const i=n.undoStack[n.undoStack.length-1],s=i.filter(c=>c.type==="object:add").map(c=>c.payload.id),r={...n.session.objects};s.forEach(c=>delete r[c]);const o=n.session.layers.map(c=>({...c,objectIds:c.objectIds.filter(f=>!s.includes(f))}));return{...n,session:{...n.session,objects:r,layers:o},undoStack:n.undoStack.slice(0,-1),redoStack:[i,...n.redoStack],isDirty:!0}}case"REDO":{if(n.redoStack.length===0)return n;const i=n.redoStack[0];let{objects:s,layers:r}={objects:n.session.objects,layers:n.session.layers};for(const o of i)({objects:s,layers:r}=et(s,r,o));return{...n,session:{...n.session,objects:s,layers:r},undoStack:[...n.undoStack,i],redoStack:n.redoStack.slice(1),isDirty:!0}}case"SET_SELECTION":return{...n,selectedObjectIds:t.ids};case"SET_DRAWING":return{...n,isDrawing:t.value};case"SET_PANNING":return{...n,isPanning:t.value};case"UPDATE_CURSOR":{const{userId:i,x:s,y:r}=t,o=n.session.collaborators[i];return o?{...n,session:{...n.session,collaborators:{...n.session.collaborators,[i]:{...o,cursorX:s,cursorY:r,lastSeenAt:new Date}}}}:n}case"REMOVE_COLLABORATOR":{const i={...n.session.collaborators};return delete i[t.userId],{...n,session:{...n.session,collaborators:i}}}case"SET_VIEWPORT":return{...n,session:{...n.session,viewport:t.viewport}};case"MARK_SAVED":return{...n,isDirty:!1,lastSavedAt:new Date};default:return n}}function yt(n){const{session:t,currentUser:i,onOperation:s,remoteOperations:r=[],readonly:o=!1,storageConfig:c,autoSaveMs:f=3e4}=n,[u,x]=a.useReducer(Nt,{session:t,activeTool:o?"select":"pen",selectedObjectIds:[],undoStack:[],redoStack:[],isDrawing:!1,isPanning:!1,isDirty:!1}),m=a.useRef(0),j=a.useRef(null),C=a.useRef(null);a.useEffect(()=>{c&&(C.current=gt(`wb_${t.id}`,c),C.current.loadWhiteboardSnapshot(t.id).then(I=>{I&&x({type:"LOAD_SESSION",session:I})}))},[t.id,c]),a.useEffect(()=>{if(!f||!C.current||!u.isDirty)return;const I=setTimeout(()=>{var W;(W=C.current)==null||W.saveWhiteboardSnapshot(u.session.id,u.session).then(()=>{x({type:"MARK_SAVED"})})},f);return()=>clearTimeout(I)},[u.isDirty,u.session,f]);const v=a.useRef(new Set);a.useEffect(()=>{for(const I of r)if(!v.current.has(I.id)&&I.userId!==i.id)if(v.current.add(I.id),I.type==="cursor:move"){const{x:W,y:B}=I.payload;x({type:"UPDATE_CURSOR",userId:I.userId,x:W,y:B})}else I.type==="viewport:sync"||x({type:"APPLY_OP",op:I,local:!1})},[r,i.id]);function R(I,W){return{id:`${i.id}_${++m.current}_${Date.now()}`,sessionId:u.session.id,type:I,userId:i.id,timestamp:new Date,payload:W}}const O=a.useCallback(I=>{o||x({type:"SET_TOOL",tool:I})},[o]),l=a.useCallback(I=>{if(o)return;const W=R("object:add",I);x({type:"APPLY_OP",op:W,local:!0}),s==null||s(W)},[o,s,u.session.id]),A=a.useCallback(I=>{if(o)return;const W=R("object:update",I);x({type:"APPLY_OP",op:W,local:!0}),s==null||s(W)},[o,s,u.session.id]),N=a.useCallback(I=>{if(!o){for(const W of I){const B=R("object:delete",{id:W});x({type:"APPLY_OP",op:B,local:!0}),s==null||s(B)}x({type:"SET_SELECTION",ids:[]})}},[o,s,u.session.id]),Y=a.useCallback(I=>{if(!o)for(const{id:W,x:B,y:M}of I){const d=R("object:move",{id:W,x:B,y:M});x({type:"APPLY_OP",op:d,local:!0}),s==null||s(d)}},[o,s,u.session.id]),H=a.useCallback(I=>{x({type:"SET_SELECTION",ids:I})},[]),D=a.useCallback(()=>{o||x({type:"UNDO"})},[o]),$=a.useCallback(()=>{o||x({type:"REDO"})},[o]),U=a.useCallback(I=>{x({type:"SET_VIEWPORT",viewport:I});const W=R("viewport:sync",I);s==null||s(W)},[s,u.session.id]),E=a.useCallback((I,W)=>{if(j.current)return;j.current=setTimeout(()=>{j.current=null},50);const B=R("cursor:move",{x:I,y:W});s==null||s(B)},[s,u.session.id]),_=a.useCallback(I=>{if(o)return;const W={id:`layer_${Date.now()}`,name:I,visible:!0,locked:!1,objectIds:[]},B=R("layer:add",W);x({type:"APPLY_OP",op:B,local:!0}),s==null||s(B)},[o,s,u.session.id]),S=a.useCallback(I=>{if(o)return;const W=R("layer:update",I);x({type:"APPLY_OP",op:W,local:!0}),s==null||s(W)},[o,s,u.session.id]),h=a.useCallback(I=>{if(o)return;const W=R("layer:delete",{id:I});x({type:"APPLY_OP",op:W,local:!0}),s==null||s(W)},[o,s,u.session.id]),k=a.useCallback(I=>{const W={user:I,cursorX:0,cursorY:0,color:Wt(I.id),selectedObjectIds:[],activeTool:"pen",lastSeenAt:new Date};x({type:"APPLY_OP",op:R("cursor:move",W),local:!1})},[]),F=a.useCallback(I=>{x({type:"REMOVE_COLLABORATOR",userId:I})},[]),J=a.useCallback(async()=>{C.current&&(await C.current.saveWhiteboardSnapshot(u.session.id,u.session),x({type:"MARK_SAVED"}))},[u.session]);return{session:u.session,activeTool:u.activeTool,selectedObjectIds:u.selectedObjectIds,isDrawing:u.isDrawing,isPanning:u.isPanning,isDirty:u.isDirty,lastSavedAt:u.lastSavedAt,canUndo:u.undoStack.length>0,canRedo:u.redoStack.length>0,collaborators:Object.values(u.session.collaborators),objects:Object.values(u.session.objects),layers:u.session.layers,viewport:u.session.viewport,setTool:O,addObject:l,updateObject:A,deleteObjects:N,moveObjects:Y,setSelection:H,undo:D,redo:$,setViewport:U,broadcastCursor:E,addLayer:_,updateLayer:S,deleteLayer:h,registerCollaborator:k,removeCollaborator:F,saveNow:J}}const Lt=[{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 Te(){return`${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function $e(n,t,i){return{sx:n*i.scale+i.x,sy:t*i.scale+i.y}}function $t(n,t,i){return{wx:(n-i.x)/i.scale,wy:(t-i.y)/i.scale}}function Bt(n,t){return Math.hypot(t.x-n.x,t.y-n.y)}function Mt(n,t){if(!(t.points.length<2)){n.save(),n.globalAlpha=t.opacity,n.strokeStyle=t.color,n.lineWidth=t.strokeWidth,n.lineCap="round",n.lineJoin="round",t.tool==="highlighter"&&(n.globalCompositeOperation="multiply"),n.beginPath(),n.moveTo(t.points[0].x,t.points[0].y);for(let i=1;i<t.points.length;i++){const s={x:(t.points[i-1].x+t.points[i].x)/2,y:(t.points[i-1].y+t.points[i].y)/2};n.quadraticCurveTo(t.points[i-1].x,t.points[i-1].y,s.x,s.y)}n.stroke(),n.restore()}}function Ut(n,t){switch(n.save(),n.globalAlpha=t.opacity,n.strokeStyle=t.strokeColor,n.lineWidth=t.strokeWidth,t.fillColor&&(n.fillStyle=t.fillColor),n.translate(t.x+t.width/2,t.y+t.height/2),n.rotate(t.rotation*Math.PI/180),n.beginPath(),t.shape){case"rect":n.rect(-t.width/2,-t.height/2,t.width,t.height);break;case"ellipse":n.ellipse(0,0,t.width/2,t.height/2,0,0,Math.PI*2);break;case"triangle":{const i=t.width/2,s=t.height/2;n.moveTo(0,-s),n.lineTo(i,s),n.lineTo(-i,s),n.closePath();break}case"diamond":{const i=t.width/2,s=t.height/2;n.moveTo(0,-s),n.lineTo(i,0),n.lineTo(0,s),n.lineTo(-i,0),n.closePath();break}}t.fillColor&&n.fill(),n.stroke(),n.restore()}function _t(n,t){if(n.save(),n.translate(t.x+t.width/2,t.y+t.height/2),n.rotate(t.rotation*Math.PI/180),n.font=`${t.fontStyle} ${t.fontWeight} ${t.fontSize}px ${t.fontFamily}`,n.fillStyle=t.color,n.textAlign=t.textAlign,n.textBaseline="middle",t.backgroundColor){const i=n.measureText(t.text),s=4;n.fillStyle=t.backgroundColor,n.fillRect(-i.width/2-s,-t.fontSize/2-s,i.width+s*2,t.fontSize+s*2),n.fillStyle=t.color}n.fillText(t.text,0,0),n.restore()}function Ft(n,t){n.save(),n.translate(t.x,t.y),n.rotate(t.rotation*Math.PI/180),n.shadowColor="rgba(0,0,0,0.15)",n.shadowBlur=8,n.shadowOffsetY=3,n.fillStyle=t.backgroundColor,n.fillRect(0,0,t.width,t.height),n.shadowColor="transparent",n.fillStyle=t.textColor,n.font=`${t.fontSize}px sans-serif`,n.textAlign="left",n.textBaseline="top";const i=10,s=t.width-i*2,r=t.fontSize*1.4,o=t.text.split(" ");let c="",f=i;for(const u of o){const x=c?`${c} ${u}`:u;n.measureText(x).width>s&&c?(n.fillText(c,i,f),c=u,f+=r):c=x}c&&n.fillText(c,i,f),n.restore()}function Kt(n,t){if(!(t.points.length<2)){if(n.save(),n.strokeStyle=t.strokeColor,n.lineWidth=t.strokeWidth,n.lineCap="round",n.beginPath(),n.moveTo(t.points[0].x,t.points[0].y),t.curved&&t.points.length>2){for(let i=1;i<t.points.length-1;i++){const s=t.points[i],r={x:(s.x+t.points[i+1].x)/2,y:(s.y+t.points[i+1].y)/2};n.quadraticCurveTo(s.x,s.y,r.x,r.y)}n.lineTo(t.points[t.points.length-1].x,t.points[t.points.length-1].y)}else for(let i=1;i<t.points.length;i++)n.lineTo(t.points[i].x,t.points[i].y);if(n.stroke(),t.arrowEnd==="arrow"){const i=t.points[t.points.length-1],s=t.points[t.points.length-2],r=Math.atan2(i.y-s.y,i.x-s.x),o=12;n.beginPath(),n.moveTo(i.x,i.y),n.lineTo(i.x-o*Math.cos(r-Math.PI/6),i.y-o*Math.sin(r-Math.PI/6)),n.moveTo(i.x,i.y),n.lineTo(i.x-o*Math.cos(r+Math.PI/6),i.y-o*Math.sin(r+Math.PI/6)),n.stroke()}n.restore()}}function Yt(n,t){n.save(),n.strokeStyle=t.borderColor??"#aaa",n.lineWidth=2,n.setLineDash([8,4]),t.backgroundColor&&(n.fillStyle=t.backgroundColor,n.fillRect(t.x,t.y,t.width,t.height)),n.strokeRect(t.x,t.y,t.width,t.height),n.setLineDash([]),n.fillStyle="#555",n.font="bold 13px sans-serif",n.fillText(t.name,t.x+8,t.y-6),n.restore()}function Ht(n,t){if(t.visible)switch(t.type){case"stroke":return Mt(n,t);case"shape":return Ut(n,t);case"text":return _t(n,t);case"sticky":return Ft(n,t);case"connector":return Kt(n,t);case"frame":return Yt(n,t);case"image":{const i=t,s=new Image;s.src=i.dataUrl??i.url,n.save(),n.translate(i.x+i.width/2,i.y+i.height/2),n.rotate(i.rotation*Math.PI/180),n.drawImage(s,-i.width/2,-i.height/2,i.width,i.height),n.restore();break}}}function He({session:n,currentUser:t,onOperation:i,remoteOperations:s=[],readonly:r=!1,enableLayers:o=!0,enableExport:c=!0,enableLaserPointer:f=!0,enableVectorEditor:u=!1,enableDiagramEditor:x=!1,onExport:m,onSessionUpdate:j,storageConfig:C,className:v,style:R,"data-testid":O}){const l=yt({session:n,currentUser:t,onOperation:i,remoteOperations:s,readonly:r,storageConfig:C,autoSaveMs:3e4}),A=a.useRef(null);a.useRef(null);const N=a.useRef(0),[Y,H]=a.useState(!1),[D,$]=a.useState("#1a1a1a"),[U,E]=a.useState(3),[_,S]=a.useState(void 0),[h,k]=a.useState(18),[F,J]=a.useState("#fef08a"),[I,W]=a.useState(null),[B,M]=a.useState(null),d=a.useRef({active:!1,startX:0,startY:0,currentPoints:[],currentId:"",spaceDown:!1,panStart:null,laserPoints:[]}),y=a.useCallback((p,g,T,P)=>{if(!l.session.gridEnabled)return;const z=l.session.gridSize*g.scale,G=(g.x%z+z)%z,b=(g.y%z+z)%z;p.strokeStyle="rgba(180,180,200,0.35)",p.lineWidth=1,p.beginPath();for(let w=G;w<T;w+=z)p.moveTo(w,0),p.lineTo(w,P);for(let w=b;w<P;w+=z)p.moveTo(0,w),p.lineTo(T,w);p.stroke()},[l.session.gridEnabled,l.session.gridSize]),q=a.useCallback((p,g)=>{for(const T of l.collaborators){if(T.user.id===t.id)continue;const{sx:P,sy:z}=$e(T.cursorX,T.cursorY,g);p.save(),p.fillStyle=T.color,p.beginPath(),p.moveTo(P,z),p.lineTo(P+14,z+5),p.lineTo(P+5,z+14),p.closePath(),p.fill(),p.fillStyle=T.color,p.font="bold 11px sans-serif",p.fillText(T.user.name,P+16,z+14),p.restore()}},[l.collaborators,t.id]),X=a.useCallback((p,g)=>{if(l.selectedObjectIds.length!==0)for(const T of l.selectedObjectIds){const P=l.session.objects[T];if(!P)continue;const{sx:z,sy:G}=$e(P.x,P.y,g),b=P.width*g.scale,w=P.height*g.scale;p.strokeStyle="#4f8df9",p.lineWidth=1.5,p.setLineDash([4,2]),p.strokeRect(z-2,G-2,b+4,w+4),p.setLineDash([]);const ee=[[z-2,G-2],[z+b+2,G-2],[z-2,G+w+2],[z+b+2,G+w+2]];p.fillStyle="#fff",p.strokeStyle="#4f8df9",p.lineWidth=1.5;for(const[Z,ie]of ee)p.fillRect(Z-4,ie-4,8,8),p.strokeRect(Z-4,ie-4,8,8)}},[l.selectedObjectIds,l.session.objects]),Q=a.useCallback(()=>{const p=A.current;if(!p)return;const g=p.getContext("2d");if(!g)return;const{width:T,height:P}=p,z=l.viewport;g.clearRect(0,0,T,P),g.fillStyle=l.session.backgroundColor,g.fillRect(0,0,T,P),y(g,z,T,P),g.save();const G=Object.values(l.session.objects).filter(b=>b.visible).sort((b,w)=>b.zIndex-w.zIndex);g.translate(z.x,z.y),g.scale(z.scale,z.scale);for(const b of G)Ht(g,b);if(d.current.active&&d.current.currentPoints.length>1){const b=d.current.currentPoints;g.strokeStyle=D,g.lineWidth=U,g.lineCap="round",g.lineJoin="round",g.beginPath(),g.moveTo(b[0].x,b[0].y);for(let w=1;w<b.length;w++)g.lineTo(b[w].x,b[w].y);g.stroke()}if(d.current.laserPoints.length>1&&l.activeTool==="laser"){const b=d.current.laserPoints;g.strokeStyle="#ff2c2c",g.lineWidth=3,g.globalAlpha=.7,g.beginPath(),g.moveTo(b[0].x,b[0].y);for(let w=1;w<b.length;w++)g.lineTo(b[w].x,b[w].y);g.stroke(),g.globalAlpha=1}g.restore(),X(g,z),q(g,z)},[l.session,l.viewport,l.activeTool,y,q,X,D,U]);a.useLayoutEffect(()=>{function p(){Q(),N.current=requestAnimationFrame(p)}return N.current=requestAnimationFrame(p),()=>cancelAnimationFrame(N.current)},[Q]),a.useEffect(()=>{const p=A.current;if(!p)return;const g=new ResizeObserver(()=>{p.width=p.offsetWidth,p.height=p.offsetHeight});return g.observe(p),p.width=p.offsetWidth,p.height=p.offsetHeight,()=>g.disconnect()},[]),a.useEffect(()=>{function p(g){if(g.target.tagName==="INPUT"||g.target.tagName==="TEXTAREA"||(g.code==="Space"&&(d.current.spaceDown=g.type==="keydown",g.preventDefault()),g.type!=="keydown"))return;(g.ctrlKey||g.metaKey)&&(g.key==="z"&&(g.preventDefault(),l.undo()),g.key==="y"&&(g.preventDefault(),l.redo()),g.key==="s"&&(g.preventDefault(),l.saveNow()),g.key==="a"&&(g.preventDefault(),l.setSelection(Object.keys(l.session.objects)))),(g.key==="Delete"||g.key==="Backspace")&&l.selectedObjectIds.length>0&&l.deleteObjects(l.selectedObjectIds);const T={v:"select",p:"pen",h:"highlighter",e:"eraser",r:"rect",c:"ellipse",t:"text",s:"sticky",i:"image",a:"arrow",l:"laser"};!g.ctrlKey&&!g.metaKey&&T[g.key]&&l.setTool(T[g.key])}return window.addEventListener("keydown",p),window.addEventListener("keyup",p),()=>{window.removeEventListener("keydown",p),window.removeEventListener("keyup",p)}},[l]);const K=a.useCallback(p=>{const g=A.current.getBoundingClientRect(),T=p.clientX-g.left,P=p.clientY-g.top,{wx:z,wy:G}=$t(T,P,l.viewport);return{x:z,y:G,pressure:p.pressure??.5}},[l.viewport]),re=a.useCallback(p=>{if(r)return;p.target.setPointerCapture(p.pointerId);const g=K(p);if(p.button===1||d.current.spaceDown){d.current.panStart={x:p.clientX,y:p.clientY,vpX:l.viewport.x,vpY:l.viewport.y};return}const T=l.activeTool;if(d.current.active=!0,d.current.startX=g.x,d.current.startY=g.y,d.current.currentId=Te(),T==="pen"||T==="highlighter")d.current.currentPoints=[g];else if(T==="laser")d.current.laserPoints=[g];else if(T==="select"){const P=Object.values(l.session.objects).filter(z=>z.visible&&z.x<=g.x&&z.y<=g.y&&z.x+z.width>=g.x&&z.y+z.height>=g.y).sort((z,G)=>G.zIndex-z.zIndex)[0];P?p.shiftKey?l.setSelection([...l.selectedObjectIds,P.id]):l.setSelection([P.id]):l.setSelection([])}},[r,K,l]),oe=a.useCallback(p=>{const g=K(p);if(l.broadcastCursor(g.x,g.y),d.current.panStart){const{x:P,y:z,vpX:G,vpY:b}=d.current.panStart;l.setViewport({...l.viewport,x:G+(p.clientX-P),y:b+(p.clientY-z)});return}if(!d.current.active)return;const T=l.activeTool;if(T==="pen"||T==="highlighter"){const P=d.current.currentPoints;(P.length===0||Bt(P[P.length-1],g)>2)&&(d.current.currentPoints=[...P,g])}else if(T==="laser"){const P=d.current.laserPoints;d.current.laserPoints=[...P.slice(-40),g]}else if(T==="select"&&l.selectedObjectIds.length>0){const P=g.x-d.current.startX,z=g.y-d.current.startY;d.current.startX=g.x,d.current.startY=g.y,l.moveObjects(l.selectedObjectIds.map(G=>{const b=l.session.objects[G];return{id:G,x:b.x+P,y:b.y+z}}))}},[K,l]),ue=a.useCallback(p=>{if(d.current.panStart){d.current.panStart=null;return}if(!d.current.active)return;const g=K(p),T=l.activeTool,P=d.current.startX,z=d.current.startY,G=d.current.currentId,b=new Date;switch(d.current.active=!1,T){case"pen":case"highlighter":{const w=d.current.currentPoints;if(w.length<2)break;const ee={id:G,type:"stroke",x:Math.min(...w.map(Z=>Z.x)),y:Math.min(...w.map(Z=>Z.y)),width:Math.max(...w.map(Z=>Z.x))-Math.min(...w.map(Z=>Z.x)),height:Math.max(...w.map(Z=>Z.y))-Math.min(...w.map(Z=>Z.y)),rotation:0,zIndex:Object.keys(l.session.objects).length,locked:!1,visible:!0,createdBy:t.id,createdAt:b,points:w,color:D,strokeWidth:U,opacity:T==="highlighter"?.4:1,tool:T};l.addObject(ee),d.current.currentPoints=[];break}case"rect":case"ellipse":case"triangle":{const w=Math.min(P,g.x),ee=Math.min(z,g.y),Z=Math.abs(g.x-P),ie=Math.abs(g.y-z);if(Z<5||ie<5)break;const ce={rect:"rect",ellipse:"ellipse",triangle:"triangle"},ge={id:G,type:"shape",x:w,y:ee,width:Z,height:ie,rotation:0,zIndex:Object.keys(l.session.objects).length,locked:!1,visible:!0,createdBy:t.id,createdAt:b,shape:ce[T],fillColor:_,strokeColor:D,strokeWidth:U,opacity:1};l.addObject(ge);break}case"arrow":case"line":{const w={id:G,type:"connector",x:Math.min(P,g.x),y:Math.min(z,g.y),width:Math.abs(g.x-P),height:Math.abs(g.y-z),rotation:0,zIndex:Object.keys(l.session.objects).length,locked:!1,visible:!0,createdBy:t.id,createdAt:b,points:[{x:P,y:z},{x:g.x,y:g.y}],strokeColor:D,strokeWidth:U,arrowStart:"none",arrowEnd:T==="arrow"?"arrow":"none",curved:!1};l.addObject(w);break}case"text":{const w={id:G,type:"text",x:g.x,y:g.y,width:200,height:h+10,rotation:0,zIndex:Object.keys(l.session.objects).length,locked:!1,visible:!0,createdBy:t.id,createdAt:b,text:"Click to edit",fontSize:h,fontFamily:"sans-serif",fontWeight:"normal",fontStyle:"normal",textAlign:"left",color:D};l.addObject(w),W(G);break}case"sticky":{const w={id:G,type:"sticky",x:g.x,y:g.y,width:180,height:150,rotation:0,zIndex:Object.keys(l.session.objects).length,locked:!1,visible:!0,createdBy:t.id,createdAt:b,text:"Note...",backgroundColor:F,textColor:"#333",fontSize:14,authorId:t.id};l.addObject(w),W(G);break}case"frame":{const w=Math.min(P,g.x),ee=Math.min(z,g.y),Z=Math.abs(g.x-P),ie=Math.abs(g.y-z);if(Z<20||ie<20)break;const ce={id:G,type:"frame",x:w,y:ee,width:Z,height:ie,rotation:0,zIndex:0,locked:!1,visible:!0,createdBy:t.id,createdAt:b,name:`Frame ${Object.keys(l.session.objects).length+1}`,childIds:[],borderColor:"#8888"};l.addObject(ce);break}case"image":{const w=document.createElement("input");w.type="file",w.accept="image/*",w.onchange=()=>{var ie;const ee=(ie=w.files)==null?void 0:ie[0];if(!ee)return;const Z=new FileReader;Z.onload=ce=>{var ze;const ge=(ze=ce.target)==null?void 0:ze.result,pe=new Image;pe.onload=()=>{const Re=400/pe.width,ye={id:Te(),type:"image",x:g.x,y:g.y,width:pe.width*Re,height:pe.height*Re,rotation:0,zIndex:Object.keys(l.session.objects).length,locked:!1,visible:!0,createdBy:t.id,createdAt:new Date,url:ge,dataUrl:ge,originalWidth:pe.width,originalHeight:pe.height};l.addObject(ye)},pe.src=ge},Z.readAsDataURL(ee)},w.click();break}}},[K,l,t.id,D,U,_,h,F]),le=a.useCallback(p=>{if(p.preventDefault(),!p.ctrlKey&&!p.metaKey){l.setViewport({...l.viewport,x:l.viewport.x-p.deltaX,y:l.viewport.y-p.deltaY});return}const g=A.current.getBoundingClientRect(),T=p.clientX-g.left,P=p.clientY-g.top,G=-p.deltaY>0?1.1:.9,b=Math.min(8,Math.max(.1,l.viewport.scale*G));l.setViewport({scale:b,x:T-(T-l.viewport.x)*(b/l.viewport.scale),y:P-(P-l.viewport.y)*(b/l.viewport.scale)})},[l]),L=a.useCallback(p=>{if(p==="json"){const z=JSON.stringify(l.session,null,2);m==null||m("json",z);const G=document.createElement("a");G.href=URL.createObjectURL(new Blob([z],{type:"application/json"})),G.download=`${l.session.title}.json`,G.click();return}const g=A.current;if(!g)return;const T=g.toDataURL("image/png");m==null||m("png",T);const P=document.createElement("a");P.href=T,P.download=`${l.session.title}.png`,P.click()},[l.session,m]);a.useEffect(()=>{j==null||j(l.session)},[l.session,j]),a.useEffect(()=>{function p(g){if(g.clipboardData){for(const T of Array.from(g.clipboardData.items))if(T.type.startsWith("image/")){const P=T.getAsFile();if(!P)continue;const z=new FileReader;z.onload=G=>{var ee;const b=(ee=G.target)==null?void 0:ee.result,w=new Image;w.onload=()=>{const ie=400/w.width,ce={id:Te(),type:"image",x:100,y:100,width:w.width*ie,height:w.height*ie,rotation:0,zIndex:Object.keys(l.session.objects).length,locked:!1,visible:!0,createdBy:t.id,createdAt:new Date,url:b,dataUrl:b,originalWidth:w.width,originalHeight:w.height};l.addObject(ce)},w.src=b},z.readAsDataURL(P);break}}}return window.addEventListener("paste",p),()=>window.removeEventListener("paste",p)},[l,t.id]);const V=I?l.session.objects[I]:null,ne=a.useMemo(()=>V?$e(V.x,V.y,l.viewport):null,[V,l.viewport]),se=["#fef08a","#bfdbfe","#bbf7d0","#fecaca","#e9d5ff","#fed7aa"],ae=a.useMemo(()=>{var g;const p={};for(const T of Lt)(p[g=T.group]??(p[g]=[])).push(T);return Object.values(p)},[]);return e.jsxs("div",{className:v,"data-testid":O,style:{position:"relative",display:"flex",flexDirection:"column",width:"100%",height:"100%",overflow:"hidden",background:"#f5f5f5",fontFamily:"system-ui, sans-serif",...R},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",background:"#fff",borderBottom:"1px solid #e5e7eb",flexShrink:0,flexWrap:"wrap"},children:[ae.map((p,g)=>e.jsxs(a.Fragment,{children:[g>0&&e.jsx("div",{style:{width:1,height:24,background:"#e5e7eb",margin:"0 2px"}}),p.map(T=>e.jsx("button",{onClick:()=>l.setTool(T.id),title:`${T.label}`,style:{padding:"4px 7px",border:`1.5px solid ${l.activeTool===T.id?"#6366f1":"transparent"}`,borderRadius:6,background:l.activeTool===T.id?"#eef2ff":"transparent",cursor:"pointer",fontSize:15,minWidth:30,color:l.activeTool===T.id?"#4f46e5":"#374151"},children:T.icon},T.id))]},g)),e.jsx("div",{style:{width:1,height:24,background:"#e5e7eb",margin:"0 4px"}}),e.jsxs("label",{title:"Stroke color",style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[e.jsx("span",{style:{fontSize:11,color:"#6b7280"},children:"Color"}),e.jsx("input",{type:"color",value:D,onChange:p=>$(p.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}})]}),e.jsxs("label",{title:"Fill color",style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[e.jsx("span",{style:{fontSize:11,color:"#6b7280"},children:"Fill"}),e.jsx("input",{type:"color",value:_??"#ffffff",onChange:p=>S(p.target.value==="#ffffff"?void 0:p.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}}),e.jsx("button",{onClick:()=>S(void 0),style:{fontSize:11,padding:"1px 5px",border:"1px solid #e5e7eb",borderRadius:4,cursor:"pointer",background:_?"#fff":"#f3f4f6"},children:"No fill"})]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:4},children:[e.jsx("span",{style:{fontSize:11,color:"#6b7280"},children:"Width"}),e.jsx("input",{type:"range",min:1,max:24,step:1,value:U,onChange:p=>E(Number(p.target.value)),style:{width:70}}),e.jsx("span",{style:{fontSize:11,color:"#6b7280",minWidth:20},children:U})]}),l.activeTool==="sticky"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{style:{fontSize:11,color:"#6b7280"},children:"Note:"}),se.map(p=>e.jsx("button",{onClick:()=>J(p),style:{width:20,height:20,background:p,border:`2px solid ${F===p?"#6366f1":"#e5e7eb"}`,borderRadius:4,cursor:"pointer"}},p))]}),e.jsx("div",{style:{flex:1}}),e.jsx("button",{onClick:l.undo,disabled:!l.canUndo,title:"Undo (Ctrl+Z)",style:de(!l.canUndo),children:"โฉ"}),e.jsx("button",{onClick:l.redo,disabled:!l.canRedo,title:"Redo (Ctrl+Y)",style:de(!l.canRedo),children:"โช"}),e.jsx("div",{style:{width:1,height:24,background:"#e5e7eb"}}),e.jsxs("span",{style:{fontSize:11,color:"#6b7280",minWidth:42,textAlign:"center"},children:[Math.round(l.viewport.scale*100),"%"]}),e.jsx("button",{onClick:()=>l.setViewport({x:0,y:0,scale:1}),style:de(),title:"Reset zoom",children:"โ"}),o&&e.jsx("button",{onClick:()=>H(p=>!p),style:de(!1,Y),title:"Layers",children:"โ"}),e.jsx("button",{onClick:()=>{const p={id:Te(),sessionId:l.session.id,type:"object:update",userId:t.id,timestamp:new Date,payload:{...l.session,gridEnabled:!l.session.gridEnabled}};i==null||i(p)},style:de(!1,l.session.gridEnabled),title:"Toggle grid",children:"#"}),u&&e.jsx("button",{onClick:()=>M(p=>p==="vector"?null:"vector"),style:de(!1,B==="vector"),title:"Vector Editor panel",children:"Vฮต"}),x&&e.jsx("button",{onClick:()=>M(p=>p==="diagram"?null:"diagram"),style:de(!1,B==="diagram"),title:"Diagram Editor panel",children:"โ"}),e.jsx("button",{onClick:()=>void l.saveNow(),style:de(),title:"Save (Ctrl+S)",children:l.isDirty?"๐พ*":"๐พ"}),c&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>L("png"),style:de(),title:"Export PNG",children:"PNGโ"}),e.jsx("button",{onClick:()=>L("json"),style:de(),title:"Export JSON",children:"JSONโ"})]})]}),e.jsxs("div",{style:{display:"flex",flex:1,overflow:"hidden",position:"relative"},children:[e.jsx("canvas",{ref:A,style:{flex:1,display:"block",cursor:Xt(l.activeTool,d.current.spaceDown)},onPointerDown:re,onPointerMove:oe,onPointerUp:ue,onWheel:le,onContextMenu:p=>p.preventDefault()}),o&&Y&&e.jsx(Gt,{layers:l.layers,objects:l.session.objects,onAdd:()=>l.addLayer(`Layer ${l.layers.length+1}`),onUpdate:p=>l.updateLayer(p),onDelete:p=>l.deleteLayer(p)}),B&&e.jsxs("div",{style:{position:"absolute",right:Y?220:0,top:0,bottom:0,width:360,background:"#fff",borderLeft:"1px solid #e5e7eb",padding:12,overflowY:"auto"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[e.jsx("strong",{style:{fontSize:13},children:B==="vector"?"Vector Editor":"Diagram Editor"}),e.jsx("button",{onClick:()=>M(null),style:{border:"none",background:"none",cursor:"pointer",fontSize:16},children:"โ"})]}),e.jsx("p",{style:{fontSize:12,color:"#6b7280"},children:B==="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."}),e.jsx("div",{id:`wb-integration-${B}`,style:{width:"100%",height:400}})]})]}),l.collaborators.length>1&&e.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:[e.jsx("span",{children:"Collaborators:"}),l.collaborators.map(p=>e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:3},children:[e.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:p.color,display:"inline-block"}}),p.user.name]},p.user.id)),l.isDirty&&e.jsx("span",{style:{marginLeft:"auto",color:"#f59e0b"},children:"โ unsaved"}),l.lastSavedAt&&!l.isDirty&&e.jsxs("span",{style:{marginLeft:"auto",color:"#10b981"},children:["โ Saved ",l.lastSavedAt.toLocaleTimeString()]})]}),V&&ne&&e.jsx("textarea",{autoFocus:!0,defaultValue:V.text,onBlur:p=>{const g={...V,text:p.target.value,updatedAt:new Date,updatedBy:t.id};l.updateObject(g),W(null)},style:{position:"absolute",left:ne.sx,top:ne.sy,minWidth:V.width*l.viewport.scale,minHeight:V.height*l.viewport.scale,fontSize:(V.fontSize??14)*l.viewport.scale,fontFamily:"sans-serif",background:V.type==="sticky"?V.backgroundColor:"rgba(255,255,255,0.95)",border:"2px solid #6366f1",borderRadius:4,padding:6,resize:"both",zIndex:1e3,color:V.type==="sticky"?V.textColor:V.color}})]})}function Gt({layers:n,objects:t,onAdd:i,onUpdate:s,onDelete:r}){return e.jsxs("div",{style:{width:200,borderLeft:"1px solid #e5e7eb",background:"#fff",display:"flex",flexDirection:"column",padding:8,gap:4,overflowY:"auto",flexShrink:0},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[e.jsx("strong",{style:{fontSize:12,color:"#374151"},children:"Layers"}),e.jsx("button",{onClick:i,style:{fontSize:16,border:"none",background:"none",cursor:"pointer",color:"#6366f1"},title:"Add layer",children:"+"})]}),[...n].reverse().map(o=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",borderRadius:5,background:"#f9fafb",opacity:o.visible?1:.5},children:[e.jsx("button",{onClick:()=>s({id:o.id,visible:!o.visible}),title:"Toggle visibility",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,color:o.visible?"#374151":"#9ca3af"},children:o.visible?"๐":"๐ซ"}),e.jsx("button",{onClick:()=>s({id:o.id,locked:!o.locked}),title:"Toggle lock",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0},children:o.locked?"๐":"๐"}),e.jsx("span",{style:{flex:1,fontSize:11,color:"#374151",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o.name}),e.jsx("span",{style:{fontSize:10,color:"#9ca3af"},children:o.objectIds.filter(c=>c in t).length}),n.length>1&&e.jsx("button",{onClick:()=>r(o.id),title:"Delete layer",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,color:"#ef4444"},children:"ร"})]},o.id))]})}function de(n=!1,t=!1){return{padding:"4px 8px",border:`1.5px solid ${t?"#6366f1":"#e5e7eb"}`,borderRadius:6,background:t?"#eef2ff":"#fff",cursor:n?"default":"pointer",opacity:n?.35:1,fontSize:13,color:t?"#4f46e5":"#374151",fontWeight:t?600:400}}function Xt(n,t){if(t)return"grab";switch(n){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:n,label:t,active:i,badge:s,onClick:r}){return e.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[e.jsxs("button",{title:t,onClick:r,style:{width:44,height:44,borderRadius:10,border:"none",background:i?"rgba(255,255,255,0.2)":"transparent",color:"#fff",fontSize:20,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",position:"relative"},children:[n,s!=null&&s>0&&e.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:s>99?"99+":s})]}),e.jsx("span",{style:{fontSize:9,color:"rgba(255,255,255,0.7)",letterSpacing:"0.03em"},children:t})]})}function qt({team:n,activeChannelId:t,onSelectChannel:i}){var c;const[s,r]=a.useState(!1),o=n.channels.reduce((f,u)=>f+u.unreadCount,0);return e.jsxs("div",{className:"nice-workspace-team",children:[e.jsxs("button",{onClick:()=>r(f=>!f),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:[e.jsx("span",{style:{fontSize:10,color:"#9ca3af"},children:s?"โถ":"โผ"}),e.jsx("div",{style:{width:20,height:20,borderRadius:4,background:n.avatarUrl?`url(${n.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:9,flexShrink:0},children:!n.avatarUrl&&((c=n.name[0])==null?void 0:c.toUpperCase())}),e.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.name}),!s&&o>0&&e.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:o})]}),!s&&n.channels.map(f=>e.jsxs("button",{onClick:()=>i(n.id,f.id),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 10px 5px 34px",background:f.id===t?"#ede9fe":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:f.unreadCount>0?"#111827":"#4b5563",fontSize:13,fontWeight:f.unreadCount>0?600:400},children:[e.jsx("span",{style:{color:"#9ca3af",fontSize:12},children:f.isPrivate?"๐":"#"}),e.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f.name}),f.mentionCount>0&&e.jsxs("span",{style:{background:"#ef4444",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:["@",f.mentionCount]}),f.unreadCount>0&&f.mentionCount===0&&e.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700},children:f.unreadCount})]},f.id))]})}function Vt({conversation:n,partner:t,isActive:i,onClick:s}){var o;const r=(t==null?void 0:t.displayName)??(t==null?void 0:t.name)??n.name??"Group";return e.jsxs("button",{onClick:s,style:{display:"flex",alignItems:"center",gap:8,padding:"5px 10px",background:i?"#ede9fe":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:n.unreadCount>0?"#111827":"#4b5563",fontWeight:n.unreadCount>0?600:400,fontSize:13},children:[e.jsxs("div",{style:{position:"relative",flexShrink:0},children:[e.jsx("div",{style:{width:24,height:24,borderRadius:"50%",background:t!=null&&t.avatarUrl?`url(${t.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:10},children:!(t!=null&&t.avatarUrl)&&((o=r[0])==null?void 0:o.toUpperCase())}),t&&e.jsx(fe,{status:t.presence.status,size:"xs",style:{position:"absolute",bottom:-1,right:-1}})]}),e.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),n.unreadCount>0&&e.jsx("span",{style:{background:"#6366f1",color:"#fff",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700,flexShrink:0},children:n.unreadCount})]})}function xt({currentUser:n,users:t,teams:i,conversations:s,messages:r,activeCall:o,incomingCall:c,meetings:f,transport:u,rtcConfig:x,enableCalls:m=!0,enableMeetings:j=!0,enableScreenSharing:C=!0,enableWhiteboard:v=!1,storageConfig:R,onSendMessage:O,onEditMessage:l,onDeleteMessage:A,onReactToMessage:N,onPinMessage:Y,onLoadMoreMessages:H,onMarkAsRead:D,onStartCall:$,onAcceptCall:U,onDeclineCall:E,onEndCall:_,onMuteAudio:S,onMuteVideo:h,onStartScreenShare:k,onStopScreenShare:F,className:J,style:I,id:W,"data-testid":B}){var z,G;const[M,d]=a.useState("teams"),[y,q]=a.useState(null),[X,Q]=a.useState(""),[K,re]=a.useState(null),oe=()=>{K||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:n.id,permissions:"edit"})},ue=a.useMemo(()=>{const b=new Map;return t.forEach(w=>b.set(w.id,w)),b},[t]),le=a.useMemo(()=>_e(s),[s]),L=a.useMemo(()=>s.reduce((b,w)=>b+w.mentionCount,0),[s]),V=a.useMemo(()=>{if(y!=null&&y.channelId)for(const b of i){const w=b.channels.find(ee=>ee.id===y.channelId);if(w)return w}},[i,y]),ne=a.useMemo(()=>{if(y!=null&&y.teamId)return i.find(b=>b.id===y.teamId)},[i,y]),se=a.useMemo(()=>s.find(b=>b.id===(y==null?void 0:y.conversationId))??null,[s,y]),ae=a.useMemo(()=>{const b=(y==null?void 0:y.channelId)??(y==null?void 0:y.conversationId);return b?r[b]??[]:[]},[r,y]),p=!!c&&!o,g=!!o,T=a.useMemo(()=>s.filter(b=>b.type==="dm"||b.type==="group"),[s]),P=a.useMemo(()=>{if(!X)return T;const b=X.toLowerCase();return T.filter(w=>{var Z;const ee=ue.get(w.participantIds.find(ie=>ie!==n.id)??"");return(ee==null?void 0:ee.name.toLowerCase().includes(b))||((Z=w.name)==null?void 0:Z.toLowerCase().includes(b))})},[T,X,ue,n.id]);return e.jsxs("div",{id:W,"data-testid":B,className:`nice-teams-workspace${J?` ${J}`:""}`,style:{display:"flex",height:"100%",overflow:"hidden",background:"#fff",position:"relative",...I},children:[e.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:[e.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:n.avatarUrl?`url(${n.avatarUrl}) center/cover`:"#818cf8",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:14,marginBottom:8,flexShrink:0},children:!n.avatarUrl&&((z=n.name[0])==null?void 0:z.toUpperCase())}),e.jsx(be,{icon:"โก",label:"Activity",active:M==="activity",badge:L,onClick:()=>d("activity")}),e.jsx(be,{icon:"๐ฌ",label:"Chat",active:M==="chat",badge:le,onClick:()=>d("chat")}),e.jsx(be,{icon:"๐ฅ",label:"Teams",active:M==="teams",onClick:()=>d("teams")}),m&&e.jsx(be,{icon:"๐",label:"Calls",active:M==="calls",onClick:()=>d("calls")}),j&&e.jsx(be,{icon:"๐
",label:"Meetings",active:M==="meetings",onClick:()=>d("meetings")}),e.jsx(be,{icon:"๐",label:"Files",active:M==="files",onClick:()=>d("files")}),v&&e.jsx(be,{icon:"๐๏ธ",label:"Board",active:M==="whiteboard",onClick:()=>{d("whiteboard"),oe()}})]}),e.jsxs("div",{className:"nice-workspace-sidebar",style:{width:240,flexShrink:0,borderRight:"1px solid #e5e7eb",display:"flex",flexDirection:"column",background:"#fafafa",overflow:"hidden"},children:[e.jsxs("div",{style:{padding:"12px 10px 8px",flexShrink:0},children:[e.jsx("div",{style:{fontWeight:700,fontSize:15,color:"#374151",marginBottom:8,textTransform:"capitalize"},children:M}),e.jsx("input",{type:"search",value:X,onChange:b=>Q(b.target.value),placeholder:`Search ${M}โฆ`,style:{width:"100%",padding:"5px 10px",border:"1px solid #e5e7eb",borderRadius:16,fontSize:12,outline:"none",boxSizing:"border-box",background:"#fff"}})]}),e.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[M==="teams"&&e.jsx(e.Fragment,{children:i.map(b=>e.jsx(qt,{team:b,activeChannelId:y==null?void 0:y.channelId,onSelectChannel:(w,ee)=>{q({type:"channel",teamId:w,channelId:ee}),D==null||D(ee)}},b.id))}),M==="chat"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:"#9ca3af",fontWeight:600,letterSpacing:"0.05em"},children:"DIRECT MESSAGES"}),P.map(b=>{const w=ue.get(b.participantIds.find(ee=>ee!==n.id)??"");return e.jsx(Vt,{conversation:b,partner:w,isActive:(y==null?void 0:y.conversationId)===b.id,onClick:()=>{q({type:b.type==="dm"?"dm":"group",conversationId:b.id}),D==null||D(b.id)}},b.id)})]}),M==="activity"&&e.jsxs("div",{style:{padding:12},children:[s.filter(b=>b.unreadCount>0).map(b=>e.jsxs("button",{onClick:()=>{d(b.type==="channel"?"teams":"chat"),q({type:b.type==="channel"?"channel":"dm",conversationId:b.id})},style:{display:"block",width:"100%",textAlign:"left",padding:"6px 0",background:"none",border:"none",cursor:"pointer",fontSize:13,color:"#374151"},children:[e.jsx("strong",{children:b.name??"Conversation"})," โ ",b.unreadCount," unread"]},b.id)),s.every(b=>b.unreadCount===0)&&e.jsx("p",{style:{color:"#9ca3af",fontSize:13,textAlign:"center",marginTop:24},children:"All caught up โ"})]}),M==="calls"&&e.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8},children:[e.jsx("button",{onClick:()=>$==null?void 0:$(t.map(b=>b.id).filter(b=>b!==n.id),"audio"),style:{background:"#6366f1",color:"#fff",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600},children:"๐ New audio call"}),e.jsx("button",{onClick:()=>$==null?void 0:$(t.map(b=>b.id).filter(b=>b!==n.id),"video"),style:{background:"#6366f1",color:"#fff",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600},children:"๐น New video call"})]}),M==="meetings"&&e.jsxs("div",{style:{padding:12},children:[(f??[]).map(b=>e.jsxs("div",{style:{padding:"8px 10px",border:"1px solid #e5e7eb",borderRadius:8,marginBottom:8},children:[e.jsx("div",{style:{fontWeight:600,fontSize:13},children:b.title}),e.jsx("div",{style:{fontSize:11,color:"#6b7280",marginTop:2},children:b.scheduledStart.toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}),e.jsx("button",{onClick:()=>{},style:{marginTop:6,background:"#6366f1",color:"#fff",border:"none",borderRadius:6,padding:"3px 10px",fontSize:12,cursor:"pointer"},children:"Join"})]},b.id)),(f??[]).length===0&&e.jsx("p",{style:{color:"#9ca3af",fontSize:13,textAlign:"center",marginTop:24},children:"No upcoming meetings"})]}),M==="files"&&e.jsx("div",{style:{padding:12},children:e.jsx("p",{style:{color:"#9ca3af",fontSize:13,textAlign:"center",marginTop:24},children:"No files shared yet"})}),M==="whiteboard"&&e.jsxs("div",{style:{padding:12},children:[e.jsxs("button",{onClick:()=>oe(),style:{width:"100%",background:"#6366f1",color:"#fff",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,marginBottom:8},children:["๐๏ธ ",K?"Open whiteboard":"New whiteboard"]}),K&&e.jsxs("div",{style:{padding:"6px 10px",border:"1px solid #e5e7eb",borderRadius:6,fontSize:12,color:"#374151"},children:[e.jsx("div",{style:{fontWeight:500},children:K.title}),e.jsxs("div",{style:{color:"#9ca3af",marginTop:2},children:[Object.keys(K.objects).length," objects"]})]})]})]})]}),e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[(y==null?void 0:y.type)==="channel"&&V?e.jsx(pt,{channel:V,messages:ae,users:(ne==null?void 0:ne.members)??t,currentUser:n,team:ne,onSendMessage:O,onEditMessage:l,onDeleteMessage:A,onReactToMessage:N,onPinMessage:Y,onLoadMoreMessages:H,onStartCall:m?$:void 0,style:{height:"100%"}}):((y==null?void 0:y.type)==="dm"||(y==null?void 0:y.type)==="group")&&se?e.jsx(Ie,{conversation:se,messages:ae,users:t,currentUser:n,onSendMessage:O,onEditMessage:l,onDeleteMessage:A,onReactToMessage:N,onPinMessage:Y,onLoadMoreMessages:H,onStartCall:m?$:void 0,style:{height:"100%"}}):M==="whiteboard"&&K?e.jsx(He,{session:K,currentUser:n,storageConfig:R,onSessionUpdate:b=>re(b),style:{height:"100%"}}):e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"#9ca3af",gap:12},children:[e.jsx("span",{style:{fontSize:56},children:M==="teams"?"๐ฅ":M==="chat"?"๐ฌ":M==="calls"?"๐":M==="whiteboard"?"๐๏ธ":"โก"}),e.jsx("span",{style:{fontSize:17,fontWeight:500},children:M==="teams"?"Select a channel to get started":M==="chat"?"Select a conversation":M==="calls"?"Start or join a call":M==="whiteboard"?'Click "New whiteboard" to start':"Nothing selected"})]}),g&&o&&e.jsx("div",{style:{position:"absolute",inset:0,zIndex:50},children:o.participants.length>2?e.jsx(Ke,{session:o,currentUser:n,enableScreenSharing:C,onEndCall:_,onMuteAudio:S,onMuteVideo:h,onStartScreenShare:k,onStopScreenShare:F}):e.jsx(Fe,{session:o,currentUser:n,enableScreenSharing:C,onEndCall:_,onMuteAudio:S,onMuteVideo:h,onStartScreenShare:k,onStopScreenShare:F})})]}),p&&c&&e.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:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:12},children:[e.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:c.caller.avatarUrl?`url(${c.caller.avatarUrl}) center/cover`:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:16},children:!c.caller.avatarUrl&&((G=c.caller.name[0])==null?void 0:G.toUpperCase())}),e.jsxs("div",{children:[e.jsx("div",{style:{fontWeight:600},children:c.caller.displayName??c.caller.name}),e.jsxs("div",{style:{fontSize:12,color:"rgba(255,255,255,0.6)"},children:["Incoming ",c.callType," call"]})]})]}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("button",{onClick:()=>E==null?void 0:E(c.callId),style:{flex:1,background:"#ef4444",color:"#fff",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13},children:"๐ต Decline"}),e.jsx("button",{onClick:()=>U==null?void 0:U(c.callId),style:{flex:1,background:"#22c55e",color:"#fff",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13},children:"๐ Accept"})]})]})]})}const Jt={"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 Qt({props:n,onExpand:t}){const[i,s]=a.useState(!1),{bubblePosition:r="bottom-right",bubbleLabel:o,currentUser:c,users:f,conversations:u=[],messages:x={},onSendMessage:m,onReactToMessage:j,onPinMessage:C,onDeleteMessage:v,onEditMessage:R,onLoadMoreMessages:O,onStartCall:l}=n,A=Jt[r],N=u[0]??null,Y=N?x[N.id]??[]:[];return e.jsxs("div",{style:{position:"fixed",zIndex:9999,...A},children:[i&&N&&e.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:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",background:"#6366f1",color:"#fff",flexShrink:0},children:[e.jsx("span",{style:{fontWeight:700,fontSize:15},children:o??"Chat"}),e.jsxs("div",{style:{display:"flex",gap:4},children:[e.jsx("button",{onClick:()=>t("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:"โ"}),e.jsx("button",{onClick:()=>s(!1),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",fontSize:18},children:"ร"})]})]}),e.jsx(Ie,{conversation:N,messages:Y,users:f,currentUser:c,showHeader:!1,onSendMessage:m,onEditMessage:R,onDeleteMessage:v,onReactToMessage:j,onPinMessage:C,onLoadMoreMessages:O,onStartCall:l,style:{flex:1}})]}),e.jsx("button",{onClick:()=>s(H=>!H),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:i?"Close chat":o??"Open chat",children:i?"โ":"๐ฌ"})]})}function Zt({call:n,onAccept:t,onDecline:i}){return e.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:[e.jsx("div",{style:{fontSize:28},children:n.callType==="video"?"๐น":"๐"}),e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{style:{fontWeight:600,fontSize:14},children:n.caller.displayName??n.caller.name}),e.jsxs("div",{style:{fontSize:12,color:"rgba(255,255,255,0.6)"},children:["Incoming ",n.callType," callโฆ"]})]}),e.jsx("button",{onClick:i,style:{background:"#ef4444",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",fontSize:18,color:"#fff"},title:"Decline",children:"๐ต"}),e.jsx("button",{onClick:t,style:{background:"#22c55e",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",fontSize:18,color:"#fff"},title:"Accept",children:"๐"})]})}function bt(n){const{mode:t,currentUser:i,users:s,conversations:r=[],messages:o={},teams:c=[],meetings:f,activeCall:u,incomingCall:x,transport:m="webrtc",rtcConfig:j,onSendMessage:C,onEditMessage:v,onDeleteMessage:R,onReactToMessage:O,onPinMessage:l,onLoadMoreMessages:A,onMarkAsRead:N,onStartCall:Y,onAcceptCall:H,onDeclineCall:D,onEndCall:$,onMuteAudio:U,onMuteVideo:E,onStartScreenShare:_,onStopScreenShare:S,onRaiseHand:h,onModeChange:k,enableScreenSharing:F=!0,enableMeetings:J=!0,enableWhiteboard:I=!1,storageConfig:W,encryptionConfig:B,className:M,style:d,id:y,"data-testid":q}=n,[X,Q]=a.useState(t),[K,re]=a.useState(null),oe=a.useMemo(()=>({id:`wb-${i.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:i.id,permissions:"edit"}),[i.id]),[ue,le]=a.useState(u??null),[L,V]=a.useState(x??null),ne=u??ue,se=x??L;a.useEffect(()=>{Q(t)},[t]),a.useEffect(()=>{u!==void 0&&le(u)},[u]),a.useEffect(()=>{x!==void 0&&V(x)},[x]);const{state:ae,startCall:p,acceptCall:g,declineCall:T,endCall:P,toggleMic:z,toggleCamera:G,startScreenShare:b,stopScreenShare:w}=ft({currentUser:i,transport:m,rtcConfig:j,onCallEnded:te=>{le(null),$==null||$(te)},onIncomingCall:te=>{V(te)}}),ee=a.useCallback(te=>{Q(te),k==null||k(te)},[k]),Z=a.useCallback(async(te,Ve)=>{if(Y){await Y(te,Ve);return}const wt=await p(te,Ve);le(wt),Q(te.length>2?"conference":"call")},[Y,p]),ie=a.useCallback(async()=>{var te;H&&se?await H(se.callId):await g(),V(null),Q((te=ae.activeCall)!=null&&te.participants&&ae.activeCall.participants.length>2?"conference":"call")},[H,se,g,ae.activeCall]),ce=a.useCallback(()=>{D&&se?D(se.callId):T(),V(null)},[D,se,T]),ge=a.useCallback(te=>{$?$(te):P(),le(null),Q(t)},[$,P,t]),pe=a.useCallback(te=>{z(),U==null||U(te)},[z,U]),ze=a.useCallback(te=>{G(),E==null||E(te)},[G,E]),qe=a.useCallback(async()=>{await b(),await(_==null?void 0:_())},[b,_]),Re=a.useCallback(()=>{w(),S==null||S()},[w,S]),ye={onSendMessage:C,onEditMessage:v,onDeleteMessage:R,onReactToMessage:O,onPinMessage:l,onLoadMoreMessages:A,onMarkAsRead:N,onStartCall:Z,onEndCall:ge,onMuteAudio:pe,onMuteVideo:ze,onStartScreenShare:qe,onStopScreenShare:Re,onRaiseHand:h},he=ne?ne.participants.length>2?"conference":"call":X,jt={width:"100%",height:"100%",position:"relative",...d};return e.jsxs("div",{id:y,"data-testid":q,className:`nice-communication nice-communication--${he}${M?` ${M}`:""}`,style:jt,children:[se&&he!=="workspace"&&e.jsx(Zt,{call:se,onAccept:ie,onDecline:ce}),he==="bubble"&&e.jsx(Qt,{props:n,onExpand:ee}),he==="chat"&&r.length>0&&e.jsx(Ie,{conversation:r[0],messages:o[r[0].id]??[],users:s,currentUser:i,...ye,style:{height:"100%"}}),he==="messenger"&&e.jsx(ut,{conversations:r,messages:o,users:s,currentUser:i,teams:c,...ye,onAcceptCall:H,onDeclineCall:D,style:{height:"100%"}}),he==="workspace"&&e.jsx(xt,{currentUser:i,users:s,teams:c,conversations:r,messages:o,meetings:f,activeCall:ne??void 0,incomingCall:se??void 0,transport:m,rtcConfig:j,enableCalls:!0,enableMeetings:J,enableScreenSharing:F,...ye,onAcceptCall:ie,onDeclineCall:ce,style:{height:"100%"}}),he==="call"&&ne&&e.jsx(Fe,{session:ne,currentUser:i,localStream:ae.localStream??void 0,enableScreenSharing:F,...ye,style:{height:"100%"}}),he==="conference"&&ne&&e.jsx(Ke,{session:ne,currentUser:i,localStream:ae.localStream??void 0,enableScreenSharing:F,...ye,style:{height:"100%"}}),he==="whiteboard"&&I&&e.jsx(He,{session:K??oe,currentUser:i,storageConfig:W,onSessionUpdate:te=>re(te),style:{height:"100%"}})]})}const en={messages:"Messages",attachments:"Attachments","whiteboard-snapshots":"Whiteboard snapshots",recordings:"Recordings",transcripts:"Transcripts",documents:"Documents","call-logs":"Call logs","audit-logs":"Audit logs"},tt={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"},tn={messages:"Messages",attachments:"Attachments",whiteboard:"Whiteboard",recordings:"Recordings",documents:"Documents",calls:"Calls (metadata)",presence:"Presence data",all:"Everything"},nn=["days","weeks","months","years","forever"];function nt(n){if(n===0)return"0 B";const t=1024,i=["B","KB","MB","GB"],s=Math.floor(Math.log(n)/Math.log(t));return`${(n/Math.pow(t,s)).toFixed(1)} ${i[s]}`}function it({value:n,onChange:t,disabled:i=!1}){return e.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[e.jsx("input",{type:"number",min:1,max:9999,value:n.unit==="forever"?"":n.value,disabled:i||n.unit==="forever",onChange:s=>t({...n,value:Math.max(1,Number(s.target.value))}),style:{width:60,padding:"3px 6px",border:"1px solid #d1d5db",borderRadius:5,fontSize:12}}),e.jsx("select",{value:n.unit,disabled:i,onChange:s=>t({...n,unit:s.target.value}),style:{padding:"3px 6px",border:"1px solid #d1d5db",borderRadius:5,fontSize:12},children:nn.map(s=>e.jsx("option",{value:s,children:s},s))})]})}function sn({config:n,onChange:t}){const i=n.retentionRules.length>0?n.retentionRules:Ye;function s(r,o){const c=i.map(f=>f.dataType===r?{...f,...o}:f);t({...n,retentionRules:c})}return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.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."}),e.jsxs("div",{style:we,children:[e.jsx("label",{style:ke,children:"Storage provider"}),e.jsxs("select",{value:n.provider,onChange:r=>t({...n,provider:r.target.value}),style:me,children:[e.jsx("option",{value:"indexeddb",children:"IndexedDB (browser)"}),e.jsx("option",{value:"localstorage",children:"LocalStorage (browser)"}),e.jsx("option",{value:"server",children:"Server"}),e.jsx("option",{value:"custom",children:"Custom adapter"})]})]}),n.provider==="server"&&e.jsxs("div",{style:we,children:[e.jsx("label",{style:ke,children:"Server URL"}),e.jsx("input",{type:"url",value:n.serverUrl??"",onChange:r=>t({...n,serverUrl:r.target.value}),placeholder:"https://your-api.example.com/storage",style:me})]}),e.jsx("hr",{style:{border:"none",borderTop:"1px solid #e5e7eb",margin:"4px 0"}}),e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12},children:[e.jsx("thead",{children:e.jsxs("tr",{style:{background:"#f9fafb"},children:[e.jsx("th",{style:Se,children:"Data type"}),e.jsx("th",{style:Se,children:"Active period"}),e.jsx("th",{style:Se,children:"Archive after"}),e.jsx("th",{style:Se,children:"Auto-delete"}),e.jsx("th",{style:Se,children:"User can delete"}),e.jsx("th",{style:Se,children:"Legal hold"})]})}),e.jsx("tbody",{children:i.map(r=>e.jsxs("tr",{style:{borderBottom:"1px solid #f3f4f6"},children:[e.jsx("td",{style:{...je,fontWeight:500,color:"#374151"},children:en[r.dataType]}),e.jsx("td",{style:je,children:e.jsx(it,{value:r.activePeriod,onChange:o=>s(r.dataType,{activePeriod:o})})}),e.jsx("td",{style:je,children:r.archivePeriod?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[e.jsx(it,{value:r.archivePeriod,onChange:o=>s(r.dataType,{archivePeriod:o})}),e.jsx("button",{onClick:()=>s(r.dataType,{archivePeriod:void 0}),style:{border:"none",background:"none",cursor:"pointer",color:"#ef4444",fontSize:14},title:"Remove archive period",children:"ร"})]}):e.jsx("button",{onClick:()=>s(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"})}),e.jsx("td",{style:{...je,textAlign:"center"},children:e.jsx("input",{type:"checkbox",checked:r.deleteAfterArchive,disabled:!r.archivePeriod,onChange:o=>s(r.dataType,{deleteAfterArchive:o.target.checked})})}),e.jsx("td",{style:{...je,textAlign:"center"},children:e.jsx("input",{type:"checkbox",checked:r.userCanDelete,onChange:o=>s(r.dataType,{userCanDelete:o.target.checked})})}),e.jsx("td",{style:{...je,textAlign:"center"},children:e.jsx("input",{type:"checkbox",checked:r.legalHoldEnabled??!1,onChange:o=>s(r.dataType,{legalHoldEnabled:o.target.checked})})})]},r.dataType))})]}),e.jsxs("div",{style:we,children:[e.jsx("label",{style:ke,children:"Storage quota"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("input",{type:"number",min:0,value:n.quota?Math.round(n.quota/1024/1024):0,onChange:r=>t({...n,quota:Number(r.target.value)*1024*1024}),style:{...me,width:90},placeholder:"0"}),e.jsx("span",{style:{fontSize:12,color:"#6b7280"},children:"MB (0 = unlimited)"})]})]})]})}function rn({config:n,onChange:t}){const i=["messages","attachments","whiteboard","recordings","documents","calls","presence"];return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.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."}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[e.jsxs("label",{style:{position:"relative",display:"inline-block",width:42,height:22},children:[e.jsx("input",{type:"checkbox",checked:n.enabled,onChange:s=>t({...n,enabled:s.target.checked}),style:{opacity:0,width:0,height:0}}),e.jsx("span",{style:{position:"absolute",inset:0,borderRadius:22,background:n.enabled?"#6366f1":"#d1d5db",transition:"background 0.2s",cursor:"pointer"},children:e.jsx("span",{style:{position:"absolute",width:16,height:16,top:3,left:n.enabled?23:3,background:"#fff",borderRadius:"50%",transition:"left 0.2s"}})})]}),e.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#374151"},children:n.enabled?"๐ Encryption enabled":"๐ Encryption disabled"})]}),n.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:we,children:[e.jsx("label",{style:ke,children:"Default algorithm"}),e.jsx("select",{value:n.defaultAlgorithm,onChange:s=>t({...n,defaultAlgorithm:s.target.value}),style:me,children:Object.entries(tt).map(([s,r])=>e.jsx("option",{value:s,children:r},s))})]}),n.defaultAlgorithm==="E2E-ECDH-P384"&&e.jsxs("div",{style:we,children:[e.jsx("label",{style:ke,children:"Key exchange URL"}),e.jsx("input",{type:"url",value:n.keyExchangeUrl??"",onChange:s=>t({...n,keyExchangeUrl:s.target.value}),placeholder:"wss://your-server/e2e-key-exchange",style:me}),e.jsx("span",{style:{fontSize:11,color:"#6b7280",marginTop:2},children:"WebSocket endpoint for ECDH public key exchange between participants."})]}),e.jsxs("div",{style:we,children:[e.jsx("label",{style:ke,children:"External key (base64, optional)"}),e.jsx("input",{type:"password",value:n.keyMaterial??"",onChange:s=>t({...n,keyMaterial:s.target.value||void 0}),placeholder:"Leave empty to auto-generate",style:me}),e.jsx("span",{style:{fontSize:11,color:"#6b7280",marginTop:2},children:"Provide a pre-shared key for symmetric algorithms. Leave empty for automatic key generation."})]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:n.showIndicator??!0,onChange:s=>t({...n,showIndicator:s.target.checked})}),e.jsx("span",{style:{fontSize:12,color:"#374151"},children:"Show lock indicator in messages"})]}),e.jsx("hr",{style:{border:"none",borderTop:"1px solid #e5e7eb",margin:"4px 0"}}),e.jsx("strong",{style:{fontSize:12,color:"#374151"},children:"Per-scope overrides"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:i.map(s=>{var f;const r=(f=n.scopeOverrides)==null?void 0:f.find(u=>u.scope===s),o=(r==null?void 0:r.enabled)??!1,c=(r==null?void 0:r.algorithm)??n.defaultAlgorithm;return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 8px",background:"#f9fafb",borderRadius:6},children:[e.jsx("input",{type:"checkbox",checked:o,onChange:u=>{const x=[...(n.scopeOverrides??[]).filter(m=>m.scope!==s),{scope:s,algorithm:c,enabled:u.target.checked}];t({...n,scopeOverrides:x})}}),e.jsx("span",{style:{minWidth:120,fontSize:12,color:"#374151"},children:tn[s]}),e.jsx("select",{value:c,disabled:!o,onChange:u=>{const x=[...(n.scopeOverrides??[]).filter(m=>m.scope!==s),{scope:s,algorithm:u.target.value,enabled:o}];t({...n,scopeOverrides:x})},style:{...me,flex:1,opacity:o?1:.4},children:Object.entries(tt).map(([u,x])=>e.jsx("option",{value:u,children:x},u))})]},s)})})]})]})}function on({storageConfig:n,encryptionConfig:t,onStorageConfigChange:i,onEncryptionConfigChange:s,currentUsageBytes:r=0,showEncryption:o=!0,showRetention:c=!0,showQuota:f=!0,className:u,style:x,"data-testid":m}){const[j,C]=a.useState("retention"),v=t??{enabled:!1,defaultAlgorithm:"AES-GCM-256",showIndicator:!0},R={...n,retentionRules:n.retentionRules.length>0?n.retentionRules:Ye};return e.jsxs("div",{className:u,"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,...x},children:[e.jsxs("div",{children:[e.jsx("h3",{style:{margin:0,fontSize:16,color:"#111827"},children:"Storage & Privacy"}),e.jsx("p",{style:{margin:"4px 0 0",fontSize:12,color:"#6b7280"},children:"Manage data retention, encryption, and storage settings."})]}),f&&n.quota&&n.quota>0&&e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:12,color:"#6b7280",marginBottom:4},children:[e.jsx("span",{children:"Storage used"}),e.jsxs("span",{children:[nt(r)," / ",nt(n.quota)]})]}),e.jsx("div",{style:{height:6,background:"#e5e7eb",borderRadius:3},children:e.jsx("div",{style:{width:`${Math.min(100,r/n.quota*100)}%`,height:"100%",background:r/n.quota>.9?"#ef4444":"#6366f1",borderRadius:3,transition:"width 0.3s"}})})]}),c&&o&&e.jsx("div",{style:{display:"flex",gap:0,borderBottom:"1px solid #e5e7eb"},children:["retention","encryption"].map(O=>e.jsx("button",{onClick:()=>C(O),style:{padding:"8px 18px",border:"none",borderBottom:`2px solid ${j===O?"#6366f1":"transparent"}`,background:"none",cursor:"pointer",fontSize:13,fontWeight:j===O?600:400,color:j===O?"#4f46e5":"#6b7280",marginBottom:-1},children:O==="retention"?"๐ฆ Retention":"๐ Encryption"},O))}),e.jsxs("div",{children:[(j==="retention"||!o)&&c&&e.jsx(sn,{config:R,onChange:i??(()=>{})}),(j==="encryption"||!c)&&o&&e.jsx(rn,{config:v,onChange:s??(()=>{})})]})]})}const we={display:"flex",flexDirection:"column",gap:4},ke={fontSize:12,fontWeight:500,color:"#374151"},me={padding:"6px 8px",border:"1px solid #d1d5db",borderRadius:6,fontSize:13,color:"#111827",background:"#fff"},Se={padding:"6px 8px",textAlign:"left",fontSize:11,fontWeight:600,color:"#6b7280",borderBottom:"1px solid #e5e7eb"},je={padding:"8px 8px",verticalAlign:"middle"};function Oe(n){const t=Math.floor(n/1e3),i=Math.floor(t/60),s=Math.floor(i/60);return s>0?`${s}:${String(i%60).padStart(2,"0")}:${String(t%60).padStart(2,"0")}`:`${String(i).padStart(2,"0")}:${String(t%60).padStart(2,"0")}`}function ln(n){if(n===0)return"0 B";const t=1024,i=["B","KB","MB","GB"],s=Math.floor(Math.log(n)/Math.log(t));return`${(n/Math.pow(t,s)).toFixed(1)} ${i[s]}`}function an(n){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(n))}const cn={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 dn({segments:n,onClose:t,currentTimeMs:i=0}){return e.jsx("div",{style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center"},children:e.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:[e.jsxs("div",{style:{padding:"14px 18px",borderBottom:"1px solid #e5e7eb",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("strong",{style:{fontSize:14,color:"#111827"},children:"Transcript"}),e.jsx("button",{onClick:t,style:pn,children:"โ"})]}),e.jsx("div",{style:{flex:1,overflowY:"auto",padding:"12px 18px"},children:n.length===0?e.jsx("p",{style:{fontSize:13,color:"#9ca3af",textAlign:"center",padding:"32px 0"},children:"No transcript available."}):n.map(s=>{const r=i>=s.startMs&&i<s.endMs;return e.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:[e.jsxs("div",{style:{display:"flex",gap:10,alignItems:"baseline",marginBottom:3},children:[e.jsx("span",{style:{fontSize:11,fontWeight:600,color:"#4f46e5"},children:s.speakerName}),e.jsxs("span",{style:{fontSize:10,color:"#9ca3af"},children:[Oe(s.startMs)," โ ",Oe(s.endMs)]}),e.jsxs("span",{style:{fontSize:10,color:"#d1d5db"},children:[Math.round(s.confidence*100),"% conf."]})]}),e.jsx("p",{style:{margin:0,fontSize:13,color:"#374151",lineHeight:1.5},children:s.text})]},s.id)})})]})})}function mt({startedAt:n}){const[t,i]=a.useState(0);return a.useEffect(()=>{const s=new Date(n).getTime(),r=setInterval(()=>i(Date.now()-s),500);return()=>clearInterval(r)},[n]),e.jsx(e.Fragment,{children:Oe(t)})}function fn({rec:n,onDelete:t,onDownload:i}){const[s,r]=a.useState(!1),[o,c]=a.useState(0),f=a.useRef(null),u=cn[n.state],x=n.state==="recording"||n.state==="paused";return e.jsxs(e.Fragment,{children:[s&&n.transcript&&e.jsx(dn,{segments:n.transcript,currentTimeMs:o,onClose:()=>r(!1)}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 12px",borderBottom:"1px solid #f3f4f6",flexWrap:"wrap"},children:[e.jsx("div",{style:{fontSize:20},children:n.sessionType==="call"?"๐":n.sessionType==="meeting"?"๐ฅ":n.sessionType==="whiteboard"?"๐ผ๏ธ":"๐ฅ๏ธ"}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.title??`Recording ${n.id.slice(0,8)}`}),e.jsxs("div",{style:{fontSize:11,color:"#9ca3af",marginTop:2,display:"flex",gap:8},children:[e.jsx("span",{children:an(n.startedAt)}),e.jsx("span",{children:x?e.jsx(mt,{startedAt:n.startedAt}):n.durationMs!=null?Oe(n.durationMs):"โ"}),n.size!=null&&e.jsx("span",{children:ln(n.size)}),e.jsxs("span",{children:[n.participants.length," participants"]})]})]}),e.jsx("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:20,background:u.bg,color:u.fg,fontWeight:500,whiteSpace:"nowrap"},children:u.label}),n.url&&n.state==="ready"&&e.jsx("audio",{ref:f,src:n.url,controls:!0,onTimeUpdate:()=>{f.current&&c(f.current.currentTime*1e3)},style:{height:32,maxWidth:180}}),e.jsxs("div",{style:{display:"flex",gap:4},children:[n.transcript&&n.transcript.length>0&&e.jsx("button",{onClick:()=>r(!0),style:Be,title:"View transcript",children:"๐"}),n.state==="ready"&&e.jsx("button",{onClick:()=>i(n),style:Be,title:"Download",children:"โฌ"}),e.jsx("button",{onClick:()=>t(n.id),style:{...Be,color:"#ef4444"},title:"Delete",children:"๐"})]})]})]})}function un({recordings:n,onRecordingStart:t,onRecordingStop:i,onRecordingPause:s,onRecordingResume:r,onRecordingDelete:o,onRecordingDownload:c,activeRecordingId:f,sessionType:u="meeting",className:x,style:m,"data-testid":j}){const[C,v]=a.useState(n??[]),[R,O]=a.useState(""),[l,A]=a.useState("all");a.useEffect(()=>{n&&v(n)},[n]);const N=C.find(E=>E.id===f),Y=(N==null?void 0:N.state)==="recording",H=(N==null?void 0:N.state)==="paused",D=C.filter(E=>{const _=l==="all"||E.sessionType===l,S=!R||(E.title??"").toLowerCase().includes(R.toLowerCase())||E.id.includes(R);return _&&S}),$=a.useCallback(E=>{v(_=>_.filter(S=>S.id!==E)),o==null||o(E)},[o]),U=a.useCallback(E=>{if(c){c(E.id);return}if(E.url){const _=document.createElement("a");_.href=E.url,_.download=`${E.title??E.id}.${E.mimeType.includes("mp4")?"mp4":"webm"}`,_.click()}else if(E.blob){const _=URL.createObjectURL(E.blob),S=document.createElement("a");S.href=_,S.download=`${E.title??E.id}.webm`,S.click(),setTimeout(()=>URL.revokeObjectURL(_),5e3)}},[c]);return e.jsxs("div",{className:x,"data-testid":j,style:{display:"flex",flexDirection:"column",background:"#fff",borderRadius:10,border:"1px solid #e5e7eb",fontFamily:"system-ui, sans-serif",overflow:"hidden",...m},children:[e.jsxs("div",{style:{padding:"14px 16px",borderBottom:"1px solid #e5e7eb",display:"flex",gap:8,alignItems:"center"},children:[e.jsx("span",{style:{fontSize:16},children:"๐๏ธ"}),e.jsx("strong",{style:{fontSize:14,color:"#111827",flex:1},children:"Recordings"}),e.jsxs("span",{style:{fontSize:12,color:"#9ca3af"},children:[C.length," total"]})]}),e.jsxs("div",{style:{padding:"12px 16px",borderBottom:"1px solid #f3f4f6",display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[e.jsxs("select",{value:u,disabled:Y||H,onChange:()=>{},style:{...st,flex:0},children:[e.jsx("option",{value:"call",children:"Call"}),e.jsx("option",{value:"meeting",children:"Meeting"}),e.jsx("option",{value:"whiteboard",children:"Whiteboard"}),e.jsx("option",{value:"screen",children:"Screen"})]}),!Y&&!H?e.jsx("button",{onClick:t,style:{...Ae,background:"#ef4444",color:"#fff"},children:"โ Start recording"}):e.jsxs(e.Fragment,{children:[H?e.jsx("button",{onClick:r,style:{...Ae,background:"#6366f1",color:"#fff"},children:"โถ Resume"}):e.jsx("button",{onClick:s,style:{...Ae,background:"#f59e0b",color:"#fff"},children:"โ Pause"}),e.jsx("button",{onClick:i,style:{...Ae,background:"#374151",color:"#fff"},children:"โ Stop"}),N&&e.jsx("span",{style:{fontSize:12,color:"#9ca3af",marginLeft:4},children:e.jsx(mt,{startedAt:N.startedAt})})]})]}),e.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid #f3f4f6",display:"flex",gap:6,alignItems:"center"},children:[e.jsx("input",{type:"search",value:R,onChange:E=>O(E.target.value),placeholder:"Search recordingsโฆ",style:{flex:1,padding:"4px 8px",border:"1px solid #e5e7eb",borderRadius:6,fontSize:12}}),e.jsxs("select",{value:l,onChange:E=>A(E.target.value),style:st,children:[e.jsx("option",{value:"all",children:"All types"}),e.jsx("option",{value:"call",children:"Calls"}),e.jsx("option",{value:"meeting",children:"Meetings"}),e.jsx("option",{value:"whiteboard",children:"Whiteboard"}),e.jsx("option",{value:"screen",children:"Screen"})]})]}),e.jsx("div",{style:{flex:1,overflowY:"auto"},children:D.length===0?e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:32,gap:8,color:"#9ca3af"},children:[e.jsx("span",{style:{fontSize:32},children:"๐๏ธ"}),e.jsx("span",{style:{fontSize:13},children:"No recordings found"}),e.jsx("span",{style:{fontSize:11},children:"Start a recording above or adjust your search filters."})]}):D.map(E=>e.jsx(fn,{rec:E,onDelete:$,onDownload:U},E.id))})]})}const Be={border:"1px solid #e5e7eb",borderRadius:6,background:"#fff",cursor:"pointer",padding:"4px 8px",fontSize:14,lineHeight:1},Ae={border:"none",borderRadius:6,cursor:"pointer",padding:"6px 14px",fontSize:12,fontWeight:500},st={padding:"4px 6px",border:"1px solid #e5e7eb",borderRadius:6,fontSize:12,color:"#374151",background:"#fff"},pn={border:"none",background:"none",cursor:"pointer",fontSize:16,color:"#9ca3af",lineHeight:1,padding:4};function rt({participant:n,isFollowing:t,onClick:i}){const s=n.user.displayName??n.user.name,r=s.split(" ").map(o=>o[0]).slice(0,2).join("").toUpperCase();return e.jsxs("button",{onClick:i,title:`${s}${t?" (following)":""} โ ${n.editingRegion??"viewing"}`,style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:"50%",background:n.color,color:"#fff",fontSize:11,fontWeight:600,border:`2px solid ${t?"#fff":n.color}`,boxShadow:t?`0 0 0 2px ${n.color}`:"none",cursor:"pointer",flexShrink:0,transition:"transform 0.15s",position:"relative",overflow:"visible"},children:[n.user.avatarUrl?e.jsx("img",{src:n.user.avatarUrl,alt:r,style:{width:"100%",height:"100%",borderRadius:"50%",objectFit:"cover"}}):r,n.isActive&&e.jsx("span",{style:{position:"absolute",bottom:-1,right:-1,width:9,height:9,borderRadius:"50%",background:"#22c55e",border:"2px solid #fff"}})]})}function hn({participant:n,containerRect:t}){if(!n.cursorX||!n.cursorY||!t)return null;const i=n.cursorX,s=n.cursorY;return e.jsxs("div",{style:{position:"absolute",left:i,top:s,pointerEvents:"none",zIndex:9e3,transform:"translate(-2px, -2px)"},children:[e.jsx("svg",{width:16,height:20,style:{display:"block"},children:e.jsx("path",{d:"M2 2 L2 16 L6 12 L10 18 L12 17 L8 11 L14 11 Z",fill:n.color,stroke:"#fff",strokeWidth:1.5})}),e.jsx("div",{style:{background:n.color,color:"#fff",fontSize:10,padding:"1px 5px",borderRadius:3,whiteSpace:"nowrap",marginTop:-2,marginLeft:10},children:n.user.displayName??n.user.name})]})}function gn({count:n}){return n===0?null:e.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:["โ ๏ธ ",n," edit conflict",n>1?"s":""," โ auto-mergingโฆ"]})}function yn(){return e.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:e.jsx("div",{style:{background:"rgba(0,0,0,0.6)",color:"#fff",fontSize:12,padding:"4px 14px",borderRadius:20},children:"๐๏ธ View only"})})}function xn({pending:n}){return n===0?e.jsx("span",{style:{fontSize:11,color:"#22c55e"},children:"โ Synced"}):e.jsxs("span",{style:{fontSize:11,color:"#f59e0b"},children:["โ ",n," pendingโฆ"]})}function bn({participant:n,isFollowing:t,onClick:i}){return e.jsxs("button",{onClick:i,style:{fontSize:11,padding:"2px 8px",border:`1px solid ${t?n.color:"#e5e7eb"}`,borderRadius:20,background:t?n.color:"#fff",color:t?"#fff":"#6b7280",cursor:"pointer",display:"flex",alignItems:"center",gap:4},children:["๐ ",t?"Unfollow":`Follow ${(n.user.displayName??n.user.name).split(" ")[0]}`]})}function mn({editorType:n,sessionId:t,currentUser:i,participants:s=[],onOperation:r,onParticipantJoin:o,onParticipantLeave:c,onCursorMove:f,isReadOnly:u=!1,showParticipants:x=!0,showCursors:m=!0,pendingOperations:j=0,conflictCount:C=0,className:v,style:R,children:O,"data-testid":l}){const A=a.useRef(null),[N,Y]=a.useState(null),[H,D]=a.useState(null),[$,U]=a.useState(!1);a.useEffect(()=>{const h=A.current;if(!h)return;const k=new ResizeObserver(()=>Y(h.getBoundingClientRect()));return k.observe(h),Y(h.getBoundingClientRect()),()=>k.disconnect()},[]);const E=a.useCallback(h=>{if(!A.current||!f)return;const k=A.current.getBoundingClientRect();f(h.clientX-k.left,h.clientY-k.top)},[f]),_=a.useCallback(h=>{D(k=>k===h?null:h)},[]),S={vector:"โ๏ธ Vector",pixel:"๐ผ๏ธ Pixel",diagram:"๐ Diagram",document:"๐ Document",whiteboard:"๐๏ธ Whiteboard"};return e.jsxs("div",{className:v,"data-testid":l,style:{display:"flex",flexDirection:"column",background:"#fff",borderRadius:8,border:"1px solid #e5e7eb",overflow:"hidden",fontFamily:"system-ui, sans-serif",...R},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid #f3f4f6",background:"#f9fafb",minHeight:40},children:[e.jsx("span",{style:{fontSize:12,color:"#6b7280",fontWeight:500},children:S[n]}),e.jsx("span",{style:{flex:1}}),e.jsx(xn,{pending:j}),x&&s.length>0&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:-4},children:[s.slice(0,5).map((h,k)=>e.jsx("div",{style:{marginLeft:k>0?-8:0,zIndex:10-k},children:e.jsx(rt,{participant:h,isFollowing:H===h.user.id,onClick:()=>{U(!0),_(h.user.id)}})},h.user.id)),s.length>5&&e.jsxs("button",{onClick:()=>U(!$),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:["+",s.length-5]})]}),x&&s.length>0&&e.jsxs("button",{onClick:()=>U(!$),style:{border:"1px solid #e5e7eb",borderRadius:5,background:$?"#eff6ff":"#fff",padding:"3px 8px",cursor:"pointer",fontSize:11,color:$?"#3b82f6":"#6b7280"},children:[s.length," online"]})]}),e.jsxs("div",{style:{display:"flex",flex:1,overflow:"hidden",position:"relative"},children:[e.jsxs("div",{ref:A,onMouseMove:E,style:{flex:1,position:"relative",overflow:"hidden"},children:[O??e.jsxs("div",{id:`collab-editor-${n}-${t}`,style:{width:"100%",height:"100%",minHeight:400,display:"flex",alignItems:"center",justifyContent:"center",background:"#f9fafb",color:"#9ca3af",fontSize:13},children:["Drop your ",n," editor here or use the"," ",e.jsx("code",{style:{background:"#e5e7eb",padding:"1px 5px",borderRadius:3,margin:"0 4px"},children:`#collab-editor-${n}-${t}`})," ","mount point."]}),m&&s.filter(h=>h.user.id!==i.id&&h.cursorX!=null&&h.cursorY!=null).map(h=>e.jsx(hn,{participant:h,containerRect:N},h.user.id)),e.jsx(gn,{count:C}),u&&e.jsx(yn,{})]}),$&&s.length>0&&e.jsxs("div",{style:{width:220,borderLeft:"1px solid #e5e7eb",background:"#f9fafb",overflowY:"auto",padding:10,display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[e.jsx("strong",{style:{fontSize:12,color:"#374151"},children:"Participants"}),e.jsx("button",{onClick:()=>U(!1),style:{border:"none",background:"none",cursor:"pointer",color:"#9ca3af",fontSize:14},children:"โ"})]}),s.map(h=>e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"8px",borderRadius:6,background:"#fff",border:"1px solid #f3f4f6"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx(rt,{participant:h,isFollowing:H===h.user.id,onClick:()=>_(h.user.id)}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:12,fontWeight:500,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:h.user.displayName??h.user.name}),e.jsx("div",{style:{fontSize:10,color:"#9ca3af"},children:h.editingRegion??"viewing"})]})]}),h.user.id!==i.id&&e.jsx(bn,{participant:h,isFollowing:H===h.user.id,onClick:()=>_(h.user.id)})]},h.user.id))]})]})]})}function Ge(n){let t="";for(let i=0;i<n.length;i++)t+=String.fromCharCode(n[i]);return btoa(t)}function Xe(n){const t=atob(n),i=new Uint8Array(t.length);for(let s=0;s<t.length;s++)i[s]=t.charCodeAt(s);return i}function vn(n){return new TextEncoder().encode(n)}function Sn(n){return new TextDecoder().decode(n)}async function jn(n){return crypto.subtle.generateKey({name:"AES-GCM",length:n},!0,["encrypt","decrypt"])}async function wn(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-384"},!0,["deriveKey"])}async function kn(n,t){return crypto.subtle.deriveKey({name:"ECDH",public:t},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Cn(n,t){const i=crypto.getRandomValues(new Uint8Array(12)),s=vn(t),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:i},n,s),o=new Uint8Array(r),c=new Uint8Array(12+o.length);return c.set(i,0),c.set(o,12),Ge(c)}async function In(n,t){const i=Xe(t),s=i.slice(0,12),r=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,r);return Sn(new Uint8Array(o))}async function ot(n,t){const i=Xe(n);return crypto.subtle.importKey("raw",i,{name:"AES-GCM",length:t},!1,["encrypt","decrypt"])}async function zn(n){const t=await crypto.subtle.exportKey("raw",n);return Ge(new Uint8Array(t))}async function Rn(n){const t=await crypto.subtle.exportKey("spki",n);return Ge(new Uint8Array(t))}async function Tn(n){const t=Xe(n);return crypto.subtle.importKey("spki",t,{name:"ECDH",namedCurve:"P-384"},!0,[])}class vt{constructor(t){this.keys={},this.ready=!1,this.config=t}async init(){if(!this.config.enabled){this.ready=!0;return}const t=this.config.defaultAlgorithm;if(this.config.keyMaterial)t==="AES-GCM-128"?this.keys.aes128=await ot(this.config.keyMaterial,128):this.keys.aes256=await ot(this.config.keyMaterial,256);else if(t==="AES-GCM-256"||t==="AES-GCM-128"){const i=t==="AES-GCM-256"?256:128,s=await jn(i);i===128?this.keys.aes128=s:this.keys.aes256=s}else if(t==="E2E-ECDH-P384"){const i=await wn();this.keys.ecdhPrivate=i.privateKey,this.keys.ecdhPublic=i.publicKey,this.keys.ecdhSessionKeys=new Map}this.ready=!0}async getPublicKeyForPeer(){return this.keys.ecdhPublic?Rn(this.keys.ecdhPublic):null}async registerPeerPublicKey(t,i){var o;if(!this.keys.ecdhPrivate)return;const s=await Tn(i),r=await kn(this.keys.ecdhPrivate,s);(o=this.keys.ecdhSessionKeys)==null||o.set(t,r)}resolveAlgorithm(t){if(t&&this.config.scopeOverrides){const i=this.config.scopeOverrides.find(s=>(s.scope===t||s.scope==="all")&&s.enabled);if(i)return i.algorithm}return this.config.defaultAlgorithm}getKey(t,i){var s;switch(t){case"AES-GCM-256":return this.keys.aes256??null;case"AES-GCM-128":return this.keys.aes128??null;case"E2E-ECDH-P384":return i?((s=this.keys.ecdhSessionKeys)==null?void 0:s.get(i))??null:null;default:return null}}async encrypt(t,i,s){if(!this.config.enabled)return t;if(!this.ready)throw new Error("EncryptionService not initialised โ call init() first");const r=this.resolveAlgorithm(i);if(r==="none")return t;const o=this.getKey(r,s);return o?Cn(o,t):(console.warn(`EncryptionService: no key found for algorithm "${r}" โ returning plaintext`),t)}async decrypt(t,i,s){if(!this.config.enabled)return t;if(!this.ready)throw new Error("EncryptionService not initialised โ call init() first");const r=this.resolveAlgorithm(i);if(r==="none")return t;const o=this.getKey(r,s);return o?In(o,t):(console.warn(`EncryptionService: no key found for algorithm "${r}" โ returning as-is`),t)}async exportSymmetricKey(t){const i=t??this.config.defaultAlgorithm,s=this.getKey(i);return s?zn(s):null}isEnabled(){return this.config.enabled}getConfig(){return this.config}updateConfig(t){this.config=t,this.ready=!1}}const Ee=new Map;function An(n,t){return Ee.has(n)||Ee.set(n,new vt(t)),Ee.get(n)}function Dn(n){Ee.delete(n)}class St{constructor(t={}){this.recorder=null,this.chunks=[],this.session=null,this.recognition=null,this.segmentCounter=0,this.callbacks=t}start(t,i){var f,u,x;if(((f=this.recorder)==null?void 0:f.state)==="recording")throw new Error("Recording already in progress");const s=i.mimeType??this.chooseMimeType(),r=new MediaRecorder(t,{mimeType:s});this.chunks=[];const o=new Date,c=`rec_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return this.session={id:c,sessionType:i.sessionType,startedAt:o,state:"recording",mimeType:s,participants:[i.speakerId??"unknown"],title:i.title??`Recording ${o.toLocaleString()}`},r.ondataavailable=m=>{m.data&&m.data.size>0&&this.chunks.push(m.data)},r.onstop=()=>{var j,C,v,R;const m=new Blob(this.chunks,{type:s});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"),(C=(j=this.callbacks).onDataAvailable)==null||C.call(j,m),(R=(v=this.callbacks).onStateChange)==null||R.call(v,"ready")},r.onerror=m=>{var j,C,v,R;(C=(j=this.callbacks).onError)==null||C.call(j,new Error(String(m))),this.session&&(this.session.state="failed"),(R=(v=this.callbacks).onStateChange)==null||R.call(v,"failed")},r.start(i.timesliceMs??1e3),this.recorder=r,i.transcribe&&this.startTranscription(i.speakerId??"unknown",i.speakerName??"Participant"),(x=(u=this.callbacks).onStateChange)==null||x.call(u,"recording"),this.session}pause(){var t,i,s;((t=this.recorder)==null?void 0:t.state)==="recording"&&(this.recorder.pause(),this.session&&(this.session.state="paused"),(s=(i=this.callbacks).onStateChange)==null||s.call(i,"paused"))}resume(){var t,i,s;((t=this.recorder)==null?void 0:t.state)==="paused"&&(this.recorder.resume(),this.session&&(this.session.state="recording"),(s=(i=this.callbacks).onStateChange)==null||s.call(i,"recording"))}stop(){var t,i;return this.stopTranscription(),this.recorder&&this.recorder.state!=="inactive"&&(this.recorder.stop(),this.session&&(this.session.state="processing"),(i=(t=this.callbacks).onStateChange)==null||i.call(t,"processing")),this.session}startTranscription(t,i){const s=window.SpeechRecognition??window.webkitSpeechRecognition;if(!s)return;const r=new s;r.continuous=!0,r.interimResults=!1,r.lang="en-US";const o=Date.now();r.onresult=c=>{var u,x;const f=c.results;for(let m=c.resultIndex;m<f.length;m++){const j=f[m];if(!j.isFinal)continue;const C=j[0],v=Date.now(),R={id:`seg_${++this.segmentCounter}`,speakerId:t,speakerName:i,text:C.transcript.trim(),startMs:v-o-1500,endMs:v-o,confidence:C.confidence??.9};this.session&&(this.session.transcript=[...this.session.transcript??[],R]),(x=(u=this.callbacks).onTranscriptSegment)==null||x.call(u,R)}},r.onerror=()=>{};try{r.start(),this.recognition=r}catch{}}stopTranscription(){var t;try{(t=this.recognition)==null||t.stop()}catch{}this.recognition=null}chooseMimeType(){const t=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm","audio/webm;codecs=opus","audio/ogg;codecs=opus"];for(const i of t)if(MediaRecorder.isTypeSupported(i))return i;return""}getState(){var t;return((t=this.session)==null?void 0:t.state)??"idle"}getSession(){return this.session}download(t){var o,c;const i=(o=this.session)==null?void 0:o.blob;if(!i)return;const s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=t??`${((c=this.session)==null?void 0:c.title)??"recording"}.webm`,r.click(),setTimeout(()=>URL.revokeObjectURL(s),3e4)}}const Pe=new Map;function En(n,t){return Pe.has(n)||Pe.set(n,new St(t)),Pe.get(n)}function Pn(n){Pe.delete(n)}exports.DEFAULT_RETENTION_RULES=Ye;exports.EncryptionService=vt;exports.MockTransport=ct;exports.NiceCallScreen=Fe;exports.NiceChannelView=pt;exports.NiceChatWindow=Ie;exports.NiceCollaborativeEditor=mn;exports.NiceCommunication=bt;exports.NiceCommunicationDefault=bt;exports.NiceMessenger=ut;exports.NicePresenceIndicator=fe;exports.NiceRecordingPanel=un;exports.NiceStorageSettings=on;exports.NiceTeamsWorkspace=xt;exports.NiceVideoConference=Ke;exports.NiceWhiteboard=He;exports.RecordingService=St;exports.StorageService=ht;exports.WebRTCTransport=at;exports.buildOptimisticMessage=kt;exports.createTransport=dt;exports.disposeEncryptionService=Dn;exports.disposeRecordingService=Pn;exports.disposeStorageService=Ot;exports.findConversationPartner=Me;exports.getDefaultMode=It;exports.getEncryptionService=An;exports.getMentionCount=Ct;exports.getRecordingService=En;exports.getStorageService=gt;exports.getUnreadCount=_e;exports.useCommunication=ft;exports.useWhiteboard=yt;
|
|
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,`
|
|
7
|
+
To mute or unmute yourself, press star 6.
|
|
8
|
+
To raise your hand, press star 9.
|
|
9
|
+
To leave the meeting, press pound.
|
|
10
|
+
For help, press star 0.
|
|
11
|
+
`)}async disconnectParticipant(e){const t=this.participants.get(e);t&&(await this.playIvr(e,"goodbye"),this.updateParticipantState(e,"disconnected"),this.emit("onParticipantLeft",{...t}),this.participants.delete(e))}async endMeeting(){for(const e of this.participants.values())await this.disconnectParticipant(e.callId)}getStatus(){return this.connectionStatus}async connect(){this.connectionStatus="connected",this.emit("onStatusChanged","connected")}async disconnect(){await this.endMeeting(),this.connectionStatus="disconnected",this.emit("onStatusChanged","disconnected")}getAudioBridgeConfig(){return{sampleRate:48e3,channels:1,codec:"opus",bitrate:64e3}}getSdpOffer(){return`v=0
|
|
12
|
+
o=nice2dev 1234567890 1234567890 IN IP4 0.0.0.0
|
|
13
|
+
s=Nice2Dev Conference Bridge
|
|
14
|
+
c=IN IP4 0.0.0.0
|
|
15
|
+
t=0 0
|
|
16
|
+
m=audio 49170 RTP/AVP 0 8 101
|
|
17
|
+
a=rtpmap:0 PCMU/8000
|
|
18
|
+
a=rtpmap:8 PCMA/8000
|
|
19
|
+
a=rtpmap:101 telephone-event/8000
|
|
20
|
+
a=fmtp:101 0-16
|
|
21
|
+
`}processSdpAnswer(e){console.log("[PstnGateway] Processing SDP answer")}}let Ue=null;function $t(s){return Ue||(Ue=new it(s)),Ue}function ti(s){return new it(s)}function ni(s){const e=l.useMemo(()=>$t(s),[]),[t,i]=l.useState("disconnected"),[r,a]=l.useState([]);l.useEffect(()=>{const S=()=>{a(e.getParticipants())};return e.on("onStatusChanged",i),e.on("onParticipantJoined",S),e.on("onParticipantLeft",S),e.on("onParticipantStateChanged",S),()=>{e.off("onStatusChanged"),e.off("onParticipantJoined"),e.off("onParticipantLeft"),e.off("onParticipantStateChanged")}},[e]);const o=l.useCallback((S,C)=>e.generateDialInInfo(S,C),[e]),c=l.useCallback(S=>e.getDialInInfo(S),[e]),p=l.useCallback(S=>e.muteParticipant(S),[e]),u=l.useCallback(S=>e.unmuteParticipant(S),[e]),m=l.useCallback(S=>e.disconnectParticipant(S),[e]),f=l.useCallback(()=>e.muteAll(),[e]),y=l.useCallback(()=>e.endMeeting(),[e]),h=l.useCallback(()=>e.connect(),[e]);return{status:t,participants:r,generateDialIn:o,getDialIn:c,mute:p,unmute:u,disconnect:m,muteAll:f,endMeeting:y,connect:h}}exports.DEFAULT_DTMF_COMMANDS=Mt;exports.DEFAULT_IVR_TEXT=Nt;exports.DEFAULT_RETENTION_RULES=Ze;exports.EmailTrackingService=At;exports.EncryptionService=Rt;exports.MailMergeService=Et;exports.MockTransport=xt;exports.NiceCallScreen=Je;exports.NiceChannelView=wt;exports.NiceChatWindow=Re;exports.NiceCollaborativeEditor=Mn;exports.NiceCommunication=Tt;exports.NiceCommunicationDefault=Tt;exports.NiceMessenger=St;exports.NicePresenceIndicator=ue;exports.NiceRecordingPanel=Tn;exports.NiceStorageSettings=Sn;exports.NiceTeamsWorkspace=It;exports.NiceVideoConference=Qe;exports.NiceWhiteboard=et;exports.PstnGatewayService=it;exports.REGION_CODES=Ve;exports.RecordingService=Pt;exports.SlackImportService=Dt;exports.StorageService=kt;exports.WebRTCTransport=yt;exports.buildOptimisticMessage=Wt;exports.createPstnGateway=ti;exports.createTransport=bt;exports.disposeEmailTrackingService=Vn;exports.disposeEncryptionService=Yn;exports.disposeMailMergeService=Jn;exports.disposeRecordingService=qn;exports.disposeSlackImportService=Zn;exports.disposeStorageService=Vt;exports.findConversationPartner=He;exports.getDefaultMode=_t;exports.getEmailTrackingService=Ye;exports.getEncryptionService=Kn;exports.getMailMergeService=Ge;exports.getMentionCount=Ft;exports.getPstnGateway=$t;exports.getRecordingService=Gn;exports.getSlackImportService=qe;exports.getStorageService=jt;exports.getUnreadCount=Xe;exports.useCommunication=vt;exports.useEmailTracking=Xn;exports.useMailMerge=Qn;exports.usePstnGateway=ni;exports.useSlackImport=ei;exports.useWhiteboard=Ct;
|