@nice2dev/ui-communication 1.1.7 → 1.1.10

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 CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),w=require("@nice2dev/ui"),l=require("react");class yt{constructor(){this.listeners=new Map}on(e,n){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(n)}off(e,n){var i;(i=this.listeners.get(e))==null||i.delete(n)}emit(e,n){var i;(i=this.listeners.get(e))==null||i.forEach(r=>r(n))}removeAll(){this.listeners.clear()}}class xt extends yt{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,n){return this.userId=n,new Promise((i,r)=>{const a=new WebSocket(e);a.onopen=()=>{this.signalingWs=a,this.connected=!0,a.send(JSON.stringify({type:"register",userId:n})),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[,n]of this.peers)n.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,n){const i=crypto.randomUUID();return this.sendSignal({type:"call:request",callId:i,callType:n,from:this.userId,to:e}),{id:i,type:n,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[n,i]of this.peers)i.close(),this.peers.delete(n)}muteAudio(e){var n;(n=this.localStream)==null||n.getAudioTracks().forEach(i=>{i.enabled=!e}),this.sendSignal({type:"peer:mute",from:this.userId,audio:e,video:!1})}muteVideo(e){var n;(n=this.localStream)==null||n.getVideoTracks().forEach(i=>{i.enabled=!e}),this.sendSignal({type:"peer:mute",from:this.userId,audio:!1,video:e})}async setAudioDevice(e){var i;const n=(i=this.localStream)==null?void 0:i.getAudioTracks()[0];n&&await n.applyConstraints({deviceId:{exact:e}})}async setVideoDevice(e){var i;const n=(i=this.localStream)==null?void 0:i.getVideoTracks()[0];n&&await n.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[,n]of this.peers)this.screenStream.getTracks().forEach(i=>n.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 n;((n=this.signalingWs)==null?void 0:n.readyState)===WebSocket.OPEN&&this.signalingWs.send(JSON.stringify(e))}async handleSignalingMessage(e){var n;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":(n=this.peers.get(e.from))==null||n.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 n=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,n),(a=this.localStream)==null||a.getTracks().forEach(o=>n.addTrack(o,this.localStream)),n.onicecandidate=o=>{o.candidate&&this.sendSignal({type:"ice-candidate",to:e,from:this.userId,candidate:o.candidate})},n.ontrack=o=>{const c=o.streams[0];c&&this.emit("stream:added",{participantId:e,stream:c})},n.onconnectionstatechange=()=>{(n.connectionState==="failed"||n.connectionState==="disconnected")&&this.emit("stream:removed",{participantId:e})},this.config.maxBitrate){const o=n.getSenders();for(const c of o){if(!c.track)continue;const u=c.getParameters();u.encodings||(u.encodings=[{}]),c.track.kind==="audio"&&this.config.maxBitrate.audio?u.encodings[0].maxBitrate=this.config.maxBitrate.audio:c.track.kind==="video"&&this.config.maxBitrate.video&&(u.encodings[0].maxBitrate=this.config.maxBitrate.video),await c.setParameters(u)}}const i=await n.createOffer();return await n.setLocalDescription(i),this.sendSignal({type:"offer",to:e,from:this.userId,sdp:i.sdp}),n}}class bt extends yt{constructor(){super(...arguments),this.type="mock",this.connected=!1,this.localStream=null}async connect(e,n){this.connected=!0,this.emit("transport:connected",{})}disconnect(){this.releaseLocalStream(),this.connected=!1,this.removeAll()}isConnected(){return this.connected}async getLocalStream(e){const n=new AudioContext,i=n.createMediaStreamDestination();n.createOscillator().connect(i);const a=i.stream,o=document.createElement("canvas");o.width=640,o.height=480;const c=o.captureStream(15),u=[...a.getTracks(),...c.getTracks()];return this.localStream=new MediaStream(u),this.localStream}releaseLocalStream(){var e;(e=this.localStream)==null||e.getTracks().forEach(n=>n.stop()),this.localStream=null}async startCall(e,n){const i={id:crypto.randomUUID(),type:n,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 vt(s,e){switch(s){case"mock":return new bt;case"webrtc":case"sfu":default:return new xt(e)}}function wt(s){const{currentUser:e,transport:n="webrtc",rtcConfig:i,signalingUrl:r,autoConnect:a=!1,onCallEnded:o,onIncomingCall:c,onStreamAdded:u,onStreamRemoved:p,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}),v=l.useCallback(()=>{if(f.current)return f.current;const C=vt(n,i);return C.on("transport:connected",()=>h(k=>({...k,isConnected:!0,connectionError:null}))),C.on("transport:disconnected",()=>h(k=>({...k,isConnected:!1}))),C.on("transport:error",k=>{const{error:M}=k;h(K=>({...K,connectionError:M.message})),m==null||m(M)}),C.on("call:incoming",k=>{const{callId:M,callType:K,callerId:P}=k,I={callId:M,callType:K,caller:{id:P,name:P,presence:{status:"online"}},startedAt:new Date};h(W=>({...W,incomingCall:I})),c==null||c(I)}),C.on("call:ended",k=>{const{callId:M}=k;h(K=>{var P;return{...K,activeCall:((P=K.activeCall)==null?void 0:P.id)===M?null:K.activeCall,localStream:null}}),o==null||o(M)}),C.on("stream:added",k=>{const{participantId:M,stream:K}=k;u==null||u(M,K)}),C.on("stream:removed",k=>{const{participantId:M}=k;p==null||p(M)}),f.current=C,C},[n,i,o,c,u,p,m]);l.useEffect(()=>!a||!r?void 0:(v().connect(r,e.id).catch(k=>{const M=k instanceof Error?k:new Error(String(k));h(K=>({...K,connectionError:M.message})),m==null||m(M)}),()=>{var k;(k=f.current)==null||k.disconnect(),f.current=null}),[a,r,e.id,v,m]);const z=l.useCallback(async C=>{await v().connect(C,e.id)},[v,e.id]),d=l.useCallback(()=>{var C;(C=f.current)==null||C.disconnect(),f.current=null,h(k=>({...k,isConnected:!1}))},[]),N=l.useCallback(async(C,k="video")=>{const M=f.current??v(),K=k==="video"?{audio:!0,video:{width:1280,height:720}}:{audio:!0,video:!1},P=await M.getLocalStream(K),I=await M.startCall(C,k);return h(W=>({...W,activeCall:I,localStream:P})),I},[v]),R=l.useCallback(async()=>{const C=f.current,{incomingCall:k}=y;if(!C||!k)return;const M=k.callType==="video"?{audio:!0,video:{width:1280,height:720}}:{audio:!0,video:!1},K=await C.getLocalStream(M);await C.acceptCall(k.callId);const P={id:k.callId,type:k.callType,participants:[],status:"active",startedAt:new Date,isRecording:!1,isTranscribing:!1,layout:"spotlight"};h(I=>({...I,activeCall:P,incomingCall:null,localStream:K}))},[y]),D=l.useCallback(()=>{var k;const{incomingCall:C}=y;C&&((k=f.current)==null||k.declineCall(C.callId),h(M=>({...M,incomingCall:null})))},[y]),_=l.useCallback(()=>{var k,M;const{activeCall:C}=y;C&&((k=f.current)==null||k.endCall(C.id),(M=f.current)==null||M.releaseLocalStream(),h(K=>({...K,activeCall:null,localStream:null,isScreenSharing:!1,screenStream:null})))},[y]),$=l.useCallback(()=>{var k;const C=!y.isMicMuted;(k=f.current)==null||k.muteAudio(C),h(M=>({...M,isMicMuted:C}))},[y.isMicMuted]),B=l.useCallback(()=>{var k;const C=!y.isCameraMuted;(k=f.current)==null||k.muteVideo(C),h(M=>({...M,isCameraMuted:C}))},[y.isCameraMuted]),Y=l.useCallback(async()=>{const C=f.current;if(!C)return;const k=await C.startScreenShare();h(M=>({...M,isScreenSharing:!0,screenStream:k}))},[]),O=l.useCallback(()=>{var C;(C=f.current)==null||C.stopScreenShare(),h(k=>({...k,isScreenSharing:!1,screenStream:null}))},[]),G=l.useCallback(()=>{h(C=>({...C,isHandRaised:!C.isHandRaised}))},[]);return{state:y,connect:z,disconnect:d,startCall:N,acceptCall:R,declineCall:D,endCall:_,toggleMic:$,toggleCamera:B,startScreenShare:Y,stopScreenShare:O,toggleHand:G,transport:f}}function Ft(s,e,n,i="text"){return{id:`optimistic-${crypto.randomUUID()}`,conversationId:s,authorId:e,content:n,contentType:i,timestamp:new Date,status:"sending",reactions:[],attachments:[],mentions:[],isPinned:!1}}function Ke(s,e,n){if(s.type!=="dm")return;const i=s.participantIds.find(r=>r!==e);return n.find(r=>r.id===i)}function Je(s){return s.reduce((e,n)=>e+n.unreadCount,0)}function _t(s){return s.reduce((e,n)=>e+n.mentionCount,0)}function Bt(s,e){return s?"workspace":e?"messenger":"bubble"}const Ut={online:"Online",away:"Away",busy:"Busy",dnd:"Do not disturb",offline:"Offline",invisible:"Invisible",unknown:"Unknown"},Ht={online:"var(--nice-success, #22c55e)",away:"var(--nice-warning, #f59e0b)",busy:"var(--nice-danger, #ef4444)",dnd:"var(--nice-danger, #ef4444)",offline:"var(--nice-text-muted, #9ca3af)",invisible:"var(--nice-text-muted, #9ca3af)",unknown:"var(--nice-border, #d1d5db)"},Kt={xs:6,sm:8,md:10,lg:14};function pe({status:s,size:e="sm",showLabel:n=!1,showTooltip:i=!1,className:r,style:a,id:o,"data-testid":c}){const u=Kt[e],p=Ht[s],m=Ut[s],f=t.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:u,height:u,borderRadius:"50%",backgroundColor:p,flexShrink:0,border:s==="offline"||s==="invisible"?"1.5px solid var(--nice-text-muted, #9ca3af)":"none",boxSizing:"border-box"}});return n?t.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,t.jsx("span",{className:"nice-presence-label",style:{fontSize:u+4,color:p},children:m})]}):t.jsx("span",{id:o,"data-testid":c,className:`nice-presence-indicator${r?` ${r}`:""}`,style:a,children:f})}function Qe({session:s,currentUser:e,localStream:n,enableScreenSharing:i=!0,enableRecording:r=!1,onEndCall:a,onMuteAudio:o,onMuteVideo:c,onStartScreenShare:u,onStopScreenShare:p,onRaiseHand:m,className:f,style:y,id:h,"data-testid":v}){var S,J;const z=l.useRef(null),d=l.useRef(null),[N,R]=l.useState(!1),[D,_]=l.useState(s.type==="audio"),[$,B]=l.useState(!1),[Y,O]=l.useState(0),[G,C]=l.useState(!1),k=s.participants.find(X=>X.user.id!==e.id);l.useEffect(()=>{z.current&&n&&(z.current.srcObject=n)},[n]),l.useEffect(()=>{d.current&&(k!=null&&k.stream)&&(d.current.srcObject=k.stream)},[k==null?void 0:k.stream]),l.useEffect(()=>{if(s.status!=="active")return;const X=setInterval(()=>O(Z=>Z+1),1e3);return()=>clearInterval(X)},[s.status]);const M=X=>{const Z=Math.floor(X/3600),q=Math.floor(X%3600/60),ae=X%60;return Z>0?`${Z}:${String(q).padStart(2,"0")}:${String(ae).padStart(2,"0")}`:`${String(q).padStart(2,"0")}:${String(ae).padStart(2,"0")}`},K=()=>{const X=!N;R(X),o==null||o(X)},P=()=>{const X=!D;_(X),c==null||c(X)},I=async()=>{$?(B(!1),p==null||p()):(B(!0),await(u==null?void 0:u()))},W=()=>{a==null||a(s.id)},U={position:"relative",width:"100%",height:"100%",background:"var(--nice-text, #111827)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",overflow:"hidden",...y},H=s.status==="ringing"||s.status==="connecting",g=k==null?void 0:k.user;return t.jsxs("div",{id:h,"data-testid":v,className:`nice-call-screen${f?` ${f}`:""}`,style:U,children:[s.type==="video"&&(k!=null&&k.stream)&&!k.isCameraOff?t.jsx("video",{ref:d,autoPlay:!0,playsInline:!0,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[t.jsx("div",{style:{width:120,height:120,borderRadius:"50%",background:g!=null&&g.avatarUrl?`url(${g.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",fontWeight:700,fontSize:48,boxShadow:H?"0 0 0 12px var(--nice-accent-tint-30, rgba(99, 102, 241, 0.3))":void 0,animation:H?"nice-call-pulse 1.5s ease-in-out infinite":void 0},children:!(g!=null&&g.avatarUrl)&&(((J=(S=g==null?void 0:g.name)==null?void 0:S[0])==null?void 0:J.toUpperCase())??"?")}),t.jsx("span",{style:{color:"var(--nice-bg, #fff)",fontSize:22,fontWeight:600},children:(g==null?void 0:g.displayName)??(g==null?void 0:g.name)??"Calling…"}),g&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx(pe,{status:g.presence.status,size:"sm"}),t.jsx("span",{style:{color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))",fontSize:13},children:H?s.status==="ringing"?"Calling…":"Connecting…":M(Y)})]})]}),s.status==="active"&&t.jsxs("div",{style:{position:"absolute",top:16,left:"50%",transform:"translateX(-50%)",color:"var(--nice-overlay-light-70, rgba(255, 255, 255, 0.7))",fontSize:13},children:[M(Y),s.isRecording&&t.jsxs("span",{style:{marginLeft:8,color:"var(--nice-danger, #ef4444)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(w.NiceIcon,{name:"circle",size:11})," REC"]})]}),(k==null?void 0:k.isMuted)&&t.jsxs("div",{style:{position:"absolute",top:16,right:70,background:"var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",borderRadius:6,padding:"3px 8px",display:"flex",alignItems:"center",gap:4,fontSize:12,color:"var(--nice-bg, #fff)"},children:[t.jsx(w.NiceIcon,{name:"mic",size:12})," ",g==null?void 0:g.name," is muted"]}),t.jsx("button",{onClick:()=>C(X=>!X),style:{position:"absolute",top:12,right:12,background:"var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",border:"none",borderRadius:6,padding:"5px 8px",color:"var(--nice-bg, #fff)",cursor:"pointer",fontSize:16},title:G?"Exit fullscreen":"Fullscreen","aria-label":G?"Exit fullscreen":"Fullscreen",children:t.jsx(w.NiceIcon,{name:G?"collapse":"expand",size:16})}),s.type==="video"&&!D&&n&&t.jsx("div",{style:{position:"absolute",bottom:90,right:20,width:140,height:90,borderRadius:10,overflow:"hidden",border:"2px solid var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))",boxShadow:"0 4px 12px var(--nice-overlay-50, rgba(0, 0, 0, 0.5))"},children:t.jsx("video",{ref:z,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"cover",transform:"scaleX(-1)"}})}),t.jsxs("div",{className:"nice-call-controls",style:{position:"absolute",bottom:24,left:"50%",transform:"translateX(-50%)",display:"flex",gap:12,background:"var(--nice-overlay-80, rgba(17, 24, 39, 0.8))",backdropFilter:"blur(8px)",borderRadius:40,padding:"8px 16px"},children:[t.jsx(Se,{icon:"mic",label:N?"Unmute":"Mute",onClick:K,active:!N,style:{background:N?"var(--nice-danger, #ef4444)":void 0}}),s.type==="video"&&t.jsx(Se,{icon:D?"camera":"video",label:D?"Turn on camera":"Turn off camera",onClick:P,active:!D,style:{background:D?"var(--nice-danger, #ef4444)":void 0}}),i&&t.jsx(Se,{icon:"monitor",label:$?"Stop sharing":"Share screen",onClick:()=>{I()},active:$,style:{background:$?"var(--nice-success, #22c55e)":void 0}}),m&&t.jsx(Se,{icon:"cursor",label:"Raise hand",onClick:()=>m(!0),active:!1}),r&&t.jsx(Se,{icon:"circle",label:s.isRecording?"Stop recording":"Start recording",onClick:()=>{},active:s.isRecording,style:{background:s.isRecording?"var(--nice-danger, #ef4444)":void 0}}),t.jsx(Se,{icon:"phone",label:"End call",onClick:W,active:!1,style:{background:"var(--nice-danger, #ef4444)",color:"var(--nice-bg, #fff)"}})]}),t.jsx("style",{children:`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),b=require("@nice2dev/ui"),l=require("react");class bt{constructor(){this.listeners=new Map}on(e,n){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(n)}off(e,n){var r;(r=this.listeners.get(e))==null||r.delete(n)}emit(e,n){var r;(r=this.listeners.get(e))==null||r.forEach(s=>s(n))}removeAll(){this.listeners.clear()}}class vt extends bt{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,n){return this.userId=n,new Promise((r,s)=>{const a=new WebSocket(e);a.onopen=()=>{this.signalingWs=a,this.connected=!0,a.send(JSON.stringify({type:"register",userId:n})),this.emit("transport:connected",{}),r()},a.onerror=o=>{s(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[,n]of this.peers)n.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,n){const r=crypto.randomUUID();return this.sendSignal({type:"call:request",callId:r,callType:n,from:this.userId,to:e}),{id:r,type:n,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[n,r]of this.peers)r.close(),this.peers.delete(n)}muteAudio(e){var n;(n=this.localStream)==null||n.getAudioTracks().forEach(r=>{r.enabled=!e}),this.sendSignal({type:"peer:mute",from:this.userId,audio:e,video:!1})}muteVideo(e){var n;(n=this.localStream)==null||n.getVideoTracks().forEach(r=>{r.enabled=!e}),this.sendSignal({type:"peer:mute",from:this.userId,audio:!1,video:e})}async setAudioDevice(e){var r;const n=(r=this.localStream)==null?void 0:r.getAudioTracks()[0];n&&await n.applyConstraints({deviceId:{exact:e}})}async setVideoDevice(e){var r;const n=(r=this.localStream)==null?void 0:r.getVideoTracks()[0];n&&await n.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[,n]of this.peers)this.screenStream.getTracks().forEach(r=>n.addTrack(r,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 n;((n=this.signalingWs)==null?void 0:n.readyState)===WebSocket.OPEN&&this.signalingWs.send(JSON.stringify(e))}async handleSignalingMessage(e){var n;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":(n=this.peers.get(e.from))==null||n.close(),this.peers.delete(e.from),this.emit("call:ended",{callId:e.callId,reason:"remote-ended"});break;case"offer":{const r=await this.getOrCreatePeer(e.from);await r.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:e.sdp}));const s=await r.createAnswer();await r.setLocalDescription(s),this.sendSignal({type:"answer",to:e.from,from:this.userId,sdp:s.sdp});break}case"answer":{const r=this.peers.get(e.from);r&&await r.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e.sdp}));break}case"ice-candidate":{const r=this.peers.get(e.from);r&&e.candidate&&await r.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 s,a;const n=new RTCPeerConnection({iceServers:(s=this.config.iceServers)==null?void 0:s.map(o=>({urls:o.urls,username:o.username,credential:o.credential})),iceTransportPolicy:this.config.iceTransportPolicy});if(this.peers.set(e,n),(a=this.localStream)==null||a.getTracks().forEach(o=>n.addTrack(o,this.localStream)),n.onicecandidate=o=>{o.candidate&&this.sendSignal({type:"ice-candidate",to:e,from:this.userId,candidate:o.candidate})},n.ontrack=o=>{const c=o.streams[0];c&&this.emit("stream:added",{participantId:e,stream:c})},n.onconnectionstatechange=()=>{(n.connectionState==="failed"||n.connectionState==="disconnected")&&this.emit("stream:removed",{participantId:e})},this.config.maxBitrate){const o=n.getSenders();for(const c of o){if(!c.track)continue;const f=c.getParameters();f.encodings||(f.encodings=[{}]),c.track.kind==="audio"&&this.config.maxBitrate.audio?f.encodings[0].maxBitrate=this.config.maxBitrate.audio:c.track.kind==="video"&&this.config.maxBitrate.video&&(f.encodings[0].maxBitrate=this.config.maxBitrate.video),await c.setParameters(f)}}const r=await n.createOffer();return await n.setLocalDescription(r),this.sendSignal({type:"offer",to:e,from:this.userId,sdp:r.sdp}),n}}class wt extends bt{constructor(){super(...arguments),this.type="mock",this.connected=!1,this.localStream=null}async connect(e,n){this.connected=!0,this.emit("transport:connected",{})}disconnect(){this.releaseLocalStream(),this.connected=!1,this.removeAll()}isConnected(){return this.connected}async getLocalStream(e){const n=new AudioContext,r=n.createMediaStreamDestination();n.createOscillator().connect(r);const a=r.stream,o=document.createElement("canvas");o.width=640,o.height=480;const c=o.captureStream(15),f=[...a.getTracks(),...c.getTracks()];return this.localStream=new MediaStream(f),this.localStream}releaseLocalStream(){var e;(e=this.localStream)==null||e.getTracks().forEach(n=>n.stop()),this.localStream=null}async startCall(e,n){const r={id:crypto.randomUUID(),type:n,participants:[],status:"connecting",startedAt:new Date,isRecording:!1,isTranscribing:!1,layout:e.length>2?"grid":"spotlight"};return setTimeout(()=>this.emit("call:accepted",{callId:r.id,participantId:e[0]??"mock"}),800),r}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 St(i,e){switch(i){case"mock":return new wt;case"webrtc":case"sfu":default:return new vt(e)}}function jt(i){const{currentUser:e,transport:n="webrtc",rtcConfig:r,signalingUrl:s,autoConnect:a=!1,onCallEnded:o,onIncomingCall:c,onStreamAdded:f,onStreamRemoved:d,onError:g}=i,p=l.useRef(null),[m,h]=l.useState({isConnected:!1,activeCall:null,incomingCall:null,localStream:null,isMicMuted:!1,isCameraMuted:!1,isScreenSharing:!1,screenStream:null,isHandRaised:!1,connectionError:null}),w=l.useCallback(()=>{if(p.current)return p.current;const C=St(n,r);return C.on("transport:connected",()=>h(j=>({...j,isConnected:!0,connectionError:null}))),C.on("transport:disconnected",()=>h(j=>({...j,isConnected:!1}))),C.on("transport:error",j=>{const{error:O}=j;h(U=>({...U,connectionError:O.message})),g==null||g(O)}),C.on("call:incoming",j=>{const{callId:O,callType:U,callerId:P}=j,T={callId:O,callType:U,caller:{id:P,name:P,presence:{status:"online"}},startedAt:new Date};h(F=>({...F,incomingCall:T})),c==null||c(T)}),C.on("call:ended",j=>{const{callId:O}=j;h(U=>{var P;return{...U,activeCall:((P=U.activeCall)==null?void 0:P.id)===O?null:U.activeCall,localStream:null}}),o==null||o(O)}),C.on("stream:added",j=>{const{participantId:O,stream:U}=j;f==null||f(O,U)}),C.on("stream:removed",j=>{const{participantId:O}=j;d==null||d(O)}),p.current=C,C},[n,r,o,c,f,d,g]);l.useEffect(()=>!a||!s?void 0:(w().connect(s,e.id).catch(j=>{const O=j instanceof Error?j:new Error(String(j));h(U=>({...U,connectionError:O.message})),g==null||g(O)}),()=>{var j;(j=p.current)==null||j.disconnect(),p.current=null}),[a,s,e.id,w,g]);const z=l.useCallback(async C=>{await w().connect(C,e.id)},[w,e.id]),u=l.useCallback(()=>{var C;(C=p.current)==null||C.disconnect(),p.current=null,h(j=>({...j,isConnected:!1}))},[]),I=l.useCallback(async(C,j="video")=>{const O=p.current??w(),U=j==="video"?{audio:!0,video:{width:1280,height:720}}:{audio:!0,video:!1},P=await O.getLocalStream(U),T=await O.startCall(C,j);return h(F=>({...F,activeCall:T,localStream:P})),T},[w]),A=l.useCallback(async()=>{const C=p.current,{incomingCall:j}=m;if(!C||!j)return;const O=j.callType==="video"?{audio:!0,video:{width:1280,height:720}}:{audio:!0,video:!1},U=await C.getLocalStream(O);await C.acceptCall(j.callId);const P={id:j.callId,type:j.callType,participants:[],status:"active",startedAt:new Date,isRecording:!1,isTranscribing:!1,layout:"spotlight"};h(T=>({...T,activeCall:P,incomingCall:null,localStream:U}))},[m]),N=l.useCallback(()=>{var j;const{incomingCall:C}=m;C&&((j=p.current)==null||j.declineCall(C.callId),h(O=>({...O,incomingCall:null})))},[m]),H=l.useCallback(()=>{var j,O;const{activeCall:C}=m;C&&((j=p.current)==null||j.endCall(C.id),(O=p.current)==null||O.releaseLocalStream(),h(U=>({...U,activeCall:null,localStream:null,isScreenSharing:!1,screenStream:null})))},[m]),E=l.useCallback(()=>{var j;const C=!m.isMicMuted;(j=p.current)==null||j.muteAudio(C),h(O=>({...O,isMicMuted:C}))},[m.isMicMuted]),B=l.useCallback(()=>{var j;const C=!m.isCameraMuted;(j=p.current)==null||j.muteVideo(C),h(O=>({...O,isCameraMuted:C}))},[m.isCameraMuted]),K=l.useCallback(async()=>{const C=p.current;if(!C)return;const j=await C.startScreenShare();h(O=>({...O,isScreenSharing:!0,screenStream:j}))},[]),J=l.useCallback(()=>{var C;(C=p.current)==null||C.stopScreenShare(),h(j=>({...j,isScreenSharing:!1,screenStream:null}))},[]),$=l.useCallback(()=>{h(C=>({...C,isHandRaised:!C.isHandRaised}))},[]);return{state:m,connect:z,disconnect:u,startCall:I,acceptCall:A,declineCall:N,endCall:H,toggleMic:E,toggleCamera:B,startScreenShare:K,stopScreenShare:J,toggleHand:$,transport:p}}function Ut(i,e,n,r="text"){return{id:`optimistic-${crypto.randomUUID()}`,conversationId:i,authorId:e,content:n,contentType:r,timestamp:new Date,status:"sending",reactions:[],attachments:[],mentions:[],isPinned:!1}}function Ge(i,e,n){if(i.type!=="dm")return;const r=i.participantIds.find(s=>s!==e);return n.find(s=>s.id===r)}function Ze(i){return i.reduce((e,n)=>e+n.unreadCount,0)}function Ht(i){return i.reduce((e,n)=>e+n.mentionCount,0)}function Kt(i,e){return i?"workspace":e?"messenger":"bubble"}const Yt={online:"Online",away:"Away",busy:"Busy",dnd:"Do not disturb",offline:"Offline",invisible:"Invisible",unknown:"Unknown"},Gt={online:"var(--nice-success, #22c55e)",away:"var(--nice-warning, #f59e0b)",busy:"var(--nice-danger, #ef4444)",dnd:"var(--nice-danger, #ef4444)",offline:"var(--nice-text-muted, #9ca3af)",invisible:"var(--nice-text-muted, #9ca3af)",unknown:"var(--nice-border, #d1d5db)"},qt={xs:6,sm:8,md:10,lg:14};function ue({status:i,size:e="sm",showLabel:n=!1,showTooltip:r=!1,className:s,style:a,id:o,"data-testid":c}){const f=qt[e],d=Gt[i],g=Yt[i],p=t.jsx("span",{className:`nice-presence-dot nice-presence-dot--${i} nice-presence-dot--${e}`,title:r?g:void 0,"aria-label":g,role:"img",style:{display:"inline-block",width:f,height:f,borderRadius:"50%",backgroundColor:d,flexShrink:0,border:i==="offline"||i==="invisible"?"1.5px solid var(--nice-border-color, #9ca3af)":"none",boxSizing:"border-box"}});return n?t.jsxs("span",{id:o,"data-testid":c,className:`nice-presence-indicator nice-presence-indicator--with-label${s?` ${s}`:""}`,style:{display:"inline-flex",alignItems:"center",gap:6,...a},children:[p,t.jsx("span",{className:"nice-presence-label",style:{fontSize:f+4,color:i==="unknown"?"var(--nice-text-muted, #9ca3af)":d},children:g})]}):t.jsx("span",{id:o,"data-testid":c,className:`nice-presence-indicator${s?` ${s}`:""}`,style:a,children:p})}function et({session:i,currentUser:e,localStream:n,enableScreenSharing:r=!0,enableRecording:s=!1,onEndCall:a,onMuteAudio:o,onMuteVideo:c,onStartScreenShare:f,onStopScreenShare:d,onRaiseHand:g,className:p,style:m,id:h,"data-testid":w}){var x,G;const z=l.useRef(null),u=l.useRef(null),[I,A]=l.useState(!1),[N,H]=l.useState(i.type==="audio"),[E,B]=l.useState(!1),[K,J]=l.useState(0),[$,C]=l.useState(!1),j=i.participants.find(X=>X.user.id!==e.id);l.useEffect(()=>{z.current&&n&&(z.current.srcObject=n)},[n]),l.useEffect(()=>{u.current&&(j!=null&&j.stream)&&(u.current.srcObject=j.stream)},[j==null?void 0:j.stream]),l.useEffect(()=>{if(i.status!=="active")return;const X=setInterval(()=>J(Q=>Q+1),1e3);return()=>clearInterval(X)},[i.status]);const O=X=>{const Q=Math.floor(X/3600),q=Math.floor(X%3600/60),ne=X%60;return Q>0?`${Q}:${String(q).padStart(2,"0")}:${String(ne).padStart(2,"0")}`:`${String(q).padStart(2,"0")}:${String(ne).padStart(2,"0")}`},U=()=>{const X=!I;A(X),o==null||o(X)},P=()=>{const X=!N;H(X),c==null||c(X)},T=async()=>{E?(B(!1),d==null||d()):(B(!0),await(f==null?void 0:f()))},F=()=>{a==null||a(i.id)},_={position:"relative",width:"100%",height:"100%",background:"var(--nice-bg-primary, #111827)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",overflow:"hidden",...m},Y=i.status==="ringing"||i.status==="connecting",S=j==null?void 0:j.user;return t.jsxs("div",{id:h,"data-testid":w,className:`nice-call-screen${p?` ${p}`:""}`,style:_,children:[i.type==="video"&&(j!=null&&j.stream)&&!j.isCameraOff?t.jsx("video",{ref:u,autoPlay:!0,playsInline:!0,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[t.jsx("div",{style:{width:120,height:120,borderRadius:"50%",background:S!=null&&S.avatarUrl?`url(${S.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:48,boxShadow:Y?"0 0 0 12px var(--nice-accent-tint-30, rgba(99, 102, 241, 0.3))":void 0,animation:Y?"nice-call-pulse 1.5s ease-in-out infinite":void 0},children:!(S!=null&&S.avatarUrl)&&(((G=(x=S==null?void 0:S.name)==null?void 0:x[0])==null?void 0:G.toUpperCase())??"?")}),t.jsx("span",{style:{color:"var(--nice-text-primary, #fff)",fontSize:22,fontWeight:600},children:(S==null?void 0:S.displayName)??(S==null?void 0:S.name)??"Calling…"}),S&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx(ue,{status:S.presence.status,size:"sm"}),t.jsx("span",{style:{color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))",fontSize:13},children:Y?i.status==="ringing"?"Calling…":"Connecting…":O(K)})]})]}),i.status==="active"&&t.jsxs("div",{style:{position:"absolute",top:16,left:"50%",transform:"translateX(-50%)",color:"var(--nice-overlay-light-70, rgba(255, 255, 255, 0.7))",fontSize:13},children:[O(K),i.isRecording&&t.jsxs("span",{style:{marginLeft:8,color:"var(--nice-danger, #ef4444)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(b.NiceIcon,{name:"circle",size:11})," REC"]})]}),(j==null?void 0:j.isMuted)&&t.jsxs("div",{style:{position:"absolute",top:16,right:70,background:"var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",borderRadius:6,padding:"3px 8px",display:"flex",alignItems:"center",gap:4,fontSize:12,color:"var(--nice-text-on-primary, #fff)"},children:[t.jsx(b.NiceIcon,{name:"mic",size:12})," ",S==null?void 0:S.name," is muted"]}),t.jsx("button",{onClick:()=>C(X=>!X),style:{position:"absolute",top:12,right:12,background:"var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",border:"none",borderRadius:6,padding:"5px 8px",color:"var(--nice-text-on-primary, #fff)",cursor:"pointer",fontSize:16},title:$?"Exit fullscreen":"Fullscreen","aria-label":$?"Exit fullscreen":"Fullscreen",children:t.jsx(b.NiceIcon,{name:$?"collapse":"expand",size:16})}),i.type==="video"&&!N&&n&&t.jsx("div",{style:{position:"absolute",bottom:90,right:20,width:140,height:90,borderRadius:10,overflow:"hidden",border:"2px solid var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))",boxShadow:"0 4px 12px var(--nice-overlay-50, rgba(0, 0, 0, 0.5))"},children:t.jsx("video",{ref:z,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"cover",transform:"scaleX(-1)"}})}),t.jsxs("div",{className:"nice-call-controls",style:{position:"absolute",bottom:24,left:"50%",transform:"translateX(-50%)",display:"flex",gap:12,background:"var(--nice-overlay-80, rgba(17, 24, 39, 0.8))",backdropFilter:"blur(8px)",borderRadius:40,padding:"8px 16px"},children:[t.jsx(we,{icon:"mic",label:I?"Unmute":"Mute",onClick:U,active:!I,style:{background:I?"var(--nice-danger, #ef4444)":void 0}}),i.type==="video"&&t.jsx(we,{icon:N?"camera":"video",label:N?"Turn on camera":"Turn off camera",onClick:P,active:!N,style:{background:N?"var(--nice-danger, #ef4444)":void 0}}),r&&t.jsx(we,{icon:"monitor",label:E?"Stop sharing":"Share screen",onClick:()=>{T()},active:E,style:{background:E?"var(--nice-success, #22c55e)":void 0}}),g&&t.jsx(we,{icon:"cursor",label:"Raise hand",onClick:()=>g(!0),active:!1}),s&&t.jsx(we,{icon:"circle",label:i.isRecording?"Stop recording":"Start recording",onClick:()=>{},active:i.isRecording,style:{background:i.isRecording?"var(--nice-danger, #ef4444)":void 0}}),t.jsx(we,{icon:"phone",label:"End call",onClick:F,active:!1,style:{background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)"}})]}),t.jsx("style",{children:`
2
2
  @keyframes nice-call-pulse {
3
3
  0%, 100% { box-shadow: 0 0 0 0 var(--nice-accent-tint-40, rgba(99, 102, 241, 0.4)); }
4
4
  50% { box-shadow: 0 0 0 24px rgba(99,102,241,0); }
5
5
  }
6
- `})]})}function Se({icon:s,label:e,onClick:n,active:i,style:r}){return t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[t.jsx("button",{onClick:n,title:e,style:{width:44,height:44,borderRadius:"50%",border:"none",background:i?"var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))":"var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",color:"var(--nice-bg, #fff)",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.2s",...r},children:t.jsx(w.NiceIcon,{name:s,size:18})}),t.jsx("span",{style:{fontSize:9,color:"var(--nice-overlay-light-50, rgba(255, 255, 255, 0.5))",textAlign:"center",maxWidth:50},children:e})]})}const Yt=["👍","❤️","😂","😮","😢","🎉"];function We({message:s,author:e,isMine:n,showAvatar:i,enableReactions:r,onReact:a,onReply:o,onEdit:c,onDelete:u,onPin:p,onOpenThread:m}){var N,R,D,_;const[f,y]=l.useState(!1),[h,v]=l.useState(!1),z=s.isDeleted,d=s.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return t.jsxs("div",{className:`nice-chat-message${n?" nice-chat-message--mine":""}${s.isPinned?" nice-chat-message--pinned":""}`,onMouseEnter:()=>y(!0),onMouseLeave:()=>{y(!1),v(!1)},style:{display:"flex",flexDirection:n?"row-reverse":"row",alignItems:"flex-end",gap:8,padding:"2px 16px",position:"relative"},children:[i&&!n&&t.jsxs("div",{style:{position:"relative",flexShrink:0},children:[t.jsx("div",{className:"nice-chat-avatar",style:{width:32,height:32,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",fontSize:13,fontWeight:600,flexShrink:0},children:!(e!=null&&e.avatarUrl)&&(((R=(N=e==null?void 0:e.name)==null?void 0:N[0])==null?void 0:R.toUpperCase())??"?")}),t.jsx(pe,{status:((D=e==null?void 0:e.presence)==null?void 0:D.status)??"unknown",size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),t.jsxs("div",{style:{maxWidth:"70%",display:"flex",flexDirection:"column",alignItems:n?"flex-end":"flex-start"},children:[!n&&e&&t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginBottom:2,paddingLeft:2},children:e.displayName??e.name}),s.replyTo&&t.jsx("div",{className:"nice-chat-reply-preview",style:{borderLeft:"3px solid var(--nice-info, #6366f1)",paddingLeft:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)",marginBottom:4,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.replyTo.content}),t.jsx("div",{className:`nice-chat-bubble${n?" nice-chat-bubble--mine":""}`,style:{padding:"8px 12px",borderRadius:n?"18px 18px 4px 18px":"18px 18px 18px 4px",background:n?"var(--nice-info, #6366f1)":"var(--nice-bg-secondary, #f3f4f6)",color:n?"var(--nice-bg, #fff)":"var(--nice-text, #111827)",fontSize:14,lineHeight:1.5,wordBreak:"break-word"},children:z?t.jsx("span",{style:{fontStyle:"italic",opacity:.6},children:"This message was deleted"}):s.contentType==="image"&&((_=s.attachments)!=null&&_[0])?t.jsx("img",{src:s.attachments[0].url,alt:s.attachments[0].name,style:{maxWidth:280,maxHeight:280,borderRadius:8,display:"block"}}):t.jsx("span",{children:s.content})}),!z&&s.attachments&&s.attachments.length>0&&s.contentType!=="image"&&t.jsx("div",{className:"nice-chat-attachments",style:{marginTop:4},children:s.attachments.map($=>t.jsxs("a",{href:$.url,target:"_blank",rel:"noreferrer",className:"nice-chat-attachment",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:12,color:n?"var(--nice-overlay-light-85, rgba(255, 255, 255, 0.85))":"var(--nice-info, #6366f1)",textDecoration:"none",background:n?"var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))":"var(--nice-primary-bg, #e0e7ff)",borderRadius:6,padding:"3px 8px",marginTop:2},children:[t.jsx(w.NiceIcon,{name:"paperclip",size:14})," ",$.name]},$.id))}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:2},children:[t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:d}),s.editedAt&&t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:"(edited)"}),n&&t.jsx("span",{style:{display:"inline-flex",alignItems:"center",color:s.status==="read"?"var(--nice-info, #6366f1)":"var(--nice-text-muted, #9ca3af)"},children:s.status==="sending"?t.jsx(w.NiceIcon,{name:"circle",size:12}):s.status==="sent"?t.jsx(w.NiceIcon,{name:"check",size:12}):t.jsxs("span",{style:{display:"inline-flex",marginRight:-6},children:[t.jsx(w.NiceIcon,{name:"check",size:12}),t.jsx(w.NiceIcon,{name:"check",size:12})]})})]}),s.reactions&&s.reactions.length>0&&t.jsx("div",{className:"nice-chat-reactions",style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:s.reactions.map($=>t.jsxs("button",{onClick:()=>a(s.id,$.emoji),style:{background:$.mine?"var(--nice-primary-bg, #e0e7ff)":"var(--nice-bg-secondary, #f3f4f6)",border:$.mine?"1px solid var(--nice-info, #6366f1)":"1px solid transparent",borderRadius:12,padding:"2px 7px",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",gap:3},children:[$.emoji," ",$.count]},$.emoji))}),(s.threadCount??0)>0&&t.jsxs("button",{className:"nice-chat-thread-btn",onClick:()=>m==null?void 0:m(s),style:{background:"none",border:"none",color:"var(--nice-info, #6366f1)",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:2,display:"inline-flex",alignItems:"center",gap:4},children:[t.jsx(w.NiceIcon,{name:"message",size:14})," ",s.threadCount," repl",s.threadCount===1?"y":"ies"]})]}),f&&!z&&t.jsxs("div",{className:"nice-chat-actions",style:{position:"absolute",top:-16,[n?"left":"right"]:16,display:"flex",gap:2,background:"var(--nice-bg, #fff)",borderRadius:8,boxShadow:"0 2px 8px var(--nice-overlay-12, rgba(0, 0, 0, 0.12))",padding:"3px 6px",zIndex:10},children:[r&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{title:"React","aria-label":"React",onClick:()=>v($=>!$),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:t.jsx(w.NiceIcon,{name:"heart",size:16})}),h&&t.jsx("div",{style:{position:"absolute",bottom:"100%",left:0,display:"flex",gap:4,background:"var(--nice-bg, #fff)",borderRadius:8,boxShadow:"0 2px 8px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",padding:"6px 8px",zIndex:20},children:Yt.map($=>t.jsx("button",{onClick:()=>{a(s.id,$),v(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:$},$))})]}),t.jsx("button",{title:"Reply","aria-label":"Reply",onClick:()=>o(s),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:t.jsx(w.NiceIcon,{name:"reply",size:16})}),n&&c&&t.jsx("button",{title:"Edit","aria-label":"Edit",onClick:()=>c(s),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:t.jsx(w.NiceIcon,{name:"edit",size:16})}),p&&t.jsx("button",{title:s.isPinned?"Unpin":"Pin","aria-label":s.isPinned?"Unpin":"Pin",onClick:()=>p(s),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:t.jsx(w.NiceIcon,{name:"map-pin",size:16})}),n&&u&&t.jsx("button",{title:"Delete","aria-label":"Delete",onClick:()=>u(s),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px",color:"var(--nice-danger, #ef4444)"},children:t.jsx(w.NiceIcon,{name:"trash",size:16})})]})]})}function ot({placeholder:s="Type a message…",maxLength:e,replyTo:n,onCancelReply:i,onSend:r,onAttach:a,disabled:o}){const[c,u]=l.useState(""),p=l.useRef(null);l.useEffect(()=>{n&&p.current&&p.current.focus()},[n]);const m=h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),f())},f=()=>{const h=c.trim();h&&(r(h),u(""),p.current&&(p.current.style.height="auto"))},y=h=>{u(h.target.value),h.target.style.height="auto",h.target.style.height=`${Math.min(h.target.scrollHeight,120)}px`};return t.jsxs("div",{className:"nice-chat-input-area",style:{padding:"8px 12px",borderTop:"1px solid var(--nice-border, #e5e7eb)",background:"var(--nice-bg, #fff)"},children:[n&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",background:"var(--nice-bg-secondary, #f3f4f6)",borderLeft:"3px solid var(--nice-info, #6366f1)",padding:"4px 8px",marginBottom:6,borderRadius:"0 4px 4px 0",fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:[t.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Replying: ",n.content]}),t.jsx("button",{onClick:i,title:"Cancel reply","aria-label":"Cancel reply",style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",marginLeft:8,display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:"close",size:16})})]}),t.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:8},children:[a&&t.jsx("button",{onClick:a,title:"Attach file","aria-label":"Attach file",style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",padding:"4px",flexShrink:0,display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:"paperclip",size:18})}),t.jsx("textarea",{ref:p,value:c,onChange:y,onKeyDown:m,placeholder:s,maxLength:e,disabled:o,rows:1,style:{flex:1,resize:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:20,padding:"8px 14px",fontSize:14,outline:"none",fontFamily:"inherit",lineHeight:1.5,overflow:"hidden"}}),t.jsx("button",{onClick:f,disabled:!c.trim()||o,title:"Send","aria-label":"Send",style:{background:c.trim()?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)",border:"none",borderRadius:"50%",width:36,height:36,cursor:c.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--nice-bg, #fff)",transition:"background 0.15s"},children:t.jsx(w.NiceIcon,{name:"send",size:16})})]}),e&&c.length>e*.8&&t.jsxs("div",{style:{textAlign:"right",fontSize:11,color:c.length>=e?"var(--nice-danger, #ef4444)":"var(--nice-text-muted, #9ca3af)",marginTop:2},children:[c.length,"/",e]})]})}function Ne({conversation:s,messages:e,users:n,currentUser:i,isLoading:r=!1,hasMore:a=!1,showHeader:o=!0,showUserAvatars:c=!0,enableReactions:u=!0,enableThreads:p=!0,enableAttachments:m=!0,placeholder:f,maxMessageLength:y,onSendMessage:h,onEditMessage:v,onDeleteMessage:z,onReactToMessage:d,onPinMessage:N,onLoadMoreMessages:R,onStartCall:D,className:_,style:$,id:B,"data-testid":Y}){var H,g;const O=l.useRef(null),G=l.useRef(null),[C,k]=l.useState(null),[M,K]=l.useState(null),P=l.useMemo(()=>{const S=new Map;return n.forEach(J=>S.set(J.id,J)),S},[n]);l.useEffect(()=>{var S;(S=O.current)==null||S.scrollIntoView({behavior:"smooth"})},[e]);const I=l.useCallback(()=>{const S=G.current;!S||!a||r||S.scrollTop===0&&e.length>0&&(R==null||R(s.id,e[0].id))},[a,r,e,s.id,R]),W=l.useCallback(S=>{h==null||h(s.id,S,"text"),k(null)},[s.id,h]),U=s.type==="dm"?P.get(s.participantIds.find(S=>S!==i.id)??""):void 0;return t.jsxs("div",{id:B,"data-testid":Y,className:`nice-chat-window${_?` ${_}`:""}`,style:{display:"flex",flexDirection:"column",height:"100%",background:"var(--nice-bg, #fff)",...$},children:[o&&t.jsxs("div",{className:"nice-chat-header",style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:(U??s).avatarUrl?`url(${(U??s).avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",fontWeight:700,fontSize:15,flexShrink:0},children:!(U??s).avatarUrl&&((H=((U==null?void 0:U.name)??s.name??"?")[0])==null?void 0:H.toUpperCase())}),t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:600,fontSize:15},children:(U==null?void 0:U.displayName)??(U==null?void 0:U.name)??s.name??"Chat"}),U&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:1},children:[t.jsx(pe,{status:U.presence.status,size:"xs"}),t.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:U.presence.statusMessage??U.presence.status})]}),s.type!=="dm"&&t.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:[s.participantIds.length," members"]})]})]}),s.type==="dm"&&D&&U&&t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:()=>D([U.id],"audio"),title:"Audio call","aria-label":"Audio call",style:{background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"5px 8px",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:"phone",size:16})}),t.jsx("button",{onClick:()=>D([U.id],"video"),title:"Video call","aria-label":"Video call",style:{background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"5px 8px",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:"video",size:16})})]})]}),t.jsxs("div",{ref:G,className:"nice-chat-messages",onScroll:I,style:{flex:1,overflowY:"auto",padding:"8px 0",display:"flex",flexDirection:"column"},children:[a&&t.jsx("button",{onClick:()=>e.length>0&&(R==null?void 0:R(s.id,e[0].id)),disabled:r,style:{display:"block",margin:"8px auto",background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,padding:"4px 16px",fontSize:12,color:"var(--nice-text-secondary, #6b7280)",cursor:"pointer"},children:r?"Loading…":"Load older messages"}),e.map((S,J)=>{const X=e[J-1],Z=c&&(!X||X.authorId!==S.authorId);return t.jsx(We,{message:S,author:P.get(S.authorId),isMine:S.authorId===i.id,showAvatar:Z,enableReactions:u,onReact:(q,ae)=>d==null?void 0:d(q,ae),onReply:q=>k(q),onEdit:v?q=>v(q.id,q.content):void 0,onDelete:z?q=>z(q.id):void 0,onPin:N?q=>N(q.id):void 0,onOpenThread:p?q=>K(q):void 0},S.id)}),t.jsx("div",{ref:O})]}),M&&t.jsxs("div",{className:"nice-chat-thread-panel",style:{position:"absolute",right:0,top:o?57:0,bottom:0,width:320,background:"var(--nice-bg, #fff)",borderLeft:"1px solid var(--nice-border, #e5e7eb)",display:"flex",flexDirection:"column",zIndex:5},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid var(--nice-border, #e5e7eb)"},children:[t.jsx("span",{style:{fontWeight:600,fontSize:14},children:"Thread"}),t.jsx("button",{onClick:()=>K(null),title:"Close thread","aria-label":"Close thread",style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:"close",size:18})})]}),t.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[t.jsx(We,{message:M,author:P.get(M.authorId),isMine:M.authorId===i.id,showAvatar:!0,enableReactions:u,onReact:(S,J)=>d==null?void 0:d(S,J),onReply:()=>{}}),(g=M.thread)==null?void 0:g.map(S=>t.jsx(We,{message:S,author:P.get(S.authorId),isMine:S.authorId===i.id,showAvatar:!0,enableReactions:u,onReact:(J,X)=>d==null?void 0:d(J,X),onReply:()=>{}},S.id))]}),t.jsx(ot,{placeholder:"Reply in thread…",onSend:S=>h==null?void 0:h(s.id,S,"text")})]}),t.jsx(ot,{placeholder:f,maxLength:y,replyTo:C,onCancelReply:()=>k(null),onSend:W,onAttach:m?()=>{}:void 0})]})}function Gt({conversation:s,partner:e,isActive:n,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,u=i?i.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"",p=i?i.isDeleted?"Message deleted":i.content.slice(0,50):"";return t.jsxs("button",{className:`nice-messenger-conv-item${n?" nice-messenger-conv-item--active":""}`,onClick:r,style:{display:"flex",alignItems:"center",gap:10,padding:"10px 14px",background:n?"var(--nice-accent-bg, #ede9fe)":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",position:"relative"},children:[t.jsxs("div",{style:{position:"relative",flexShrink:0},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:c?`url(${c}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",fontWeight:700,fontSize:16},children:!c&&o}),e&&t.jsx(pe,{status:e.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}}),s.type!=="dm"&&t.jsx("span",{style:{position:"absolute",bottom:-2,right:-2,background:"var(--nice-bg-secondary, #f3f4f6)",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:4,padding:"1px 2px",color:"var(--nice-text-secondary, #6b7280)",display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:"hash",size:10})})]}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline"},children:[t.jsx("span",{style:{fontWeight:s.unreadCount>0?700:500,fontSize:14,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",flexShrink:0,marginLeft:4},children:u})]}),t.jsx("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:p})]}),(s.unreadCount>0||s.mentionCount>0)&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,alignItems:"flex-end",flexShrink:0},children:[s.mentionCount>0&&t.jsxs("span",{style:{background:"var(--nice-danger, #ef4444)",color:"var(--nice-bg, #fff)",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:["@",s.mentionCount]}),s.unreadCount>0&&t.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-bg, #fff)",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:s.unreadCount>99?"99+":s.unreadCount})]}),s.isMuted&&t.jsx("span",{style:{position:"absolute",bottom:8,right:8,color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex"},children:t.jsx(w.NiceIcon,{name:"mic",size:12,title:"Muted"})})]})}function St({conversations:s,messages:e,users:n,currentUser:i,activeConversationId:r,teams:a,enableGroupConversations:o=!0,showPresence:c=!0,enableSearch:u=!0,onSendMessage:p,onEditMessage:m,onDeleteMessage:f,onReactToMessage:y,onPinMessage:h,onLoadMoreMessages:v,onMarkAsRead:z,onStartCall:d,onCreateConversation:N,className:R,style:D,id:_,"data-testid":$}){var H;const[B,Y]=l.useState(r??null),[O,G]=l.useState(""),[C,k]=l.useState("all");l.useMemo(()=>{const g=new Map;return n.forEach(S=>g.set(S.id,S)),g},[n]);const M=l.useMemo(()=>{let g=s;if(C==="unread"&&(g=g.filter(S=>S.unreadCount>0)),C==="groups"&&(g=g.filter(S=>S.type!=="dm")),O.trim()){const S=O.toLowerCase();g=g.filter(J=>{var Z,q;const X=Ke(J,i.id,n);return(X==null?void 0:X.name.toLowerCase().includes(S))||((Z=J.name)==null?void 0:Z.toLowerCase().includes(S))||((q=J.lastMessage)==null?void 0:q.content.toLowerCase().includes(S))})}return[...g].sort((S,J)=>{var q,ae;if(S.isPinned!==J.isPinned)return S.isPinned?-1:1;const X=((q=S.lastMessage)==null?void 0:q.timestamp.getTime())??S.updatedAt.getTime();return(((ae=J.lastMessage)==null?void 0:ae.timestamp.getTime())??J.updatedAt.getTime())-X})},[s,C,O,i.id,n]),K=l.useMemo(()=>s.find(g=>g.id===B)??null,[s,B]),P=l.useMemo(()=>B?e[B]??[]:[],[e,B]),I=l.useCallback(g=>{Y(g),z==null||z(g)},[z]),W=l.useMemo(()=>Je(s),[s]),U=a??[];return t.jsxs("div",{id:_,"data-testid":$,className:`nice-messenger${R?` ${R}`:""}`,style:{display:"flex",height:"100%",background:"var(--nice-bg, #fff)",overflow:"hidden",...D},children:[t.jsxs("div",{className:"nice-messenger-sidebar",style:{width:280,flexShrink:0,borderRight:"1px solid var(--nice-border, #e5e7eb)",display:"flex",flexDirection:"column",background:"var(--nice-bg-secondary, #fafafa)"},children:[t.jsxs("div",{style:{padding:"14px 14px 8px",borderBottom:"1px solid var(--nice-border, #e5e7eb)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("span",{style:{fontWeight:700,fontSize:16},children:["Messages"," ",W>0&&t.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-bg, #fff)",borderRadius:10,fontSize:10,padding:"1px 6px",fontWeight:700,marginLeft:4},children:W})]}),o&&N&&t.jsx("button",{onClick:()=>N([],"group"),title:"New conversation","aria-label":"New conversation",style:{background:"var(--nice-info, #6366f1)",border:"none",borderRadius:6,padding:"5px 8px",cursor:"pointer",color:"var(--nice-bg, #fff)",display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:"plus",size:13})})]}),u&&t.jsx("input",{type:"search",value:O,onChange:g=>G(g.target.value),placeholder:"Search conversations…",style:{width:"100%",marginTop:8,padding:"6px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,fontSize:13,outline:"none",boxSizing:"border-box",background:"var(--nice-bg, #fff)"}}),t.jsx("div",{style:{display:"flex",gap:2,marginTop:8},children:["all","unread","groups"].map(g=>t.jsx("button",{onClick:()=>k(g),style:{flex:1,padding:"4px 0",border:"none",borderRadius:6,background:C===g?"var(--nice-info, #6366f1)":"transparent",color:C===g?"var(--nice-bg, #fff)":"var(--nice-text-secondary, #6b7280)",cursor:"pointer",fontSize:12,textTransform:"capitalize",fontWeight:C===g?600:400},children:g},g))})]}),c&&t.jsxs("div",{style:{padding:"8px 14px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",overflowX:"auto"},children:[t.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",marginBottom:6},children:"ONLINE NOW"}),t.jsx("div",{style:{display:"flex",gap:10},children:n.filter(g=>g.id!==i.id&&g.presence.status==="online").slice(0,6).map(g=>{var S;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:3},children:[t.jsxs("div",{style:{position:"relative"},children:[t.jsx("div",{style:{width:34,height:34,borderRadius:"50%",background:g.avatarUrl?`url(${g.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",fontWeight:700,fontSize:13,cursor:"pointer"},title:g.name,children:!g.avatarUrl&&((S=g.name[0])==null?void 0:S.toUpperCase())}),t.jsx(pe,{status:g.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),t.jsx("span",{style:{fontSize:10,color:"var(--nice-text-secondary, #6b7280)",maxWidth:36,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.displayName??g.name.split(" ")[0]})]},g.id)})})]}),t.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[U.length>0&&C==="all"&&t.jsx("div",{style:{padding:"8px 14px 4px",fontSize:11,color:"var(--nice-text-muted, #9ca3af)",fontWeight:600,letterSpacing:"0.05em"},children:"DIRECT MESSAGES"}),M.length===0?t.jsx("div",{style:{padding:24,textAlign:"center",color:"var(--nice-text-muted, #9ca3af)",fontSize:13},children:"No conversations"}):M.map(g=>t.jsx(Gt,{conversation:g,partner:Ke(g,i.id,n),isActive:g.id===B,lastMessage:g.lastMessage,onClick:()=>I(g.id)},g.id))]}),t.jsxs("div",{style:{padding:"10px 14px",borderTop:"1px solid var(--nice-border, #e5e7eb)",display:"flex",alignItems:"center",gap:8},children:[t.jsxs("div",{style:{position:"relative"},children:[t.jsx("div",{style:{width:32,height:32,borderRadius:"50%",background:i.avatarUrl?`url(${i.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",fontWeight:700,fontSize:13},children:!i.avatarUrl&&((H=i.name[0])==null?void 0:H.toUpperCase())}),t.jsx(pe,{status:i.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontWeight:600,fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.displayName??i.name}),t.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.presence.statusMessage??i.presence.status})]})]})]}),t.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:K?t.jsx(Ne,{conversation:K,messages:P,users:n,currentUser:i,onSendMessage:p,onEditMessage:m,onDeleteMessage:f,onReactToMessage:y,onPinMessage:h,onLoadMoreMessages:v,onStartCall:d,style:{height:"100%"}}):t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"var(--nice-text-muted, #9ca3af)",gap:12},children:[t.jsx(w.NiceIcon,{name:"message",size:48}),t.jsx("span",{style:{fontSize:15},children:"Select a conversation to start messaging"})]})})]})}const qt=["👍","❤️","😂","🎉","😮","😢"];function Fe({message:s,author:e,isMine:n,enableReactions:i,enableThreads:r,onReact:a,onOpenThread:o,onReply:c}){var v,z,d;const[u,p]=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 t.jsxs("div",{className:`nice-channel-msg${u?" nice-channel-msg--hovered":""}${n?" nice-channel-msg--mine":""}`,onMouseEnter:()=>p(!0),onMouseLeave:()=>{p(!1),f(!1)},style:{display:"flex",gap:10,padding:"4px 16px",position:"relative",background:u?"rgba(99,102,241,0.04)":"transparent"},children:[t.jsx("div",{style:{width:36,flexShrink:0},children:t.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",fontWeight:700,fontSize:14},children:!(e!=null&&e.avatarUrl)&&(((z=(v=e==null?void 0:e.name)==null?void 0:v[0])==null?void 0:z.toUpperCase())??"?")})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:2},children:[t.jsx("span",{style:{fontWeight:600,fontSize:14,color:"var(--nice-text, #111827)"},children:(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??"Unknown"}),e&&t.jsx(pe,{status:e.presence.status,size:"xs"}),t.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:[h," ",y]}),s.editedAt&&t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:"(edited)"}),s.isPinned&&t.jsxs("span",{style:{fontSize:11,color:"var(--nice-info, #6366f1)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(w.NiceIcon,{name:"map-pin",size:12})," Pinned"]})]}),s.isDeleted?t.jsx("span",{style:{fontStyle:"italic",color:"var(--nice-text-muted, #9ca3af)",fontSize:14},children:"This message was deleted"}):t.jsx("div",{style:{fontSize:14,lineHeight:1.6,color:"var(--nice-text, #1f2937)",wordBreak:"break-word"},children:s.contentType==="image"&&((d=s.attachments)!=null&&d[0])?t.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"&&t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:4},children:s.attachments.map(N=>t.jsxs("a",{href:N.url,target:"_blank",rel:"noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:12,color:"var(--nice-info, #6366f1)",background:"var(--nice-accent-bg, #ede9fe)",borderRadius:6,padding:"3px 8px",textDecoration:"none"},children:[t.jsx(w.NiceIcon,{name:"paperclip",size:14})," ",N.name]},N.id))}),s.reactions&&s.reactions.length>0&&t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:s.reactions.map(N=>t.jsxs("button",{onClick:()=>a(s.id,N.emoji),style:{background:N.mine?"var(--nice-accent-bg, #ede9fe)":"var(--nice-bg-secondary, #f3f4f6)",border:N.mine?"1px solid var(--nice-info, #6366f1)":"1px solid transparent",borderRadius:12,padding:"2px 7px",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",gap:3},children:[N.emoji," ",N.count]},N.emoji))}),r&&(s.threadCount??0)>0&&t.jsxs("button",{onClick:()=>o(s),style:{background:"none",border:"none",color:"var(--nice-info, #6366f1)",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:3,display:"inline-flex",alignItems:"center",gap:4},children:[t.jsx(w.NiceIcon,{name:"message",size:14})," ",s.threadCount," repl",s.threadCount===1?"y":"ies"," ",t.jsx(w.NiceIcon,{name:"arrow-right",size:12})]})]}),u&&!s.isDeleted&&t.jsxs("div",{style:{position:"absolute",top:-16,right:16,display:"flex",gap:2,background:"var(--nice-bg, #fff)",borderRadius:8,boxShadow:"0 2px 8px var(--nice-overlay-12, rgba(0, 0, 0, 0.12))",padding:"3px 6px",zIndex:10},children:[i&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{onClick:()=>f(N=>!N),title:"React","aria-label":"React",style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:t.jsx(w.NiceIcon,{name:"heart",size:16})}),m&&t.jsx("div",{style:{position:"absolute",bottom:"100%",right:0,display:"flex",gap:4,background:"var(--nice-bg, #fff)",borderRadius:8,boxShadow:"0 2px 8px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",padding:"6px 8px",zIndex:20},children:qt.map(N=>t.jsx("button",{onClick:()=>{a(s.id,N),f(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:N},N))})]}),t.jsx("button",{onClick:()=>c(s),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},title:"Reply","aria-label":"Reply",children:t.jsx(w.NiceIcon,{name:"reply",size:16})}),r&&t.jsx("button",{onClick:()=>o(s),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},title:"Open thread","aria-label":"Open thread",children:t.jsx(w.NiceIcon,{name:"message",size:16})})]})]})}function jt({channel:s,messages:e,users:n,currentUser:i,team:r,isLoading:a=!1,hasMore:o=!1,enableThreads:c=!0,enableReactions:u=!0,enableAttachments:p=!0,onSendMessage:m,onEditMessage:f,onDeleteMessage:y,onReactToMessage:h,onPinMessage:v,onLoadMoreMessages:z,onStartCall:d,className:N,style:R,id:D,"data-testid":_}){var H;const $=l.useRef(null),B=l.useRef(null),[Y,O]=l.useState(""),[G,C]=l.useState(null),[k,M]=l.useState(null),K=l.useMemo(()=>{const g=new Map;return n.forEach(S=>g.set(S.id,S)),g},[n]);l.useEffect(()=>{var g;(g=$.current)==null||g.scrollIntoView({behavior:"smooth"})},[e]);const P=l.useCallback(()=>{const g=B.current;!g||!o||a||g.scrollTop===0&&e.length>0&&(z==null||z(s.id,e[0].id))},[o,a,e,s.id,z]),I=l.useCallback(()=>{const g=Y.trim();g&&(m==null||m(s.id,g,"text"),O(""),C(null))},[Y,s.id,m]),W=g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),I())},U=n.filter(g=>g.presence.status==="online").length;return t.jsxs("div",{id:D,"data-testid":_,className:`nice-channel-view${N?` ${N}`:""}`,style:{display:"flex",height:"100%",background:"var(--nice-bg, #fff)",overflow:"hidden",...R},children:[t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx(w.NiceIcon,{name:"hash",size:20,style:{color:"var(--nice-text-secondary, #6b7280)"}}),t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:700,fontSize:16},children:s.name}),s.description&&t.jsx("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",marginTop:1},children:s.description})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:[t.jsx("span",{style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:"var(--nice-success, #22c55e)",marginRight:4,verticalAlign:"middle"}}),U," online"]}),d&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>d(n.map(g=>g.id),"audio"),style:{background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"5px 8px",cursor:"pointer",display:"inline-flex",alignItems:"center"},title:"Audio call","aria-label":"Audio call",children:t.jsx(w.NiceIcon,{name:"phone",size:15})}),t.jsx("button",{onClick:()=>d(n.map(g=>g.id),"video"),style:{background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"5px 8px",cursor:"pointer",display:"inline-flex",alignItems:"center"},title:"Video meet","aria-label":"Video meet",children:t.jsx(w.NiceIcon,{name:"video",size:15})})]})]})]}),t.jsxs("div",{ref:B,onScroll:P,style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[o&&t.jsx("button",{onClick:()=>e.length>0&&(z==null?void 0:z(s.id,e[0].id)),disabled:a,style:{display:"block",margin:"8px auto",background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,padding:"4px 16px",fontSize:12,color:"var(--nice-text-secondary, #6b7280)",cursor:"pointer"},children:a?"Loading…":"Load older messages"}),e.map(g=>t.jsx(Fe,{message:g,author:K.get(g.authorId),isMine:g.authorId===i.id,enableReactions:u,enableThreads:c,onReact:(S,J)=>h==null?void 0:h(S,J),onOpenThread:S=>M(S),onReply:S=>C(S)},g.id)),t.jsx("div",{ref:$})]}),t.jsxs("div",{style:{padding:"8px 16px",borderTop:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[G&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",background:"var(--nice-bg-secondary, #f3f4f6)",borderLeft:"3px solid var(--nice-info, #6366f1)",padding:"3px 8px",marginBottom:6,borderRadius:"0 4px 4px 0",fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:[t.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Replying to: ",G.content]}),t.jsx("button",{onClick:()=>C(null),title:"Cancel reply","aria-label":"Cancel reply",style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:"close",size:16})})]}),t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-end"},children:[p&&t.jsx("button",{title:"Attach","aria-label":"Attach",style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",padding:"6px 4px",display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:"paperclip",size:18})}),t.jsx("textarea",{value:Y,onChange:g=>O(g.target.value),onKeyDown:W,placeholder:`Message #${s.name}`,rows:1,style:{flex:1,resize:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:"8px 12px",fontSize:14,outline:"none",fontFamily:"inherit",lineHeight:1.5,overflow:"hidden",maxHeight:100}}),t.jsx("button",{onClick:I,disabled:!Y.trim(),title:"Send","aria-label":"Send",style:{background:Y.trim()?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)",border:"none",borderRadius:"50%",width:36,height:36,cursor:Y.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--nice-bg, #fff)",transition:"background 0.15s"},children:t.jsx(w.NiceIcon,{name:"send",size:15})})]})]})]}),k&&t.jsxs("div",{style:{width:340,flexShrink:0,borderLeft:"1px solid var(--nice-border, #e5e7eb)",display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[t.jsx("span",{style:{fontWeight:600,fontSize:14},children:"Thread"}),t.jsx("button",{onClick:()=>M(null),title:"Close thread","aria-label":"Close thread",style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:"close",size:18})})]}),t.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[t.jsx(Fe,{message:k,author:K.get(k.authorId),isMine:k.authorId===i.id,enableReactions:u,enableThreads:!1,onReact:(g,S)=>h==null?void 0:h(g,S),onOpenThread:()=>{},onReply:()=>{}}),t.jsxs("div",{style:{padding:"6px 14px",color:"var(--nice-text-muted, #9ca3af)",fontSize:12,borderTop:"1px solid var(--nice-bg-secondary, #f3f4f6)"},children:[k.threadCount??0," repl",k.threadCount===1?"y":"ies"]}),(H=k.thread)==null?void 0:H.map(g=>t.jsx(Fe,{message:g,author:K.get(g.authorId),isMine:g.authorId===i.id,enableReactions:u,enableThreads:!1,onReact:(S,J)=>h==null?void 0:h(S,J),onOpenThread:()=>{},onReply:()=>{}},g.id))]}),t.jsx("div",{style:{padding:"8px 12px",borderTop:"1px solid var(--nice-border, #e5e7eb)"},children:t.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-end"},children:[t.jsx("textarea",{placeholder:"Reply in thread…",rows:1,onKeyDown:g=>{if(g.key==="Enter"&&!g.shiftKey){g.preventDefault();const S=g.target.value.trim();S&&(m==null||m(s.id,S,"text"),g.target.value="")}},style:{flex:1,resize:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:"7px 10px",fontSize:13,outline:"none",fontFamily:"inherit",overflow:"hidden"}}),t.jsx("button",{title:"Send","aria-label":"Send",style:{background:"var(--nice-info, #6366f1)",border:"none",borderRadius:"50%",width:32,height:32,cursor:"pointer",color:"var(--nice-bg, #fff)",display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsx(w.NiceIcon,{name:"send",size:14})})]})})]})]})}function _e({participant:s,isLocal:e,isPinned:n,onPin:i,size:r="medium"}){var z;const a=l.useRef(null),{user:o,isMuted:c,isCameraOff:u,isScreenSharing:p,isSpeaking:m,isHandRaised:f,stream:y,screenStream:h}=s;l.useEffect(()=>{if(!a.current)return;const d=p?h:y;d&&(a.current.srcObject=d)},[y,h,p]);const v=!u&&!!y;return t.jsxs("div",{className:`nice-conference-tile${m?" nice-conference-tile--speaking":""}${n?" nice-conference-tile--pinned":""}`,style:{position:"relative",background:"var(--nice-text, #1f2937)",borderRadius:10,overflow:"hidden",border:m?"2px solid var(--nice-success, #22c55e)":n?"2px solid var(--nice-info, #6366f1)":"2px solid transparent",display:"flex",alignItems:"center",justifyContent:"center",aspectRatio:"16/9"},children:[v?t.jsx("video",{ref:a,autoPlay:!0,muted:e,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"cover",transform:e&&!p?"scaleX(-1)":"none"}}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:8},children:[t.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`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",fontWeight:700,fontSize:r==="large"?28:r==="small"?12:18},children:!o.avatarUrl&&((z=o.name[0])==null?void 0:z.toUpperCase())}),r!=="small"&&t.jsx("span",{style:{color:"var(--nice-bg, #fff)",fontSize:12},children:o.displayName??o.name})]}),t.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, var(--nice-overlay-60, rgba(0, 0, 0, 0.6)))",padding:"6px 8px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("span",{style:{color:"var(--nice-bg, #fff)",fontSize:11,fontWeight:500},children:[o.displayName??o.name,e&&" (You)"]}),t.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[f&&t.jsx(w.NiceIcon,{name:"cursor",size:13}),c&&t.jsx(w.NiceIcon,{name:"mic",size:12}),p&&t.jsx(w.NiceIcon,{name:"monitor",size:12}),r!=="small"&&t.jsx("div",{style:{width:6,height:6,borderRadius:"50%",background:m?"var(--nice-success, #22c55e)":"transparent",border:"1px solid var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))"}})]})]}),r!=="small"&&t.jsx("button",{onClick:i,style:{position:"absolute",top:6,right:6,background:"var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",border:"none",borderRadius:4,padding:"2px 5px",color:n?"var(--nice-info, #6366f1)":"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))",cursor:"pointer",fontSize:12},title:n?"Unpin":"Pin","aria-label":n?"Unpin":"Pin",children:t.jsx(w.NiceIcon,{name:"map-pin",size:12})}),s.connectionQuality!=="none"&&r!=="small"&&t.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=>t.jsx("div",{style:{flex:1,background:s.connectionQuality==="excellent"||s.connectionQuality==="good"&&d<=2||s.connectionQuality==="fair"&&d<=1?"var(--nice-success, #22c55e)":"var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))",height:`${d*30}%`,borderRadius:1}},d))})]})}function Ze({session:s,currentUser:e,localStream:n,enableScreenSharing:i=!0,enableRecording:r=!1,enableTranscription:a=!1,enableRaiseHand:o=!0,maxGridCols:c=4,onEndCall:u,onMuteAudio:p,onMuteVideo:m,onStartScreenShare:f,onStopScreenShare:y,onRaiseHand:h,className:v,style:z,id:d,"data-testid":N}){const[R,D]=l.useState(!1),[_,$]=l.useState(!1),[B,Y]=l.useState(!1),[O,G]=l.useState(!1),[C,k]=l.useState(s.pinnedParticipantId??null),[M,K]=l.useState(s.layout==="sidebar"?"grid":s.layout??"grid"),[P,I]=l.useState(0),[W,U]=l.useState(!1);l.useEffect(()=>{if(s.status!=="active")return;const F=setInterval(()=>I(Q=>Q+1),1e3);return()=>clearInterval(F)},[s.status]);const H=F=>{const Q=Math.floor(F/3600),ie=Math.floor(F%3600/60),re=F%60;return Q>0?`${Q}:${String(ie).padStart(2,"0")}:${String(re).padStart(2,"0")}`:`${String(ie).padStart(2,"0")}:${String(re).padStart(2,"0")}`},g=()=>{const F=!R;D(F),p==null||p(F)},S=()=>{const F=!_;$(F),m==null||m(F)},J=async()=>{B?(Y(!1),y==null||y()):(Y(!0),await(f==null?void 0:f()))},X=()=>{const F=!O;G(F),h==null||h(F)},Z=[{user:e,isMuted:R,isCameraOff:_,isScreenSharing:B,isSpeaking:!1,isHandRaised:O,stream:n,connectionQuality:"excellent"},...s.participants],q=C?Z.find(F=>F.user.id===C):null,ae=Z.filter(F=>F.user.id!==C),oe=Z.length,fe=Math.min(c,oe<=1?1:oe<=2||oe<=4?2:oe<=9?3:4),le=M==="spotlight"||q!=null;return t.jsxs("div",{id:d,"data-testid":N,className:`nice-video-conference${v?` ${v}`:""}`,style:{position:"relative",width:"100%",height:"100%",background:"var(--nice-text, #111827)",display:"flex",flexDirection:"column",overflow:"hidden",...z},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 16px",flexShrink:0,color:"var(--nice-bg, #fff)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[t.jsxs("span",{style:{fontSize:15,fontWeight:600},children:[s.id.slice(0,8),"…"]}),t.jsx("span",{style:{fontSize:12,color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"},children:H(P)}),s.isRecording&&t.jsxs("span",{style:{fontSize:11,color:"var(--nice-danger, #ef4444)",display:"flex",alignItems:"center",gap:4},children:[t.jsx(w.NiceIcon,{name:"circle",size:11})," Recording"]})]}),t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[t.jsx("button",{onClick:()=>K(M==="grid"?"spotlight":"grid"),style:{display:"flex",alignItems:"center",gap:4,background:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",border:"none",borderRadius:6,padding:"4px 10px",color:"var(--nice-bg, #fff)",cursor:"pointer",fontSize:12},children:M==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(w.NiceIcon,{name:"grid",size:14})," Grid"]}):t.jsxs(t.Fragment,{children:[t.jsx(w.NiceIcon,{name:"square",size:14})," Spotlight"]})}),t.jsxs("button",{onClick:()=>U(F=>!F),style:{display:"flex",alignItems:"center",gap:4,background:W?"var(--nice-info, #6366f1)":"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",border:"none",borderRadius:6,padding:"4px 10px",color:"var(--nice-bg, #fff)",cursor:"pointer",fontSize:12},children:[t.jsx(w.NiceIcon,{name:"users",size:14})," ",Z.length]})]})]}),t.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden",gap:4,padding:"0 8px 8px"},children:[t.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:4,overflow:"hidden"},children:le&&q?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{flex:1},children:t.jsx(_e,{participant:q,isLocal:q.user.id===e.id,isPinned:!0,onPin:()=>k(null),size:"large"})}),t.jsx("div",{style:{display:"flex",gap:4,height:90,flexShrink:0,overflowX:"auto"},children:ae.map(F=>t.jsx("div",{style:{width:140,flexShrink:0},children:t.jsx(_e,{participant:F,isLocal:F.user.id===e.id,isPinned:!1,onPin:()=>k(F.user.id),size:"small"})},F.user.id))})]}):t.jsx("div",{style:{flex:1,display:"grid",gridTemplateColumns:`repeat(${fe}, 1fr)`,gap:6,overflow:"hidden"},children:Z.map(F=>t.jsx(_e,{participant:F,isLocal:F.user.id===e.id,isPinned:F.user.id===C,onPin:()=>k(Q=>Q===F.user.id?null:F.user.id),size:oe<=4?"large":"medium"},F.user.id))})}),W&&t.jsxs("div",{style:{width:220,flexShrink:0,background:"var(--nice-overlay-light-5, rgba(255, 255, 255, 0.05))",borderRadius:10,display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"10px 12px",fontWeight:600,fontSize:13,color:"var(--nice-bg, #fff)",borderBottom:"1px solid var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))"},children:["Participants (",Z.length,")"]}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:8},children:Z.map(F=>{var Q;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px"},children:[t.jsx("div",{style:{width:28,height:28,borderRadius:"50%",background:F.user.avatarUrl?`url(${F.user.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",fontSize:11,fontWeight:700},children:!F.user.avatarUrl&&((Q=F.user.name[0])==null?void 0:Q.toUpperCase())}),t.jsx("div",{style:{flex:1,minWidth:0},children:t.jsxs("div",{style:{color:"var(--nice-bg, #fff)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[F.user.displayName??F.user.name,F.user.id===e.id&&" (You)"]})}),t.jsxs("div",{style:{display:"flex",gap:3,alignItems:"center"},children:[F.isHandRaised&&t.jsx(w.NiceIcon,{name:"cursor",size:11}),F.isMuted&&t.jsx(w.NiceIcon,{name:"mic",size:11}),t.jsx(pe,{status:F.user.presence.status,size:"xs"})]})]},F.user.id)})})]})]}),t.jsxs("div",{className:"nice-conference-controls",style:{display:"flex",justifyContent:"center",gap:10,padding:"10px 16px",flexShrink:0,background:"var(--nice-overlay-30, rgba(0, 0, 0, 0.3))"},children:[t.jsx(be,{icon:"mic",label:R?"Unmute":"Mute",onClick:g,danger:R}),t.jsx(be,{icon:_?"camera":"video",label:_?"Start video":"Stop video",onClick:S,danger:_}),i&&t.jsx(be,{icon:"monitor",label:B?"Stop share":"Share",onClick:()=>{J()},active:B}),o&&t.jsx(be,{icon:"cursor",label:"Raise hand",onClick:X,active:O}),r&&t.jsx(be,{icon:"circle",label:s.isRecording?"Stop rec":"Record",onClick:()=>{},active:s.isRecording,danger:s.isRecording}),a&&t.jsx(be,{icon:"type",label:s.isTranscribing?"Stop captions":"Captions",onClick:()=>{},active:s.isTranscribing}),t.jsx(be,{icon:"phone",label:"Leave",onClick:()=>u==null?void 0:u(s.id),end:!0})]})]})}function be({icon:s,label:e,onClick:n,active:i,danger:r,end:a}){return t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[t.jsx("button",{title:e,onClick:n,style:{width:46,height:46,borderRadius:"50%",border:"none",background:a?"var(--nice-danger, #ef4444)":r?"var(--nice-danger-dark, #450a0a)":i?"var(--nice-info, #6366f1)":"var(--nice-overlay-light-12, rgba(255, 255, 255, 0.12))",color:"var(--nice-bg, #fff)",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.15s"},children:t.jsx(w.NiceIcon,{name:s,size:18})}),t.jsx("span",{style:{fontSize:9,color:"var(--nice-overlay-light-50, rgba(255, 255, 255, 0.5))",textAlign:"center",maxWidth:52},children:e})]})}function Ye(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 ze(s,e=new Date){if(s.unit!=="forever")return new Date(e.getTime()+Ye(s))}class lt{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,n)=>{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=()=>n(i.error)})}async save(e,n,i){const r=await this.openDb();return new Promise((a,o)=>{const p=r.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:e,data:n,expiresAt:i==null?void 0:i.toISOString()});p.onsuccess=()=>a(),p.onerror=()=>o(p.error)})}async load(e){const n=await this.openDb();return new Promise((i,r)=>{const c=n.transaction(this.storeName,"readonly").objectStore(this.storeName).get(e);c.onsuccess=()=>{const u=c.result;if(!u){i(void 0);return}if(u.expiresAt&&new Date(u.expiresAt)<new Date){this.delete(e),i(void 0);return}i(u.data)},c.onerror=()=>r(c.error)})}async delete(e){const n=await this.openDb();return new Promise((i,r)=>{const c=n.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(e);c.onsuccess=()=>i(),c.onerror=()=>r(c.error)})}async list(e){const n=await this.openDb();return new Promise((i,r)=>{const c=n.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();c.onsuccess=()=>i((c.result??[]).filter(u=>u.startsWith(e))),c.onerror=()=>r(c.error)})}async clear(e){if(!e){const i=await this.openDb();return new Promise((r,a)=>{const u=i.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();u.onsuccess=()=>r(),u.onerror=()=>a(u.error)})}const n=await this.list(e);await Promise.all(n.map(i=>this.delete(i)))}}class Vt{constructor(e="nice_comm__"){this.prefix=e}async save(e,n,i){const r={data:n,expiresAt:i==null?void 0:i.toISOString()};localStorage.setItem(this.prefix+e,JSON.stringify(r))}async load(e){const n=localStorage.getItem(this.prefix+e);if(n)try{const i=JSON.parse(n);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 n=[];for(let i=0;i<localStorage.length;i++){const r=localStorage.key(i);r&&r.startsWith(this.prefix+e)&&n.push(r.slice(this.prefix.length))}return n}async clear(e){(await this.list(e??"")).forEach(i=>localStorage.removeItem(this.prefix+i))}}class kt{constructor(e,n){this.config=e,this.encryption=n,this.adapter=this.buildAdapter()}buildAdapter(){switch(this.config.provider){case"localstorage":return new Vt;case"custom":return this.config.customAdapter??new lt;default:return new lt}}getRuleFor(e){return this.config.retentionRules.find(n=>n.dataType===e)}async encode(e){var i;const n=JSON.stringify(e);return(i=this.encryption)!=null&&i.isEnabled()?this.encryption.encrypt(n,"messages"):n}async decode(e){var n;if(typeof e!="string")return e;if(!((n=this.encryption)!=null&&n.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,n){const i=this.getRuleFor("messages"),r=i?ze(i.activePeriod):void 0,a=await this.encode(n);await this.adapter.save(`msg:${e}`,a,r)}async loadMessages(e){const n=await this.adapter.load(`msg:${e}`);if(!n)return[];const i=await this.decode(n);return Array.isArray(i)?i:[]}async appendMessage(e,n){const i=await this.loadMessages(e);await this.saveMessages(e,[...i,n])}async saveWhiteboardSnapshot(e,n){const i=this.getRuleFor("whiteboard-snapshots"),r=i?ze(i.activePeriod):void 0,a=await this.encode(n);await this.adapter.save(`wb:${e}`,a,r)}async loadWhiteboardSnapshot(e){const n=await this.adapter.load(`wb:${e}`);return n?await this.decode(n):null}async saveRecordingMeta(e){const n=this.getRuleFor("recordings"),i=n?ze(n.activePeriod):void 0,r=await this.encode(e);await this.adapter.save(`rec:${e.id}`,r,i)}async loadRecordingMeta(e){const n=await this.adapter.load(`rec:${e}`);return n?await this.decode(n):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,n){const i=this.getRuleFor("documents"),r=i?ze(i.activePeriod):void 0,a=await this.encode(n);await this.adapter.save(`doc:${e}`,a,r)}async loadDocument(e){const n=await this.adapter.load(`doc:${e}`);return n?this.decode(n):null}async enforceRetention(){let e=0,n=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 u=await this.adapter.list(a);for(const p of u){const m=await this.adapter.load(p);if(m){if(Ye(c.activePeriod),c.archivePeriod){const f=`archive:${p}`,y=ze(c.archivePeriod,i);await this.adapter.save(f,m,y),e++}if(c.deleteAfterArchive&&c.archivePeriod){const f=Ye(c.archivePeriod);new Date(i.getTime()+f)<i&&(await this.adapter.delete(`archive:${p}`),n++)}}}}return{archived:e,deleted:n}}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 et=[{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 Ct(s,e,n){return Me.has(s)||Me.set(s,new kt(e,n)),Me.get(s)}function Xt(s){Me.delete(s)}const ct=["var(--nice-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-accent, #3f51b5)","var(--nice-primary, #2196f3)","var(--nice-info, #00bcd4)","var(--nice-success, #4caf50)","var(--nice-warning, #ff9800)","var(--nice-danger, #ff5722)","var(--nice-warning-dark, #795548)","var(--nice-text-secondary, #607d8b)"];function Jt(s){let e=0;for(let n=0;n<s.length;n++)e=e*31+s.charCodeAt(n)>>>0;return ct[e%ct.length]}function dt(s,e,n){const i={...s},r=[...e];switch(n.type){case"object:add":case"object:update":{const a=n.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}=n.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}=n.payload;i[a]&&(i[a]={...i[a],x:o,y:c,updatedAt:n.timestamp});break}case"layer:add":{const a=n.payload;r.find(o=>o.id===a.id)||r.push(a);break}case"layer:update":{const a=n.payload,o=r.findIndex(c=>c.id===a.id);o!==-1&&(r[o]={...r[o],...a});break}case"layer:delete":{const{id:a}=n.payload,o=r.findIndex(c=>c.id===a);o!==-1&&r.splice(o,1);break}}return{objects:i,layers:r}}function Qt(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:n,local:i}=e,{objects:r,layers:a}=dt(s.session.objects,s.session.layers,n),o={...s.session,objects:r,layers:a,updatedAt:n.timestamp},u=i&&["object:add","object:update","object:delete","object:move","layer:add","layer:update","layer:delete"].includes(n.type)?[...s.undoStack,[n]]:s.undoStack;return{...s,session:o,undoStack:u,redoStack:i?[]:s.redoStack,isDirty:!0}}case"UNDO":{if(s.undoStack.length===0)return s;const n=s.undoStack[s.undoStack.length-1],i=n.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:[n,...s.redoStack],isDirty:!0}}case"REDO":{if(s.redoStack.length===0)return s;const n=s.redoStack[0];let{objects:i,layers:r}={objects:s.session.objects,layers:s.session.layers};for(const a of n)({objects:i,layers:r}=dt(i,r,a));return{...s,session:{...s.session,objects:i,layers:r},undoStack:[...s.undoStack,n],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:n,x:i,y:r}=e,a=s.session.collaborators[n];return a?{...s,session:{...s.session,collaborators:{...s.session.collaborators,[n]:{...a,cursorX:i,cursorY:r,lastSeenAt:new Date}}}}:s}case"REMOVE_COLLABORATOR":{const n={...s.session.collaborators};return delete n[e.userId],{...s,session:{...s.session,collaborators:n}}}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 It(s){const{session:e,currentUser:n,onOperation:i,remoteOperations:r=[],readonly:a=!1,storageConfig:o,autoSaveMs:c=3e4}=s,[u,p]=l.useReducer(Qt,{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=Ct(`wb_${e.id}`,o),y.current.loadWhiteboardSnapshot(e.id).then(I=>{I&&p({type:"LOAD_SESSION",session:I})}))},[e.id,o]),l.useEffect(()=>{if(!c||!y.current||!u.isDirty)return;const I=setTimeout(()=>{var W;(W=y.current)==null||W.saveWhiteboardSnapshot(u.session.id,u.session).then(()=>{p({type:"MARK_SAVED"})})},c);return()=>clearTimeout(I)},[u.isDirty,u.session,c]);const h=l.useRef(new Set);l.useEffect(()=>{for(const I of r)if(!h.current.has(I.id)&&I.userId!==n.id)if(h.current.add(I.id),I.type==="cursor:move"){const{x:W,y:U}=I.payload;p({type:"UPDATE_CURSOR",userId:I.userId,x:W,y:U})}else I.type==="viewport:sync"||p({type:"APPLY_OP",op:I,local:!1})},[r,n.id]);function v(I,W){return{id:`${n.id}_${++m.current}_${Date.now()}`,sessionId:u.session.id,type:I,userId:n.id,timestamp:new Date,payload:W}}const z=l.useCallback(I=>{a||p({type:"SET_TOOL",tool:I})},[a]),d=l.useCallback(I=>{if(a)return;const W=v("object:add",I);p({type:"APPLY_OP",op:W,local:!0}),i==null||i(W)},[a,i,u.session.id]),N=l.useCallback(I=>{if(a)return;const W=v("object:update",I);p({type:"APPLY_OP",op:W,local:!0}),i==null||i(W)},[a,i,u.session.id]),R=l.useCallback(I=>{if(!a){for(const W of I){const U=v("object:delete",{id:W});p({type:"APPLY_OP",op:U,local:!0}),i==null||i(U)}p({type:"SET_SELECTION",ids:[]})}},[a,i,u.session.id]),D=l.useCallback(I=>{if(!a)for(const{id:W,x:U,y:H}of I){const g=v("object:move",{id:W,x:U,y:H});p({type:"APPLY_OP",op:g,local:!0}),i==null||i(g)}},[a,i,u.session.id]),_=l.useCallback(I=>{p({type:"SET_SELECTION",ids:I})},[]),$=l.useCallback(()=>{a||p({type:"UNDO"})},[a]),B=l.useCallback(()=>{a||p({type:"REDO"})},[a]),Y=l.useCallback(I=>{p({type:"SET_VIEWPORT",viewport:I});const W=v("viewport:sync",I);i==null||i(W)},[i,u.session.id]),O=l.useCallback((I,W)=>{if(f.current)return;f.current=setTimeout(()=>{f.current=null},50);const U=v("cursor:move",{x:I,y:W});i==null||i(U)},[i,u.session.id]),G=l.useCallback(I=>{if(a)return;const W={id:`layer_${Date.now()}`,name:I,visible:!0,locked:!1,objectIds:[]},U=v("layer:add",W);p({type:"APPLY_OP",op:U,local:!0}),i==null||i(U)},[a,i,u.session.id]),C=l.useCallback(I=>{if(a)return;const W=v("layer:update",I);p({type:"APPLY_OP",op:W,local:!0}),i==null||i(W)},[a,i,u.session.id]),k=l.useCallback(I=>{if(a)return;const W=v("layer:delete",{id:I});p({type:"APPLY_OP",op:W,local:!0}),i==null||i(W)},[a,i,u.session.id]),M=l.useCallback(I=>{const W={user:I,cursorX:0,cursorY:0,color:Jt(I.id),selectedObjectIds:[],activeTool:"pen",lastSeenAt:new Date};p({type:"APPLY_OP",op:v("cursor:move",W),local:!1})},[]),K=l.useCallback(I=>{p({type:"REMOVE_COLLABORATOR",userId:I})},[]),P=l.useCallback(async()=>{y.current&&(await y.current.saveWhiteboardSnapshot(u.session.id,u.session),p({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:z,addObject:d,updateObject:N,deleteObjects:R,moveObjects:D,setSelection:_,undo:$,redo:B,setViewport:Y,broadcastCursor:O,addLayer:G,updateLayer:C,deleteLayer:k,registerCollaborator:M,removeCollaborator:K,saveNow:P}}const Zt=[{id:"select",label:"Select",icon:"cursor",group:"select"},{id:"laser",label:"Laser",icon:"circle",group:"select"},{id:"pen",label:"Pen",icon:"pen",group:"draw"},{id:"highlighter",label:"Highlight",icon:"brush",group:"draw"},{id:"eraser",label:"Eraser",icon:"eraser",group:"draw"},{id:"line",label:"Line",icon:"line",group:"shape"},{id:"arrow",label:"Arrow",icon:"arrow-right",group:"shape"},{id:"rect",label:"Rectangle",icon:"square",group:"shape"},{id:"ellipse",label:"Ellipse",icon:"circle",group:"shape"},{id:"triangle",label:"Triangle",icon:"triangle",group:"shape"},{id:"frame",label:"Frame",icon:"crop",group:"shape"},{id:"text",label:"Text",icon:"type",group:"insert"},{id:"sticky",label:"Sticky",icon:"clipboard",group:"insert"},{id:"image",label:"Image",icon:"image",group:"insert"}];function Ee(){return`${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Be(s,e,n){return{sx:s*n.scale+n.x,sy:e*n.scale+n.y}}function en(s,e,n){return{wx:(s-n.x)/n.scale,wy:(e-n.y)/n.scale}}function tn(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function nn(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 n=1;n<e.points.length;n++){const i={x:(e.points[n-1].x+e.points[n].x)/2,y:(e.points[n-1].y+e.points[n].y)/2};s.quadraticCurveTo(e.points[n-1].x,e.points[n-1].y,i.x,i.y)}s.stroke(),s.restore()}}function sn(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 n=e.width/2,i=e.height/2;s.moveTo(0,-i),s.lineTo(n,i),s.lineTo(-n,i),s.closePath();break}case"diamond":{const n=e.width/2,i=e.height/2;s.moveTo(0,-i),s.lineTo(n,0),s.lineTo(0,i),s.lineTo(-n,0),s.closePath();break}}e.fillColor&&s.fill(),s.stroke(),s.restore()}function rn(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 n=s.measureText(e.text),i=4;s.fillStyle=e.backgroundColor,s.fillRect(-n.width/2-i,-e.fontSize/2-i,n.width+i*2,e.fontSize+i*2),s.fillStyle=e.color}s.fillText(e.text,0,0),s.restore()}function an(s,e){s.save(),s.translate(e.x,e.y),s.rotate(e.rotation*Math.PI/180),s.shadowColor="var(--nice-overlay-15, 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 n=10,i=e.width-n*2,r=e.fontSize*1.4,a=e.text.split(" ");let o="",c=n;for(const u of a){const p=o?`${o} ${u}`:u;s.measureText(p).width>i&&o?(s.fillText(o,n,c),o=u,c+=r):o=p}o&&s.fillText(o,n,c),s.restore()}function on(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 n=1;n<e.points.length-1;n++){const i=e.points[n],r={x:(i.x+e.points[n+1].x)/2,y:(i.y+e.points[n+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 n=1;n<e.points.length;n++)s.lineTo(e.points[n].x,e.points[n].y);if(s.stroke(),e.arrowEnd==="arrow"){const n=e.points[e.points.length-1],i=e.points[e.points.length-2],r=Math.atan2(n.y-i.y,n.x-i.x),a=12;s.beginPath(),s.moveTo(n.x,n.y),s.lineTo(n.x-a*Math.cos(r-Math.PI/6),n.y-a*Math.sin(r-Math.PI/6)),s.moveTo(n.x,n.y),s.lineTo(n.x-a*Math.cos(r+Math.PI/6),n.y-a*Math.sin(r+Math.PI/6)),s.stroke()}s.restore()}}function ln(s,e){s.save(),s.strokeStyle=e.borderColor??"var(--nice-text-muted, #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="var(--nice-text-secondary, #555)",s.font="bold 13px sans-serif",s.fillText(e.name,e.x+8,e.y-6),s.restore()}function cn(s,e){if(e.visible)switch(e.type){case"stroke":return nn(s,e);case"shape":return sn(s,e);case"text":return rn(s,e);case"sticky":return an(s,e);case"connector":return on(s,e);case"frame":return ln(s,e);case"image":{const n=e,i=new Image;i.src=n.dataUrl??n.url,s.save(),s.translate(n.x+n.width/2,n.y+n.height/2),s.rotate(n.rotation*Math.PI/180),s.drawImage(i,-n.width/2,-n.height/2,n.width,n.height),s.restore();break}}}function tt(s){const{t:e}=w.useNiceTranslation();return s.session?t.jsx(dn,{...s,session:s.session}):t.jsx("div",{className:s.className,style:s.style,"data-testid":s["data-testid"],children:t.jsx(w.NiceEmpty,{title:e("whiteboard.noSession","No whiteboard session")})})}function dn({session:s,currentUser:e,onOperation:n,remoteOperations:i=[],readonly:r=!1,enableLayers:a=!0,enableExport:o=!0,enableLaserPointer:c=!0,enableVectorEditor:u=!1,enableDiagramEditor:p=!1,onExport:m,onSessionUpdate:f,storageConfig:y,className:h,style:v,"data-testid":z}){const d=It({session:s,currentUser:e,onOperation:n,remoteOperations:i,readonly:r,storageConfig:y,autoSaveMs:3e4}),N=l.useRef(null);l.useRef(null);const R=l.useRef(0),[D,_]=l.useState(!1),[$,B]=l.useState("var(--nice-bg, #1a1a1a)"),[Y,O]=l.useState(3),[G,C]=l.useState(void 0),[k,M]=l.useState(18),[K,P]=l.useState("var(--nice-warning-bg, #fef08a)"),[I,W]=l.useState(null),[U,H]=l.useState(null),g=l.useRef({active:!1,startX:0,startY:0,currentPoints:[],currentId:"",spaceDown:!1,panStart:null,laserPoints:[]}),S=l.useCallback((x,b,E,L)=>{if(!d.session.gridEnabled)return;const A=d.session.gridSize*b.scale,V=(b.x%A+A)%A,j=(b.y%A+A)%A;x.strokeStyle="rgba(180,180,200,0.35)",x.lineWidth=1,x.beginPath();for(let T=V;T<E;T+=A)x.moveTo(T,0),x.lineTo(T,L);for(let T=j;T<L;T+=A)x.moveTo(0,T),x.lineTo(E,T);x.stroke()},[d.session.gridEnabled,d.session.gridSize]),J=l.useCallback((x,b)=>{for(const E of d.collaborators){if(E.user.id===e.id)continue;const{sx:L,sy:A}=Be(E.cursorX,E.cursorY,b);x.save(),x.fillStyle=E.color,x.beginPath(),x.moveTo(L,A),x.lineTo(L+14,A+5),x.lineTo(L+5,A+14),x.closePath(),x.fill(),x.fillStyle=E.color,x.font="bold 11px sans-serif",x.fillText(E.user.name,L+16,A+14),x.restore()}},[d.collaborators,e.id]),X=l.useCallback((x,b)=>{if(d.selectedObjectIds.length!==0)for(const E of d.selectedObjectIds){const L=d.session.objects[E];if(!L)continue;const{sx:A,sy:V}=Be(L.x,L.y,b),j=L.width*b.scale,T=L.height*b.scale;x.strokeStyle="var(--nice-primary, #4f8df9)",x.lineWidth=1.5,x.setLineDash([4,2]),x.strokeRect(A-2,V-2,j+4,T+4),x.setLineDash([]);const te=[[A-2,V-2],[A+j+2,V-2],[A-2,V+T+2],[A+j+2,V+T+2]];x.fillStyle="var(--nice-bg, #fff)",x.strokeStyle="var(--nice-primary, #4f8df9)",x.lineWidth=1.5;for(const[ee,se]of te)x.fillRect(ee-4,se-4,8,8),x.strokeRect(ee-4,se-4,8,8)}},[d.selectedObjectIds,d.session.objects]),Z=l.useCallback(()=>{const x=N.current;if(!x)return;const b=x.getContext("2d");if(!b)return;const{width:E,height:L}=x,A=d.viewport;b.clearRect(0,0,E,L),b.fillStyle=d.session.backgroundColor,b.fillRect(0,0,E,L),S(b,A,E,L),b.save();const V=Object.values(d.session.objects).filter(j=>j.visible).sort((j,T)=>j.zIndex-T.zIndex);b.translate(A.x,A.y),b.scale(A.scale,A.scale);for(const j of V)cn(b,j);if(g.current.active&&g.current.currentPoints.length>1){const j=g.current.currentPoints;b.strokeStyle=$,b.lineWidth=Y,b.lineCap="round",b.lineJoin="round",b.beginPath(),b.moveTo(j[0].x,j[0].y);for(let T=1;T<j.length;T++)b.lineTo(j[T].x,j[T].y);b.stroke()}if(g.current.laserPoints.length>1&&d.activeTool==="laser"){const j=g.current.laserPoints;b.strokeStyle="#ff2c2c",b.lineWidth=3,b.globalAlpha=.7,b.beginPath(),b.moveTo(j[0].x,j[0].y);for(let T=1;T<j.length;T++)b.lineTo(j[T].x,j[T].y);b.stroke(),b.globalAlpha=1}b.restore(),X(b,A),J(b,A)},[d.session,d.viewport,d.activeTool,S,J,X,$,Y]);l.useLayoutEffect(()=>{function x(){Z(),R.current=requestAnimationFrame(x)}return R.current=requestAnimationFrame(x),()=>cancelAnimationFrame(R.current)},[Z]),l.useEffect(()=>{const x=N.current;if(!x)return;const b=new ResizeObserver(()=>{x.width=x.offsetWidth,x.height=x.offsetHeight});return b.observe(x),x.width=x.offsetWidth,x.height=x.offsetHeight,()=>b.disconnect()},[]),l.useEffect(()=>{function x(b){if(b.target.tagName==="INPUT"||b.target.tagName==="TEXTAREA"||(b.code==="Space"&&(g.current.spaceDown=b.type==="keydown",b.preventDefault()),b.type!=="keydown"))return;(b.ctrlKey||b.metaKey)&&(b.key==="z"&&(b.preventDefault(),d.undo()),b.key==="y"&&(b.preventDefault(),d.redo()),b.key==="s"&&(b.preventDefault(),d.saveNow()),b.key==="a"&&(b.preventDefault(),d.setSelection(Object.keys(d.session.objects)))),(b.key==="Delete"||b.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"};!b.ctrlKey&&!b.metaKey&&E[b.key]&&d.setTool(E[b.key])}return window.addEventListener("keydown",x),window.addEventListener("keyup",x),()=>{window.removeEventListener("keydown",x),window.removeEventListener("keyup",x)}},[d]);const q=l.useCallback(x=>{const b=N.current.getBoundingClientRect(),E=x.clientX-b.left,L=x.clientY-b.top,{wx:A,wy:V}=en(E,L,d.viewport);return{x:A,y:V,pressure:x.pressure??.5}},[d.viewport]),ae=l.useCallback(x=>{if(r)return;x.target.setPointerCapture(x.pointerId);const b=q(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=b.x,g.current.startY=b.y,g.current.currentId=Ee(),E==="pen"||E==="highlighter")g.current.currentPoints=[b];else if(E==="laser")g.current.laserPoints=[b];else if(E==="select"){const L=Object.values(d.session.objects).filter(A=>A.visible&&A.x<=b.x&&A.y<=b.y&&A.x+A.width>=b.x&&A.y+A.height>=b.y).sort((A,V)=>V.zIndex-A.zIndex)[0];L?x.shiftKey?d.setSelection([...d.selectedObjectIds,L.id]):d.setSelection([L.id]):d.setSelection([])}},[r,q,d]),oe=l.useCallback(x=>{const b=q(x);if(d.broadcastCursor(b.x,b.y),g.current.panStart){const{x:L,y:A,vpX:V,vpY:j}=g.current.panStart;d.setViewport({...d.viewport,x:V+(x.clientX-L),y:j+(x.clientY-A)});return}if(!g.current.active)return;const E=d.activeTool;if(E==="pen"||E==="highlighter"){const L=g.current.currentPoints;(L.length===0||tn(L[L.length-1],b)>2)&&(g.current.currentPoints=[...L,b])}else if(E==="laser"){const L=g.current.laserPoints;g.current.laserPoints=[...L.slice(-40),b]}else if(E==="select"&&d.selectedObjectIds.length>0){const L=b.x-g.current.startX,A=b.y-g.current.startY;g.current.startX=b.x,g.current.startY=b.y,d.moveObjects(d.selectedObjectIds.map(V=>{const j=d.session.objects[V];return{id:V,x:j.x+L,y:j.y+A}}))}},[q,d]),fe=l.useCallback(x=>{if(g.current.panStart){g.current.panStart=null;return}if(!g.current.active)return;const b=q(x),E=d.activeTool,L=g.current.startX,A=g.current.startY,V=g.current.currentId,j=new Date;switch(g.current.active=!1,E){case"pen":case"highlighter":{const T=g.current.currentPoints;if(T.length<2)break;const te={id:V,type:"stroke",x:Math.min(...T.map(ee=>ee.x)),y:Math.min(...T.map(ee=>ee.y)),width:Math.max(...T.map(ee=>ee.x))-Math.min(...T.map(ee=>ee.x)),height:Math.max(...T.map(ee=>ee.y))-Math.min(...T.map(ee=>ee.y)),rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:j,points:T,color:$,strokeWidth:Y,opacity:E==="highlighter"?.4:1,tool:E};d.addObject(te),g.current.currentPoints=[];break}case"rect":case"ellipse":case"triangle":{const T=Math.min(L,b.x),te=Math.min(A,b.y),ee=Math.abs(b.x-L),se=Math.abs(b.y-A);if(ee<5||se<5)break;const de={rect:"rect",ellipse:"ellipse",triangle:"triangle"},ye={id:V,type:"shape",x:T,y:te,width:ee,height:se,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:j,shape:de[E],fillColor:G,strokeColor:$,strokeWidth:Y,opacity:1};d.addObject(ye);break}case"arrow":case"line":{const T={id:V,type:"connector",x:Math.min(L,b.x),y:Math.min(A,b.y),width:Math.abs(b.x-L),height:Math.abs(b.y-A),rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:j,points:[{x:L,y:A},{x:b.x,y:b.y}],strokeColor:$,strokeWidth:Y,arrowStart:"none",arrowEnd:E==="arrow"?"arrow":"none",curved:!1};d.addObject(T);break}case"text":{const T={id:V,type:"text",x:b.x,y:b.y,width:200,height:k+10,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:j,text:"Click to edit",fontSize:k,fontFamily:"sans-serif",fontWeight:"normal",fontStyle:"normal",textAlign:"left",color:$};d.addObject(T),W(V);break}case"sticky":{const T={id:V,type:"sticky",x:b.x,y:b.y,width:180,height:150,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:j,text:"Note...",backgroundColor:K,textColor:"var(--nice-text, #333)",fontSize:14,authorId:e.id};d.addObject(T),W(V);break}case"frame":{const T=Math.min(L,b.x),te=Math.min(A,b.y),ee=Math.abs(b.x-L),se=Math.abs(b.y-A);if(ee<20||se<20)break;const de={id:V,type:"frame",x:T,y:te,width:ee,height:se,rotation:0,zIndex:0,locked:!1,visible:!0,createdBy:e.id,createdAt:j,name:`Frame ${Object.keys(d.session.objects).length+1}`,childIds:[],borderColor:"#8888"};d.addObject(de);break}case"image":{const T=document.createElement("input");T.type="file",T.accept="image/*",T.onchange=()=>{var se;const te=(se=T.files)==null?void 0:se[0];if(!te)return;const ee=new FileReader;ee.onload=de=>{var Pe;const ye=(Pe=de.target)==null?void 0:Pe.result,he=new Image;he.onload=()=>{const Ae=400/he.width,xe={id:Ee(),type:"image",x:b.x,y:b.y,width:he.width*Ae,height:he.height*Ae,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:ye,dataUrl:ye,originalWidth:he.width,originalHeight:he.height};d.addObject(xe)},he.src=ye},ee.readAsDataURL(te)},T.click();break}}},[q,d,e.id,$,Y,G,k,K]),le=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 b=N.current.getBoundingClientRect(),E=x.clientX-b.left,L=x.clientY-b.top,V=-x.deltaY>0?1.1:.9,j=Math.min(8,Math.max(.1,d.viewport.scale*V));d.setViewport({scale:j,x:E-(E-d.viewport.x)*(j/d.viewport.scale),y:L-(L-d.viewport.y)*(j/d.viewport.scale)})},[d]),F=l.useCallback(x=>{if(x==="json"){const A=JSON.stringify(d.session,null,2);m==null||m("json",A);const V=document.createElement("a");V.href=URL.createObjectURL(new Blob([A],{type:"application/json"})),V.download=`${d.session.title}.json`,V.click();return}const b=N.current;if(!b)return;const E=b.toDataURL("image/png");m==null||m("png",E);const L=document.createElement("a");L.href=E,L.download=`${d.session.title}.png`,L.click()},[d.session,m]);l.useEffect(()=>{f==null||f(d.session)},[d.session,f]),l.useEffect(()=>{function x(b){if(b.clipboardData){for(const E of Array.from(b.clipboardData.items))if(E.type.startsWith("image/")){const L=E.getAsFile();if(!L)continue;const A=new FileReader;A.onload=V=>{var te;const j=(te=V.target)==null?void 0:te.result,T=new Image;T.onload=()=>{const se=400/T.width,de={id:Ee(),type:"image",x:100,y:100,width:T.width*se,height:T.height*se,rotation:0,zIndex:Object.keys(d.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:j,dataUrl:j,originalWidth:T.width,originalHeight:T.height};d.addObject(de)},T.src=j},A.readAsDataURL(L);break}}}return window.addEventListener("paste",x),()=>window.removeEventListener("paste",x)},[d,e.id]);const Q=I?d.session.objects[I]:null,ie=l.useMemo(()=>Q?Be(Q.x,Q.y,d.viewport):null,[Q,d.viewport]),re=["var(--nice-warning-bg, #fef08a)","var(--nice-primary-bg, #bfdbfe)","#bbf7d0","var(--nice-danger-bg, #fecaca)","var(--nice-accent-bg, #e9d5ff)","var(--nice-warning-bg, #fed7aa)"],ce=l.useMemo(()=>{var b;const x={};for(const E of Zt)(x[b=E.group]??(x[b]=[])).push(E);return Object.values(x)},[]);return t.jsxs("div",{className:h,"data-testid":z,style:{position:"relative",display:"flex",flexDirection:"column",width:"100%",height:"100%",overflow:"hidden",background:"var(--nice-bg-secondary, #f5f5f5)",fontFamily:"system-ui, sans-serif",...v},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",background:"var(--nice-bg, #fff)",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0,flexWrap:"wrap"},children:[ce.map((x,b)=>t.jsxs(l.Fragment,{children:[b>0&&t.jsx("div",{style:{width:1,height:24,background:"var(--nice-border, #e5e7eb)",margin:"0 2px"}}),x.map(E=>t.jsx("button",{onClick:()=>d.setTool(E.id),title:`${E.label}`,style:{padding:"4px 7px",border:`1.5px solid ${d.activeTool===E.id?"var(--nice-info, #6366f1)":"transparent"}`,borderRadius:6,background:d.activeTool===E.id?"var(--nice-primary-bg, #eef2ff)":"transparent",cursor:"pointer",fontSize:15,minWidth:30,color:d.activeTool===E.id?"var(--nice-accent, #4f46e5)":"var(--nice-text, #374151)",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:t.jsx(w.NiceIcon,{name:E.icon,size:15})},E.id))]},b)),t.jsx("div",{style:{width:1,height:24,background:"var(--nice-border, #e5e7eb)",margin:"0 4px"}}),t.jsxs("label",{title:"Stroke color",style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:"Color"}),t.jsx("input",{type:"color",value:$,onChange:x=>B(x.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}})]}),t.jsxs("label",{title:"Fill color",style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:"Fill"}),t.jsx("input",{type:"color",value:G??"var(--nice-bg, #fff)",onChange:x=>C(x.target.value==="var(--nice-bg, #fff)"?void 0:x.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}}),t.jsx("button",{onClick:()=>C(void 0),style:{fontSize:11,padding:"1px 5px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:4,cursor:"pointer",background:G?"var(--nice-bg, #fff)":"var(--nice-bg-secondary, #f3f4f6)"},children:"No fill"})]}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:4},children:[t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:"Width"}),t.jsx("input",{type:"range",min:1,max:24,step:1,value:Y,onChange:x=>O(Number(x.target.value)),style:{width:70}}),t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",minWidth:20},children:Y})]}),d.activeTool==="sticky"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:"Note:"}),re.map(x=>t.jsx("button",{onClick:()=>P(x),style:{width:20,height:20,background:x,border:`2px solid ${K===x?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)"}`,borderRadius:4,cursor:"pointer"}},x))]}),t.jsx("div",{style:{flex:1}}),t.jsx("button",{onClick:d.undo,disabled:!d.canUndo,title:"Undo (Ctrl+Z)","aria-label":"Undo",style:ue(!d.canUndo),children:t.jsx(w.NiceIcon,{name:"reply",size:13})}),t.jsx("button",{onClick:d.redo,disabled:!d.canRedo,title:"Redo (Ctrl+Y)","aria-label":"Redo",style:ue(!d.canRedo),children:t.jsx(w.NiceIcon,{name:"forward",size:13})}),t.jsx("div",{style:{width:1,height:24,background:"var(--nice-border, #e5e7eb)"}}),t.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",minWidth:42,textAlign:"center"},children:[Math.round(d.viewport.scale*100),"%"]}),t.jsx("button",{onClick:()=>d.setViewport({x:0,y:0,scale:1}),style:ue(),title:"Reset zoom","aria-label":"Reset zoom",children:t.jsx(w.NiceIcon,{name:"target",size:13})}),a&&t.jsx("button",{onClick:()=>_(x=>!x),style:ue(!1,D),title:"Layers","aria-label":"Layers",children:t.jsx(w.NiceIcon,{name:"layers",size:13})}),t.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}};n==null||n(x)},style:ue(!1,d.session.gridEnabled),title:"Toggle grid","aria-label":"Toggle grid",children:t.jsx(w.NiceIcon,{name:"hash",size:13})}),u&&t.jsx("button",{onClick:()=>H(x=>x==="vector"?null:"vector"),style:ue(!1,U==="vector"),title:"Vector Editor panel","aria-label":"Vector Editor panel",children:t.jsx(w.NiceIcon,{name:"pen",size:13})}),p&&t.jsx("button",{onClick:()=>H(x=>x==="diagram"?null:"diagram"),style:ue(!1,U==="diagram"),title:"Diagram Editor panel","aria-label":"Diagram Editor panel",children:t.jsx(w.NiceIcon,{name:"hexagon",size:13})}),t.jsx("button",{onClick:()=>void d.saveNow(),style:ue(),title:"Save (Ctrl+S)","aria-label":"Save",children:t.jsxs("span",{style:{display:"inline-flex",alignItems:"center"},children:[t.jsx(w.NiceIcon,{name:"save",size:13}),d.isDirty&&"*"]})}),o&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>F("png"),style:ue(),title:"Export PNG","aria-label":"Export PNG",children:t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:2},children:["PNG",t.jsx(w.NiceIcon,{name:"download",size:12})]})}),t.jsx("button",{onClick:()=>F("json"),style:ue(),title:"Export JSON","aria-label":"Export JSON",children:t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:2},children:["JSON",t.jsx(w.NiceIcon,{name:"download",size:12})]})})]})]}),t.jsxs("div",{style:{display:"flex",flex:1,overflow:"hidden",position:"relative"},children:[t.jsx("canvas",{ref:N,style:{flex:1,display:"block",cursor:pn(d.activeTool,g.current.spaceDown)},onPointerDown:ae,onPointerMove:oe,onPointerUp:fe,onWheel:le,onContextMenu:x=>x.preventDefault()}),a&&D&&t.jsx(un,{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)}),U&&t.jsxs("div",{style:{position:"absolute",right:D?220:0,top:0,bottom:0,width:360,background:"var(--nice-bg, #fff)",borderLeft:"1px solid var(--nice-border, #e5e7eb)",padding:12,overflowY:"auto"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[t.jsx("strong",{style:{fontSize:13},children:U==="vector"?"Vector Editor":"Diagram Editor"}),t.jsx("button",{onClick:()=>H(null),style:{border:"none",background:"none",cursor:"pointer",fontSize:16},"aria-label":"Close",children:t.jsx(w.NiceIcon,{name:"close",size:16})})]}),t.jsx("p",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:U==="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."}),t.jsx("div",{id:`wb-integration-${U}`,style:{width:"100%",height:400}})]})]}),d.collaborators.length>1&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",background:"var(--nice-bg, #fff)",borderTop:"1px solid var(--nice-bg-secondary, #f3f4f6)",fontSize:11,color:"var(--nice-text-secondary, #6b7280)",flexShrink:0},children:[t.jsx("span",{children:"Collaborators:"}),d.collaborators.map(x=>t.jsxs("span",{style:{display:"flex",alignItems:"center",gap:3},children:[t.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:x.color,display:"inline-block"}}),x.user.name]},x.user.id)),d.isDirty&&t.jsxs("span",{style:{marginLeft:"auto",color:"var(--nice-warning, #f59e0b)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(w.NiceIcon,{name:"circle",size:10})," unsaved"]}),d.lastSavedAt&&!d.isDirty&&t.jsxs("span",{style:{marginLeft:"auto",color:"var(--nice-success, #10b981)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(w.NiceIcon,{name:"check",size:10})," Saved ",d.lastSavedAt.toLocaleTimeString()]})]}),Q&&ie&&t.jsx("textarea",{autoFocus:!0,defaultValue:Q.text,onBlur:x=>{const b={...Q,text:x.target.value,updatedAt:new Date,updatedBy:e.id};d.updateObject(b),W(null)},style:{position:"absolute",left:ie.sx,top:ie.sy,minWidth:Q.width*d.viewport.scale,minHeight:Q.height*d.viewport.scale,fontSize:(Q.fontSize??14)*d.viewport.scale,fontFamily:"sans-serif",background:Q.type==="sticky"?Q.backgroundColor:"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",border:"2px solid var(--nice-info, #6366f1)",borderRadius:4,padding:6,resize:"both",zIndex:1e3,color:Q.type==="sticky"?Q.textColor:Q.color}})]})}function un({layers:s,objects:e,onAdd:n,onUpdate:i,onDelete:r}){return t.jsxs("div",{style:{width:200,borderLeft:"1px solid var(--nice-border, #e5e7eb)",background:"var(--nice-bg, #fff)",display:"flex",flexDirection:"column",padding:8,gap:4,overflowY:"auto",flexShrink:0},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[t.jsx("strong",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:"Layers"}),t.jsx("button",{onClick:n,style:{fontSize:16,border:"none",background:"none",cursor:"pointer",color:"var(--nice-info, #6366f1)",display:"inline-flex",alignItems:"center"},title:"Add layer","aria-label":"Add layer",children:t.jsx(w.NiceIcon,{name:"plus",size:16})})]}),[...s].reverse().map(a=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",borderRadius:5,background:"var(--nice-bg-secondary, #f9fafb)",opacity:a.visible?1:.5},children:[t.jsx("button",{onClick:()=>i({id:a.id,visible:!a.visible}),title:"Toggle visibility","aria-label":"Toggle visibility",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,display:"inline-flex",alignItems:"center",color:a.visible?"var(--nice-text, #374151)":"var(--nice-text-muted, #9ca3af)"},children:t.jsx(w.NiceIcon,{name:a.visible?"eye":"eye-off",size:13})}),t.jsx("button",{onClick:()=>i({id:a.id,locked:!a.locked}),title:"Toggle lock","aria-label":"Toggle lock",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,display:"inline-flex",alignItems:"center",opacity:a.locked?1:.5},children:t.jsx(w.NiceIcon,{name:"lock",size:13})}),t.jsx("span",{style:{flex:1,fontSize:11,color:"var(--nice-text, #374151)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.name}),t.jsx("span",{style:{fontSize:10,color:"var(--nice-text-muted, #9ca3af)"},children:a.objectIds.filter(o=>o in e).length}),s.length>1&&t.jsx("button",{onClick:()=>r(a.id),title:"Delete layer","aria-label":"Delete layer",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,display:"inline-flex",alignItems:"center",color:"var(--nice-danger, #ef4444)"},children:t.jsx(w.NiceIcon,{name:"trash",size:13})})]},a.id))]})}function ue(s=!1,e=!1){return{padding:"4px 8px",border:`1.5px solid ${e?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)"}`,borderRadius:6,background:e?"var(--nice-primary-bg, #eef2ff)":"var(--nice-bg, #fff)",cursor:s?"default":"pointer",opacity:s?.35:1,fontSize:13,color:e?"var(--nice-accent, #4f46e5)":"var(--nice-text, #374151)",fontWeight:e?600:400}}function pn(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 ve({icon:s,label:e,active:n,badge:i,onClick:r}){return t.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[t.jsxs("button",{title:e,onClick:r,style:{width:44,height:44,borderRadius:10,border:"none",background:n?"var(--nice-overlay-light-20, rgba(255, 255, 255, 0.2))":"transparent",color:"var(--nice-bg, #fff)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",position:"relative"},children:[t.jsx(w.NiceIcon,{name:s,size:20}),i!=null&&i>0&&t.jsx("span",{style:{position:"absolute",top:4,right:4,background:"var(--nice-danger, #ef4444)",color:"var(--nice-bg, #fff)",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700,lineHeight:1.4},children:i>99?"99+":i})]}),t.jsx("span",{style:{fontSize:9,color:"var(--nice-overlay-light-70, rgba(255, 255, 255, 0.7))",letterSpacing:"0.03em"},children:e})]})}function fn({team:s,activeChannelId:e,onSelectChannel:n}){var o;const[i,r]=l.useState(!1),a=s.channels.reduce((c,u)=>c+u.unreadCount,0);return t.jsxs("div",{className:"nice-workspace-team",children:[t.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:"var(--nice-text, #374151)",fontSize:13,fontWeight:600},children:[t.jsx("span",{style:{color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:i?"chevron-right":"chevron-down",size:12})}),t.jsx("div",{style:{width:20,height:20,borderRadius:4,background:s.avatarUrl?`url(${s.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",fontWeight:700,fontSize:9,flexShrink:0},children:!s.avatarUrl&&((o=s.name[0])==null?void 0:o.toUpperCase())}),t.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.name}),!i&&a>0&&t.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-bg, #fff)",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:a})]}),!i&&s.channels.map(c=>t.jsxs("button",{onClick:()=>n(s.id,c.id),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 10px 5px 34px",background:c.id===e?"var(--nice-accent-bg, #ede9fe)":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:c.unreadCount>0?"var(--nice-text, #111827)":"var(--nice-text-secondary, #4b5563)",fontSize:13,fontWeight:c.unreadCount>0?600:400},children:[t.jsx("span",{style:{color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:c.isPrivate?"lock":"hash",size:12})}),t.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.name}),c.mentionCount>0&&t.jsxs("span",{style:{background:"var(--nice-danger, #ef4444)",color:"var(--nice-bg, #fff)",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:["@",c.mentionCount]}),c.unreadCount>0&&c.mentionCount===0&&t.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-bg, #fff)",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700},children:c.unreadCount})]},c.id))]})}function hn({conversation:s,partner:e,isActive:n,onClick:i}){var a;const r=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??s.name??"Group";return t.jsxs("button",{onClick:i,style:{display:"flex",alignItems:"center",gap:8,padding:"5px 10px",background:n?"var(--nice-accent-bg, #ede9fe)":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:s.unreadCount>0?"var(--nice-text, #111827)":"var(--nice-text-secondary, #4b5563)",fontWeight:s.unreadCount>0?600:400,fontSize:13},children:[t.jsxs("div",{style:{position:"relative",flexShrink:0},children:[t.jsx("div",{style:{width:24,height:24,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",fontWeight:700,fontSize:10},children:!(e!=null&&e.avatarUrl)&&((a=r[0])==null?void 0:a.toUpperCase())}),e&&t.jsx(pe,{status:e.presence.status,size:"xs",style:{position:"absolute",bottom:-1,right:-1}})]}),t.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),s.unreadCount>0&&t.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-bg, #fff)",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700,flexShrink:0},children:s.unreadCount})]})}function zt({currentUser:s,users:e,teams:n,conversations:i,messages:r,activeCall:a,incomingCall:o,meetings:c,transport:u,rtcConfig:p,enableCalls:m=!0,enableMeetings:f=!0,enableScreenSharing:y=!0,enableWhiteboard:h=!1,storageConfig:v,onSendMessage:z,onEditMessage:d,onDeleteMessage:N,onReactToMessage:R,onPinMessage:D,onLoadMoreMessages:_,onMarkAsRead:$,onStartCall:B,onAcceptCall:Y,onDeclineCall:O,onEndCall:G,onMuteAudio:C,onMuteVideo:k,onStartScreenShare:M,onStopScreenShare:K,className:P,style:I,id:W,"data-testid":U}){var A,V;const[H,g]=l.useState("teams"),[S,J]=l.useState(null),[X,Z]=l.useState(""),[q,ae]=l.useState(null),oe=()=>{q||ae({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:"var(--nice-bg, #fff)",gridEnabled:!0,gridSize:20,snapEnabled:!0,createdAt:new Date,updatedAt:new Date,ownerId:s.id,permissions:"edit"})},fe=l.useMemo(()=>{const j=new Map;return e.forEach(T=>j.set(T.id,T)),j},[e]),le=l.useMemo(()=>Je(i),[i]),F=l.useMemo(()=>i.reduce((j,T)=>j+T.mentionCount,0),[i]),Q=l.useMemo(()=>{if(S!=null&&S.channelId)for(const j of n){const T=j.channels.find(te=>te.id===S.channelId);if(T)return T}},[n,S]),ie=l.useMemo(()=>{if(S!=null&&S.teamId)return n.find(j=>j.id===S.teamId)},[n,S]),re=l.useMemo(()=>i.find(j=>j.id===(S==null?void 0:S.conversationId))??null,[i,S]),ce=l.useMemo(()=>{const j=(S==null?void 0:S.channelId)??(S==null?void 0:S.conversationId);return j?r[j]??[]:[]},[r,S]),x=!!o&&!a,b=!!a,E=l.useMemo(()=>i.filter(j=>j.type==="dm"||j.type==="group"),[i]),L=l.useMemo(()=>{if(!X)return E;const j=X.toLowerCase();return E.filter(T=>{var ee;const te=fe.get(T.participantIds.find(se=>se!==s.id)??"");return(te==null?void 0:te.name.toLowerCase().includes(j))||((ee=T.name)==null?void 0:ee.toLowerCase().includes(j))})},[E,X,fe,s.id]);return t.jsxs("div",{id:W,"data-testid":U,className:`nice-teams-workspace${P?` ${P}`:""}`,style:{position:"relative",height:"100%",...I},children:[t.jsx(w.NiceAppShell,{flush:!0,height:"100%",className:"nice-teams-workspace__shell",style:{background:"var(--nice-bg, #fff)",overflow:"hidden"},sidebar:t.jsxs("div",{style:{display:"flex",height:"100%",minHeight:0},children:[t.jsxs("div",{className:"nice-workspace-nav-rail",style:{width:64,flexShrink:0,background:"var(--nice-accent, #4f46e5)",display:"flex",flexDirection:"column",alignItems:"center",padding:"12px 0",gap:6},children:[t.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:s.avatarUrl?`url(${s.avatarUrl}) center/cover`:"var(--nice-accent, #818cf8)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",fontWeight:700,fontSize:14,marginBottom:8,flexShrink:0},children:!s.avatarUrl&&((A=s.name[0])==null?void 0:A.toUpperCase())}),t.jsx(ve,{icon:"zap",label:"Activity",active:H==="activity",badge:F,onClick:()=>g("activity")}),t.jsx(ve,{icon:"message",label:"Chat",active:H==="chat",badge:le,onClick:()=>g("chat")}),t.jsx(ve,{icon:"users",label:"Teams",active:H==="teams",onClick:()=>g("teams")}),m&&t.jsx(ve,{icon:"phone",label:"Calls",active:H==="calls",onClick:()=>g("calls")}),f&&t.jsx(ve,{icon:"calendar",label:"Meetings",active:H==="meetings",onClick:()=>g("meetings")}),t.jsx(ve,{icon:"folder",label:"Files",active:H==="files",onClick:()=>g("files")}),h&&t.jsx(ve,{icon:"edit",label:"Board",active:H==="whiteboard",onClick:()=>{g("whiteboard"),oe()}})]}),t.jsxs("div",{className:"nice-workspace-sidebar",style:{width:240,flexShrink:0,borderRight:"1px solid var(--nice-border, #e5e7eb)",display:"flex",flexDirection:"column",background:"var(--nice-bg-secondary, #fafafa)",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"12px 10px 8px",flexShrink:0},children:[t.jsx("div",{style:{fontWeight:700,fontSize:15,color:"var(--nice-text, #374151)",marginBottom:8,textTransform:"capitalize"},children:H}),t.jsx("input",{type:"search",value:X,onChange:j=>Z(j.target.value),placeholder:`Search ${H}…`,style:{width:"100%",padding:"5px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,fontSize:12,outline:"none",boxSizing:"border-box",background:"var(--nice-bg, #fff)"}})]}),t.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[H==="teams"&&t.jsx(t.Fragment,{children:n.map(j=>t.jsx(fn,{team:j,activeChannelId:S==null?void 0:S.channelId,onSelectChannel:(T,te)=>{J({type:"channel",teamId:T,channelId:te}),$==null||$(te)}},j.id))}),H==="chat"&&t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:"var(--nice-text-muted, #9ca3af)",fontWeight:600,letterSpacing:"0.05em"},children:"DIRECT MESSAGES"}),L.map(j=>{const T=fe.get(j.participantIds.find(te=>te!==s.id)??"");return t.jsx(hn,{conversation:j,partner:T,isActive:(S==null?void 0:S.conversationId)===j.id,onClick:()=>{J({type:j.type==="dm"?"dm":"group",conversationId:j.id}),$==null||$(j.id)}},j.id)})]}),H==="activity"&&t.jsxs("div",{style:{padding:12},children:[i.filter(j=>j.unreadCount>0).map(j=>t.jsxs("button",{onClick:()=>{g(j.type==="channel"?"teams":"chat"),J({type:j.type==="channel"?"channel":"dm",conversationId:j.id})},style:{display:"block",width:"100%",textAlign:"left",padding:"6px 0",background:"none",border:"none",cursor:"pointer",fontSize:13,color:"var(--nice-text, #374151)"},children:[t.jsx("strong",{children:j.name??"Conversation"})," — ",j.unreadCount," unread"]},j.id)),i.every(j=>j.unreadCount===0)&&t.jsxs("p",{style:{color:"var(--nice-text-muted, #9ca3af)",fontSize:13,textAlign:"center",marginTop:24,display:"flex",alignItems:"center",justifyContent:"center",gap:4},children:["All caught up ",t.jsx(w.NiceIcon,{name:"check",size:13})]})]}),H==="calls"&&t.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("button",{onClick:()=>B==null?void 0:B(e.map(j=>j.id).filter(j=>j!==s.id),"audio"),style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-bg, #fff)",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[t.jsx(w.NiceIcon,{name:"phone",size:14})," New audio call"]}),t.jsxs("button",{onClick:()=>B==null?void 0:B(e.map(j=>j.id).filter(j=>j!==s.id),"video"),style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-bg, #fff)",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[t.jsx(w.NiceIcon,{name:"video",size:14})," New video call"]})]}),H==="meetings"&&t.jsxs("div",{style:{padding:12},children:[(c??[]).map(j=>t.jsxs("div",{style:{padding:"8px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,marginBottom:8},children:[t.jsx("div",{style:{fontWeight:600,fontSize:13},children:j.title}),t.jsx("div",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginTop:2},children:j.scheduledStart.toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}),t.jsx("button",{onClick:()=>{},style:{marginTop:6,background:"var(--nice-info, #6366f1)",color:"var(--nice-bg, #fff)",border:"none",borderRadius:6,padding:"3px 10px",fontSize:12,cursor:"pointer"},children:"Join"})]},j.id)),(c??[]).length===0&&t.jsx("p",{style:{color:"var(--nice-text-muted, #9ca3af)",fontSize:13,textAlign:"center",marginTop:24},children:"No upcoming meetings"})]}),H==="files"&&t.jsx("div",{style:{padding:12},children:t.jsx("p",{style:{color:"var(--nice-text-muted, #9ca3af)",fontSize:13,textAlign:"center",marginTop:24},children:"No files shared yet"})}),H==="whiteboard"&&t.jsxs("div",{style:{padding:12},children:[t.jsxs("button",{onClick:()=>oe(),style:{width:"100%",background:"var(--nice-info, #6366f1)",color:"var(--nice-bg, #fff)",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,marginBottom:8,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[t.jsx(w.NiceIcon,{name:"edit",size:14})," ",q?"Open whiteboard":"New whiteboard"]}),q&&t.jsxs("div",{style:{padding:"6px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,fontSize:12,color:"var(--nice-text, #374151)"},children:[t.jsx("div",{style:{fontWeight:500},children:q.title}),t.jsxs("div",{style:{color:"var(--nice-text-muted, #9ca3af)",marginTop:2},children:[Object.keys(q.objects).length," objects"]})]})]})]})]})]}),children:t.jsxs("div",{style:{flex:1,height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[(S==null?void 0:S.type)==="channel"&&Q?t.jsx(jt,{channel:Q,messages:ce,users:(ie==null?void 0:ie.members)??e,currentUser:s,team:ie,onSendMessage:z,onEditMessage:d,onDeleteMessage:N,onReactToMessage:R,onPinMessage:D,onLoadMoreMessages:_,onStartCall:m?B:void 0,style:{height:"100%"}}):((S==null?void 0:S.type)==="dm"||(S==null?void 0:S.type)==="group")&&re?t.jsx(Ne,{conversation:re,messages:ce,users:e,currentUser:s,onSendMessage:z,onEditMessage:d,onDeleteMessage:N,onReactToMessage:R,onPinMessage:D,onLoadMoreMessages:_,onStartCall:m?B:void 0,style:{height:"100%"}}):H==="whiteboard"&&q?t.jsx(tt,{session:q,currentUser:s,storageConfig:v,onSessionUpdate:j=>ae(j),style:{height:"100%"}}):t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"var(--nice-text-muted, #9ca3af)",gap:12},children:[t.jsx(w.NiceIcon,{name:H==="teams"?"users":H==="chat"?"message":H==="calls"?"phone":H==="whiteboard"?"edit":"zap",size:56}),t.jsx("span",{style:{fontSize:17,fontWeight:500},children:H==="teams"?"Select a channel to get started":H==="chat"?"Select a conversation":H==="calls"?"Start or join a call":H==="whiteboard"?'Click "New whiteboard" to start':"Nothing selected"})]}),b&&a&&t.jsx("div",{style:{position:"absolute",inset:0,zIndex:50},children:a.participants.length>2?t.jsx(Ze,{session:a,currentUser:s,enableScreenSharing:y,onEndCall:G,onMuteAudio:C,onMuteVideo:k,onStartScreenShare:M,onStopScreenShare:K}):t.jsx(Qe,{session:a,currentUser:s,enableScreenSharing:y,onEndCall:G,onMuteAudio:C,onMuteVideo:k,onStartScreenShare:M,onStopScreenShare:K})})]})}),x&&o&&t.jsxs("div",{style:{position:"absolute",top:16,right:16,width:300,background:"var(--nice-text, #1f2937)",borderRadius:12,padding:16,boxShadow:"0 8px 32px var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",zIndex:100,color:"var(--nice-bg, #fff)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:12},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:o.caller.avatarUrl?`url(${o.caller.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",fontWeight:700,fontSize:16},children:!o.caller.avatarUrl&&((V=o.caller.name[0])==null?void 0:V.toUpperCase())}),t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:600},children:o.caller.displayName??o.caller.name}),t.jsxs("div",{style:{fontSize:12,color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"},children:["Incoming ",o.callType," call"]})]})]}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsxs("button",{onClick:()=>O==null?void 0:O(o.callId),style:{flex:1,background:"var(--nice-danger, #ef4444)",color:"var(--nice-bg, #fff)",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[t.jsx(w.NiceIcon,{name:"phone",size:14})," Decline"]}),t.jsxs("button",{onClick:()=>Y==null?void 0:Y(o.callId),style:{flex:1,background:"var(--nice-success, #22c55e)",color:"var(--nice-bg, #fff)",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[t.jsx(w.NiceIcon,{name:"phone",size:14})," Accept"]})]})]})]})}const gn={"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 mn({props:s,onExpand:e}){const[n,i]=l.useState(!1),{bubblePosition:r="bottom-right",bubbleLabel:a,currentUser:o,users:c,conversations:u=[],messages:p={},onSendMessage:m,onReactToMessage:f,onPinMessage:y,onDeleteMessage:h,onEditMessage:v,onLoadMoreMessages:z,onStartCall:d}=s,N=gn[r],R=u[0]??null,D=R?p[R.id]??[]:[];return t.jsxs("div",{style:{position:"fixed",zIndex:9999,...N},children:[n&&R&&t.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:"var(--nice-bg, #fff)",borderRadius:16,boxShadow:"0 8px 40px var(--nice-overlay-20, rgba(0, 0, 0, 0.18))",overflow:"hidden",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",background:"var(--nice-info, #6366f1)",color:"var(--nice-bg, #fff)",flexShrink:0},children:[t.jsx("span",{style:{fontWeight:700,fontSize:15},children:a??"Chat"}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:()=>e("messenger"),title:"Open full chat","aria-label":"Open full chat",style:{background:"var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))",border:"none",borderRadius:6,padding:"3px 7px",color:"var(--nice-bg, #fff)",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:"expand",size:13})}),t.jsx("button",{onClick:()=>i(!1),title:"Close","aria-label":"Close",style:{background:"none",border:"none",color:"var(--nice-bg, #fff)",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:"close",size:18})})]})]}),t.jsx(Ne,{conversation:R,messages:D,users:c,currentUser:o,showHeader:!1,onSendMessage:m,onEditMessage:v,onDeleteMessage:h,onReactToMessage:f,onPinMessage:y,onLoadMoreMessages:z,onStartCall:d,style:{flex:1}})]}),t.jsx("button",{onClick:()=>i(_=>!_),style:{width:56,height:56,borderRadius:"50%",background:"var(--nice-info, #6366f1)",border:"none",boxShadow:"0 4px 16px var(--nice-accent-tint-40, rgba(99, 102, 241, 0.4))",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-bg, #fff)",transition:"transform 0.15s"},title:n?"Close chat":a??"Open chat","aria-label":n?"Close chat":a??"Open chat",children:t.jsx(w.NiceIcon,{name:n?"close":"message",size:24})})]})}function yn({call:s,onAccept:e,onDecline:n}){return t.jsxs("div",{style:{position:"fixed",top:16,left:"50%",transform:"translateX(-50%)",zIndex:9998,background:"var(--nice-text, #1f2937)",color:"var(--nice-bg, #fff)",borderRadius:12,padding:"12px 20px",boxShadow:"0 8px 32px var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",display:"flex",alignItems:"center",gap:16,minWidth:280},children:[t.jsx("div",{style:{display:"flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:s.callType==="video"?"video":"phone",size:28})}),t.jsxs("div",{style:{flex:1},children:[t.jsx("div",{style:{fontWeight:600,fontSize:14},children:s.caller.displayName??s.caller.name}),t.jsxs("div",{style:{fontSize:12,color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"},children:["Incoming ",s.callType," call…"]})]}),t.jsx("button",{onClick:n,style:{background:"var(--nice-danger, #ef4444)",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",color:"var(--nice-bg, #fff)",display:"inline-flex",alignItems:"center",justifyContent:"center"},title:"Decline","aria-label":"Decline",children:t.jsx(w.NiceIcon,{name:"phone",size:18})}),t.jsx("button",{onClick:e,style:{background:"var(--nice-success, #22c55e)",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",color:"var(--nice-bg, #fff)",display:"inline-flex",alignItems:"center",justifyContent:"center"},title:"Accept","aria-label":"Accept",children:t.jsx(w.NiceIcon,{name:"phone",size:18})})]})}function Tt(s){const{mode:e,currentUser:n,users:i,conversations:r=[],messages:a={},teams:o=[],meetings:c,activeCall:u,incomingCall:p,transport:m="webrtc",rtcConfig:f,onSendMessage:y,onEditMessage:h,onDeleteMessage:v,onReactToMessage:z,onPinMessage:d,onLoadMoreMessages:N,onMarkAsRead:R,onStartCall:D,onAcceptCall:_,onDeclineCall:$,onEndCall:B,onMuteAudio:Y,onMuteVideo:O,onStartScreenShare:G,onStopScreenShare:C,onRaiseHand:k,onModeChange:M,enableScreenSharing:K=!0,enableMeetings:P=!0,enableWhiteboard:I=!1,storageConfig:W,encryptionConfig:U,className:H,style:g,id:S,"data-testid":J}=s,[X,Z]=l.useState(e),[q,ae]=l.useState(null),oe=l.useMemo(()=>({id:`wb-${n.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:"var(--nice-bg, #fff)",gridEnabled:!0,gridSize:20,snapEnabled:!0,createdAt:new Date,updatedAt:new Date,ownerId:n.id,permissions:"edit"}),[n.id]),[fe,le]=l.useState(u??null),[F,Q]=l.useState(p??null),ie=u??fe,re=p??F;l.useEffect(()=>{Z(e)},[e]),l.useEffect(()=>{u!==void 0&&le(u)},[u]),l.useEffect(()=>{p!==void 0&&Q(p)},[p]);const{state:ce,startCall:x,acceptCall:b,declineCall:E,endCall:L,toggleMic:A,toggleCamera:V,startScreenShare:j,stopScreenShare:T}=wt({currentUser:n,transport:m,rtcConfig:f,onCallEnded:ne=>{le(null),B==null||B(ne)},onIncomingCall:ne=>{Q(ne)}}),te=l.useCallback(ne=>{Z(ne),M==null||M(ne)},[M]),ee=l.useCallback(async(ne,at)=>{if(D){await D(ne,at);return}const Wt=await x(ne,at);le(Wt),Z(ne.length>2?"conference":"call")},[D,x]),se=l.useCallback(async()=>{var ne;_&&re?await _(re.callId):await b(),Q(null),Z((ne=ce.activeCall)!=null&&ne.participants&&ce.activeCall.participants.length>2?"conference":"call")},[_,re,b,ce.activeCall]),de=l.useCallback(()=>{$&&re?$(re.callId):E(),Q(null)},[$,re,E]),ye=l.useCallback(ne=>{B?B(ne):L(),le(null),Z(e)},[B,L,e]),he=l.useCallback(ne=>{A(),Y==null||Y(ne)},[A,Y]),Pe=l.useCallback(ne=>{V(),O==null||O(ne)},[V,O]),rt=l.useCallback(async()=>{await j(),await(G==null?void 0:G())},[j,G]),Ae=l.useCallback(()=>{T(),C==null||C()},[T,C]),xe={onSendMessage:y,onEditMessage:h,onDeleteMessage:v,onReactToMessage:z,onPinMessage:d,onLoadMoreMessages:N,onMarkAsRead:R,onStartCall:ee,onEndCall:ye,onMuteAudio:he,onMuteVideo:Pe,onStartScreenShare:rt,onStopScreenShare:Ae,onRaiseHand:k},ge=ie?ie.participants.length>2?"conference":"call":X,Lt={width:"100%",height:"100%",position:"relative",...g};return t.jsxs("div",{id:S,"data-testid":J,className:`nice-communication nice-communication--${ge}${H?` ${H}`:""}`,style:Lt,children:[re&&ge!=="workspace"&&t.jsx(yn,{call:re,onAccept:se,onDecline:de}),ge==="bubble"&&t.jsx(mn,{props:s,onExpand:te}),ge==="chat"&&r.length>0&&t.jsx(Ne,{conversation:r[0],messages:a[r[0].id]??[],users:i,currentUser:n,...xe,style:{height:"100%"}}),ge==="messenger"&&t.jsx(St,{conversations:r,messages:a,users:i,currentUser:n,teams:o,...xe,onAcceptCall:_,onDeclineCall:$,style:{height:"100%"}}),ge==="workspace"&&t.jsx(zt,{currentUser:n,users:i,teams:o,conversations:r,messages:a,meetings:c,activeCall:ie??void 0,incomingCall:re??void 0,transport:m,rtcConfig:f,enableCalls:!0,enableMeetings:P,enableScreenSharing:K,...xe,onAcceptCall:se,onDeclineCall:de,style:{height:"100%"}}),ge==="call"&&ie&&t.jsx(Qe,{session:ie,currentUser:n,localStream:ce.localStream??void 0,enableScreenSharing:K,...xe,style:{height:"100%"}}),ge==="conference"&&ie&&t.jsx(Ze,{session:ie,currentUser:n,localStream:ce.localStream??void 0,enableScreenSharing:K,...xe,style:{height:"100%"}}),ge==="whiteboard"&&I&&t.jsx(tt,{session:q??oe,currentUser:n,storageConfig:W,onSessionUpdate:ne=>ae(ne),style:{height:"100%"}})]})}const xn={messages:"Messages",attachments:"Attachments","whiteboard-snapshots":"Whiteboard snapshots",recordings:"Recordings",transcripts:"Transcripts",documents:"Documents","call-logs":"Call logs","audit-logs":"Audit logs"},ut={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"},bn={messages:"Messages",attachments:"Attachments",whiteboard:"Whiteboard",recordings:"Recordings",documents:"Documents",calls:"Calls (metadata)",presence:"Presence data",all:"Everything"},vn=["days","weeks","months","years","forever"];function pt(s){if(s===0)return"0 B";const e=1024,n=["B","KB","MB","GB"],i=Math.floor(Math.log(s)/Math.log(e));return`${(s/Math.pow(e,i)).toFixed(1)} ${n[i]}`}function ft({value:s,onChange:e,disabled:n=!1}){return t.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[t.jsx("input",{type:"number",min:1,max:9999,value:s.unit==="forever"?"":s.value,disabled:n||s.unit==="forever",onChange:i=>e({...s,value:Math.max(1,Number(i.target.value))}),style:{width:60,padding:"3px 6px",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:5,fontSize:12}}),t.jsx("select",{value:s.unit,disabled:n,onChange:i=>e({...s,unit:i.target.value}),style:{padding:"3px 6px",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:5,fontSize:12},children:vn.map(i=>t.jsx("option",{value:i,children:i},i))})]})}function wn({config:s,onChange:e}){const n=s.retentionRules.length>0?s.retentionRules:et;function i(r,a){const o=n.map(c=>c.dataType===r?{...c,...a}:c);e({...s,retentionRules:o})}return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx("p",{style:{fontSize:12,color:"var(--nice-text-secondary, #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."}),t.jsxs("div",{style:Ce,children:[t.jsx("label",{style:Ie,children:"Storage provider"}),t.jsxs("select",{value:s.provider,onChange:r=>e({...s,provider:r.target.value}),style:we,children:[t.jsx("option",{value:"indexeddb",children:"IndexedDB (browser)"}),t.jsx("option",{value:"localstorage",children:"LocalStorage (browser)"}),t.jsx("option",{value:"server",children:"Server"}),t.jsx("option",{value:"custom",children:"Custom adapter"})]})]}),s.provider==="server"&&t.jsxs("div",{style:Ce,children:[t.jsx("label",{style:Ie,children:"Server URL"}),t.jsx("input",{type:"url",value:s.serverUrl??"",onChange:r=>e({...s,serverUrl:r.target.value}),placeholder:"https://your-api.example.com/storage",style:we})]}),t.jsx("hr",{style:{border:"none",borderTop:"1px solid var(--nice-border, #e5e7eb)",margin:"4px 0"}}),t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{background:"var(--nice-bg-secondary, #f9fafb)"},children:[t.jsx("th",{style:je,children:"Data type"}),t.jsx("th",{style:je,children:"Active period"}),t.jsx("th",{style:je,children:"Archive after"}),t.jsx("th",{style:je,children:"Auto-delete"}),t.jsx("th",{style:je,children:"User can delete"}),t.jsx("th",{style:je,children:"Legal hold"})]})}),t.jsx("tbody",{children:n.map(r=>t.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)"},children:[t.jsx("td",{style:{...ke,fontWeight:500,color:"var(--nice-text, #374151)"},children:xn[r.dataType]}),t.jsx("td",{style:ke,children:t.jsx(ft,{value:r.activePeriod,onChange:a=>i(r.dataType,{activePeriod:a})})}),t.jsx("td",{style:ke,children:r.archivePeriod?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[t.jsx(ft,{value:r.archivePeriod,onChange:a=>i(r.dataType,{archivePeriod:a})}),t.jsx("button",{onClick:()=>i(r.dataType,{archivePeriod:void 0}),style:{border:"none",background:"none",cursor:"pointer",color:"var(--nice-danger, #ef4444)",display:"inline-flex",alignItems:"center"},title:"Remove archive period","aria-label":"Remove archive period",children:t.jsx(w.NiceIcon,{name:"close",size:14})})]}):t.jsxs("button",{onClick:()=>i(r.dataType,{archivePeriod:{value:1,unit:"years"}}),style:{fontSize:11,padding:"2px 8px",border:"1px dashed var(--nice-border, #d1d5db)",borderRadius:4,cursor:"pointer",background:"none",color:"var(--nice-text-secondary, #6b7280)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(w.NiceIcon,{name:"plus",size:11})," Add"]})}),t.jsx("td",{style:{...ke,textAlign:"center"},children:t.jsx("input",{type:"checkbox",checked:r.deleteAfterArchive,disabled:!r.archivePeriod,onChange:a=>i(r.dataType,{deleteAfterArchive:a.target.checked})})}),t.jsx("td",{style:{...ke,textAlign:"center"},children:t.jsx("input",{type:"checkbox",checked:r.userCanDelete,onChange:a=>i(r.dataType,{userCanDelete:a.target.checked})})}),t.jsx("td",{style:{...ke,textAlign:"center"},children:t.jsx("input",{type:"checkbox",checked:r.legalHoldEnabled??!1,onChange:a=>i(r.dataType,{legalHoldEnabled:a.target.checked})})})]},r.dataType))})]}),t.jsxs("div",{style:Ce,children:[t.jsx("label",{style:Ie,children:"Storage quota"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.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:{...we,width:90},placeholder:"0"}),t.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:"MB (0 = unlimited)"})]})]})]})}function Sn({config:s,onChange:e}){const n=["messages","attachments","whiteboard","recordings","documents","calls","presence"];return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx("p",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",margin:0},children:"Configure encryption at rest and in transit. E2E-ECDH ensures only participants can read conversations — the server never sees plaintext."}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsxs("label",{style:{position:"relative",display:"inline-block",width:42,height:22},children:[t.jsx("input",{type:"checkbox",checked:s.enabled,onChange:i=>e({...s,enabled:i.target.checked}),style:{opacity:0,width:0,height:0}}),t.jsx("span",{style:{position:"absolute",inset:0,borderRadius:22,background:s.enabled?"var(--nice-info, #6366f1)":"var(--nice-border, #d1d5db)",transition:"background 0.2s",cursor:"pointer"},children:t.jsx("span",{style:{position:"absolute",width:16,height:16,top:3,left:s.enabled?23:3,background:"var(--nice-bg, #fff)",borderRadius:"50%",transition:"left 0.2s"}})})]}),t.jsxs("span",{style:{fontSize:13,fontWeight:500,color:"var(--nice-text, #374151)",display:"inline-flex",alignItems:"center",gap:5},children:[t.jsx(w.NiceIcon,{name:"lock",size:14})," ",s.enabled?"Encryption enabled":"Encryption disabled"]})]}),s.enabled&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:Ce,children:[t.jsx("label",{style:Ie,children:"Default algorithm"}),t.jsx("select",{value:s.defaultAlgorithm,onChange:i=>e({...s,defaultAlgorithm:i.target.value}),style:we,children:Object.entries(ut).map(([i,r])=>t.jsx("option",{value:i,children:r},i))})]}),s.defaultAlgorithm==="E2E-ECDH-P384"&&t.jsxs("div",{style:Ce,children:[t.jsx("label",{style:Ie,children:"Key exchange URL"}),t.jsx("input",{type:"url",value:s.keyExchangeUrl??"",onChange:i=>e({...s,keyExchangeUrl:i.target.value}),placeholder:"wss://your-server/e2e-key-exchange",style:we}),t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginTop:2},children:"WebSocket endpoint for ECDH public key exchange between participants."})]}),t.jsxs("div",{style:Ce,children:[t.jsx("label",{style:Ie,children:"External key (base64, optional)"}),t.jsx("input",{type:"password",value:s.keyMaterial??"",onChange:i=>e({...s,keyMaterial:i.target.value||void 0}),placeholder:"Leave empty to auto-generate",style:we}),t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginTop:2},children:"Provide a pre-shared key for symmetric algorithms. Leave empty for automatic key generation."})]}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:s.showIndicator??!0,onChange:i=>e({...s,showIndicator:i.target.checked})}),t.jsx("span",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:"Show lock indicator in messages"})]}),t.jsx("hr",{style:{border:"none",borderTop:"1px solid var(--nice-border, #e5e7eb)",margin:"4px 0"}}),t.jsx("strong",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:"Per-scope overrides"}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:n.map(i=>{var c;const r=(c=s.scopeOverrides)==null?void 0:c.find(u=>u.scope===i),a=(r==null?void 0:r.enabled)??!1,o=(r==null?void 0:r.algorithm)??s.defaultAlgorithm;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 8px",background:"var(--nice-bg-secondary, #f9fafb)",borderRadius:6},children:[t.jsx("input",{type:"checkbox",checked:a,onChange:u=>{const p=[...(s.scopeOverrides??[]).filter(m=>m.scope!==i),{scope:i,algorithm:o,enabled:u.target.checked}];e({...s,scopeOverrides:p})}}),t.jsx("span",{style:{minWidth:120,fontSize:12,color:"var(--nice-text, #374151)"},children:bn[i]}),t.jsx("select",{value:o,disabled:!a,onChange:u=>{const p=[...(s.scopeOverrides??[]).filter(m=>m.scope!==i),{scope:i,algorithm:u.target.value,enabled:a}];e({...s,scopeOverrides:p})},style:{...we,flex:1,opacity:a?1:.4},children:Object.entries(ut).map(([u,p])=>t.jsx("option",{value:u,children:p},u))})]},i)})})]})]})}function jn({storageConfig:s,defaultStorageConfig:e,encryptionConfig:n,onStorageConfigChange:i,onEncryptionConfigChange:r,currentUsageBytes:a=0,showEncryption:o=!0,showRetention:c=!0,showQuota:u=!0,className:p,style:m,"data-testid":f}){const[y,h]=l.useState("retention"),[v,z]=w.useControllableState({value:s,defaultValue:e,fallbackValue:{provider:"indexeddb",retentionRules:[]},onChange:i,componentName:"NiceStorageSettings"}),d=n??{enabled:!1,defaultAlgorithm:"AES-GCM-256",showIndicator:!0},N={...v,retentionRules:v.retentionRules.length>0?v.retentionRules:et};return t.jsxs("div",{className:p,"data-testid":f,style:{display:"flex",flexDirection:"column",gap:16,padding:20,background:"var(--nice-bg, #fff)",borderRadius:10,border:"1px solid var(--nice-border, #e5e7eb)",fontFamily:"system-ui, sans-serif",maxWidth:800,...m},children:[t.jsxs("div",{children:[t.jsx("h3",{style:{margin:0,fontSize:16,color:"var(--nice-text, #111827)"},children:"Storage & Privacy"}),t.jsx("p",{style:{margin:"4px 0 0",fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:"Manage data retention, encryption, and storage settings."})]}),u&&v.quota&&v.quota>0&&t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:12,color:"var(--nice-text-secondary, #6b7280)",marginBottom:4},children:[t.jsx("span",{children:"Storage used"}),t.jsxs("span",{children:[pt(a)," / ",pt(v.quota)]})]}),t.jsx("div",{style:{height:6,background:"var(--nice-border, #e5e7eb)",borderRadius:3},children:t.jsx("div",{style:{width:`${Math.min(100,a/v.quota*100)}%`,height:"100%",background:a/v.quota>.9?"var(--nice-danger, #ef4444)":"var(--nice-info, #6366f1)",borderRadius:3,transition:"width 0.3s"}})})]}),c&&o&&t.jsx("div",{style:{display:"flex",gap:0,borderBottom:"1px solid var(--nice-border, #e5e7eb)"},children:["retention","encryption"].map(R=>t.jsx("button",{onClick:()=>h(R),style:{padding:"8px 18px",border:"none",borderBottom:`2px solid ${y===R?"var(--nice-info, #6366f1)":"transparent"}`,background:"none",cursor:"pointer",fontSize:13,fontWeight:y===R?600:400,color:y===R?"var(--nice-accent, #4f46e5)":"var(--nice-text-secondary, #6b7280)",marginBottom:-1,display:"inline-flex",alignItems:"center",gap:6},children:R==="retention"?t.jsxs(t.Fragment,{children:[t.jsx(w.NiceIcon,{name:"archive",size:13})," Retention"]}):t.jsxs(t.Fragment,{children:[t.jsx(w.NiceIcon,{name:"lock",size:13})," Encryption"]})},R))}),t.jsxs("div",{children:[(y==="retention"||!o)&&c&&t.jsx(wn,{config:N,onChange:z}),(y==="encryption"||!c)&&o&&t.jsx(Sn,{config:d,onChange:r??(()=>{})})]})]})}const Ce={display:"flex",flexDirection:"column",gap:4},Ie={fontSize:12,fontWeight:500,color:"var(--nice-text, #374151)"},we={padding:"6px 8px",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6,fontSize:13,color:"var(--nice-text, #111827)",background:"var(--nice-bg, #fff)"},je={padding:"6px 8px",textAlign:"left",fontSize:11,fontWeight:600,color:"var(--nice-text-secondary, #6b7280)",borderBottom:"1px solid var(--nice-border, #e5e7eb)"},ke={padding:"8px 8px",verticalAlign:"middle"};function Le(s){const e=Math.floor(s/1e3),n=Math.floor(e/60),i=Math.floor(n/60);return i>0?`${i}:${String(n%60).padStart(2,"0")}:${String(e%60).padStart(2,"0")}`:`${String(n).padStart(2,"0")}:${String(e%60).padStart(2,"0")}`}function kn(s){if(s===0)return"0 B";const e=1024,n=["B","KB","MB","GB"],i=Math.floor(Math.log(s)/Math.log(e));return`${(s/Math.pow(e,i)).toFixed(1)} ${n[i]}`}function Cn(s){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(s))}const In={idle:{label:"Idle",icon:null,bg:"var(--nice-bg-secondary, #f3f4f6)",fg:"var(--nice-text-secondary, #6b7280)"},recording:{label:"Recording",icon:"circle",bg:"var(--nice-danger-bg, #fee2e2)",fg:"var(--nice-danger-dark, #dc2626)"},paused:{label:"Paused",icon:"pause",bg:"var(--nice-warning-bg, #fef3c7)",fg:"var(--nice-warning-dark, #d97706)"},processing:{label:"Processing",icon:"clock",bg:"var(--nice-accent-bg, #ede9fe)",fg:"var(--nice-accent, #7c3aed)"},ready:{label:"Ready",icon:"check",bg:"var(--nice-success-bg, #dcfce7)",fg:"var(--nice-success-dark, #16a34a)"},failed:{label:"Failed",icon:"close",bg:"var(--nice-danger-bg, #fee2e2)",fg:"var(--nice-danger-dark, #dc2626)"}};function zn({segments:s,onClose:e,currentTimeMs:n=0}){return t.jsx("div",{style:{position:"fixed",inset:0,zIndex:9999,background:"var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsxs("div",{style:{background:"var(--nice-bg, #fff)",borderRadius:12,width:"90%",maxWidth:640,maxHeight:"80vh",display:"flex",flexDirection:"column",boxShadow:"0 20px 40px var(--nice-overlay-20, rgba(0, 0, 0, 0.2))",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"14px 18px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsx("strong",{style:{fontSize:14,color:"var(--nice-text, #111827)"},children:"Transcript"}),t.jsx("button",{onClick:e,style:Nn,"aria-label":"Close",children:t.jsx(w.NiceIcon,{name:"close",size:16})})]}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"12px 18px"},children:s.length===0?t.jsx("p",{style:{fontSize:13,color:"var(--nice-text-muted, #9ca3af)",textAlign:"center",padding:"32px 0"},children:"No transcript available."}):s.map(i=>{const r=n>=i.startMs&&n<i.endMs;return t.jsxs("div",{style:{marginBottom:12,padding:"8px 10px",borderRadius:6,background:r?"var(--nice-primary-bg, #eff6ff)":"transparent",borderLeft:`3px solid ${r?"var(--nice-primary, #3b82f6)":"transparent"}`,transition:"background 0.2s"},children:[t.jsxs("div",{style:{display:"flex",gap:10,alignItems:"baseline",marginBottom:3},children:[t.jsx("span",{style:{fontSize:11,fontWeight:600,color:"var(--nice-accent, #4f46e5)"},children:i.speakerName}),t.jsxs("span",{style:{fontSize:10,color:"var(--nice-text-muted, #9ca3af)"},children:[Le(i.startMs)," – ",Le(i.endMs)]}),t.jsxs("span",{style:{fontSize:10,color:"var(--nice-border, #d1d5db)"},children:[Math.round(i.confidence*100),"% conf."]})]}),t.jsx("p",{style:{margin:0,fontSize:13,color:"var(--nice-text, #374151)",lineHeight:1.5},children:i.text})]},i.id)})})]})})}function Rt({startedAt:s}){const[e,n]=l.useState(0);return l.useEffect(()=>{const i=new Date(s).getTime(),r=setInterval(()=>n(Date.now()-i),500);return()=>clearInterval(r)},[s]),t.jsx(t.Fragment,{children:Le(e)})}function Tn({rec:s,onDelete:e,onDownload:n}){const[i,r]=l.useState(!1),[a,o]=l.useState(0),c=l.useRef(null),u=In[s.state],p=s.state==="recording"||s.state==="paused";return t.jsxs(t.Fragment,{children:[i&&s.transcript&&t.jsx(zn,{segments:s.transcript,currentTimeMs:a,onClose:()=>r(!1)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",flexWrap:"wrap"},children:[t.jsx("div",{style:{display:"flex",alignItems:"center"},children:t.jsx(w.NiceIcon,{name:s.sessionType==="call"?"phone":s.sessionType==="meeting"?"video":s.sessionType==="whiteboard"?"image":"monitor",size:20})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:13,fontWeight:500,color:"var(--nice-text, #111827)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.title??`Recording ${s.id.slice(0,8)}`}),t.jsxs("div",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",marginTop:2,display:"flex",gap:8},children:[t.jsx("span",{children:Cn(s.startedAt)}),t.jsx("span",{children:p?t.jsx(Rt,{startedAt:s.startedAt}):s.durationMs!=null?Le(s.durationMs):"—"}),s.size!=null&&t.jsx("span",{children:kn(s.size)}),t.jsxs("span",{children:[s.participants.length," participants"]})]})]}),t.jsxs("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:20,background:u.bg,color:u.fg,fontWeight:500,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[u.icon&&t.jsx(w.NiceIcon,{name:u.icon,size:11}),u.label]}),s.url&&s.state==="ready"&&t.jsx("audio",{ref:c,src:s.url,controls:!0,onTimeUpdate:()=>{c.current&&o(c.current.currentTime*1e3)},style:{height:32,maxWidth:180}}),t.jsxs("div",{style:{display:"flex",gap:4},children:[s.transcript&&s.transcript.length>0&&t.jsx("button",{onClick:()=>r(!0),style:Ue,title:"View transcript","aria-label":"View transcript",children:t.jsx(w.NiceIcon,{name:"type",size:14})}),s.state==="ready"&&t.jsx("button",{onClick:()=>n(s),style:Ue,title:"Download","aria-label":"Download",children:t.jsx(w.NiceIcon,{name:"download",size:14})}),t.jsx("button",{onClick:()=>e(s.id),style:{...Ue,color:"var(--nice-danger, #ef4444)"},title:"Delete","aria-label":"Delete",children:t.jsx(w.NiceIcon,{name:"trash",size:14})})]})]})]})}function Rn({recordings:s,onRecordingStart:e,onRecordingStop:n,onRecordingPause:i,onRecordingResume:r,onRecordingDelete:a,onRecordingDownload:o,activeRecordingId:c,sessionType:u="meeting",className:p,style:m,"data-testid":f}){const[y,h]=l.useState(s??[]),[v,z]=l.useState(""),[d,N]=l.useState("all");l.useEffect(()=>{s&&h(s)},[s]);const R=y.find(O=>O.id===c),D=(R==null?void 0:R.state)==="recording",_=(R==null?void 0:R.state)==="paused",$=y.filter(O=>{const G=d==="all"||O.sessionType===d,C=!v||(O.title??"").toLowerCase().includes(v.toLowerCase())||O.id.includes(v);return G&&C}),B=l.useCallback(O=>{h(G=>G.filter(C=>C.id!==O)),a==null||a(O)},[a]),Y=l.useCallback(O=>{if(o){o(O.id);return}if(O.url){const G=document.createElement("a");G.href=O.url,G.download=`${O.title??O.id}.${O.mimeType.includes("mp4")?"mp4":"webm"}`,G.click()}else if(O.blob){const G=URL.createObjectURL(O.blob),C=document.createElement("a");C.href=G,C.download=`${O.title??O.id}.webm`,C.click(),setTimeout(()=>URL.revokeObjectURL(G),5e3)}},[o]);return t.jsxs("div",{className:p,"data-testid":f,style:{display:"flex",flexDirection:"column",background:"var(--nice-bg, #fff)",borderRadius:10,border:"1px solid var(--nice-border, #e5e7eb)",fontFamily:"system-ui, sans-serif",overflow:"hidden",...m},children:[t.jsxs("div",{style:{padding:"14px 16px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",display:"flex",gap:8,alignItems:"center"},children:[t.jsx(w.NiceIcon,{name:"mic",size:16}),t.jsx("strong",{style:{fontSize:14,color:"var(--nice-text, #111827)",flex:1},children:"Recordings"}),t.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-muted, #9ca3af)"},children:[y.length," total"]})]}),t.jsxs("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[t.jsxs("select",{value:u,disabled:D||_,onChange:()=>{},style:{...ht,flex:0},children:[t.jsx("option",{value:"call",children:"Call"}),t.jsx("option",{value:"meeting",children:"Meeting"}),t.jsx("option",{value:"whiteboard",children:"Whiteboard"}),t.jsx("option",{value:"screen",children:"Screen"})]}),!D&&!_?t.jsxs("button",{onClick:e,style:{...De,background:"var(--nice-danger, #ef4444)",color:"var(--nice-bg, #fff)"},children:[t.jsx(w.NiceIcon,{name:"circle",size:12})," Start recording"]}):t.jsxs(t.Fragment,{children:[_?t.jsxs("button",{onClick:r,style:{...De,background:"var(--nice-info, #6366f1)",color:"var(--nice-bg, #fff)"},children:[t.jsx(w.NiceIcon,{name:"play",size:12})," Resume"]}):t.jsxs("button",{onClick:i,style:{...De,background:"var(--nice-warning, #f59e0b)",color:"var(--nice-bg, #fff)"},children:[t.jsx(w.NiceIcon,{name:"pause",size:12})," Pause"]}),t.jsxs("button",{onClick:n,style:{...De,background:"var(--nice-text, #374151)",color:"var(--nice-bg, #fff)"},children:[t.jsx(w.NiceIcon,{name:"stop",size:12})," Stop"]}),R&&t.jsx("span",{style:{fontSize:12,color:"var(--nice-text-muted, #9ca3af)",marginLeft:4},children:t.jsx(Rt,{startedAt:R.startedAt})})]})]}),t.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",display:"flex",gap:6,alignItems:"center"},children:[t.jsx("input",{type:"search",value:v,onChange:O=>z(O.target.value),placeholder:"Search recordings…",style:{flex:1,padding:"4px 8px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,fontSize:12}}),t.jsxs("select",{value:d,onChange:O=>N(O.target.value),style:ht,children:[t.jsx("option",{value:"all",children:"All types"}),t.jsx("option",{value:"call",children:"Calls"}),t.jsx("option",{value:"meeting",children:"Meetings"}),t.jsx("option",{value:"whiteboard",children:"Whiteboard"}),t.jsx("option",{value:"screen",children:"Screen"})]})]}),t.jsx("div",{style:{flex:1,overflowY:"auto"},children:$.length===0?t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:32,gap:8,color:"var(--nice-text-muted, #9ca3af)"},children:[t.jsx(w.NiceIcon,{name:"mic",size:32}),t.jsx("span",{style:{fontSize:13},children:"No recordings found"}),t.jsx("span",{style:{fontSize:11},children:"Start a recording above or adjust your search filters."})]}):$.map(O=>t.jsx(Tn,{rec:O,onDelete:B,onDownload:Y},O.id))})]})}const Ue={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,background:"var(--nice-bg, #fff)",cursor:"pointer",padding:"4px 8px",fontSize:14,lineHeight:1},De={border:"none",borderRadius:6,cursor:"pointer",padding:"6px 14px",fontSize:12,fontWeight:500,display:"inline-flex",alignItems:"center",gap:4},ht={padding:"4px 6px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,fontSize:12,color:"var(--nice-text, #374151)",background:"var(--nice-bg, #fff)"},Nn={border:"none",background:"none",cursor:"pointer",fontSize:16,color:"var(--nice-text-muted, #9ca3af)",lineHeight:1,padding:4};function gt({participant:s,isFollowing:e,onClick:n}){const i=s.user.displayName??s.user.name,r=i.split(" ").map(a=>a[0]).slice(0,2).join("").toUpperCase();return t.jsxs("button",{onClick:n,title:`${i}${e?" (following)":""} — ${s.editingRegion??"viewing"}`,style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:"50%",background:s.color,color:"var(--nice-bg, #fff)",fontSize:11,fontWeight:600,border:`2px solid ${e?"var(--nice-bg, #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?t.jsx("img",{src:s.user.avatarUrl,alt:r,style:{width:"100%",height:"100%",borderRadius:"50%",objectFit:"cover"}}):r,s.isActive&&t.jsx("span",{style:{position:"absolute",bottom:-1,right:-1,width:9,height:9,borderRadius:"50%",background:"var(--nice-success, #22c55e)",border:"2px solid var(--nice-bg, #FFF)"}})]})}function Pn({participant:s,containerRect:e}){if(!s.cursorX||!s.cursorY||!e)return null;const n=s.cursorX,i=s.cursorY;return t.jsxs("div",{style:{position:"absolute",left:n,top:i,pointerEvents:"none",zIndex:9e3,transform:"translate(-2px, -2px)"},children:[t.jsx("svg",{width:16,height:20,style:{display:"block"},children:t.jsx("path",{d:"M2 2 L2 16 L6 12 L10 18 L12 17 L8 11 L14 11 Z",fill:s.color,stroke:"var(--nice-bg, #fff)",strokeWidth:1.5})}),t.jsx("div",{style:{background:s.color,color:"var(--nice-bg, #fff)",fontSize:10,padding:"1px 5px",borderRadius:3,whiteSpace:"nowrap",marginTop:-2,marginLeft:10},children:s.user.displayName??s.user.name})]})}function An({count:s}){return s===0?null:t.jsxs("div",{style:{position:"absolute",top:8,left:"50%",transform:"translateX(-50%)",zIndex:8e3,background:"var(--nice-warning-bg, #fef3c7)",border:"1px solid var(--nice-warning-light, #fbbf24)",borderRadius:6,padding:"4px 12px",fontSize:12,color:"var(--nice-warning-dark, #92400e)",display:"flex",alignItems:"center",gap:6,boxShadow:"0 2px 8px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",pointerEvents:"none"},children:[t.jsx(w.NiceIcon,{name:"warning",size:12})," ",s," edit conflict",s>1?"s":""," — auto-merging…"]})}function En(){return t.jsx("div",{style:{position:"absolute",inset:0,zIndex:7e3,background:"var(--nice-overlay-3, rgba(0, 0, 0, 0.03))",cursor:"not-allowed",display:"flex",alignItems:"flex-end",justifyContent:"center",paddingBottom:12,pointerEvents:"none"},children:t.jsxs("div",{style:{background:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",color:"var(--nice-bg, #fff)",fontSize:12,padding:"4px 14px",borderRadius:20,display:"inline-flex",alignItems:"center",gap:4},children:[t.jsx(w.NiceIcon,{name:"eye",size:12})," View only"]})})}function Dn({pending:s}){return s===0?t.jsxs("span",{style:{fontSize:11,color:"var(--nice-success, #22c55e)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(w.NiceIcon,{name:"check",size:11})," Synced"]}):t.jsxs("span",{style:{fontSize:11,color:"var(--nice-warning, #f59e0b)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(w.NiceIcon,{name:"upload",size:11})," ",s," pending…"]})}function Mn({participant:s,isFollowing:e,onClick:n}){return t.jsxs("button",{onClick:n,style:{fontSize:11,padding:"2px 8px",border:`1px solid ${e?s.color:"var(--nice-border, #e5e7eb)"}`,borderRadius:20,background:e?s.color:"var(--nice-bg, #fff)",color:e?"var(--nice-bg, #fff)":"var(--nice-text-secondary, #6b7280)",cursor:"pointer",display:"flex",alignItems:"center",gap:4},children:[t.jsx(w.NiceIcon,{name:"eye",size:11})," ",e?"Unfollow":`Follow ${(s.user.displayName??s.user.name).split(" ")[0]}`]})}function $n({editorType:s,sessionId:e,currentUser:n,participants:i=[],onOperation:r,onParticipantJoin:a,onParticipantLeave:o,onCursorMove:c,isReadOnly:u=!1,showParticipants:p=!0,showCursors:m=!0,pendingOperations:f=0,conflictCount:y=0,className:h,style:v,children:z,"data-testid":d}){const N=l.useRef(null),[R,D]=l.useState(null),[_,$]=l.useState(null),[B,Y]=l.useState(!1);l.useEffect(()=>{const P=N.current;if(!P)return;const I=new ResizeObserver(()=>D(P.getBoundingClientRect()));return I.observe(P),D(P.getBoundingClientRect()),()=>I.disconnect()},[]);const O=l.useCallback(P=>{if(!N.current||!c)return;const I=N.current.getBoundingClientRect();c(P.clientX-I.left,P.clientY-I.top)},[c]),G=l.useCallback(P=>{$(I=>I===P?null:P)},[]),C={vector:{icon:"pen",label:"Vector"},pixel:{icon:"image",label:"Pixel"},diagram:{icon:"bar-chart",label:"Diagram"},document:{icon:"file",label:"Document"},whiteboard:{icon:"edit",label:"Whiteboard"}},k=t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",background:"var(--nice-bg-secondary, #f9fafb)",minHeight:40},children:[t.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",fontWeight:500,display:"inline-flex",alignItems:"center",gap:4},children:[t.jsx(w.NiceIcon,{name:C[s].icon,size:12}),C[s].label]}),t.jsx("span",{style:{flex:1}}),t.jsx(Dn,{pending:f}),p&&i.length>0&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:-4},children:[i.slice(0,5).map((P,I)=>t.jsx("div",{style:{marginLeft:I>0?-8:0,zIndex:10-I},children:t.jsx(gt,{participant:P,isFollowing:_===P.user.id,onClick:()=>{Y(!0),G(P.user.id)}})},P.user.id)),i.length>5&&t.jsxs("button",{onClick:()=>Y(!B),style:{marginLeft:-4,zIndex:5,width:30,height:30,borderRadius:"50%",background:"var(--nice-border, #e5e7eb)",border:"2px solid var(--nice-bg, #FFF)",fontSize:10,fontWeight:600,color:"var(--nice-text, #374151)",cursor:"pointer"},children:["+",i.length-5]})]}),p&&i.length>0&&t.jsxs("button",{onClick:()=>Y(!B),style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:5,background:B?"var(--nice-primary-bg, #eff6ff)":"var(--nice-bg, #fff)",padding:"3px 8px",cursor:"pointer",fontSize:11,color:B?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #6b7280)"},children:[i.length," online"]})]}),M=t.jsxs("div",{ref:N,onMouseMove:O,style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},children:[z??t.jsxs("div",{id:`collab-editor-${s}-${e}`,style:{width:"100%",height:"100%",minHeight:400,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-bg-secondary, #f9fafb)",color:"var(--nice-text-muted, #9ca3af)",fontSize:13},children:["Drop your ",s," editor here or use the"," ",t.jsx("code",{style:{background:"var(--nice-border, #e5e7eb)",padding:"1px 5px",borderRadius:3,margin:"0 4px"},children:`#collab-editor-${s}-${e}`})," ","mount point."]}),m&&i.filter(P=>P.user.id!==n.id&&P.cursorX!=null&&P.cursorY!=null).map(P=>t.jsx(Pn,{participant:P,containerRect:R},P.user.id)),t.jsx(An,{count:y}),u&&t.jsx(En,{})]}),K=B&&i.length>0?t.jsxs("div",{style:{width:220,height:"100%",borderLeft:"1px solid var(--nice-border, #e5e7eb)",background:"var(--nice-bg-secondary, #f9fafb)",overflowY:"auto",padding:10,display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[t.jsx("strong",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:"Participants"}),t.jsx("button",{onClick:()=>Y(!1),style:{border:"none",background:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",fontSize:14},"aria-label":"Close",children:t.jsx(w.NiceIcon,{name:"close",size:14})})]}),i.map(P=>t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"8px",borderRadius:6,background:"var(--nice-bg, #fff)",border:"1px solid var(--nice-bg-secondary, #f3f4f6)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx(gt,{participant:P,isFollowing:_===P.user.id,onClick:()=>G(P.user.id)}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:12,fontWeight:500,color:"var(--nice-text, #111827)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:P.user.displayName??P.user.name}),t.jsx("div",{style:{fontSize:10,color:"var(--nice-text-muted, #9ca3af)"},children:P.editingRegion??"viewing"})]})]}),P.user.id!==n.id&&t.jsx(Mn,{participant:P,isFollowing:_===P.user.id,onClick:()=>G(P.user.id)})]},P.user.id))]}):void 0;return t.jsx(w.NiceAppShell,{flush:!0,className:h,"data-testid":d,style:{background:"var(--nice-bg, #fff)",fontFamily:"system-ui, sans-serif",...v},menubar:k,rightSidebar:K,children:M})}function nt(s){let e="";for(let n=0;n<s.length;n++)e+=String.fromCharCode(s[n]);return btoa(e)}function it(s){const e=atob(s),n=new Uint8Array(e.length);for(let i=0;i<e.length;i++)n[i]=e.charCodeAt(i);return n}function On(s){return new TextEncoder().encode(s)}function Ln(s){return new TextDecoder().decode(s)}async function Wn(s){return crypto.subtle.generateKey({name:"AES-GCM",length:s},!0,["encrypt","decrypt"])}async function Fn(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-384"},!0,["deriveKey"])}async function _n(s,e){return crypto.subtle.deriveKey({name:"ECDH",public:e},s,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Bn(s,e){const n=crypto.getRandomValues(new Uint8Array(12)),i=On(e),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},s,i),a=new Uint8Array(r),o=new Uint8Array(12+a.length);return o.set(n,0),o.set(a,12),nt(o)}async function Un(s,e){const n=it(e),i=n.slice(0,12),r=n.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},s,r);return Ln(new Uint8Array(a))}async function mt(s,e){const n=it(s);return crypto.subtle.importKey("raw",n,{name:"AES-GCM",length:e},!1,["encrypt","decrypt"])}async function Hn(s){const e=await crypto.subtle.exportKey("raw",s);return nt(new Uint8Array(e))}async function Kn(s){const e=await crypto.subtle.exportKey("spki",s);return nt(new Uint8Array(e))}async function Yn(s){const e=it(s);return crypto.subtle.importKey("spki",e,{name:"ECDH",namedCurve:"P-384"},!0,[])}class Nt{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 mt(this.config.keyMaterial,128):this.keys.aes256=await mt(this.config.keyMaterial,256);else if(e==="AES-GCM-256"||e==="AES-GCM-128"){const n=e==="AES-GCM-256"?256:128,i=await Wn(n);n===128?this.keys.aes128=i:this.keys.aes256=i}else if(e==="E2E-ECDH-P384"){const n=await Fn();this.keys.ecdhPrivate=n.privateKey,this.keys.ecdhPublic=n.publicKey,this.keys.ecdhSessionKeys=new Map}this.ready=!0}async getPublicKeyForPeer(){return this.keys.ecdhPublic?Kn(this.keys.ecdhPublic):null}async registerPeerPublicKey(e,n){var a;if(!this.keys.ecdhPrivate)return;const i=await Yn(n),r=await _n(this.keys.ecdhPrivate,i);(a=this.keys.ecdhSessionKeys)==null||a.set(e,r)}resolveAlgorithm(e){if(e&&this.config.scopeOverrides){const n=this.config.scopeOverrides.find(i=>(i.scope===e||i.scope==="all")&&i.enabled);if(n)return n.algorithm}return this.config.defaultAlgorithm}getKey(e,n){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 n?((i=this.keys.ecdhSessionKeys)==null?void 0:i.get(n))??null:null;default:return null}}async encrypt(e,n,i){if(!this.config.enabled)return e;if(!this.ready)throw new Error("EncryptionService not initialised — call init() first");const r=this.resolveAlgorithm(n);if(r==="none")return e;const a=this.getKey(r,i);return a?Bn(a,e):(console.warn(`EncryptionService: no key found for algorithm "${r}" — returning plaintext`),e)}async decrypt(e,n,i){if(!this.config.enabled)return e;if(!this.ready)throw new Error("EncryptionService not initialised — call init() first");const r=this.resolveAlgorithm(n);if(r==="none")return e;const a=this.getKey(r,i);return a?Un(a,e):(console.warn(`EncryptionService: no key found for algorithm "${r}" — returning as-is`),e)}async exportSymmetricKey(e){const n=e??this.config.defaultAlgorithm,i=this.getKey(n);return i?Hn(i):null}isEnabled(){return this.config.enabled}getConfig(){return this.config}updateConfig(e){this.config=e,this.ready=!1}}const $e=new Map;function Gn(s,e){return $e.has(s)||$e.set(s,new Nt(e)),$e.get(s)}function qn(s){$e.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,n){var c,u,p;if(((c=this.recorder)==null?void 0:c.state)==="recording")throw new Error("Recording already in progress");const i=n.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:n.sessionType,startedAt:a,state:"recording",mimeType:i,participants:[n.speakerId??"unknown"],title:n.title??`Recording ${a.toLocaleString()}`},r.ondataavailable=m=>{m.data&&m.data.size>0&&this.chunks.push(m.data)},r.onstop=()=>{var f,y,h,v;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),(v=(h=this.callbacks).onStateChange)==null||v.call(h,"ready")},r.onerror=m=>{var f,y,h,v;(y=(f=this.callbacks).onError)==null||y.call(f,new Error(String(m))),this.session&&(this.session.state="failed"),(v=(h=this.callbacks).onStateChange)==null||v.call(h,"failed")},r.start(n.timesliceMs??1e3),this.recorder=r,n.transcribe&&this.startTranscription(n.speakerId??"unknown",n.speakerName??"Participant"),(p=(u=this.callbacks).onStateChange)==null||p.call(u,"recording"),this.session}pause(){var e,n,i;((e=this.recorder)==null?void 0:e.state)==="recording"&&(this.recorder.pause(),this.session&&(this.session.state="paused"),(i=(n=this.callbacks).onStateChange)==null||i.call(n,"paused"))}resume(){var e,n,i;((e=this.recorder)==null?void 0:e.state)==="paused"&&(this.recorder.resume(),this.session&&(this.session.state="recording"),(i=(n=this.callbacks).onStateChange)==null||i.call(n,"recording"))}stop(){var e,n;return this.stopTranscription(),this.recorder&&this.recorder.state!=="inactive"&&(this.recorder.stop(),this.session&&(this.session.state="processing"),(n=(e=this.callbacks).onStateChange)==null||n.call(e,"processing")),this.session}startTranscription(e,n){const i=window,r=i.SpeechRecognition??i.webkitSpeechRecognition;if(!r)return;const a=new r;a.continuous=!0,a.interimResults=!1,a.lang="en-US";const o=Date.now();a.onresult=c=>{var p,m;const u=c.results;for(let f=c.resultIndex;f<u.length;f++){const y=u[f];if(!y.isFinal)continue;const h=y[0],v=Date.now(),z={id:`seg_${++this.segmentCounter}`,speakerId:e,speakerName:n,text:h.transcript.trim(),startMs:v-o-1500,endMs:v-o,confidence:h.confidence??.9};this.session&&(this.session.transcript=[...this.session.transcript??[],z]),(m=(p=this.callbacks).onTranscriptSegment)==null||m.call(p,z)}},a.onerror=()=>{};try{a.start(),this.recognition=a}catch{}}stopTranscription(){var e;try{(e=this.recognition)==null||e.stop()}catch{}this.recognition=null}chooseMimeType(){const e=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm","audio/webm;codecs=opus","audio/ogg;codecs=opus"];for(const n of e)if(MediaRecorder.isTypeSupported(n))return n;return""}getState(){var e;return((e=this.session)==null?void 0:e.state)??"idle"}getSession(){return this.session}download(e){var a,o;const n=(a=this.session)==null?void 0:a.blob;if(!n)return;const i=URL.createObjectURL(n),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 Oe=new Map;function Vn(s,e){return Oe.has(s)||Oe.set(s,new Pt(e)),Oe.get(s)}function Xn(s){Oe.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 n=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}?${n}`;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 n=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,metadata:e.metadata});return`${this.config.serverUrl}${this.config.pixelPath}?${n}`}wrapLink(e){const n=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,url:e.url,linkName:e.linkName});return`${this.config.serverUrl}${this.config.redirectPath}?${n}`}wrapLinksForTracking(e,n){const i=n.excludePatterns??[/^mailto:/i,/^tel:/i,/^#/,/unsubscribe/i],r=/<a\s+([^>]*?)href=["']([^"']+)["']([^>]*?)>/gi;return e.replace(r,(a,o,c,u)=>{if(i.some(y=>y.test(c)))return a;const m=this.extractLinkName(o+u)??c,f=this.wrapLink({url:c,messageId:n.messageId,recipientId:n.recipientId,campaignId:n.campaignId,linkName:m});return`<a ${o}href="${this.escapeHtml(f)}"${u}>`})}recordEvent(e){const n={...e,id:this.generateEventId(),timestamp:new Date,ipAddress:this.config.anonymizeIp?this.anonymizeIpAddress(e.ipAddress):e.ipAddress};return this.events.push(n),this.notifyListeners(n),n}parseTrackingParams(e){const n=e.get("mid"),i=e.get("rid");if(!n||!i)return null;const r={};return e.forEach((a,o)=>{o.startsWith("m_")&&(r[o.substring(2)]=a)}),{messageId:n,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 n=this.events;e&&(n=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(n.map(y=>y.recipientHash)),r=n.filter(y=>y.type==="open"),a=n.filter(y=>y.type==="click"),o=n.filter(y=>y.type==="bounce"),c=n.filter(y=>y.type==="unsubscribe"),u=n.filter(y=>y.type==="complaint"),p=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:p,clicks:a.length,uniqueClicks:m,bounces:o.length,unsubscribes:c.length,complaints:u.length,openRate:f>0?p/f:0,clickRate:f>0?m/f:0,clickToOpenRate:p>0?m/p:0,bounceRate:f>0?o.length/(f+o.length):0}}getLinkStats(e){let n=this.events.filter(o=>o.type==="click"&&o.url);e&&(n=n.filter(o=>!(e.campaignId&&o.campaignId!==e.campaignId||e.messageId&&o.messageId!==e.messageId)));const i=new Map;for(const o of n){const c=o.url;i.has(c)||i.set(c,{url:c,linkName:void 0,total:0,unique:new Set});const u=i.get(c);u.total++,u.unique.add(o.recipientHash)}const r=n.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 n=this.events.filter(r=>r.type==="open");e!=null&&e.campaignId&&(n=n.filter(r=>r.campaignId===e.campaignId));const i={desktop:0,mobile:0,tablet:0,unknown:0};for(const r of n){const a=r.device??"unknown";i[a]=(i[a]??0)+1}return i}on(e,n){return this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(n),()=>{var i;(i=this.eventListeners.get(e))==null||i.delete(n)}}onAny(e){const n=["open","click","bounce","unsubscribe","complaint"].map(i=>this.on(i,e));return()=>{n.forEach(i=>i())}}generateUnsubscribeLink(e){const n=new URLSearchParams;return n.set("rid",this.hashRecipientId(e.recipientId)),e.listId&&n.set("lid",e.listId),n.set("action","unsubscribe"),`${this.config.serverUrl}/unsubscribe?${n.toString()}`}generateListUnsubscribeHeader(e){return`<${this.generateUnsubscribeLink(e)}>`}clearEvents(){this.events=[]}exportEvents(e){return e!=null&&e.anonymize?this.events.map(n=>({...n,recipientHash:"anonymized",ipAddress:void 0,userAgent:void 0})):[...this.events]}buildTrackingParams(e){const n=new URLSearchParams;if(n.set("mid",e.messageId),n.set("rid",this.hashRecipientId(e.recipientId)),e.campaignId&&n.set("cid",e.campaignId),e.url&&n.set("url",e.url),e.linkName&&n.set("ln",e.linkName),e.metadata)for(const[i,r]of Object.entries(e.metadata))n.set(`m_${i}`,r);return n.toString()}hashRecipientId(e){let n=0;for(let i=0;i<e.length;i++){const r=e.charCodeAt(i);n=(n<<5)-n+r,n=n&n}return Math.abs(n).toString(36)}anonymizeIpAddress(e){if(e){if(e.includes(".")){const n=e.split(".");return n[3]="0",n.join(".")}return e.includes(":")?e.split(":").slice(0,3).join(":")+"::":e}}extractLinkName(e){const n=e.match(/title=["']([^"']+)["']/i);if(n)return n[1];const i=e.match(/data-link-name=["']([^"']+)["']/i);if(i)return i[1]}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}generateEventId(){return`evt_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}notifyListeners(e){const n=this.eventListeners.get(e.type);if(n)for(const i of n)try{i(e)}catch(r){console.error("Tracking event listener error:",r)}}}let me=null;function Ge(s){if(!me&&s&&(me=new At(s)),!me)throw new Error("EmailTrackingService not initialized. Call with config first.");return me}function Jn(){me==null||me.clearEvents(),me=null}function Qn(s){const{config:e,campaignId:n,autoRefreshInterval:i}=s,r=l.useMemo(()=>{if(e)return Ge(e);try{return Ge()}catch{return null}},[e]),[a,o]=l.useState(null),[c,u]=l.useState([]),p=l.useCallback(()=>{r&&(o(r.getStats({campaignId:n})),u(r.getLinkStats({campaignId:n})))},[r,n]);l.useEffect(()=>{if(p(),i&&r){const h=setInterval(p,i);return()=>clearInterval(h)}},[p,i,r]),l.useEffect(()=>{if(r)return r.onAny(()=>{p()})},[r,p]);const m=l.useCallback((h,v)=>r?r.generateTrackingPixel({messageId:h,recipientId:v,campaignId:n}):"",[r,n]),f=l.useCallback((h,v,z)=>r?r.wrapLinksForTracking(h,{messageId:v,recipientId:z,campaignId:n}):h,[r,n]),y=l.useCallback(h=>{r==null||r.recordEvent(h)},[r]);return{generatePixel:m,wrapLinks:f,stats:a,linkStats:c,recordEvent:y,refreshStats:p}}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 n={...e,id:this.generateId("tpl"),createdAt:new Date,updatedAt:new Date};return this.templates.set(n.id,n),n}updateTemplate(e,n){const i=this.templates.get(e);if(!i)throw new Error(`Template not found: ${e}`);const r={...i,...n,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 n=/\{\{([^}]+)\}\}/g,i=new Set;let r;for(;(r=n.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 n={...e,id:this.generateId("cmp"),status:"draft",recipients:e.recipients.map(i=>({...i,status:"pending"})),createdAt:new Date};return this.campaigns.set(n.id,n),n}getCampaign(e){return this.campaigns.get(e)}updateCampaign(e,n){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,...n};return this.campaigns.set(e,r),r}addRecipients(e,n){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=n.map(a=>({...a,status:"pending"}));i.recipients.push(...r),this.campaigns.set(e,i)}removeRecipient(e,n){const i=this.campaigns.get(e);if(!i)return!1;const r=i.recipients.findIndex(a=>a.id===n);return r===-1?!1:(i.recipients.splice(r,1),!0)}listCampaigns(){return Array.from(this.campaigns.values())}validateCampaign(e){const n=this.campaigns.get(e);if(!n)return{isValid:!1,errors:[{type:"syntax_error",message:"Campaign not found"}],warnings:[],missingFields:new Map};const i=this.templates.get(n.templateId);if(!i)return{isValid:!1,errors:[{type:"syntax_error",message:"Template not found"}],warnings:[],missingFields:new Map};const r=[],a=[],o=new Map;n.recipients.length===0&&r.push({type:"empty_recipient",message:"No recipients in campaign"});for(const p of n.recipients){if(!p.email){r.push({type:"empty_recipient",recipientId:p.id,message:`Recipient ${p.id} has no email address`});continue}const m=[];for(const f of i.fields)f.required&&!(f.name in p.data)&&(m.push(f.name),r.push({type:"missing_field",field:f.name,recipientId:p.id,message:`Required field "${f.name}" missing for ${p.email}`}));m.length>0&&o.set(p.id,m)}const c=this.extractFields(i.subject+i.htmlBody+(i.textBody??"")),u=i.fields.map(p=>p.name);for(const p of c)u.includes(p)||a.push({type:"unused_field",field:p,message:`Field "${p}" used in template but not defined`});return{isValid:r.length===0,errors:r,warnings:a,missingFields:o}}previewMerge(e,n){const i=this.templates.get(e);if(!i)throw new Error(`Template not found: ${e}`);return{subject:this.processTemplate(i.subject,n,i.fields),html:this.processTemplate(i.htmlBody,n,i.fields),text:i.textBody?this.processTemplate(i.textBody,n,i.fields):void 0}}async*sendCampaign(e){const n=this.campaigns.get(e);if(!n)throw new Error(`Campaign not found: ${e}`);const i=this.templates.get(n.templateId);if(!i)throw new Error(`Template not found: ${n.templateId}`);const r=this.validateCampaign(e);if(!r.isValid)throw new Error(`Campaign validation failed: ${r.errors.map(y=>y.message).join(", ")}`);n.status="sending",n.startedAt=new Date,this.campaigns.set(e,n);const a=new AbortController;this.abortControllers.set(e,a);const o=n.recipients.filter(y=>y.status==="pending"),c=o.length;let u=0,p=0;const m=Date.now(),f=60*1e3/(n.rateLimit??this.config.rateLimit);try{for(let y=0;y<o.length;y++){if(a.signal.aborted){n.status="paused";break}const h=o[y];try{const D=this.previewMerge(i.id,h.data),_=await this.config.sendEmail({to:h.email,cc:h.cc,bcc:h.bcc,from:n.fromEmail,fromName:n.fromName,replyTo:n.replyTo,subject:h.subjectOverride??D.subject,html:D.html,text:D.text});_.success?(h.status="sent",u++):(h.status="failed",h.error=_.error,p++)}catch(D){h.status="failed",h.error=D instanceof Error?D.message:"Unknown error",p++}const v=u+p,z=Date.now()-m,d=v>0?z/v:f,N=c-v,R=Math.round(N*d/1e3);yield{campaignId:e,total:c,sent:u,failed:p,pending:c-v,current:h.email,percentage:Math.round(v/c*100),estimatedTimeRemaining:R,isComplete:!1},y<o.length-1&&await this.delay(f)}n.status="completed",n.completedAt=new Date,this.campaigns.set(e,n),yield{campaignId:e,total:c,sent:u,failed:p,pending:0,percentage:100,isComplete:!0}}finally{this.abortControllers.delete(e)}}pauseCampaign(e){const n=this.abortControllers.get(e);n&&n.abort();const i=this.campaigns.get(e);i&&i.status==="sending"&&(i.status="paused",this.campaigns.set(e,i))}async*resumeCampaign(e){const n=this.campaigns.get(e);if(!n)throw new Error(`Campaign not found: ${e}`);if(n.status!=="paused")throw new Error("Campaign is not paused");n.status="draft",this.campaigns.set(e,n),yield*this.sendCampaign(e)}cancelCampaign(e){this.pauseCampaign(e);const n=this.campaigns.get(e);n&&(n.status="cancelled",this.campaigns.set(e,n))}async*retryFailed(e){const n=this.campaigns.get(e);if(!n)throw new Error(`Campaign not found: ${e}`);for(const i of n.recipients)i.status==="failed"&&(i.status="pending",i.error=void 0);n.status="draft",this.campaigns.set(e,n),yield*this.sendCampaign(e)}processTemplate(e,n,i){const r=new Map(i.map(a=>[a.name,a]));return e=this.processConditionals(e,n),e=this.processLoops(e,n),e=e.replace(/\{\{([^}#/]+)\}\}/g,(a,o)=>{const[c,...u]=o.trim().split("|").map(f=>f.trim());let p=this.getNestedValue(n,c);const m=r.get(c);p==null&&(p=(m==null?void 0:m.defaultValue)??""),m&&p!==""&&(p=this.formatValue(p,m));for(const f of u)p=this.applyFormatter(p,f);return String(p)}),e}processConditionals(e,n){const i=/\{\{#if\s+([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g;return e.replace(i,(r,a,o,c="")=>{const u=this.getNestedValue(n,a.trim());return this.isTruthy(u)?o:c})}processLoops(e,n){const i=/\{\{#each\s+([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g;return e.replace(i,(r,a,o)=>{const c=this.getNestedValue(n,a.trim());return Array.isArray(c)?c.map((u,p)=>{let m=o;return typeof u!="object"&&(m=m.replace(/\{\{this\}\}/g,String(u))),m=m.replace(/\{\{this\.([^}]+)\}\}/g,(f,y)=>String(this.getNestedValue(u,y)??"")),m=m.replace(/\{\{@index\}\}/g,String(p)),m=m.replace(/\{\{@first\}\}/g,String(p===0)),m=m.replace(/\{\{@last\}\}/g,String(p===c.length-1)),m}).join(""):""})}formatValue(e,n){switch(n.type){case"date":return e instanceof Date?this.config.dateFormatter(e,n.format??"short"):typeof e=="string"||typeof e=="number"?this.config.dateFormatter(new Date(e),n.format??"short"):String(e);case"number":return typeof e=="number"?this.config.numberFormatter(e,n.format??""):String(e);case"currency":if(typeof e=="number"){const[i="USD",r="en-US"]=(n.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(n.format??", "):String(e);default:return String(e)}}applyFormatter(e,n){const i=String(e);switch(n.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,n){const i=n.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,n){const i={};switch(n){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,n){if(!n)return new Intl.NumberFormat().format(e);const i=parseInt(n,10);return isNaN(i)?String(e):new Intl.NumberFormat("en-US",{minimumFractionDigits:i,maximumFractionDigits:i}).format(e)}defaultCurrencyFormatter(e,n,i){return new Intl.NumberFormat(i,{style:"currency",currency:n}).format(e)}generateId(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}delay(e){return new Promise(n=>setTimeout(n,e))}}let Te=null;function qe(s){if(!Te&&s&&(Te=new Et(s)),!Te)throw new Error("MailMergeService not initialized. Call with config first.");return Te}function Zn(){Te=null}function ei(s={}){const{config:e}=s,n=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,u]=l.useState([]),[p,m]=l.useState([]),f=l.useCallback(()=>{n&&(u(n.listTemplates()),m(n.listCampaigns()))},[n]),y=l.useCallback(R=>{if(!n)throw new Error("Service not initialized");const D=n.createTemplate(R);return f(),D},[n,f]),h=l.useCallback(R=>{if(!n)throw new Error("Service not initialized");const D=n.createCampaign(R);return f(),D},[n,f]),v=l.useCallback((R,D)=>{if(!n)throw new Error("Service not initialized");return n.previewMerge(R,D)},[n]),z=l.useCallback(R=>{if(!n)throw new Error("Service not initialized");return n.validateCampaign(R)},[n]),d=l.useCallback(async function*(R){if(!n)throw new Error("Service not initialized");o(!0);try{for await(const D of n.sendCampaign(R))r(D),yield D}finally{o(!1),f()}},[n,f]),N=l.useCallback(R=>{n==null||n.pauseCampaign(R),o(!1),f()},[n,f]);return{createTemplate:y,createCampaign:h,preview:v,validate:z,send:d,pause:N,progress:i,isSending:a,templates:c,campaigns:p}}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 n=await this.extractZipContents(e),i=n.get("users.json"),r=i?JSON.parse(i):[],a=n.get("channels.json"),o=a?JSON.parse(a):[],c=n.get("groups.json");if(c){const m=JSON.parse(c);o.push(...m.map(f=>({...f,is_private:!0})))}const u=n.get("dms.json");if(u){const m=JSON.parse(u);o.push(...m.map(f=>({...f,is_im:!0})))}const p=new Map;for(const m of o){const f=[],y=m.name;for(const[h,v]of n)if(h.startsWith(y+"/")&&h.endsWith(".json"))try{const z=JSON.parse(v);f.push(...z)}catch(z){console.warn(`Failed to parse messages from ${h}:`,z)}f.length>0&&p.set(m.id,f)}return{users:r,channels:o,messages:p}}parseSlackExportFromJson(e){return{users:e.users??[],channels:e.channels??[],messages:new Map(Object.entries(e.messages??{})),files:e.files}}previewImport(e,n={}){const i=e.users.filter(f=>n.importUsers!==!1&&!f.deleted),r=i.map(f=>this.mapUser(f)),a=e.channels.filter(f=>!(n.skipArchived&&f.is_archived||n.skipDirectMessages&&(f.is_im||f.is_mpim)||n.channelFilter&&!n.channelFilter.includes(f.id)&&!n.channelFilter.includes(f.name))),o=a.map(f=>this.mapChannel(f,new Map));let c=0;const u=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 z=this.filterMessages(y,n);u.set(h.name,z.length),c+=z.length}let p=0,m=0;for(const f of e.messages.values())for(const y of f)y.files&&(p+=y.files.length,m+=y.files.reduce((h,v)=>h+(v.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:u},files:{total:p,totalSize:m}}}async*import(e,n={}){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(n.importUsers!==!1){const p=e.users.filter(f=>!f.deleted);let m=0;for(const f of p){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:p.length,processed:m,failed:i.filter(v=>v.phase==="users").length,current:f.name,percentage:Math.round(m/p.length*100),isComplete:!1,errors:i},await this.delay(c)}}if(n.importChannels!==!1){const p=e.channels.filter(f=>{var y;return n.skipArchived&&f.is_archived||n.skipDirectMessages&&(f.is_im||f.is_mpim)?!1:(y=n.channelFilter)!=null&&y.length?n.channelFilter.includes(f.id)||n.channelFilter.includes(f.name):!0});let m=0;for(const f of p){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:p.length,processed:m,failed:i.filter(v=>v.phase==="channels").length,current:f.name,percentage:Math.round(m/p.length*100),isComplete:!1,errors:i},await this.delay(c)}}if(n.importMessages!==!1){const p=[];for(const[y,h]of e.messages){if(!this.mapping.channels.has(y))continue;const v=this.filterMessages(h,n);for(const z of v)p.push({channelId:y,message:z})}p.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 p){if(this.abortController.signal.aborted)break;const v=this.mapMessage(h,y,this.mapping,m),z=await this.config.createMessage(v);z.success&&z.id?((!h.thread_ts||h.thread_ts===h.ts)&&m.set(h.ts,z.id),r.messagesImported++,v.isThreadReply&&r.threadsImported++,r.reactionsImported+=v.reactions.length):i.push({phase:"messages",itemId:h.ts,itemType:"message",message:z.error??"Failed to create message"}),f++,yield{phase:"messages",total:p.length,processed:f,failed:i.filter(d=>d.phase==="messages").length,current:`${f}/${p.length}`,percentage:Math.round(f/p.length*100),isComplete:!1,errors:i},await this.delay(c)}}if(n.importFiles&&n.downloadFiles&&this.config.uploadFile&&this.config.downloadFile){const p=[];for(const f of e.messages.values())for(const y of f)y.files&&p.push(...y.files);let m=0;for(const f of p){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),v=await this.config.uploadFile(f,h);v.success&&v.url?(this.mapping.files.set(f.id,v.url),r.filesImported++):i.push({phase:"files",itemId:f.id,itemType:"file",message:v.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:p.length,processed:m,failed:i.filter(y=>y.phase==="files").length,current:f.name,percentage:Math.round(m/p.length*100),isComplete:!1,errors:i},await this.delay(c)}}const u=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:u,duration:u.getTime()-a.getTime()}}finally{this.abortController=null}}cancel(){var e;(e=this.abortController)==null||e.abort()}mapUser(e){var n,i,r,a,o;return{slackId:e.id,email:e.email,displayName:((n=e.profile)==null?void 0:n.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,n){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?n.get(e.creator):void 0,memberIds:(e.members??[]).map(o=>n.get(o)).filter(o=>!!o),createdAt:e.created?new Date(e.created*1e3):void 0}}mapMessage(e,n,i,r){const a=i.channels.get(n)??n,o=e.user?i.users.get(e.user):void 0,{text:c,html:u}=this.convertSlackMessage(e.text,i.users),p=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(v=>i.users.get(v)).filter(v=>!!v),count:h.count}));return{channelId:a,senderId:o,content:c,htmlContent:u,threadId:m,isThreadReply:p,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,n){let i=e,r=this.escapeHtml(e);const a=/<@([A-Z0-9]+)(?:\|([^>]+))?>/g;return i=i.replace(a,(o,c,u)=>u?`@${u}`:"@user"),r=r.replace(/&lt;@([A-Z0-9]+)(?:\|([^&]+))?&gt;/g,(o,c,u)=>`<span class="mention" data-user-id="${n.get(c)??c}">@${u??"user"}</span>`),i=i.replace(/<#([A-Z0-9]+)\|([^>]+)>/g,"#$2"),r=r.replace(/&lt;#([A-Z0-9]+)\|([^&]+)&gt;/g,'<span class="channel-mention">#$2</span>'),i=i.replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)"),i=i.replace(/<(https?:\/\/[^>]+)>/g,"$1"),r=r.replace(/&lt;(https?:\/\/[^|&]+)\|([^&]+)&gt;/g,'<a href="$1">$2</a>'),r=r.replace(/&lt;(https?:\/\/[^&]+)&gt;/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 n={":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)=>n[i]??i)}filterMessages(e,n){return e.filter(i=>i.subtype==="bot_message"?!0:!(n.messagesAfter&&new Date(parseFloat(i.ts)*1e3)<n.messagesAfter||n.messagesBefore&&new Date(parseFloat(i.ts)*1e3)>n.messagesBefore||!n.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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}delay(e){return new Promise(n=>setTimeout(n,e))}}let Re=null;function Ve(s){if(!Re&&s&&(Re=new Dt(s)),!Re)throw new Error("SlackImportService not initialized. Call with config first.");return Re}function ti(){Re=null}function ni(s={}){const{config:e}=s,n=l.useMemo(()=>{if(e)return Ve(e);try{return Ve()}catch{return null}},[e]),[i,r]=l.useState(null),[a,o]=l.useState(!1),[c,u]=l.useState(null),p=l.useCallback(h=>{if(!n)throw new Error("Service not initialized");return n.parseSlackExportFromJson(h)},[n]),m=l.useCallback((h,v)=>{if(!n)throw new Error("Service not initialized");return n.previewImport(h,v)},[n]),f=l.useCallback(async function*(h,v){var z,d;if(!n)throw new Error("Service not initialized");o(!0),u(null);try{for await(const _ of n.import(h,v))r(_),yield _;const N=n.import(h,v);let R;for await(const _ of N)R=_;const D=(d=(z=N.next)==null?void 0:z.call(N))==null?void 0:d.value;return D&&u(D),D}finally{o(!1)}},[n]),y=l.useCallback(()=>{n==null||n.cancel(),o(!1)},[n]);return{parseJson:p,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:"*#"},$t={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."},Xe={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 st{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={...$t,...e.ivrText}}on(e,n){this.eventHandlers[e]=n}off(e){delete this.eventHandlers[e]}emit(e,...n){const i=this.eventHandlers[e];i&&i(...n)}generateDialInInfo(e,n){const i=this.getAvailableNumbers(),r=this.generateAccessPin(),a=this.generateAccessPin(8),o={meetingId:e,dialInNumbers:i,accessPin:r,hostPin:a,meetingTitle:n,expiresAt:Date.now()+1440*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 n=Xe[e],i=Math.floor(1e9+Math.random()*9e9).toString();return`${n}${i}`}formatPhoneNumber(e){const n=Xe[e],i=this.generatePhoneNumber(e).slice(n.length);return e==="US"||e==="CA"?`${n} (${i.slice(0,3)}) ${i.slice(3,6)}-${i.slice(6)}`:`${n} ${i}`}generateAccessPin(e=6){return Math.floor(Math.random()*Math.pow(10,e)).toString().padStart(e,"0")}async handleIncomingCall(e,n,i){const r={callId:e,callerNumber:n,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,n,i){const r=this.participants.get(e);if(!r)return{success:!1,isHost:!1};const a=this.meetingDialIns.get(n);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,n){const i=this.participants.get(e);if(!i)return;const r=i.state;i.state=n,this.emit("onParticipantStateChanged",{...i},r)}async muteParticipant(e){const n=this.participants.get(e);n&&(n.audioStats.isMuted=!0,this.updateParticipantState(e,"muted"),await this.playIvr(e,"muted"))}async unmuteParticipant(e){const n=this.participants.get(e);n&&(n.audioStats.isMuted=!1,this.updateParticipantState(e,"joined"),await this.playIvr(e,"unmuted"))}async toggleMute(e){const n=this.participants.get(e);return n?n.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 n of this.participants.values())e&&(n.isHost||n.isModerator)||await this.muteParticipant(n.callId)}async unmuteAll(){for(const e of this.participants.values())await this.unmuteParticipant(e.callId)}async handleDtmf(e,n){const i=this.participants.get(e);i&&(this.emit("onDtmfReceived",{...i},n),n===this.dtmfCommands.toggleMute?await this.toggleMute(e):n===this.dtmfCommands.raiseHand?console.log(`Participant ${e} raised hand`):n===this.dtmfCommands.leave?await this.disconnectParticipant(e):n===this.dtmfCommands.help?await this.playHelp(e):(i.isHost||i.isModerator)&&(n===this.dtmfCommands.hostMuteAll?await this.muteAll():n===this.dtmfCommands.hostUnmuteAll?await this.unmuteAll():n===this.dtmfCommands.hostEndMeeting&&await this.endMeeting()))}setDtmfCommands(e){this.dtmfCommands={...this.dtmfCommands,...e}}async playIvr(e,n){const i=this.ivrText[n];console.log(`[IVR -> ${e}] ${i}`),await new Promise(r=>setTimeout(r,i.length*50))}async playCustomMessage(e,n){console.log(`[TTS -> ${e}] ${n}`),await new Promise(i=>setTimeout(i,n.length*50))}async playHelp(e){await this.playCustomMessage(e,`
6
+ `})]})}function we({icon:i,label:e,onClick:n,active:r,style:s}){return t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[t.jsx("button",{onClick:n,title:e,style:{width:44,height:44,borderRadius:"50%",border:"none",background:r?"var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))":"var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",color:"var(--nice-text-on-primary, #fff)",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.2s",...s},children:t.jsx(b.NiceIcon,{name:i,size:18})}),t.jsx("span",{style:{fontSize:9,color:"var(--nice-overlay-light-50, rgba(255, 255, 255, 0.5))",textAlign:"center",maxWidth:50},children:e})]})}const Vt=["👍","❤️","😂","😮","😢","🎉"];function _e({message:i,author:e,isMine:n,showAvatar:r,enableReactions:s,onReact:a,onReply:o,onEdit:c,onDelete:f,onPin:d,onOpenThread:g}){var I,A,N,H;const[p,m]=l.useState(!1),[h,w]=l.useState(!1),z=i.isDeleted,u=i.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return t.jsxs("div",{className:`nice-chat-message${n?" nice-chat-message--mine":""}${i.isPinned?" nice-chat-message--pinned":""}`,onMouseEnter:()=>m(!0),onMouseLeave:()=>{m(!1),w(!1)},style:{display:"flex",flexDirection:n?"row-reverse":"row",alignItems:"flex-end",gap:8,padding:"2px 16px",position:"relative"},children:[r&&!n&&t.jsxs("div",{style:{position:"relative",flexShrink:0},children:[t.jsx("div",{className:"nice-chat-avatar",style:{width:32,height:32,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontSize:13,fontWeight:600,flexShrink:0},children:!(e!=null&&e.avatarUrl)&&(((A=(I=e==null?void 0:e.name)==null?void 0:I[0])==null?void 0:A.toUpperCase())??"?")}),t.jsx(ue,{status:((N=e==null?void 0:e.presence)==null?void 0:N.status)??"unknown",size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),t.jsxs("div",{style:{maxWidth:"70%",display:"flex",flexDirection:"column",alignItems:n?"flex-end":"flex-start"},children:[!n&&e&&t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginBottom:2,paddingLeft:2},children:e.displayName??e.name}),i.replyTo&&t.jsx("div",{className:"nice-chat-reply-preview",style:{borderLeft:"3px solid var(--nice-info, #6366f1)",paddingLeft:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)",marginBottom:4,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.replyTo.content}),t.jsx("div",{className:`nice-chat-bubble${n?" nice-chat-bubble--mine":""}`,style:{padding:"8px 12px",borderRadius:n?"18px 18px 4px 18px":"18px 18px 18px 4px",background:n?"var(--nice-info, #6366f1)":"var(--nice-bg-secondary, #f3f4f6)",color:n?"var(--nice-text-on-primary, #fff)":"var(--nice-text, #111827)",fontSize:14,lineHeight:1.5,wordBreak:"break-word"},children:z?t.jsx("span",{style:{fontStyle:"italic",opacity:.6},children:"This message was deleted"}):i.contentType==="image"&&((H=i.attachments)!=null&&H[0])?t.jsx("img",{src:i.attachments[0].url,alt:i.attachments[0].name,style:{maxWidth:280,maxHeight:280,borderRadius:8,display:"block"}}):t.jsx("span",{children:i.content})}),!z&&i.attachments&&i.attachments.length>0&&i.contentType!=="image"&&t.jsx("div",{className:"nice-chat-attachments",style:{marginTop:4},children:i.attachments.map(E=>t.jsxs("a",{href:E.url,target:"_blank",rel:"noreferrer",className:"nice-chat-attachment",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:12,color:n?"var(--nice-overlay-light-85, rgba(255, 255, 255, 0.85))":"var(--nice-info, #6366f1)",textDecoration:"none",background:n?"var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))":"var(--nice-primary-bg, #e0e7ff)",borderRadius:6,padding:"3px 8px",marginTop:2},children:[t.jsx(b.NiceIcon,{name:"paperclip",size:14})," ",E.name]},E.id))}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:2},children:[t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:u}),i.editedAt&&t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:"(edited)"}),n&&t.jsx("span",{style:{display:"inline-flex",alignItems:"center",color:i.status==="read"?"var(--nice-info, #6366f1)":"var(--nice-text-muted, #9ca3af)"},children:i.status==="sending"?t.jsx(b.NiceIcon,{name:"circle",size:12}):i.status==="sent"?t.jsx(b.NiceIcon,{name:"check",size:12}):t.jsxs("span",{style:{display:"inline-flex",marginRight:-6},children:[t.jsx(b.NiceIcon,{name:"check",size:12}),t.jsx(b.NiceIcon,{name:"check",size:12})]})})]}),i.reactions&&i.reactions.length>0&&t.jsx("div",{className:"nice-chat-reactions",style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:i.reactions.map(E=>t.jsxs("button",{onClick:()=>a(i.id,E.emoji),style:{background:E.mine?"var(--nice-primary-bg, #e0e7ff)":"var(--nice-bg-secondary, #f3f4f6)",border:E.mine?"1px solid var(--nice-info, #6366f1)":"1px solid transparent",borderRadius:12,padding:"2px 7px",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",gap:3},children:[E.emoji," ",E.count]},E.emoji))}),(i.threadCount??0)>0&&t.jsxs("button",{className:"nice-chat-thread-btn",onClick:()=>g==null?void 0:g(i),style:{background:"none",border:"none",color:"var(--nice-info, #6366f1)",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:2,display:"inline-flex",alignItems:"center",gap:4},children:[t.jsx(b.NiceIcon,{name:"message",size:14})," ",i.threadCount," repl",i.threadCount===1?"y":"ies"]})]}),p&&!z&&t.jsxs("div",{className:"nice-chat-actions",style:{position:"absolute",top:-16,[n?"left":"right"]:16,display:"flex",gap:2,background:"var(--nice-bg, #fff)",borderRadius:8,boxShadow:"0 2px 8px var(--nice-overlay-12, rgba(0, 0, 0, 0.12))",padding:"3px 6px",zIndex:10},children:[s&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{title:"React","aria-label":"React",onClick:()=>w(E=>!E),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:t.jsx(b.NiceIcon,{name:"heart",size:16})}),h&&t.jsx("div",{style:{position:"absolute",bottom:"100%",left:0,display:"flex",gap:4,background:"var(--nice-bg, #fff)",borderRadius:8,boxShadow:"0 2px 8px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",padding:"6px 8px",zIndex:20},children:Vt.map(E=>t.jsx("button",{onClick:()=>{a(i.id,E),w(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:E},E))})]}),t.jsx("button",{title:"Reply","aria-label":"Reply",onClick:()=>o(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:t.jsx(b.NiceIcon,{name:"reply",size:16})}),n&&c&&t.jsx("button",{title:"Edit","aria-label":"Edit",onClick:()=>c(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:t.jsx(b.NiceIcon,{name:"edit",size:16})}),d&&t.jsx("button",{title:i.isPinned?"Unpin":"Pin","aria-label":i.isPinned?"Unpin":"Pin",onClick:()=>d(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:t.jsx(b.NiceIcon,{name:"map-pin",size:16})}),n&&f&&t.jsx("button",{title:"Delete","aria-label":"Delete",onClick:()=>f(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px",color:"var(--nice-danger, #ef4444)"},children:t.jsx(b.NiceIcon,{name:"trash",size:16})})]})]})}function ct({placeholder:i="Type a message…",maxLength:e,replyTo:n,onCancelReply:r,onSend:s,onAttach:a,disabled:o}){const[c,f]=l.useState(""),d=l.useRef(null);l.useEffect(()=>{n&&d.current&&d.current.focus()},[n]);const g=h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),p())},p=()=>{const h=c.trim();h&&(s(h),f(""),d.current&&(d.current.style.height="auto"))},m=h=>{f(h.target.value),h.target.style.height="auto",h.target.style.height=`${Math.min(h.target.scrollHeight,120)}px`};return t.jsxs("div",{className:"nice-chat-input-area",style:{padding:"8px 12px",borderTop:"1px solid var(--nice-border, #e5e7eb)",background:"var(--nice-bg, #fff)"},children:[n&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",background:"var(--nice-bg-secondary, #f3f4f6)",borderLeft:"3px solid var(--nice-info, #6366f1)",padding:"4px 8px",marginBottom:6,borderRadius:"0 4px 4px 0",fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:[t.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Replying: ",n.content]}),t.jsx("button",{onClick:r,title:"Cancel reply","aria-label":"Cancel reply",style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",marginLeft:8,display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:"close",size:16})})]}),t.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:8},children:[a&&t.jsx("button",{onClick:a,title:"Attach file","aria-label":"Attach file",style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",padding:"4px",flexShrink:0,display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:"paperclip",size:18})}),t.jsx("textarea",{ref:d,value:c,onChange:m,onKeyDown:g,placeholder:i,maxLength:e,disabled:o,rows:1,style:{flex:1,resize:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:20,padding:"8px 14px",fontSize:14,outline:"none",fontFamily:"inherit",lineHeight:1.5,overflow:"hidden"}}),t.jsx("button",{onClick:p,disabled:!c.trim()||o,title:"Send","aria-label":"Send",style:{background:c.trim()?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)",border:"none",borderRadius:"50%",width:36,height:36,cursor:c.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--nice-text-on-primary, #fff)",transition:"background 0.15s"},children:t.jsx(b.NiceIcon,{name:"send",size:16})})]}),e&&c.length>e*.8&&t.jsxs("div",{style:{textAlign:"right",fontSize:11,color:c.length>=e?"var(--nice-danger, #ef4444)":"var(--nice-text-muted, #9ca3af)",marginTop:2},children:[c.length,"/",e]})]})}function Ne({conversation:i,messages:e,users:n,currentUser:r,isLoading:s=!1,hasMore:a=!1,showHeader:o=!0,showUserAvatars:c=!0,enableReactions:f=!0,enableThreads:d=!0,enableAttachments:g=!0,placeholder:p,maxMessageLength:m,onSendMessage:h,onEditMessage:w,onDeleteMessage:z,onReactToMessage:u,onPinMessage:I,onLoadMoreMessages:A,onStartCall:N,className:H,style:E,id:B,"data-testid":K}){var Y,S;const J=l.useRef(null),$=l.useRef(null),[C,j]=l.useState(null),[O,U]=l.useState(null),P=l.useMemo(()=>{const x=new Map;return n.forEach(G=>x.set(G.id,G)),x},[n]);l.useEffect(()=>{var x;(x=J.current)==null||x.scrollIntoView({behavior:"smooth"})},[e]);const T=l.useCallback(()=>{const x=$.current;!x||!a||s||x.scrollTop===0&&e.length>0&&(A==null||A(i.id,e[0].id))},[a,s,e,i.id,A]),F=l.useCallback(x=>{h==null||h(i.id,x,"text"),j(null)},[i.id,h]),_=i.type==="dm"?P.get(i.participantIds.find(x=>x!==r.id)??""):void 0;return t.jsxs("div",{id:B,"data-testid":K,className:`nice-chat-window${H?` ${H}`:""}`,style:{display:"flex",flexDirection:"column",height:"100%",background:"var(--nice-bg, #fff)",...E},children:[o&&t.jsxs("div",{className:"nice-chat-header",style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:(_??i).avatarUrl?`url(${(_??i).avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:15,flexShrink:0},children:!(_??i).avatarUrl&&((Y=((_==null?void 0:_.name)??i.name??"?")[0])==null?void 0:Y.toUpperCase())}),t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:600,fontSize:15},children:(_==null?void 0:_.displayName)??(_==null?void 0:_.name)??i.name??"Chat"}),_&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:1},children:[t.jsx(ue,{status:_.presence.status,size:"xs"}),t.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:_.presence.statusMessage??_.presence.status})]}),i.type!=="dm"&&t.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:[i.participantIds.length," members"]})]})]}),i.type==="dm"&&N&&_&&t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:()=>N([_.id],"audio"),title:"Audio call","aria-label":"Audio call",style:{background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"5px 8px",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:"phone",size:16})}),t.jsx("button",{onClick:()=>N([_.id],"video"),title:"Video call","aria-label":"Video call",style:{background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"5px 8px",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:"video",size:16})})]})]}),t.jsxs("div",{ref:$,className:"nice-chat-messages",onScroll:T,style:{flex:1,overflowY:"auto",padding:"8px 0",display:"flex",flexDirection:"column"},children:[a&&t.jsx("button",{onClick:()=>e.length>0&&(A==null?void 0:A(i.id,e[0].id)),disabled:s,style:{display:"block",margin:"8px auto",background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,padding:"4px 16px",fontSize:12,color:"var(--nice-text-secondary, #6b7280)",cursor:"pointer"},children:s?"Loading…":"Load older messages"}),e.map((x,G)=>{const X=e[G-1],Q=c&&(!X||X.authorId!==x.authorId);return t.jsx(_e,{message:x,author:P.get(x.authorId),isMine:x.authorId===r.id,showAvatar:Q,enableReactions:f,onReact:(q,ne)=>u==null?void 0:u(q,ne),onReply:q=>j(q),onEdit:w?q=>w(q.id,q.content):void 0,onDelete:z?q=>z(q.id):void 0,onPin:I?q=>I(q.id):void 0,onOpenThread:d?q=>U(q):void 0},x.id)}),t.jsx("div",{ref:J})]}),O&&t.jsxs("div",{className:"nice-chat-thread-panel",style:{position:"absolute",right:0,top:o?57:0,bottom:0,width:320,background:"var(--nice-bg, #fff)",borderLeft:"1px solid var(--nice-border, #e5e7eb)",display:"flex",flexDirection:"column",zIndex:5},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid var(--nice-border, #e5e7eb)"},children:[t.jsx("span",{style:{fontWeight:600,fontSize:14},children:"Thread"}),t.jsx("button",{onClick:()=>U(null),title:"Close thread","aria-label":"Close thread",style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:"close",size:18})})]}),t.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[t.jsx(_e,{message:O,author:P.get(O.authorId),isMine:O.authorId===r.id,showAvatar:!0,enableReactions:f,onReact:(x,G)=>u==null?void 0:u(x,G),onReply:()=>{}}),(S=O.thread)==null?void 0:S.map(x=>t.jsx(_e,{message:x,author:P.get(x.authorId),isMine:x.authorId===r.id,showAvatar:!0,enableReactions:f,onReact:(G,X)=>u==null?void 0:u(G,X),onReply:()=>{}},x.id))]}),t.jsx(ct,{placeholder:"Reply in thread…",onSend:x=>h==null?void 0:h(i.id,x,"text")})]}),t.jsx(ct,{placeholder:p,maxLength:m,replyTo:C,onCancelReply:()=>j(null),onSend:F,onAttach:g?()=>{}:void 0})]})}function Xt({conversation:i,partner:e,isActive:n,lastMessage:r,onClick:s}){var g;const a=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??i.name??"Group",o=((g=a[0])==null?void 0:g.toUpperCase())??"?",c=(e==null?void 0:e.avatarUrl)??i.avatarUrl,f=r?r.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"",d=r?r.isDeleted?"Message deleted":r.content.slice(0,50):"";return t.jsxs("button",{className:`nice-messenger-conv-item${n?" nice-messenger-conv-item--active":""}`,onClick:s,style:{display:"flex",alignItems:"center",gap:10,padding:"10px 14px",background:n?"var(--nice-accent-tint-10, #ede9fe)":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",position:"relative"},children:[t.jsxs("div",{style:{position:"relative",flexShrink:0},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:c?`url(${c}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-on-primary, #fff)",fontWeight:700,fontSize:16},children:!c&&o}),e&&t.jsx(ue,{status:e.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}}),i.type!=="dm"&&t.jsx("span",{style:{position:"absolute",bottom:-2,right:-2,background:"var(--nice-bg-secondary, #f3f4f6)",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:4,padding:"1px 2px",color:"var(--nice-text-secondary, #6b7280)",display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:"hash",size:10})})]}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline"},children:[t.jsx("span",{style:{fontWeight:i.unreadCount>0?700:500,fontSize:14,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",flexShrink:0,marginLeft:4},children:f})]}),t.jsx("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:d})]}),(i.unreadCount>0||i.mentionCount>0)&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,alignItems:"flex-end",flexShrink:0},children:[i.mentionCount>0&&t.jsxs("span",{style:{background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:["@",i.mentionCount]}),i.unreadCount>0&&t.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:i.unreadCount>99?"99+":i.unreadCount})]}),i.isMuted&&t.jsx("span",{style:{position:"absolute",bottom:8,right:8,color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex"},children:t.jsx(b.NiceIcon,{name:"mic",size:12,title:"Muted"})})]})}function kt({conversations:i,messages:e,users:n,currentUser:r,activeConversationId:s,teams:a,enableGroupConversations:o=!0,showPresence:c=!0,enableSearch:f=!0,onSendMessage:d,onEditMessage:g,onDeleteMessage:p,onReactToMessage:m,onPinMessage:h,onLoadMoreMessages:w,onMarkAsRead:z,onStartCall:u,onCreateConversation:I,className:A,style:N,id:H,"data-testid":E}){var S;const[B,K]=l.useState(s??null),[J,$]=l.useState(""),[C,j]=l.useState("all");l.useMemo(()=>{const x=new Map;return n.forEach(G=>x.set(G.id,G)),x},[n]);const O=l.useMemo(()=>{let x=i;if(C==="unread"&&(x=x.filter(G=>G.unreadCount>0)),C==="groups"&&(x=x.filter(G=>G.type!=="dm")),J.trim()){const G=J.toLowerCase();x=x.filter(X=>{var q,ne;const Q=Ge(X,r.id,n);return(Q==null?void 0:Q.name.toLowerCase().includes(G))||((q=X.name)==null?void 0:q.toLowerCase().includes(G))||((ne=X.lastMessage)==null?void 0:ne.content.toLowerCase().includes(G))})}return[...x].sort((G,X)=>{var ne,ce;if(G.isPinned!==X.isPinned)return G.isPinned?-1:1;const Q=((ne=G.lastMessage)==null?void 0:ne.timestamp.getTime())??G.updatedAt.getTime();return(((ce=X.lastMessage)==null?void 0:ce.timestamp.getTime())??X.updatedAt.getTime())-Q})},[i,C,J,r.id,n]),U=l.useMemo(()=>i.find(x=>x.id===B)??null,[i,B]),P=l.useMemo(()=>B?e[B]??[]:[],[e,B]),T=l.useCallback(x=>{K(x),z==null||z(x)},[z]),F=l.useMemo(()=>Ze(i),[i]),_=a??[],Y=n.filter(x=>x.id!==r.id&&x.presence.status==="online").slice(0,6);return t.jsxs("div",{id:H,"data-testid":E,className:`nice-messenger${A?` ${A}`:""}`,style:{display:"flex",height:"100%",background:"var(--nice-bg, #fff)",overflow:"hidden",...N},children:[t.jsxs("div",{className:"nice-messenger-sidebar",style:{width:280,flexShrink:0,borderRight:"1px solid var(--nice-border, #e5e7eb)",display:"flex",flexDirection:"column",background:"var(--nice-bg-secondary, #fafafa)"},children:[t.jsxs("div",{style:{padding:"14px 14px 8px",borderBottom:"1px solid var(--nice-border, #e5e7eb)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("span",{style:{fontWeight:700,fontSize:16},children:["Messages"," ",F>0&&t.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:10,padding:"1px 6px",fontWeight:700,marginLeft:4},children:F})]}),o&&I&&t.jsx("button",{onClick:()=>I([],"group"),title:"New conversation","aria-label":"New conversation",style:{background:"var(--nice-info, #6366f1)",border:"none",borderRadius:6,padding:"5px 8px",cursor:"pointer",color:"var(--nice-text-on-primary, #fff)",display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:"plus",size:13})})]}),f&&t.jsx("input",{type:"search",value:J,onChange:x=>$(x.target.value),placeholder:"Search conversations…",style:{width:"100%",marginTop:8,padding:"6px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,fontSize:13,outline:"none",boxSizing:"border-box",background:"var(--nice-bg, #fff)"}}),t.jsx("div",{style:{display:"flex",gap:2,marginTop:8},children:["all","unread","groups"].map(x=>t.jsx("button",{onClick:()=>j(x),style:{flex:1,padding:"4px 0",border:"none",borderRadius:6,background:C===x?"var(--nice-info, #6366f1)":"transparent",color:C===x?"var(--nice-text-on-primary, #fff)":"var(--nice-text-secondary, #6b7280)",cursor:"pointer",fontSize:12,textTransform:"capitalize",fontWeight:C===x?600:400},children:x},x))})]}),c&&Y.length>0&&t.jsxs("div",{style:{padding:"8px 14px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",overflowX:"auto"},children:[t.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",marginBottom:6},children:"ONLINE NOW"}),t.jsx("div",{style:{display:"flex",gap:10},children:Y.map(x=>{var G;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:3},children:[t.jsxs("div",{style:{position:"relative"},children:[t.jsx("div",{style:{width:34,height:34,borderRadius:"50%",background:x.avatarUrl?`url(${x.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:13,cursor:"pointer"},title:x.name,children:!x.avatarUrl&&((G=x.name[0])==null?void 0:G.toUpperCase())}),t.jsx(ue,{status:x.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),t.jsx("span",{style:{fontSize:10,color:"var(--nice-text-secondary, #6b7280)",maxWidth:36,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.displayName??x.name.split(" ")[0]})]},x.id)})})]}),t.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[_.length>0&&C==="all"&&t.jsx("div",{style:{padding:"8px 14px 4px",fontSize:11,color:"var(--nice-text-muted, #9ca3af)",fontWeight:600,letterSpacing:"0.05em"},children:"DIRECT MESSAGES"}),O.length===0?t.jsx("div",{style:{padding:24,textAlign:"center",color:"var(--nice-text-muted, #9ca3af)",fontSize:13},children:"No conversations"}):O.map(x=>t.jsx(Xt,{conversation:x,partner:Ge(x,r.id,n),isActive:x.id===B,lastMessage:x.lastMessage,onClick:()=>T(x.id)},x.id))]}),t.jsxs("div",{style:{padding:"10px 14px",borderTop:"1px solid var(--nice-border, #e5e7eb)",display:"flex",alignItems:"center",gap:8},children:[t.jsxs("div",{style:{position:"relative"},children:[t.jsx("div",{style:{width:32,height:32,borderRadius:"50%",background:r.avatarUrl?`url(${r.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:13},children:!r.avatarUrl&&((S=r.name[0])==null?void 0:S.toUpperCase())}),t.jsx(ue,{status:r.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontWeight:600,fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.displayName??r.name}),t.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.presence.statusMessage??r.presence.status})]})]})]}),t.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:U?t.jsx(Ne,{conversation:U,messages:P,users:n,currentUser:r,onSendMessage:d,onEditMessage:g,onDeleteMessage:p,onReactToMessage:m,onPinMessage:h,onLoadMoreMessages:w,onStartCall:u,style:{height:"100%"}}):t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"var(--nice-text-muted, #9ca3af)",gap:12},children:[t.jsx(b.NiceIcon,{name:"message",size:48}),t.jsx("span",{style:{fontSize:15},children:"Select a conversation to start messaging"})]})})]})}const Jt=["👍","❤️","😂","🎉","😮","😢"];function Be({message:i,author:e,isMine:n,enableReactions:r,enableThreads:s,onReact:a,onOpenThread:o,onReply:c}){var w,z,u;const[f,d]=l.useState(!1),[g,p]=l.useState(!1),m=i.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),h=i.timestamp.toLocaleDateString([],{month:"short",day:"numeric"});return t.jsxs("div",{className:`nice-channel-msg${f?" nice-channel-msg--hovered":""}${n?" nice-channel-msg--mine":""}`,onMouseEnter:()=>d(!0),onMouseLeave:()=>{d(!1),p(!1)},style:{display:"flex",gap:10,padding:"4px 16px",position:"relative",background:f?"rgba(99,102,241,0.04)":"transparent"},children:[t.jsx("div",{style:{width:36,flexShrink:0},children:t.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:14},children:!(e!=null&&e.avatarUrl)&&(((z=(w=e==null?void 0:e.name)==null?void 0:w[0])==null?void 0:z.toUpperCase())??"?")})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:2},children:[t.jsx("span",{style:{fontWeight:600,fontSize:14,color:"var(--nice-text, #111827)"},children:(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??"Unknown"}),e&&t.jsx(ue,{status:e.presence.status,size:"xs"}),t.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:[h," ",m]}),i.editedAt&&t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:"(edited)"}),i.isPinned&&t.jsxs("span",{style:{fontSize:11,color:"var(--nice-info, #6366f1)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(b.NiceIcon,{name:"map-pin",size:12})," Pinned"]})]}),i.isDeleted?t.jsx("span",{style:{fontStyle:"italic",color:"var(--nice-text-muted, #9ca3af)",fontSize:14},children:"This message was deleted"}):t.jsx("div",{style:{fontSize:14,lineHeight:1.6,color:"var(--nice-text, #1f2937)",wordBreak:"break-word"},children:i.contentType==="image"&&((u=i.attachments)!=null&&u[0])?t.jsx("img",{src:i.attachments[0].url,alt:i.attachments[0].name,style:{maxWidth:400,maxHeight:300,borderRadius:8,display:"block",marginTop:4}}):i.content}),!i.isDeleted&&i.attachments&&i.attachments.length>0&&i.contentType!=="image"&&t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:4},children:i.attachments.map(I=>t.jsxs("a",{href:I.url,target:"_blank",rel:"noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:12,color:"var(--nice-info, #6366f1)",background:"var(--nice-accent-tint-10, #ede9fe)",borderRadius:6,padding:"3px 8px",textDecoration:"none"},children:[t.jsx(b.NiceIcon,{name:"paperclip",size:14})," ",I.name]},I.id))}),i.reactions&&i.reactions.length>0&&t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:i.reactions.map(I=>t.jsxs("button",{onClick:()=>a(i.id,I.emoji),style:{background:I.mine?"var(--nice-accent-tint-10, #ede9fe)":"var(--nice-bg-secondary, #f3f4f6)",border:I.mine?"1px solid var(--nice-info, #6366f1)":"1px solid transparent",borderRadius:12,padding:"2px 7px",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",gap:3},children:[I.emoji," ",I.count]},I.emoji))}),s&&(i.threadCount??0)>0&&t.jsxs("button",{onClick:()=>o(i),style:{background:"none",border:"none",color:"var(--nice-info, #6366f1)",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:3,display:"inline-flex",alignItems:"center",gap:4},children:[t.jsx(b.NiceIcon,{name:"message",size:14})," ",i.threadCount," repl",i.threadCount===1?"y":"ies"," ",t.jsx(b.NiceIcon,{name:"arrow-right",size:12})]})]}),f&&!i.isDeleted&&t.jsxs("div",{style:{position:"absolute",top:-16,right:16,display:"flex",gap:2,background:"var(--nice-bg, #fff)",borderRadius:8,boxShadow:"0 2px 8px var(--nice-overlay-12, rgba(0, 0, 0, 0.12))",padding:"3px 6px",zIndex:10},children:[r&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{onClick:()=>p(I=>!I),title:"React","aria-label":"React",style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:t.jsx(b.NiceIcon,{name:"heart",size:16})}),g&&t.jsx("div",{style:{position:"absolute",bottom:"100%",right:0,display:"flex",gap:4,background:"var(--nice-bg, #fff)",borderRadius:8,boxShadow:"0 2px 8px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",padding:"6px 8px",zIndex:20},children:Jt.map(I=>t.jsx("button",{onClick:()=>{a(i.id,I),p(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:I},I))})]}),t.jsx("button",{onClick:()=>c(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},title:"Reply","aria-label":"Reply",children:t.jsx(b.NiceIcon,{name:"reply",size:16})}),s&&t.jsx("button",{onClick:()=>o(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},title:"Open thread","aria-label":"Open thread",children:t.jsx(b.NiceIcon,{name:"message",size:16})})]})]})}function Ct({channel:i,messages:e,users:n,currentUser:r,team:s,isLoading:a=!1,hasMore:o=!1,enableThreads:c=!0,enableReactions:f=!0,enableAttachments:d=!0,onSendMessage:g,onEditMessage:p,onDeleteMessage:m,onReactToMessage:h,onPinMessage:w,onLoadMoreMessages:z,onStartCall:u,className:I,style:A,id:N,"data-testid":H}){var Y;const E=l.useRef(null),B=l.useRef(null),[K,J]=l.useState(""),[$,C]=l.useState(null),[j,O]=l.useState(null),U=l.useMemo(()=>{const S=new Map;return n.forEach(x=>S.set(x.id,x)),S},[n]);l.useEffect(()=>{var S;(S=E.current)==null||S.scrollIntoView({behavior:"smooth"})},[e]);const P=l.useCallback(()=>{const S=B.current;!S||!o||a||S.scrollTop===0&&e.length>0&&(z==null||z(i.id,e[0].id))},[o,a,e,i.id,z]),T=l.useCallback(()=>{const S=K.trim();S&&(g==null||g(i.id,S,"text"),J(""),C(null))},[K,i.id,g]),F=S=>{S.key==="Enter"&&!S.shiftKey&&(S.preventDefault(),T())},_=n.filter(S=>S.presence.status==="online").length;return t.jsxs("div",{id:N,"data-testid":H,className:`nice-channel-view${I?` ${I}`:""}`,style:{display:"flex",height:"100%",background:"var(--nice-bg, #fff)",overflow:"hidden",...A},children:[t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx(b.NiceIcon,{name:"hash",size:20,style:{color:"var(--nice-text-secondary, #6b7280)"}}),t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:700,fontSize:16},children:i.name}),i.description&&t.jsx("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",marginTop:1},children:i.description})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:[t.jsx("span",{style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:"var(--nice-success, #22c55e)",marginRight:4,verticalAlign:"middle"}}),_," online"]}),u&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>u(n.map(S=>S.id),"audio"),style:{background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"5px 8px",cursor:"pointer",display:"inline-flex",alignItems:"center"},title:"Audio call","aria-label":"Audio call",children:t.jsx(b.NiceIcon,{name:"phone",size:15})}),t.jsx("button",{onClick:()=>u(n.map(S=>S.id),"video"),style:{background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"5px 8px",cursor:"pointer",display:"inline-flex",alignItems:"center"},title:"Video meet","aria-label":"Video meet",children:t.jsx(b.NiceIcon,{name:"video",size:15})})]})]})]}),t.jsxs("div",{ref:B,onScroll:P,style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[o&&t.jsx("button",{onClick:()=>e.length>0&&(z==null?void 0:z(i.id,e[0].id)),disabled:a,style:{display:"block",margin:"8px auto",background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,padding:"4px 16px",fontSize:12,color:"var(--nice-text-secondary, #6b7280)",cursor:"pointer"},children:a?"Loading…":"Load older messages"}),e.map(S=>t.jsx(Be,{message:S,author:U.get(S.authorId),isMine:S.authorId===r.id,enableReactions:f,enableThreads:c,onReact:(x,G)=>h==null?void 0:h(x,G),onOpenThread:x=>O(x),onReply:x=>C(x)},S.id)),t.jsx("div",{ref:E})]}),t.jsxs("div",{style:{padding:"8px 16px",borderTop:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[$&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",background:"var(--nice-bg-secondary, #f3f4f6)",borderLeft:"3px solid var(--nice-info, #6366f1)",padding:"3px 8px",marginBottom:6,borderRadius:"0 4px 4px 0",fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:[t.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Replying to: ",$.content]}),t.jsx("button",{onClick:()=>C(null),title:"Cancel reply","aria-label":"Cancel reply",style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:"close",size:16})})]}),t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-end"},children:[d&&t.jsx("button",{title:"Attach","aria-label":"Attach",style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",padding:"6px 4px",display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:"paperclip",size:18})}),t.jsx("textarea",{value:K,onChange:S=>J(S.target.value),onKeyDown:F,placeholder:`Message #${i.name}`,rows:1,style:{flex:1,resize:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:"8px 12px",fontSize:14,outline:"none",fontFamily:"inherit",lineHeight:1.5,overflow:"hidden",maxHeight:100}}),t.jsx("button",{onClick:T,disabled:!K.trim(),title:"Send","aria-label":"Send",style:{background:K.trim()?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)",border:"none",borderRadius:"50%",width:36,height:36,cursor:K.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--nice-text-on-primary, #fff)",transition:"background 0.15s"},children:t.jsx(b.NiceIcon,{name:"send",size:15})})]})]})]}),j&&t.jsxs("div",{style:{width:340,flexShrink:0,borderLeft:"1px solid var(--nice-border, #e5e7eb)",display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[t.jsx("span",{style:{fontWeight:600,fontSize:14},children:"Thread"}),t.jsx("button",{onClick:()=>O(null),title:"Close thread","aria-label":"Close thread",style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:"close",size:18})})]}),t.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[t.jsx(Be,{message:j,author:U.get(j.authorId),isMine:j.authorId===r.id,enableReactions:f,enableThreads:!1,onReact:(S,x)=>h==null?void 0:h(S,x),onOpenThread:()=>{},onReply:()=>{}}),t.jsxs("div",{style:{padding:"6px 14px",color:"var(--nice-text-muted, #9ca3af)",fontSize:12,borderTop:"1px solid var(--nice-bg-secondary, #f3f4f6)"},children:[j.threadCount??0," repl",j.threadCount===1?"y":"ies"]}),(Y=j.thread)==null?void 0:Y.map(S=>t.jsx(Be,{message:S,author:U.get(S.authorId),isMine:S.authorId===r.id,enableReactions:f,enableThreads:!1,onReact:(x,G)=>h==null?void 0:h(x,G),onOpenThread:()=>{},onReply:()=>{}},S.id))]}),t.jsx("div",{style:{padding:"8px 12px",borderTop:"1px solid var(--nice-border, #e5e7eb)"},children:t.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-end"},children:[t.jsx("textarea",{placeholder:"Reply in thread…",rows:1,onKeyDown:S=>{if(S.key==="Enter"&&!S.shiftKey){S.preventDefault();const x=S.target.value.trim();x&&(g==null||g(i.id,x,"text"),S.target.value="")}},style:{flex:1,resize:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:"7px 10px",fontSize:13,outline:"none",fontFamily:"inherit",overflow:"hidden"}}),t.jsx("button",{title:"Send","aria-label":"Send",style:{background:"var(--nice-info, #6366f1)",border:"none",borderRadius:"50%",width:32,height:32,cursor:"pointer",color:"var(--nice-text-on-primary, #fff)",display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsx(b.NiceIcon,{name:"send",size:14})})]})})]})]})}function Ue({participant:i,isLocal:e,isPinned:n,onPin:r,size:s="medium",fill:a=!1}){var u;const o=l.useRef(null),{user:c,isMuted:f,isCameraOff:d,isScreenSharing:g,isSpeaking:p,isHandRaised:m,stream:h,screenStream:w}=i;l.useEffect(()=>{if(!o.current)return;const I=g?w:h;I&&(o.current.srcObject=I)},[h,w,g]);const z=!d&&!!h;return t.jsxs("div",{className:`nice-conference-tile${p?" nice-conference-tile--speaking":""}${n?" nice-conference-tile--pinned":""}`,style:{position:"relative",background:"var(--nice-bg-secondary, #1f2937)",borderRadius:10,overflow:"hidden",border:p?"2px solid var(--nice-success, #22c55e)":n?"2px solid var(--nice-info, #6366f1)":"2px solid transparent",display:"flex",alignItems:"center",justifyContent:"center",...a?{height:"100%",minHeight:0}:{aspectRatio:"16/9"}},children:[z?t.jsx("video",{ref:o,autoPlay:!0,muted:e,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"cover",transform:e&&!g?"scaleX(-1)":"none"}}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:8},children:[t.jsx("div",{style:{width:s==="large"?64:s==="small"?28:44,height:s==="large"?64:s==="small"?28:44,borderRadius:"50%",background:c.avatarUrl?`url(${c.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:s==="large"?28:s==="small"?12:18},children:!c.avatarUrl&&((u=c.name[0])==null?void 0:u.toUpperCase())}),s!=="small"&&t.jsx("span",{style:{color:"var(--nice-text-primary, #fff)",fontSize:12},children:c.displayName??c.name})]}),t.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, var(--nice-overlay-60, rgba(0, 0, 0, 0.6)))",padding:"6px 8px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("span",{style:{color:"var(--nice-text-on-primary, #fff)",fontSize:11,fontWeight:500},children:[c.displayName??c.name,e&&" (You)"]}),t.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[m&&t.jsx(b.NiceIcon,{name:"cursor",size:13}),f&&t.jsx(b.NiceIcon,{name:"mic",size:12}),g&&t.jsx(b.NiceIcon,{name:"monitor",size:12}),s!=="small"&&t.jsx("div",{style:{width:6,height:6,borderRadius:"50%",background:p?"var(--nice-success, #22c55e)":"transparent",border:"1px solid var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))"}})]})]}),s!=="small"&&t.jsx("button",{onClick:r,style:{position:"absolute",top:6,right:6,background:"var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",border:"none",borderRadius:4,padding:"2px 5px",color:n?"var(--nice-info, #6366f1)":"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))",cursor:"pointer",fontSize:12},title:n?"Unpin":"Pin","aria-label":n?"Unpin":"Pin",children:t.jsx(b.NiceIcon,{name:"map-pin",size:12})}),i.connectionQuality!=="none"&&s!=="small"&&t.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(I=>t.jsx("div",{style:{flex:1,background:i.connectionQuality==="excellent"||i.connectionQuality==="good"&&I<=2||i.connectionQuality==="fair"&&I<=1?"var(--nice-success, #22c55e)":"var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))",height:`${I*30}%`,borderRadius:1}},I))})]})}function tt({session:i,currentUser:e,localStream:n,enableScreenSharing:r=!0,enableRecording:s=!1,enableTranscription:a=!1,enableRaiseHand:o=!0,maxGridCols:c=4,onEndCall:f,onMuteAudio:d,onMuteVideo:g,onStartScreenShare:p,onStopScreenShare:m,onRaiseHand:h,className:w,style:z,id:u,"data-testid":I}){const[A,N]=l.useState(!1),[H,E]=l.useState(!1),[B,K]=l.useState(!1),[J,$]=l.useState(!1),[C,j]=l.useState(i.pinnedParticipantId??null),[O,U]=l.useState(i.layout==="sidebar"?"grid":i.layout??"grid"),[P,T]=l.useState(0),[F,_]=l.useState(!1);l.useEffect(()=>{U(i.layout==="spotlight"?"spotlight":"grid")},[i.layout]),l.useEffect(()=>{if(i.status!=="active")return;const L=setInterval(()=>T(Z=>Z+1),1e3);return()=>clearInterval(L)},[i.status]);const Y=L=>{const Z=Math.floor(L/3600),se=Math.floor(L%3600/60),ae=L%60;return Z>0?`${Z}:${String(se).padStart(2,"0")}:${String(ae).padStart(2,"0")}`:`${String(se).padStart(2,"0")}:${String(ae).padStart(2,"0")}`},S=()=>{const L=!A;N(L),d==null||d(L)},x=()=>{const L=!H;E(L),g==null||g(L)},G=async()=>{B?(K(!1),m==null||m()):(K(!0),await(p==null?void 0:p()))},X=()=>{const L=!J;$(L),h==null||h(L)},Q=[{user:e,isMuted:A,isCameraOff:H,isScreenSharing:B,isSpeaking:!1,isHandRaised:J,stream:n,connectionQuality:"excellent"},...i.participants.filter(L=>L.user.id!==e.id)],q=C?Q.find(L=>L.user.id===C):null,ne=q??(O==="spotlight"?Q.find(L=>L.isSpeaking)??Q[1]??Q[0]:null),ce=Q.filter(L=>L.user.id!==(ne==null?void 0:ne.user.id)),le=Q.length,ye=Math.min(c,le<=1?1:le<=2||le<=4?2:le<=9?3:4);return t.jsxs("div",{id:u,"data-testid":I,className:`nice-video-conference${w?` ${w}`:""}`,style:{position:"relative",width:"100%",height:"100%",background:"var(--nice-bg-primary, #111827)",display:"flex",flexDirection:"column",overflow:"hidden",...z},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 16px",flexShrink:0,color:"var(--nice-text-primary, #fff)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[t.jsxs("span",{style:{fontSize:15,fontWeight:600},children:[i.id.slice(0,8),"…"]}),t.jsx("span",{style:{fontSize:12,color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"},children:Y(P)}),i.isRecording&&t.jsxs("span",{style:{fontSize:11,color:"var(--nice-danger, #ef4444)",display:"flex",alignItems:"center",gap:4},children:[t.jsx(b.NiceIcon,{name:"circle",size:11})," Recording"]})]}),t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[t.jsx("button",{onClick:()=>U(O==="grid"?"spotlight":"grid"),style:{display:"flex",alignItems:"center",gap:4,background:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",border:"none",borderRadius:6,padding:"4px 10px",color:"var(--nice-text-on-primary, #fff)",cursor:"pointer",fontSize:12},children:O==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(b.NiceIcon,{name:"grid",size:14})," Grid"]}):t.jsxs(t.Fragment,{children:[t.jsx(b.NiceIcon,{name:"square",size:14})," Spotlight"]})}),t.jsxs("button",{onClick:()=>_(L=>!L),style:{display:"flex",alignItems:"center",gap:4,background:F?"var(--nice-info, #6366f1)":"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",border:"none",borderRadius:6,padding:"4px 10px",color:"var(--nice-text-on-primary, #fff)",cursor:"pointer",fontSize:12},children:[t.jsx(b.NiceIcon,{name:"users",size:14})," ",Q.length]})]})]}),t.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden",gap:4,padding:"0 8px 8px"},children:[t.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:4,overflow:"hidden"},children:ne?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{flex:1,minHeight:0},children:t.jsx(Ue,{participant:ne,isLocal:ne.user.id===e.id,isPinned:q!=null,onPin:()=>j(q?null:ne.user.id),size:"large",fill:!0})}),t.jsx("div",{style:{display:"flex",gap:4,height:90,flexShrink:0,overflowX:"auto"},children:ce.map(L=>t.jsx("div",{style:{width:140,flexShrink:0},children:t.jsx(Ue,{participant:L,isLocal:L.user.id===e.id,isPinned:!1,onPin:()=>j(L.user.id),size:"small"})},L.user.id))})]}):t.jsx("div",{style:{flex:1,display:"grid",gridTemplateColumns:`repeat(${ye}, 1fr)`,gridAutoRows:"minmax(0, 1fr)",gap:6,overflow:"hidden"},children:Q.map(L=>t.jsx(Ue,{participant:L,isLocal:L.user.id===e.id,isPinned:L.user.id===C,onPin:()=>j(Z=>Z===L.user.id?null:L.user.id),size:le<=4?"large":"medium",fill:!0},L.user.id))})}),F&&t.jsxs("div",{style:{width:220,flexShrink:0,background:"var(--nice-overlay-light-5, rgba(255, 255, 255, 0.05))",borderRadius:10,display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"10px 12px",fontWeight:600,fontSize:13,color:"var(--nice-text-primary, #fff)",borderBottom:"1px solid var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))"},children:["Participants (",Q.length,")"]}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:8},children:Q.map(L=>{var Z;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px"},children:[t.jsx("div",{style:{width:28,height:28,borderRadius:"50%",background:L.user.avatarUrl?`url(${L.user.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontSize:11,fontWeight:700},children:!L.user.avatarUrl&&((Z=L.user.name[0])==null?void 0:Z.toUpperCase())}),t.jsx("div",{style:{flex:1,minWidth:0},children:t.jsxs("div",{style:{color:"var(--nice-text-primary, #fff)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[L.user.displayName??L.user.name,L.user.id===e.id&&" (You)"]})}),t.jsxs("div",{style:{display:"flex",gap:3,alignItems:"center"},children:[L.isHandRaised&&t.jsx(b.NiceIcon,{name:"cursor",size:11}),L.isMuted&&t.jsx(b.NiceIcon,{name:"mic",size:11}),t.jsx(ue,{status:L.user.presence.status,size:"xs"})]})]},L.user.id)})})]})]}),t.jsxs("div",{className:"nice-conference-controls",style:{display:"flex",justifyContent:"center",gap:10,padding:"10px 16px",flexShrink:0,background:"var(--nice-overlay-30, rgba(0, 0, 0, 0.3))"},children:[t.jsx(xe,{icon:"mic",label:A?"Unmute":"Mute",onClick:S,danger:A}),t.jsx(xe,{icon:H?"camera":"video",label:H?"Start video":"Stop video",onClick:x,danger:H}),r&&t.jsx(xe,{icon:"monitor",label:B?"Stop share":"Share",onClick:()=>{G()},active:B}),o&&t.jsx(xe,{icon:"cursor",label:"Raise hand",onClick:X,active:J}),s&&t.jsx(xe,{icon:"circle",label:i.isRecording?"Stop rec":"Record",onClick:()=>{},active:i.isRecording,danger:i.isRecording}),a&&t.jsx(xe,{icon:"type",label:i.isTranscribing?"Stop captions":"Captions",onClick:()=>{},active:i.isTranscribing}),t.jsx(xe,{icon:"phone",label:"Leave",onClick:()=>f==null?void 0:f(i.id),end:!0})]})]})}function xe({icon:i,label:e,onClick:n,active:r,danger:s,end:a}){return t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[t.jsx("button",{title:e,onClick:n,style:{width:46,height:46,borderRadius:"50%",border:"none",background:a?"var(--nice-danger, #ef4444)":s?"var(--nice-danger-dark, #450a0a)":r?"var(--nice-info, #6366f1)":"var(--nice-overlay-light-12, rgba(255, 255, 255, 0.12))",color:"var(--nice-text-on-primary, #fff)",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.15s"},children:t.jsx(b.NiceIcon,{name:i,size:18})}),t.jsx("span",{style:{fontSize:9,color:"var(--nice-overlay-light-50, rgba(255, 255, 255, 0.5))",textAlign:"center",maxWidth:52},children:e})]})}function qe(i){const e={days:864e5,weeks:6048e5,months:2592e6,years:31536e6,forever:Number.MAX_SAFE_INTEGER};return i.unit==="forever"?e.forever:e[i.unit]*i.value}function ze(i,e=new Date){if(i.unit!=="forever")return new Date(e.getTime()+qe(i))}class dt{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,n)=>{const r=indexedDB.open(this.dbName,1);r.onupgradeneeded=s=>{const a=s.target.result;a.objectStoreNames.contains(this.storeName)||a.createObjectStore(this.storeName,{keyPath:"key"})},r.onsuccess=s=>{this.db=s.target.result,e(this.db)},r.onerror=()=>n(r.error)})}async save(e,n,r){const s=await this.openDb();return new Promise((a,o)=>{const d=s.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:e,data:n,expiresAt:r==null?void 0:r.toISOString()});d.onsuccess=()=>a(),d.onerror=()=>o(d.error)})}async load(e){const n=await this.openDb();return new Promise((r,s)=>{const c=n.transaction(this.storeName,"readonly").objectStore(this.storeName).get(e);c.onsuccess=()=>{const f=c.result;if(!f){r(void 0);return}if(f.expiresAt&&new Date(f.expiresAt)<new Date){this.delete(e),r(void 0);return}r(f.data)},c.onerror=()=>s(c.error)})}async delete(e){const n=await this.openDb();return new Promise((r,s)=>{const c=n.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(e);c.onsuccess=()=>r(),c.onerror=()=>s(c.error)})}async list(e){const n=await this.openDb();return new Promise((r,s)=>{const c=n.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();c.onsuccess=()=>r((c.result??[]).filter(f=>f.startsWith(e))),c.onerror=()=>s(c.error)})}async clear(e){if(!e){const r=await this.openDb();return new Promise((s,a)=>{const f=r.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();f.onsuccess=()=>s(),f.onerror=()=>a(f.error)})}const n=await this.list(e);await Promise.all(n.map(r=>this.delete(r)))}}class Qt{constructor(e="nice_comm__"){this.prefix=e}async save(e,n,r){const s={data:n,expiresAt:r==null?void 0:r.toISOString()};localStorage.setItem(this.prefix+e,JSON.stringify(s))}async load(e){const n=localStorage.getItem(this.prefix+e);if(n)try{const r=JSON.parse(n);if(r.expiresAt&&new Date(r.expiresAt)<new Date){await this.delete(e);return}return r.data}catch{return}}async delete(e){localStorage.removeItem(this.prefix+e)}async list(e){const n=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&s.startsWith(this.prefix+e)&&n.push(s.slice(this.prefix.length))}return n}async clear(e){(await this.list(e??"")).forEach(r=>localStorage.removeItem(this.prefix+r))}}class It{constructor(e,n){this.config=e,this.encryption=n,this.adapter=this.buildAdapter()}buildAdapter(){switch(this.config.provider){case"localstorage":return new Qt;case"custom":return this.config.customAdapter??new dt;default:return new dt}}getRuleFor(e){return this.config.retentionRules.find(n=>n.dataType===e)}async encode(e){var r;const n=JSON.stringify(e);return(r=this.encryption)!=null&&r.isEnabled()?this.encryption.encrypt(n,"messages"):n}async decode(e){var n;if(typeof e!="string")return e;if(!((n=this.encryption)!=null&&n.isEnabled()))try{return JSON.parse(e)}catch{return e}try{const r=await this.encryption.decrypt(e,"messages");return JSON.parse(r)}catch{return e}}async saveMessages(e,n){const r=this.getRuleFor("messages"),s=r?ze(r.activePeriod):void 0,a=await this.encode(n);await this.adapter.save(`msg:${e}`,a,s)}async loadMessages(e){const n=await this.adapter.load(`msg:${e}`);if(!n)return[];const r=await this.decode(n);return Array.isArray(r)?r:[]}async appendMessage(e,n){const r=await this.loadMessages(e);await this.saveMessages(e,[...r,n])}async saveWhiteboardSnapshot(e,n){const r=this.getRuleFor("whiteboard-snapshots"),s=r?ze(r.activePeriod):void 0,a=await this.encode(n);await this.adapter.save(`wb:${e}`,a,s)}async loadWhiteboardSnapshot(e){const n=await this.adapter.load(`wb:${e}`);return n?await this.decode(n):null}async saveRecordingMeta(e){const n=this.getRuleFor("recordings"),r=n?ze(n.activePeriod):void 0,s=await this.encode(e);await this.adapter.save(`rec:${e.id}`,s,r)}async loadRecordingMeta(e){const n=await this.adapter.load(`rec:${e}`);return n?await this.decode(n):null}async listRecordings(){const e=await this.adapter.list("rec:");return(await Promise.all(e.map(r=>this.loadRecordingMeta(r.slice(4))))).filter(Boolean)}async deleteRecording(e){await this.adapter.delete(`rec:${e}`)}async saveDocument(e,n){const r=this.getRuleFor("documents"),s=r?ze(r.activePeriod):void 0,a=await this.encode(n);await this.adapter.save(`doc:${e}`,a,s)}async loadDocument(e){const n=await this.adapter.load(`doc:${e}`);return n?this.decode(n):null}async enforceRetention(){let e=0,n=0;const r=new Date,s=[{prefix:"msg:",type:"messages"},{prefix:"wb:",type:"whiteboard-snapshots"},{prefix:"rec:",type:"recordings"},{prefix:"doc:",type:"documents"}];for(const{prefix:a,type:o}of s){const c=this.getRuleFor(o);if(!c)continue;const f=await this.adapter.list(a);for(const d of f){const g=await this.adapter.load(d);if(g){if(qe(c.activePeriod),c.archivePeriod){const p=`archive:${d}`,m=ze(c.archivePeriod,r);await this.adapter.save(p,g,m),e++}if(c.deleteAfterArchive&&c.archivePeriod){const p=qe(c.archivePeriod);new Date(r.getTime()+p)<r&&(await this.adapter.delete(`archive:${d}`),n++)}}}}return{archived:e,deleted:n}}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 nt=[{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 zt(i,e,n){return Me.has(i)||Me.set(i,new It(e,n)),Me.get(i)}function Zt(i){Me.delete(i)}const pt=["var(--nice-color-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-accent, #3f51b5)","var(--nice-primary, #2196f3)","var(--nice-info, #00bcd4)","var(--nice-success, #4caf50)","var(--nice-warning, #ff9800)","var(--nice-danger, #ff5722)","var(--nice-warning-dark, #795548)","var(--nice-text-secondary, #607d8b)"];function en(i){let e=0;for(let n=0;n<i.length;n++)e=e*31+i.charCodeAt(n)>>>0;return pt[e%pt.length]}function ut(i,e,n){const r={...i},s=[...e];switch(n.type){case"object:add":case"object:update":{const a=n.payload;if(r[a.id]=a,s.length>0&&!s[0].objectIds.includes(a.id)){const o=a.layerId?s.find(c=>c.id===a.layerId)??s[0]:s[0];o.objectIds=[...o.objectIds,a.id]}break}case"object:delete":{const{id:a}=n.payload;delete r[a],s.forEach(o=>{o.objectIds=o.objectIds.filter(c=>c!==a)});break}case"object:move":{const{id:a,x:o,y:c}=n.payload;r[a]&&(r[a]={...r[a],x:o,y:c,updatedAt:n.timestamp});break}case"layer:add":{const a=n.payload;s.find(o=>o.id===a.id)||s.push(a);break}case"layer:update":{const a=n.payload,o=s.findIndex(c=>c.id===a.id);o!==-1&&(s[o]={...s[o],...a});break}case"layer:delete":{const{id:a}=n.payload,o=s.findIndex(c=>c.id===a);o!==-1&&s.splice(o,1);break}}return{objects:r,layers:s}}function tn(i,e){switch(e.type){case"LOAD_SESSION":return{...i,session:e.session,undoStack:[],redoStack:[],isDirty:!1};case"SET_TOOL":return{...i,activeTool:e.tool};case"APPLY_OP":{const{op:n,local:r}=e,{objects:s,layers:a}=ut(i.session.objects,i.session.layers,n),o={...i.session,objects:s,layers:a,updatedAt:n.timestamp},f=r&&["object:add","object:update","object:delete","object:move","layer:add","layer:update","layer:delete"].includes(n.type)?[...i.undoStack,[n]]:i.undoStack;return{...i,session:o,undoStack:f,redoStack:r?[]:i.redoStack,isDirty:!0}}case"UNDO":{if(i.undoStack.length===0)return i;const n=i.undoStack[i.undoStack.length-1],r=n.filter(o=>o.type==="object:add").map(o=>o.payload.id),s={...i.session.objects};r.forEach(o=>delete s[o]);const a=i.session.layers.map(o=>({...o,objectIds:o.objectIds.filter(c=>!r.includes(c))}));return{...i,session:{...i.session,objects:s,layers:a},undoStack:i.undoStack.slice(0,-1),redoStack:[n,...i.redoStack],isDirty:!0}}case"REDO":{if(i.redoStack.length===0)return i;const n=i.redoStack[0];let{objects:r,layers:s}={objects:i.session.objects,layers:i.session.layers};for(const a of n)({objects:r,layers:s}=ut(r,s,a));return{...i,session:{...i.session,objects:r,layers:s},undoStack:[...i.undoStack,n],redoStack:i.redoStack.slice(1),isDirty:!0}}case"SET_SELECTION":return{...i,selectedObjectIds:e.ids};case"SET_DRAWING":return{...i,isDrawing:e.value};case"SET_PANNING":return{...i,isPanning:e.value};case"UPDATE_CURSOR":{const{userId:n,x:r,y:s}=e,a=i.session.collaborators[n];return a?{...i,session:{...i.session,collaborators:{...i.session.collaborators,[n]:{...a,cursorX:r,cursorY:s,lastSeenAt:new Date}}}}:i}case"REMOVE_COLLABORATOR":{const n={...i.session.collaborators};return delete n[e.userId],{...i,session:{...i.session,collaborators:n}}}case"SET_VIEWPORT":return{...i,session:{...i.session,viewport:e.viewport}};case"MARK_SAVED":return{...i,isDirty:!1,lastSavedAt:new Date};default:return i}}function Tt(i){const{session:e,currentUser:n,onOperation:r,remoteOperations:s=[],readonly:a=!1,storageConfig:o,autoSaveMs:c=3e4}=i,[f,d]=l.useReducer(tn,{session:e,activeTool:a?"select":"pen",selectedObjectIds:[],undoStack:[],redoStack:[],isDrawing:!1,isPanning:!1,isDirty:!1}),g=l.useRef(0),p=l.useRef(null),m=l.useRef(null);l.useEffect(()=>{o&&(m.current=zt(`wb_${e.id}`,o),m.current.loadWhiteboardSnapshot(e.id).then(T=>{T&&d({type:"LOAD_SESSION",session:T})}))},[e.id,o]),l.useEffect(()=>{if(!c||!m.current||!f.isDirty)return;const T=setTimeout(()=>{var F;(F=m.current)==null||F.saveWhiteboardSnapshot(f.session.id,f.session).then(()=>{d({type:"MARK_SAVED"})})},c);return()=>clearTimeout(T)},[f.isDirty,f.session,c]);const h=l.useRef(new Set);l.useEffect(()=>{for(const T of s)if(!h.current.has(T.id)&&T.userId!==n.id)if(h.current.add(T.id),T.type==="cursor:move"){const{x:F,y:_}=T.payload;d({type:"UPDATE_CURSOR",userId:T.userId,x:F,y:_})}else T.type==="viewport:sync"||d({type:"APPLY_OP",op:T,local:!1})},[s,n.id]);function w(T,F){return{id:`${n.id}_${++g.current}_${Date.now()}`,sessionId:f.session.id,type:T,userId:n.id,timestamp:new Date,payload:F}}const z=l.useCallback(T=>{a||d({type:"SET_TOOL",tool:T})},[a]),u=l.useCallback(T=>{if(a)return;const F=w("object:add",T);d({type:"APPLY_OP",op:F,local:!0}),r==null||r(F)},[a,r,f.session.id]),I=l.useCallback(T=>{if(a)return;const F=w("object:update",T);d({type:"APPLY_OP",op:F,local:!0}),r==null||r(F)},[a,r,f.session.id]),A=l.useCallback(T=>{if(!a){for(const F of T){const _=w("object:delete",{id:F});d({type:"APPLY_OP",op:_,local:!0}),r==null||r(_)}d({type:"SET_SELECTION",ids:[]})}},[a,r,f.session.id]),N=l.useCallback(T=>{if(!a)for(const{id:F,x:_,y:Y}of T){const S=w("object:move",{id:F,x:_,y:Y});d({type:"APPLY_OP",op:S,local:!0}),r==null||r(S)}},[a,r,f.session.id]),H=l.useCallback(T=>{d({type:"SET_SELECTION",ids:T})},[]),E=l.useCallback(()=>{a||d({type:"UNDO"})},[a]),B=l.useCallback(()=>{a||d({type:"REDO"})},[a]),K=l.useCallback(T=>{d({type:"SET_VIEWPORT",viewport:T});const F=w("viewport:sync",T);r==null||r(F)},[r,f.session.id]),J=l.useCallback((T,F)=>{if(p.current)return;p.current=setTimeout(()=>{p.current=null},50);const _=w("cursor:move",{x:T,y:F});r==null||r(_)},[r,f.session.id]),$=l.useCallback(T=>{if(a)return;const F={id:`layer_${Date.now()}`,name:T,visible:!0,locked:!1,objectIds:[]},_=w("layer:add",F);d({type:"APPLY_OP",op:_,local:!0}),r==null||r(_)},[a,r,f.session.id]),C=l.useCallback(T=>{if(a)return;const F=w("layer:update",T);d({type:"APPLY_OP",op:F,local:!0}),r==null||r(F)},[a,r,f.session.id]),j=l.useCallback(T=>{if(a)return;const F=w("layer:delete",{id:T});d({type:"APPLY_OP",op:F,local:!0}),r==null||r(F)},[a,r,f.session.id]),O=l.useCallback(T=>{const F={user:T,cursorX:0,cursorY:0,color:en(T.id),selectedObjectIds:[],activeTool:"pen",lastSeenAt:new Date};d({type:"APPLY_OP",op:w("cursor:move",F),local:!1})},[]),U=l.useCallback(T=>{d({type:"REMOVE_COLLABORATOR",userId:T})},[]),P=l.useCallback(async()=>{m.current&&(await m.current.saveWhiteboardSnapshot(f.session.id,f.session),d({type:"MARK_SAVED"}))},[f.session]);return{session:f.session,activeTool:f.activeTool,selectedObjectIds:f.selectedObjectIds,isDrawing:f.isDrawing,isPanning:f.isPanning,isDirty:f.isDirty,lastSavedAt:f.lastSavedAt,canUndo:f.undoStack.length>0,canRedo:f.redoStack.length>0,collaborators:Object.values(f.session.collaborators),objects:Object.values(f.session.objects),layers:f.session.layers,viewport:f.session.viewport,setTool:z,addObject:u,updateObject:I,deleteObjects:A,moveObjects:N,setSelection:H,undo:E,redo:B,setViewport:K,broadcastCursor:J,addLayer:$,updateLayer:C,deleteLayer:j,registerCollaborator:O,removeCollaborator:U,saveNow:P}}const nn=[{id:"select",label:"Select",icon:"cursor",group:"select"},{id:"laser",label:"Laser",icon:"circle",group:"select"},{id:"pen",label:"Pen",icon:"pen",group:"draw"},{id:"highlighter",label:"Highlight",icon:"brush",group:"draw"},{id:"eraser",label:"Eraser",icon:"eraser",group:"draw"},{id:"line",label:"Line",icon:"line",group:"shape"},{id:"arrow",label:"Arrow",icon:"arrow-right",group:"shape"},{id:"rect",label:"Rectangle",icon:"square",group:"shape"},{id:"ellipse",label:"Ellipse",icon:"circle",group:"shape"},{id:"triangle",label:"Triangle",icon:"triangle",group:"shape"},{id:"frame",label:"Frame",icon:"crop",group:"shape"},{id:"text",label:"Text",icon:"type",group:"insert"},{id:"sticky",label:"Sticky",icon:"clipboard",group:"insert"},{id:"image",label:"Image",icon:"image",group:"insert"}];function Ee(){return`${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function He(i,e,n){return{sx:i*n.scale+n.x,sy:e*n.scale+n.y}}function rn(i,e,n){return{wx:(i-n.x)/n.scale,wy:(e-n.y)/n.scale}}function sn(i,e){return Math.hypot(e.x-i.x,e.y-i.y)}function an(i,e){if(!(e.points.length<2)){i.save(),i.globalAlpha=e.opacity,i.strokeStyle=b.resolveCssColor(e.color,i.canvas),i.lineWidth=e.strokeWidth,i.lineCap="round",i.lineJoin="round",e.tool==="highlighter"&&(i.globalCompositeOperation="multiply"),i.beginPath(),i.moveTo(e.points[0].x,e.points[0].y);for(let n=1;n<e.points.length;n++){const r={x:(e.points[n-1].x+e.points[n].x)/2,y:(e.points[n-1].y+e.points[n].y)/2};i.quadraticCurveTo(e.points[n-1].x,e.points[n-1].y,r.x,r.y)}i.stroke(),i.restore()}}function on(i,e){switch(i.save(),i.globalAlpha=e.opacity,i.strokeStyle=b.resolveCssColor(e.strokeColor,i.canvas),i.lineWidth=e.strokeWidth,e.fillColor&&(i.fillStyle=b.resolveCssColor(e.fillColor,i.canvas)),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(e.rotation*Math.PI/180),i.beginPath(),e.shape){case"rect":i.rect(-e.width/2,-e.height/2,e.width,e.height);break;case"ellipse":i.ellipse(0,0,e.width/2,e.height/2,0,0,Math.PI*2);break;case"triangle":{const n=e.width/2,r=e.height/2;i.moveTo(0,-r),i.lineTo(n,r),i.lineTo(-n,r),i.closePath();break}case"diamond":{const n=e.width/2,r=e.height/2;i.moveTo(0,-r),i.lineTo(n,0),i.lineTo(0,r),i.lineTo(-n,0),i.closePath();break}}e.fillColor&&i.fill(),i.stroke(),i.restore()}function ln(i,e){if(i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(e.rotation*Math.PI/180),i.font=`${e.fontStyle} ${e.fontWeight} ${e.fontSize}px ${e.fontFamily}`,i.fillStyle=b.resolveCssColor(e.color,i.canvas),i.textAlign=e.textAlign,i.textBaseline="middle",e.backgroundColor){const n=i.measureText(e.text),r=4;i.fillStyle=b.resolveCssColor(e.backgroundColor,i.canvas),i.fillRect(-n.width/2-r,-e.fontSize/2-r,n.width+r*2,e.fontSize+r*2),i.fillStyle=b.resolveCssColor(e.color,i.canvas)}i.fillText(e.text,0,0),i.restore()}function cn(i,e){i.save(),i.translate(e.x,e.y),i.rotate(e.rotation*Math.PI/180),i.shadowColor=b.resolveCssColor("var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",i.canvas),i.shadowBlur=8,i.shadowOffsetY=3,i.fillStyle=b.resolveCssColor(e.backgroundColor,i.canvas),i.fillRect(0,0,e.width,e.height),i.shadowColor="transparent",i.fillStyle=b.resolveCssColor(e.textColor,i.canvas),i.font=`${e.fontSize}px sans-serif`,i.textAlign="left",i.textBaseline="top";const n=10,r=e.width-n*2,s=e.fontSize*1.4,a=e.text.split(" ");let o="",c=n;for(const f of a){const d=o?`${o} ${f}`:f;i.measureText(d).width>r&&o?(i.fillText(o,n,c),o=f,c+=s):o=d}o&&i.fillText(o,n,c),i.restore()}function dn(i,e){if(!(e.points.length<2)){if(i.save(),i.strokeStyle=b.resolveCssColor(e.strokeColor,i.canvas),i.lineWidth=e.strokeWidth,i.lineCap="round",i.beginPath(),i.moveTo(e.points[0].x,e.points[0].y),e.curved&&e.points.length>2){for(let n=1;n<e.points.length-1;n++){const r=e.points[n],s={x:(r.x+e.points[n+1].x)/2,y:(r.y+e.points[n+1].y)/2};i.quadraticCurveTo(r.x,r.y,s.x,s.y)}i.lineTo(e.points[e.points.length-1].x,e.points[e.points.length-1].y)}else for(let n=1;n<e.points.length;n++)i.lineTo(e.points[n].x,e.points[n].y);if(i.stroke(),e.arrowEnd==="arrow"){const n=e.points[e.points.length-1],r=e.points[e.points.length-2],s=Math.atan2(n.y-r.y,n.x-r.x),a=12;i.beginPath(),i.moveTo(n.x,n.y),i.lineTo(n.x-a*Math.cos(s-Math.PI/6),n.y-a*Math.sin(s-Math.PI/6)),i.moveTo(n.x,n.y),i.lineTo(n.x-a*Math.cos(s+Math.PI/6),n.y-a*Math.sin(s+Math.PI/6)),i.stroke()}i.restore()}}function pn(i,e){i.save(),i.strokeStyle=b.resolveCssColor(e.borderColor??"var(--nice-text-muted, #aaa)",i.canvas),i.lineWidth=2,i.setLineDash([8,4]),e.backgroundColor&&(i.fillStyle=b.resolveCssColor(e.backgroundColor,i.canvas),i.fillRect(e.x,e.y,e.width,e.height)),i.strokeRect(e.x,e.y,e.width,e.height),i.setLineDash([]),i.fillStyle=b.resolveCssColor("var(--nice-text-secondary, #555)",i.canvas),i.font="bold 13px sans-serif",i.fillText(e.name,e.x+8,e.y-6),i.restore()}function un(i,e){if(e.visible)switch(e.type){case"stroke":return an(i,e);case"shape":return on(i,e);case"text":return ln(i,e);case"sticky":return cn(i,e);case"connector":return dn(i,e);case"frame":return pn(i,e);case"image":{const n=e,r=new Image;r.src=n.dataUrl??n.url,i.save(),i.translate(n.x+n.width/2,n.y+n.height/2),i.rotate(n.rotation*Math.PI/180),i.drawImage(r,-n.width/2,-n.height/2,n.width,n.height),i.restore();break}}}function it(i){const{t:e}=b.useNiceTranslation();return i.session?t.jsx(fn,{...i,session:i.session}):t.jsx("div",{className:i.className,style:i.style,"data-testid":i["data-testid"],children:t.jsx(b.NiceEmpty,{title:e("whiteboard.noSession","No whiteboard session")})})}function fn({session:i,currentUser:e,onOperation:n,remoteOperations:r=[],readonly:s=!1,enableLayers:a=!0,enableExport:o=!0,enableLaserPointer:c=!0,enableVectorEditor:f=!1,enableDiagramEditor:d=!1,onExport:g,onSessionUpdate:p,storageConfig:m,className:h,style:w,"data-testid":z}){const u=Tt({session:i,currentUser:e,onOperation:n,remoteOperations:r,readonly:s,storageConfig:m,autoSaveMs:3e4}),I=l.useRef(null);l.useRef(null);const A=l.useRef(0),[N,H]=l.useState(!1),[E,B]=l.useState("#1a1a1a"),[K,J]=l.useState(3),[$,C]=l.useState(void 0),[j,O]=l.useState(18),[U,P]=l.useState("var(--nice-warning-bg, #fef08a)"),[T,F]=l.useState(null),[_,Y]=l.useState(null),S=l.useRef({active:!1,startX:0,startY:0,currentPoints:[],currentId:"",spaceDown:!1,panStart:null,laserPoints:[]}),x=l.useCallback((y,v,M,W)=>{if(!u.session.gridEnabled)return;const D=u.session.gridSize*v.scale,V=(v.x%D+D)%D,k=(v.y%D+D)%D;y.strokeStyle="rgba(180,180,200,0.35)",y.lineWidth=1,y.beginPath();for(let R=V;R<M;R+=D)y.moveTo(R,0),y.lineTo(R,W);for(let R=k;R<W;R+=D)y.moveTo(0,R),y.lineTo(M,R);y.stroke()},[u.session.gridEnabled,u.session.gridSize]),G=l.useCallback((y,v)=>{for(const M of u.collaborators){if(M.user.id===e.id)continue;const{sx:W,sy:D}=He(M.cursorX,M.cursorY,v);y.save(),y.fillStyle=M.color,y.beginPath(),y.moveTo(W,D),y.lineTo(W+14,D+5),y.lineTo(W+5,D+14),y.closePath(),y.fill(),y.fillStyle=M.color,y.font="bold 11px sans-serif",y.fillText(M.user.name,W+16,D+14),y.restore()}},[u.collaborators,e.id]),X=l.useCallback((y,v)=>{if(u.selectedObjectIds.length!==0)for(const M of u.selectedObjectIds){const W=u.session.objects[M];if(!W)continue;const{sx:D,sy:V}=He(W.x,W.y,v),k=W.width*v.scale,R=W.height*v.scale;y.strokeStyle=b.resolveCssColor("var(--nice-primary, #4f8df9)",y.canvas),y.lineWidth=1.5,y.setLineDash([4,2]),y.strokeRect(D-2,V-2,k+4,R+4),y.setLineDash([]);const te=[[D-2,V-2],[D+k+2,V-2],[D-2,V+R+2],[D+k+2,V+R+2]];y.fillStyle=b.resolveCssColor("var(--nice-bg, #fff)",y.canvas),y.strokeStyle=b.resolveCssColor("var(--nice-primary, #4f8df9)",y.canvas),y.lineWidth=1.5;for(const[ee,re]of te)y.fillRect(ee-4,re-4,8,8),y.strokeRect(ee-4,re-4,8,8)}},[u.selectedObjectIds,u.session.objects]),Q=l.useCallback(()=>{const y=I.current;if(!y)return;const v=y.getContext("2d");if(!v)return;const{width:M,height:W}=y,D=u.viewport;v.clearRect(0,0,M,W),v.fillStyle=b.resolveCssColor(u.session.backgroundColor,y),v.fillRect(0,0,M,W),x(v,D,M,W),v.save();const V=Object.values(u.session.objects).filter(k=>k.visible).sort((k,R)=>k.zIndex-R.zIndex);v.translate(D.x,D.y),v.scale(D.scale,D.scale);for(const k of V)un(v,k);if(S.current.active&&S.current.currentPoints.length>1){const k=S.current.currentPoints;v.strokeStyle=b.resolveCssColor(E,y),v.lineWidth=K,v.lineCap="round",v.lineJoin="round",v.beginPath(),v.moveTo(k[0].x,k[0].y);for(let R=1;R<k.length;R++)v.lineTo(k[R].x,k[R].y);v.stroke()}if(S.current.laserPoints.length>1&&u.activeTool==="laser"){const k=S.current.laserPoints;v.strokeStyle="#ff2c2c",v.lineWidth=3,v.globalAlpha=.7,v.beginPath(),v.moveTo(k[0].x,k[0].y);for(let R=1;R<k.length;R++)v.lineTo(k[R].x,k[R].y);v.stroke(),v.globalAlpha=1}v.restore(),X(v,D),G(v,D)},[u.session,u.viewport,u.activeTool,x,G,X,E,K]);l.useLayoutEffect(()=>{function y(){Q(),A.current=requestAnimationFrame(y)}return A.current=requestAnimationFrame(y),()=>cancelAnimationFrame(A.current)},[Q]),l.useEffect(()=>{const y=I.current;if(!y)return;const v=new ResizeObserver(()=>{y.width=y.offsetWidth,y.height=y.offsetHeight});return v.observe(y),y.width=y.offsetWidth,y.height=y.offsetHeight,()=>v.disconnect()},[]),l.useEffect(()=>{function y(v){if(v.target.tagName==="INPUT"||v.target.tagName==="TEXTAREA"||(v.code==="Space"&&(S.current.spaceDown=v.type==="keydown",v.preventDefault()),v.type!=="keydown"))return;(v.ctrlKey||v.metaKey)&&(v.key==="z"&&(v.preventDefault(),u.undo()),v.key==="y"&&(v.preventDefault(),u.redo()),v.key==="s"&&(v.preventDefault(),u.saveNow()),v.key==="a"&&(v.preventDefault(),u.setSelection(Object.keys(u.session.objects)))),(v.key==="Delete"||v.key==="Backspace")&&u.selectedObjectIds.length>0&&u.deleteObjects(u.selectedObjectIds);const M={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&&M[v.key]&&u.setTool(M[v.key])}return window.addEventListener("keydown",y),window.addEventListener("keyup",y),()=>{window.removeEventListener("keydown",y),window.removeEventListener("keyup",y)}},[u]);const q=l.useCallback(y=>{const v=I.current.getBoundingClientRect(),M=y.clientX-v.left,W=y.clientY-v.top,{wx:D,wy:V}=rn(M,W,u.viewport);return{x:D,y:V,pressure:y.pressure??.5}},[u.viewport]),ne=l.useCallback(y=>{if(s)return;y.target.setPointerCapture(y.pointerId);const v=q(y);if(y.button===1||S.current.spaceDown){S.current.panStart={x:y.clientX,y:y.clientY,vpX:u.viewport.x,vpY:u.viewport.y};return}const M=u.activeTool;if(S.current.active=!0,S.current.startX=v.x,S.current.startY=v.y,S.current.currentId=Ee(),M==="pen"||M==="highlighter")S.current.currentPoints=[v];else if(M==="laser")S.current.laserPoints=[v];else if(M==="select"){const W=Object.values(u.session.objects).filter(D=>D.visible&&D.x<=v.x&&D.y<=v.y&&D.x+D.width>=v.x&&D.y+D.height>=v.y).sort((D,V)=>V.zIndex-D.zIndex)[0];W?y.shiftKey?u.setSelection([...u.selectedObjectIds,W.id]):u.setSelection([W.id]):u.setSelection([])}},[s,q,u]),ce=l.useCallback(y=>{const v=q(y);if(u.broadcastCursor(v.x,v.y),S.current.panStart){const{x:W,y:D,vpX:V,vpY:k}=S.current.panStart;u.setViewport({...u.viewport,x:V+(y.clientX-W),y:k+(y.clientY-D)});return}if(!S.current.active)return;const M=u.activeTool;if(M==="pen"||M==="highlighter"){const W=S.current.currentPoints;(W.length===0||sn(W[W.length-1],v)>2)&&(S.current.currentPoints=[...W,v])}else if(M==="laser"){const W=S.current.laserPoints;S.current.laserPoints=[...W.slice(-40),v]}else if(M==="select"&&u.selectedObjectIds.length>0){const W=v.x-S.current.startX,D=v.y-S.current.startY;S.current.startX=v.x,S.current.startY=v.y,u.moveObjects(u.selectedObjectIds.map(V=>{const k=u.session.objects[V];return{id:V,x:k.x+W,y:k.y+D}}))}},[q,u]),le=l.useCallback(y=>{if(S.current.panStart){S.current.panStart=null;return}if(!S.current.active)return;const v=q(y),M=u.activeTool,W=S.current.startX,D=S.current.startY,V=S.current.currentId,k=new Date;switch(S.current.active=!1,M){case"pen":case"highlighter":{const R=S.current.currentPoints;if(R.length<2)break;const te={id:V,type:"stroke",x:Math.min(...R.map(ee=>ee.x)),y:Math.min(...R.map(ee=>ee.y)),width:Math.max(...R.map(ee=>ee.x))-Math.min(...R.map(ee=>ee.x)),height:Math.max(...R.map(ee=>ee.y))-Math.min(...R.map(ee=>ee.y)),rotation:0,zIndex:Object.keys(u.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,points:R,color:E,strokeWidth:K,opacity:M==="highlighter"?.4:1,tool:M};u.addObject(te),S.current.currentPoints=[];break}case"rect":case"ellipse":case"triangle":{const R=Math.min(W,v.x),te=Math.min(D,v.y),ee=Math.abs(v.x-W),re=Math.abs(v.y-D);if(ee<5||re<5)break;const de={rect:"rect",ellipse:"ellipse",triangle:"triangle"},ge={id:V,type:"shape",x:R,y:te,width:ee,height:re,rotation:0,zIndex:Object.keys(u.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,shape:de[M],fillColor:$,strokeColor:E,strokeWidth:K,opacity:1};u.addObject(ge);break}case"arrow":case"line":{const R={id:V,type:"connector",x:Math.min(W,v.x),y:Math.min(D,v.y),width:Math.abs(v.x-W),height:Math.abs(v.y-D),rotation:0,zIndex:Object.keys(u.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,points:[{x:W,y:D},{x:v.x,y:v.y}],strokeColor:E,strokeWidth:K,arrowStart:"none",arrowEnd:M==="arrow"?"arrow":"none",curved:!1};u.addObject(R);break}case"text":{const R={id:V,type:"text",x:v.x,y:v.y,width:200,height:j+10,rotation:0,zIndex:Object.keys(u.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,text:"Click to edit",fontSize:j,fontFamily:"sans-serif",fontWeight:"normal",fontStyle:"normal",textAlign:"left",color:E};u.addObject(R),F(V);break}case"sticky":{const R={id:V,type:"sticky",x:v.x,y:v.y,width:180,height:150,rotation:0,zIndex:Object.keys(u.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:k,text:"Note...",backgroundColor:U,textColor:"var(--nice-text, #333)",fontSize:14,authorId:e.id};u.addObject(R),F(V);break}case"frame":{const R=Math.min(W,v.x),te=Math.min(D,v.y),ee=Math.abs(v.x-W),re=Math.abs(v.y-D);if(ee<20||re<20)break;const de={id:V,type:"frame",x:R,y:te,width:ee,height:re,rotation:0,zIndex:0,locked:!1,visible:!0,createdBy:e.id,createdAt:k,name:`Frame ${Object.keys(u.session.objects).length+1}`,childIds:[],borderColor:"#8888"};u.addObject(de);break}case"image":{const R=document.createElement("input");R.type="file",R.accept="image/*",R.onchange=()=>{var re;const te=(re=R.files)==null?void 0:re[0];if(!te)return;const ee=new FileReader;ee.onload=de=>{var Pe;const ge=(Pe=de.target)==null?void 0:Pe.result,fe=new Image;fe.onload=()=>{const Ae=400/fe.width,We={id:Ee(),type:"image",x:v.x,y:v.y,width:fe.width*Ae,height:fe.height*Ae,rotation:0,zIndex:Object.keys(u.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:ge,dataUrl:ge,originalWidth:fe.width,originalHeight:fe.height};u.addObject(We)},fe.src=ge},ee.readAsDataURL(te)},R.click();break}}},[q,u,e.id,E,K,$,j,U]),ye=l.useCallback(y=>{if(y.preventDefault(),!y.ctrlKey&&!y.metaKey){u.setViewport({...u.viewport,x:u.viewport.x-y.deltaX,y:u.viewport.y-y.deltaY});return}const v=I.current.getBoundingClientRect(),M=y.clientX-v.left,W=y.clientY-v.top,V=-y.deltaY>0?1.1:.9,k=Math.min(8,Math.max(.1,u.viewport.scale*V));u.setViewport({scale:k,x:M-(M-u.viewport.x)*(k/u.viewport.scale),y:W-(W-u.viewport.y)*(k/u.viewport.scale)})},[u]),L=l.useCallback(y=>{if(y==="json"){const D=JSON.stringify(u.session,null,2);g==null||g("json",D);const V=document.createElement("a");V.href=URL.createObjectURL(new Blob([D],{type:"application/json"})),V.download=`${u.session.title}.json`,V.click();return}const v=I.current;if(!v)return;const M=v.toDataURL("image/png");g==null||g("png",M);const W=document.createElement("a");W.href=M,W.download=`${u.session.title}.png`,W.click()},[u.session,g]);l.useEffect(()=>{p==null||p(u.session)},[u.session,p]),l.useEffect(()=>{function y(v){if(v.clipboardData){for(const M of Array.from(v.clipboardData.items))if(M.type.startsWith("image/")){const W=M.getAsFile();if(!W)continue;const D=new FileReader;D.onload=V=>{var te;const k=(te=V.target)==null?void 0:te.result,R=new Image;R.onload=()=>{const re=400/R.width,de={id:Ee(),type:"image",x:100,y:100,width:R.width*re,height:R.height*re,rotation:0,zIndex:Object.keys(u.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:k,dataUrl:k,originalWidth:R.width,originalHeight:R.height};u.addObject(de)},R.src=k},D.readAsDataURL(W);break}}}return window.addEventListener("paste",y),()=>window.removeEventListener("paste",y)},[u,e.id]);const Z=T?u.session.objects[T]:null,se=l.useMemo(()=>Z?He(Z.x,Z.y,u.viewport):null,[Z,u.viewport]),ae=["var(--nice-warning-bg, #fef08a)","var(--nice-primary-bg, #bfdbfe)","#bbf7d0","var(--nice-danger-bg, #fecaca)","var(--nice-accent-tint-10, #e9d5ff)","var(--nice-warning-bg, #fed7aa)"],oe=l.useMemo(()=>{var v;const y={};for(const M of nn)(y[v=M.group]??(y[v]=[])).push(M);return Object.values(y)},[]);return t.jsxs("div",{className:h,"data-testid":z,style:{position:"relative",display:"flex",flexDirection:"column",width:"100%",height:"100%",overflow:"hidden",background:"var(--nice-bg-secondary, #f5f5f5)",fontFamily:"system-ui, sans-serif",...w},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",background:"var(--nice-bg, #fff)",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0,flexWrap:"wrap"},children:[oe.map((y,v)=>t.jsxs(l.Fragment,{children:[v>0&&t.jsx("div",{style:{width:1,height:24,background:"var(--nice-border, #e5e7eb)",margin:"0 2px"}}),y.map(M=>t.jsx("button",{onClick:()=>u.setTool(M.id),title:`${M.label}`,style:{padding:"4px 7px",border:`1.5px solid ${u.activeTool===M.id?"var(--nice-info, #6366f1)":"transparent"}`,borderRadius:6,background:u.activeTool===M.id?"var(--nice-primary-bg, #eef2ff)":"transparent",cursor:"pointer",fontSize:15,minWidth:30,color:u.activeTool===M.id?"var(--nice-accent, #4f46e5)":"var(--nice-text, #374151)",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:t.jsx(b.NiceIcon,{name:M.icon,size:15})},M.id))]},v)),t.jsx("div",{style:{width:1,height:24,background:"var(--nice-border, #e5e7eb)",margin:"0 4px"}}),t.jsxs("label",{title:"Stroke color",style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:"Color"}),t.jsx("input",{type:"color",value:E,onChange:y=>B(y.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}})]}),t.jsxs("label",{title:"Fill color",style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:"Fill"}),t.jsx("input",{type:"color",value:$??"#ffffff",onChange:y=>C(y.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}}),t.jsx("button",{onClick:()=>C(void 0),style:{fontSize:11,padding:"1px 5px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:4,cursor:"pointer",background:$?"var(--nice-bg, #fff)":"var(--nice-bg-secondary, #f3f4f6)"},children:"No fill"})]}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:4},children:[t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:"Width"}),t.jsx("input",{type:"range",min:1,max:24,step:1,value:K,onChange:y=>J(Number(y.target.value)),style:{width:70}}),t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",minWidth:20},children:K})]}),u.activeTool==="sticky"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:"Note:"}),ae.map(y=>t.jsx("button",{onClick:()=>P(y),style:{width:20,height:20,background:y,border:`2px solid ${U===y?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)"}`,borderRadius:4,cursor:"pointer"}},y))]}),t.jsx("div",{style:{flex:1}}),t.jsx("button",{onClick:u.undo,disabled:!u.canUndo,title:"Undo (Ctrl+Z)","aria-label":"Undo",style:pe(!u.canUndo),children:t.jsx(b.NiceIcon,{name:"reply",size:13})}),t.jsx("button",{onClick:u.redo,disabled:!u.canRedo,title:"Redo (Ctrl+Y)","aria-label":"Redo",style:pe(!u.canRedo),children:t.jsx(b.NiceIcon,{name:"forward",size:13})}),t.jsx("div",{style:{width:1,height:24,background:"var(--nice-border, #e5e7eb)"}}),t.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",minWidth:42,textAlign:"center"},children:[Math.round(u.viewport.scale*100),"%"]}),t.jsx("button",{onClick:()=>u.setViewport({x:0,y:0,scale:1}),style:pe(),title:"Reset zoom","aria-label":"Reset zoom",children:t.jsx(b.NiceIcon,{name:"target",size:13})}),a&&t.jsx("button",{onClick:()=>H(y=>!y),style:pe(!1,N),title:"Layers","aria-label":"Layers",children:t.jsx(b.NiceIcon,{name:"layers",size:13})}),t.jsx("button",{onClick:()=>{const y={id:Ee(),sessionId:u.session.id,type:"object:update",userId:e.id,timestamp:new Date,payload:{...u.session,gridEnabled:!u.session.gridEnabled}};n==null||n(y)},style:pe(!1,u.session.gridEnabled),title:"Toggle grid","aria-label":"Toggle grid",children:t.jsx(b.NiceIcon,{name:"hash",size:13})}),f&&t.jsx("button",{onClick:()=>Y(y=>y==="vector"?null:"vector"),style:pe(!1,_==="vector"),title:"Vector Editor panel","aria-label":"Vector Editor panel",children:t.jsx(b.NiceIcon,{name:"pen",size:13})}),d&&t.jsx("button",{onClick:()=>Y(y=>y==="diagram"?null:"diagram"),style:pe(!1,_==="diagram"),title:"Diagram Editor panel","aria-label":"Diagram Editor panel",children:t.jsx(b.NiceIcon,{name:"hexagon",size:13})}),t.jsx("button",{onClick:()=>void u.saveNow(),style:pe(),title:"Save (Ctrl+S)","aria-label":"Save",children:t.jsxs("span",{style:{display:"inline-flex",alignItems:"center"},children:[t.jsx(b.NiceIcon,{name:"save",size:13}),u.isDirty&&"*"]})}),o&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>L("png"),style:pe(),title:"Export PNG","aria-label":"Export PNG",children:t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:2},children:["PNG",t.jsx(b.NiceIcon,{name:"download",size:12})]})}),t.jsx("button",{onClick:()=>L("json"),style:pe(),title:"Export JSON","aria-label":"Export JSON",children:t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:2},children:["JSON",t.jsx(b.NiceIcon,{name:"download",size:12})]})})]})]}),t.jsxs("div",{style:{display:"flex",flex:1,overflow:"hidden",position:"relative"},children:[t.jsx("canvas",{ref:I,style:{flex:1,display:"block",cursor:gn(u.activeTool,S.current.spaceDown)},onPointerDown:ne,onPointerMove:ce,onPointerUp:le,onWheel:ye,onContextMenu:y=>y.preventDefault()}),a&&N&&t.jsx(hn,{layers:u.layers,objects:u.session.objects,onAdd:()=>u.addLayer(`Layer ${u.layers.length+1}`),onUpdate:y=>u.updateLayer(y),onDelete:y=>u.deleteLayer(y)}),_&&t.jsxs("div",{style:{position:"absolute",right:N?220:0,top:0,bottom:0,width:360,background:"var(--nice-bg, #fff)",borderLeft:"1px solid var(--nice-border, #e5e7eb)",padding:12,overflowY:"auto"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[t.jsx("strong",{style:{fontSize:13},children:_==="vector"?"Vector Editor":"Diagram Editor"}),t.jsx("button",{onClick:()=>Y(null),style:{border:"none",background:"none",cursor:"pointer",fontSize:16},"aria-label":"Close",children:t.jsx(b.NiceIcon,{name:"close",size:16})})]}),t.jsx("p",{style:{fontSize:12,color:"var(--nice-text-secondary, #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."}),t.jsx("div",{id:`wb-integration-${_}`,style:{width:"100%",height:400}})]})]}),u.collaborators.length>1&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",background:"var(--nice-bg, #fff)",borderTop:"1px solid var(--nice-bg-secondary, #f3f4f6)",fontSize:11,color:"var(--nice-text-secondary, #6b7280)",flexShrink:0},children:[t.jsx("span",{children:"Collaborators:"}),u.collaborators.map(y=>t.jsxs("span",{style:{display:"flex",alignItems:"center",gap:3},children:[t.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:y.color,display:"inline-block"}}),y.user.name]},y.user.id)),u.isDirty&&t.jsxs("span",{style:{marginLeft:"auto",color:"var(--nice-warning, #f59e0b)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(b.NiceIcon,{name:"circle",size:10})," unsaved"]}),u.lastSavedAt&&!u.isDirty&&t.jsxs("span",{style:{marginLeft:"auto",color:"var(--nice-success, #10b981)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(b.NiceIcon,{name:"check",size:10})," Saved ",u.lastSavedAt.toLocaleTimeString()]})]}),Z&&se&&t.jsx("textarea",{autoFocus:!0,defaultValue:Z.text,onBlur:y=>{const v={...Z,text:y.target.value,updatedAt:new Date,updatedBy:e.id};u.updateObject(v),F(null)},style:{position:"absolute",left:se.sx,top:se.sy,minWidth:Z.width*u.viewport.scale,minHeight:Z.height*u.viewport.scale,fontSize:(Z.fontSize??14)*u.viewport.scale,fontFamily:"sans-serif",background:Z.type==="sticky"?Z.backgroundColor:"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",border:"2px solid var(--nice-info, #6366f1)",borderRadius:4,padding:6,resize:"both",zIndex:1e3,color:Z.type==="sticky"?Z.textColor:Z.color}})]})}function hn({layers:i,objects:e,onAdd:n,onUpdate:r,onDelete:s}){return t.jsxs("div",{style:{width:200,borderLeft:"1px solid var(--nice-border, #e5e7eb)",background:"var(--nice-bg, #fff)",display:"flex",flexDirection:"column",padding:8,gap:4,overflowY:"auto",flexShrink:0},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[t.jsx("strong",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:"Layers"}),t.jsx("button",{onClick:n,style:{fontSize:16,border:"none",background:"none",cursor:"pointer",color:"var(--nice-info, #6366f1)",display:"inline-flex",alignItems:"center"},title:"Add layer","aria-label":"Add layer",children:t.jsx(b.NiceIcon,{name:"plus",size:16})})]}),[...i].reverse().map(a=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",borderRadius:5,background:"var(--nice-bg-secondary, #f9fafb)",opacity:a.visible?1:.5},children:[t.jsx("button",{onClick:()=>r({id:a.id,visible:!a.visible}),title:"Toggle visibility","aria-label":"Toggle visibility",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,display:"inline-flex",alignItems:"center",color:a.visible?"var(--nice-text, #374151)":"var(--nice-text-muted, #9ca3af)"},children:t.jsx(b.NiceIcon,{name:a.visible?"eye":"eye-off",size:13})}),t.jsx("button",{onClick:()=>r({id:a.id,locked:!a.locked}),title:"Toggle lock","aria-label":"Toggle lock",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,display:"inline-flex",alignItems:"center",opacity:a.locked?1:.5},children:t.jsx(b.NiceIcon,{name:"lock",size:13})}),t.jsx("span",{style:{flex:1,fontSize:11,color:"var(--nice-text, #374151)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.name}),t.jsx("span",{style:{fontSize:10,color:"var(--nice-text-muted, #9ca3af)"},children:a.objectIds.filter(o=>o in e).length}),i.length>1&&t.jsx("button",{onClick:()=>s(a.id),title:"Delete layer","aria-label":"Delete layer",style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,display:"inline-flex",alignItems:"center",color:"var(--nice-danger, #ef4444)"},children:t.jsx(b.NiceIcon,{name:"trash",size:13})})]},a.id))]})}function pe(i=!1,e=!1){return{padding:"4px 8px",border:`1.5px solid ${e?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)"}`,borderRadius:6,background:e?"var(--nice-primary-bg, #eef2ff)":"var(--nice-bg, #fff)",cursor:i?"default":"pointer",opacity:i?.35:1,fontSize:13,color:e?"var(--nice-accent, #4f46e5)":"var(--nice-text, #374151)",fontWeight:e?600:400}}function gn(i,e){if(e)return"grab";switch(i){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:i,label:e,active:n,badge:r,onClick:s}){return t.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[t.jsxs("button",{title:e,onClick:s,style:{width:44,height:44,borderRadius:10,border:"none",background:n?"var(--nice-overlay-light-20, rgba(255, 255, 255, 0.2))":"transparent",color:"var(--nice-text-on-primary, #fff)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",position:"relative"},children:[t.jsx(b.NiceIcon,{name:i,size:20}),r!=null&&r>0&&t.jsx("span",{style:{position:"absolute",top:4,right:4,background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700,lineHeight:1.4},children:r>99?"99+":r})]}),t.jsx("span",{style:{fontSize:9,color:"var(--nice-overlay-light-70, rgba(255, 255, 255, 0.7))",letterSpacing:"0.03em"},children:e})]})}function mn({team:i,activeChannelId:e,onSelectChannel:n}){var o;const[r,s]=l.useState(!1),a=i.channels.reduce((c,f)=>c+f.unreadCount,0);return t.jsxs("div",{className:"nice-workspace-team",children:[t.jsxs("button",{onClick:()=>s(c=>!c),style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",background:"none",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:"var(--nice-text, #374151)",fontSize:13,fontWeight:600},children:[t.jsx("span",{style:{color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:r?"chevron-right":"chevron-down",size:12})}),t.jsx("div",{style:{width:20,height:20,borderRadius:4,background:i.avatarUrl?`url(${i.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:9,flexShrink:0},children:!i.avatarUrl&&((o=i.name[0])==null?void 0:o.toUpperCase())}),t.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.name}),!r&&a>0&&t.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:a})]}),!r&&i.channels.map(c=>t.jsxs("button",{onClick:()=>n(i.id,c.id),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 10px 5px 34px",background:c.id===e?"var(--nice-accent-tint-10, #ede9fe)":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:c.unreadCount>0?"var(--nice-text, #111827)":"var(--nice-text-secondary, #4b5563)",fontSize:13,fontWeight:c.unreadCount>0?600:400},children:[t.jsx("span",{style:{color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:c.isPrivate?"lock":"hash",size:12})}),t.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.name}),c.mentionCount>0&&t.jsxs("span",{style:{background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:["@",c.mentionCount]}),c.unreadCount>0&&c.mentionCount===0&&t.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700},children:c.unreadCount})]},c.id))]})}function yn({conversation:i,partner:e,isActive:n,onClick:r}){var a;const s=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??i.name??"Group";return t.jsxs("button",{onClick:r,style:{display:"flex",alignItems:"center",gap:8,padding:"5px 10px",background:n?"var(--nice-accent-tint-10, #ede9fe)":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:i.unreadCount>0?"var(--nice-text, #111827)":"var(--nice-text-secondary, #4b5563)",fontWeight:i.unreadCount>0?600:400,fontSize:13},children:[t.jsxs("div",{style:{position:"relative",flexShrink:0},children:[t.jsx("div",{style:{width:24,height:24,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:10},children:!(e!=null&&e.avatarUrl)&&((a=s[0])==null?void 0:a.toUpperCase())}),e&&t.jsx(ue,{status:e.presence.status,size:"xs",style:{position:"absolute",bottom:-1,right:-1}})]}),t.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),i.unreadCount>0&&t.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700,flexShrink:0},children:i.unreadCount})]})}function Rt({currentUser:i,users:e,teams:n,conversations:r,messages:s,activeCall:a,incomingCall:o,meetings:c,transport:f,rtcConfig:d,enableCalls:g=!0,enableMeetings:p=!0,enableScreenSharing:m=!0,enableWhiteboard:h=!1,storageConfig:w,onSendMessage:z,onEditMessage:u,onDeleteMessage:I,onReactToMessage:A,onPinMessage:N,onLoadMoreMessages:H,onMarkAsRead:E,onStartCall:B,onAcceptCall:K,onDeclineCall:J,onEndCall:$,onMuteAudio:C,onMuteVideo:j,onStartScreenShare:O,onStopScreenShare:U,className:P,style:T,id:F,"data-testid":_}){var D,V;const[Y,S]=l.useState("teams"),[x,G]=l.useState(null),[X,Q]=l.useState(""),[q,ne]=l.useState(null),ce=()=>{q||ne({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:i.id,permissions:"edit"})},le=l.useMemo(()=>{const k=new Map;return e.forEach(R=>k.set(R.id,R)),k},[e]),ye=l.useMemo(()=>Ze(r),[r]),L=l.useMemo(()=>r.reduce((k,R)=>k+R.mentionCount,0),[r]),Z=l.useMemo(()=>{if(x!=null&&x.channelId)for(const k of n){const R=k.channels.find(te=>te.id===x.channelId);if(R)return R}},[n,x]),se=l.useMemo(()=>{if(x!=null&&x.teamId)return n.find(k=>k.id===x.teamId)},[n,x]),ae=l.useMemo(()=>r.find(k=>k.id===(x==null?void 0:x.conversationId))??null,[r,x]),oe=l.useMemo(()=>{const k=(x==null?void 0:x.channelId)??(x==null?void 0:x.conversationId);return k?s[k]??[]:[]},[s,x]),y=!!o&&!a,v=!!a,M=l.useMemo(()=>r.filter(k=>k.type==="dm"||k.type==="group"),[r]),W=l.useMemo(()=>{if(!X)return M;const k=X.toLowerCase();return M.filter(R=>{var ee;const te=le.get(R.participantIds.find(re=>re!==i.id)??"");return(te==null?void 0:te.name.toLowerCase().includes(k))||((ee=R.name)==null?void 0:ee.toLowerCase().includes(k))})},[M,X,le,i.id]);return t.jsxs("div",{id:F,"data-testid":_,className:`nice-teams-workspace${P?` ${P}`:""}`,style:{position:"relative",height:"100%",...T},children:[t.jsx(b.NiceAppShell,{flush:!0,height:"100%",className:"nice-teams-workspace__shell",style:{background:"var(--nice-bg, #fff)",overflow:"hidden"},sidebar:t.jsxs("div",{style:{display:"flex",height:"100%",minHeight:0},children:[t.jsxs("div",{className:"nice-workspace-nav-rail",style:{width:64,flexShrink:0,background:"var(--nice-accent, #4f46e5)",display:"flex",flexDirection:"column",alignItems:"center",padding:"12px 0",gap:6},children:[t.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:i.avatarUrl?`url(${i.avatarUrl}) center/cover`:"var(--nice-accent, #818cf8)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:14,marginBottom:8,flexShrink:0},children:!i.avatarUrl&&((D=i.name[0])==null?void 0:D.toUpperCase())}),t.jsx(be,{icon:"zap",label:"Activity",active:Y==="activity",badge:L,onClick:()=>S("activity")}),t.jsx(be,{icon:"message",label:"Chat",active:Y==="chat",badge:ye,onClick:()=>S("chat")}),t.jsx(be,{icon:"users",label:"Teams",active:Y==="teams",onClick:()=>S("teams")}),g&&t.jsx(be,{icon:"phone",label:"Calls",active:Y==="calls",onClick:()=>S("calls")}),p&&t.jsx(be,{icon:"calendar",label:"Meetings",active:Y==="meetings",onClick:()=>S("meetings")}),t.jsx(be,{icon:"folder",label:"Files",active:Y==="files",onClick:()=>S("files")}),h&&t.jsx(be,{icon:"edit",label:"Board",active:Y==="whiteboard",onClick:()=>{S("whiteboard"),ce()}})]}),t.jsxs("div",{className:"nice-workspace-sidebar",style:{width:240,flexShrink:0,borderRight:"1px solid var(--nice-border, #e5e7eb)",display:"flex",flexDirection:"column",background:"var(--nice-bg-secondary, #fafafa)",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"12px 10px 8px",flexShrink:0},children:[t.jsx("div",{style:{fontWeight:700,fontSize:15,color:"var(--nice-text, #374151)",marginBottom:8,textTransform:"capitalize"},children:Y}),t.jsx("input",{type:"search",value:X,onChange:k=>Q(k.target.value),placeholder:`Search ${Y}…`,style:{width:"100%",padding:"5px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,fontSize:12,outline:"none",boxSizing:"border-box",background:"var(--nice-bg, #fff)"}})]}),t.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[Y==="teams"&&t.jsx(t.Fragment,{children:n.map(k=>t.jsx(mn,{team:k,activeChannelId:x==null?void 0:x.channelId,onSelectChannel:(R,te)=>{G({type:"channel",teamId:R,channelId:te}),E==null||E(te)}},k.id))}),Y==="chat"&&t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:"var(--nice-text-muted, #9ca3af)",fontWeight:600,letterSpacing:"0.05em"},children:"DIRECT MESSAGES"}),W.map(k=>{const R=le.get(k.participantIds.find(te=>te!==i.id)??"");return t.jsx(yn,{conversation:k,partner:R,isActive:(x==null?void 0:x.conversationId)===k.id,onClick:()=>{G({type:k.type==="dm"?"dm":"group",conversationId:k.id}),E==null||E(k.id)}},k.id)})]}),Y==="activity"&&t.jsxs("div",{style:{padding:12},children:[r.filter(k=>k.unreadCount>0).map(k=>t.jsxs("button",{onClick:()=>{S(k.type==="channel"?"teams":"chat"),G({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:"var(--nice-text, #374151)"},children:[t.jsx("strong",{children:k.name??"Conversation"})," — ",k.unreadCount," unread"]},k.id)),r.every(k=>k.unreadCount===0)&&t.jsxs("p",{style:{color:"var(--nice-text-muted, #9ca3af)",fontSize:13,textAlign:"center",marginTop:24,display:"flex",alignItems:"center",justifyContent:"center",gap:4},children:["All caught up ",t.jsx(b.NiceIcon,{name:"check",size:13})]})]}),Y==="calls"&&t.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("button",{onClick:()=>B==null?void 0:B(e.map(k=>k.id).filter(k=>k!==i.id),"audio"),style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[t.jsx(b.NiceIcon,{name:"phone",size:14})," New audio call"]}),t.jsxs("button",{onClick:()=>B==null?void 0:B(e.map(k=>k.id).filter(k=>k!==i.id),"video"),style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[t.jsx(b.NiceIcon,{name:"video",size:14})," New video call"]})]}),Y==="meetings"&&t.jsxs("div",{style:{padding:12},children:[(c??[]).map(k=>t.jsxs("div",{style:{padding:"8px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,marginBottom:8},children:[t.jsx("div",{style:{fontWeight:600,fontSize:13},children:k.title}),t.jsx("div",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginTop:2},children:k.scheduledStart.toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}),t.jsx("button",{onClick:()=>{},style:{marginTop:6,background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:6,padding:"3px 10px",fontSize:12,cursor:"pointer"},children:"Join"})]},k.id)),(c??[]).length===0&&t.jsx("p",{style:{color:"var(--nice-text-muted, #9ca3af)",fontSize:13,textAlign:"center",marginTop:24},children:"No upcoming meetings"})]}),Y==="files"&&t.jsx("div",{style:{padding:12},children:t.jsx("p",{style:{color:"var(--nice-text-muted, #9ca3af)",fontSize:13,textAlign:"center",marginTop:24},children:"No files shared yet"})}),Y==="whiteboard"&&t.jsxs("div",{style:{padding:12},children:[t.jsxs("button",{onClick:()=>ce(),style:{width:"100%",background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,marginBottom:8,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[t.jsx(b.NiceIcon,{name:"edit",size:14})," ",q?"Open whiteboard":"New whiteboard"]}),q&&t.jsxs("div",{style:{padding:"6px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,fontSize:12,color:"var(--nice-text, #374151)"},children:[t.jsx("div",{style:{fontWeight:500},children:q.title}),t.jsxs("div",{style:{color:"var(--nice-text-muted, #9ca3af)",marginTop:2},children:[Object.keys(q.objects).length," objects"]})]})]})]})]})]}),children:t.jsxs("div",{style:{flex:1,height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[(x==null?void 0:x.type)==="channel"&&Z?t.jsx(Ct,{channel:Z,messages:oe,users:(se==null?void 0:se.members)??e,currentUser:i,team:se,onSendMessage:z,onEditMessage:u,onDeleteMessage:I,onReactToMessage:A,onPinMessage:N,onLoadMoreMessages:H,onStartCall:g?B:void 0,style:{height:"100%"}}):((x==null?void 0:x.type)==="dm"||(x==null?void 0:x.type)==="group")&&ae?t.jsx(Ne,{conversation:ae,messages:oe,users:e,currentUser:i,onSendMessage:z,onEditMessage:u,onDeleteMessage:I,onReactToMessage:A,onPinMessage:N,onLoadMoreMessages:H,onStartCall:g?B:void 0,style:{height:"100%"}}):Y==="whiteboard"&&q?t.jsx(it,{session:q,currentUser:i,storageConfig:w,onSessionUpdate:k=>ne(k),style:{height:"100%"}}):t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"var(--nice-text-muted, #9ca3af)",gap:12},children:[t.jsx(b.NiceIcon,{name:Y==="teams"?"users":Y==="chat"?"message":Y==="calls"?"phone":Y==="whiteboard"?"edit":"zap",size:56}),t.jsx("span",{style:{fontSize:17,fontWeight:500},children:Y==="teams"?"Select a channel to get started":Y==="chat"?"Select a conversation":Y==="calls"?"Start or join a call":Y==="whiteboard"?'Click "New whiteboard" to start':"Nothing selected"})]}),v&&a&&t.jsx("div",{style:{position:"absolute",inset:0,zIndex:50},children:a.participants.length>2?t.jsx(tt,{session:a,currentUser:i,enableScreenSharing:m,onEndCall:$,onMuteAudio:C,onMuteVideo:j,onStartScreenShare:O,onStopScreenShare:U}):t.jsx(et,{session:a,currentUser:i,enableScreenSharing:m,onEndCall:$,onMuteAudio:C,onMuteVideo:j,onStartScreenShare:O,onStopScreenShare:U})})]})}),y&&o&&t.jsxs("div",{style:{position:"absolute",top:16,right:16,width:300,background:"var(--nice-text, #1f2937)",borderRadius:12,padding:16,boxShadow:"0 8px 32px var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",zIndex:100,color:"var(--nice-text-inverse, #fff)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:12},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:o.caller.avatarUrl?`url(${o.caller.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:16},children:!o.caller.avatarUrl&&((V=o.caller.name[0])==null?void 0:V.toUpperCase())}),t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:600},children:o.caller.displayName??o.caller.name}),t.jsxs("div",{style:{fontSize:12,color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"},children:["Incoming ",o.callType," call"]})]})]}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsxs("button",{onClick:()=>J==null?void 0:J(o.callId),style:{flex:1,background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[t.jsx(b.NiceIcon,{name:"phone",size:14})," Decline"]}),t.jsxs("button",{onClick:()=>K==null?void 0:K(o.callId),style:{flex:1,background:"var(--nice-success, #22c55e)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[t.jsx(b.NiceIcon,{name:"phone",size:14})," Accept"]})]})]})]})}const xn={"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 bn({props:i,onExpand:e}){const[n,r]=l.useState(!1),{bubblePosition:s="bottom-right",bubbleLabel:a,currentUser:o,users:c,conversations:f=[],messages:d={},activeConversationId:g,onSendMessage:p,onReactToMessage:m,onPinMessage:h,onDeleteMessage:w,onEditMessage:z,onLoadMoreMessages:u,onStartCall:I}=i,A=xn[s],N=f.find(E=>E.id===g)??f[0]??null,H=N?d[N.id]??[]:[];return t.jsxs("div",{style:{position:"fixed",zIndex:9999,...A},children:[n&&N&&t.jsxs("div",{style:{position:"absolute",bottom:s.startsWith("bottom")?64:void 0,top:s.startsWith("top")?64:void 0,right:s.endsWith("right")?0:void 0,left:s.endsWith("left")?0:void 0,width:360,height:500,background:"var(--nice-bg, #fff)",borderRadius:16,boxShadow:"0 8px 40px var(--nice-overlay-20, rgba(0, 0, 0, 0.18))",overflow:"hidden",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",flexShrink:0},children:[t.jsx("span",{style:{fontWeight:700,fontSize:15},children:a??"Chat"}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:()=>e("messenger"),title:"Open full chat","aria-label":"Open full chat",style:{background:"var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))",border:"none",borderRadius:6,padding:"3px 7px",color:"var(--nice-text-on-primary, #fff)",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:"expand",size:13})}),t.jsx("button",{onClick:()=>r(!1),title:"Close","aria-label":"Close",style:{background:"none",border:"none",color:"var(--nice-text-primary, #fff)",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:"close",size:18})})]})]}),t.jsx(Ne,{conversation:N,messages:H,users:c,currentUser:o,showHeader:!1,onSendMessage:p,onEditMessage:z,onDeleteMessage:w,onReactToMessage:m,onPinMessage:h,onLoadMoreMessages:u,onStartCall:I,style:{flex:1}})]}),t.jsx("button",{onClick:()=>r(E=>!E),style:{width:56,height:56,borderRadius:"50%",background:"var(--nice-info, #6366f1)",border:"none",boxShadow:"0 4px 16px var(--nice-accent-tint-40, rgba(99, 102, 241, 0.4))",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-on-primary, #fff)",transition:"transform 0.15s"},title:n?"Close chat":a??"Open chat","aria-label":n?"Close chat":a??"Open chat",children:t.jsx(b.NiceIcon,{name:n?"close":"message",size:24})})]})}function vn({call:i,onAccept:e,onDecline:n}){return t.jsxs("div",{style:{position:"fixed",top:16,left:"50%",transform:"translateX(-50%)",zIndex:9998,background:"var(--nice-text, #1f2937)",color:"var(--nice-text-inverse, #fff)",borderRadius:12,padding:"12px 20px",boxShadow:"0 8px 32px var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",display:"flex",alignItems:"center",gap:16,minWidth:280},children:[t.jsx("div",{style:{display:"flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:i.callType==="video"?"video":"phone",size:28})}),t.jsxs("div",{style:{flex:1},children:[t.jsx("div",{style:{fontWeight:600,fontSize:14},children:i.caller.displayName??i.caller.name}),t.jsxs("div",{style:{fontSize:12,color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"},children:["Incoming ",i.callType," call…"]})]}),t.jsx("button",{onClick:n,style:{background:"var(--nice-danger, #ef4444)",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",color:"var(--nice-text-on-primary, #fff)",display:"inline-flex",alignItems:"center",justifyContent:"center"},title:"Decline","aria-label":"Decline",children:t.jsx(b.NiceIcon,{name:"phone",size:18})}),t.jsx("button",{onClick:e,style:{background:"var(--nice-success, #22c55e)",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",color:"var(--nice-text-on-primary, #fff)",display:"inline-flex",alignItems:"center",justifyContent:"center"},title:"Accept","aria-label":"Accept",children:t.jsx(b.NiceIcon,{name:"phone",size:18})})]})}function Nt(i){const{mode:e,currentUser:n,users:r,conversations:s=[],messages:a={},activeConversationId:o,teams:c=[],meetings:f,activeCall:d,incomingCall:g,transport:p="webrtc",rtcConfig:m,onSendMessage:h,onEditMessage:w,onDeleteMessage:z,onReactToMessage:u,onPinMessage:I,onLoadMoreMessages:A,onMarkAsRead:N,onStartCall:H,onAcceptCall:E,onDeclineCall:B,onEndCall:K,onMuteAudio:J,onMuteVideo:$,onStartScreenShare:C,onStopScreenShare:j,onRaiseHand:O,onModeChange:U,enableScreenSharing:P=!0,enableMeetings:T=!0,enableWhiteboard:F=!1,storageConfig:_,encryptionConfig:Y,className:S,style:x,id:G,"data-testid":X}=i,[Q,q]=l.useState(e),[ne,ce]=l.useState(null),le=l.useMemo(()=>({id:`wb-${n.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:n.id,permissions:"edit"}),[n.id]),[ye,L]=l.useState(d??null),[Z,se]=l.useState(g??null),ae=d??ye,oe=g??Z;l.useEffect(()=>{q(e)},[e]),l.useEffect(()=>{d!==void 0&&L(d)},[d]),l.useEffect(()=>{g!==void 0&&se(g)},[g]);const{state:y,startCall:v,acceptCall:M,declineCall:W,endCall:D,toggleMic:V,toggleCamera:k,startScreenShare:R,stopScreenShare:te}=jt({currentUser:n,transport:p,rtcConfig:m,onCallEnded:ie=>{L(null),K==null||K(ie)},onIncomingCall:ie=>{se(ie)}}),ee=l.useCallback(ie=>{q(ie),U==null||U(ie)},[U]),re=l.useCallback(async(ie,lt)=>{if(H){await H(ie,lt);return}const Bt=await v(ie,lt);L(Bt),q(ie.length>2?"conference":"call")},[H,v]),de=l.useCallback(async()=>{var ie;E&&oe?await E(oe.callId):await M(),se(null),q((ie=y.activeCall)!=null&&ie.participants&&y.activeCall.participants.length>2?"conference":"call")},[E,oe,M,y.activeCall]),ge=l.useCallback(()=>{B&&oe?B(oe.callId):W(),se(null)},[B,oe,W]),fe=l.useCallback(ie=>{K?K(ie):D(),L(null),q(e)},[K,D,e]),Pe=l.useCallback(ie=>{V(),J==null||J(ie)},[V,J]),ot=l.useCallback(ie=>{k(),$==null||$(ie)},[k,$]),Ae=l.useCallback(async()=>{await R(),await(C==null?void 0:C())},[R,C]),We=l.useCallback(()=>{te(),j==null||j()},[te,j]),Ie={onSendMessage:h,onEditMessage:w,onDeleteMessage:z,onReactToMessage:u,onPinMessage:I,onLoadMoreMessages:A,onMarkAsRead:N,onStartCall:re,onEndCall:fe,onMuteAudio:Pe,onMuteVideo:ot,onStartScreenShare:Ae,onStopScreenShare:We,onRaiseHand:O},Fe=s.find(ie=>ie.id===o)??s[0],he=ae?ae.participants.length>2?"conference":"call":Q,_t={width:"100%",height:"100%",position:"relative",...x};return t.jsxs("div",{id:G,"data-testid":X,className:`nice-communication nice-communication--${he}${S?` ${S}`:""}`,style:_t,children:[oe&&he!=="workspace"&&t.jsx(vn,{call:oe,onAccept:de,onDecline:ge}),he==="bubble"&&t.jsx(bn,{props:i,onExpand:ee}),he==="chat"&&Fe&&t.jsx(Ne,{conversation:Fe,messages:a[Fe.id]??[],users:r,currentUser:n,...Ie,style:{height:"100%"}}),he==="messenger"&&t.jsx(kt,{conversations:s,messages:a,activeConversationId:o,users:r,currentUser:n,teams:c,...Ie,onAcceptCall:E,onDeclineCall:B,style:{height:"100%"}}),he==="workspace"&&t.jsx(Rt,{currentUser:n,users:r,teams:c,conversations:s,messages:a,meetings:f,activeCall:ae??void 0,incomingCall:oe??void 0,transport:p,rtcConfig:m,enableCalls:!0,enableMeetings:T,enableScreenSharing:P,...Ie,onAcceptCall:de,onDeclineCall:ge,style:{height:"100%"}}),he==="call"&&ae&&t.jsx(et,{session:ae,currentUser:n,localStream:y.localStream??void 0,enableScreenSharing:P,...Ie,style:{height:"100%"}}),he==="conference"&&ae&&t.jsx(tt,{session:ae,currentUser:n,localStream:y.localStream??void 0,enableScreenSharing:P,...Ie,style:{height:"100%"}}),he==="whiteboard"&&F&&t.jsx(it,{session:ne??le,currentUser:n,storageConfig:_,onSessionUpdate:ie=>ce(ie),style:{height:"100%"}})]})}const wn={messages:"Messages",attachments:"Attachments","whiteboard-snapshots":"Whiteboard snapshots",recordings:"Recordings",transcripts:"Transcripts",documents:"Documents","call-logs":"Call logs","audit-logs":"Audit logs"},ft={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"},Sn={messages:"Messages",attachments:"Attachments",whiteboard:"Whiteboard",recordings:"Recordings",documents:"Documents",calls:"Calls (metadata)",presence:"Presence data",all:"Everything"},jn=["days","weeks","months","years","forever"];function ht(i){if(i===0)return"0 B";const e=1024,n=["B","KB","MB","GB"],r=Math.floor(Math.log(i)/Math.log(e));return`${(i/Math.pow(e,r)).toFixed(1)} ${n[r]}`}function gt({value:i,onChange:e,disabled:n=!1}){return t.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[t.jsx("input",{type:"number",min:1,max:9999,value:i.unit==="forever"?"":i.value,disabled:n||i.unit==="forever",onChange:r=>e({...i,value:Math.max(1,Number(r.target.value))}),style:{width:60,padding:"3px 6px",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:5,fontSize:12}}),t.jsx("select",{value:i.unit,disabled:n,onChange:r=>e({...i,unit:r.target.value}),style:{padding:"3px 6px",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:5,fontSize:12},children:jn.map(r=>t.jsx("option",{value:r,children:r},r))})]})}function kn({config:i,onChange:e}){const n=i.retentionRules.length>0?i.retentionRules:nt;function r(s,a){const o=n.map(c=>c.dataType===s?{...c,...a}:c);e({...i,retentionRules:o})}return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx("p",{style:{fontSize:12,color:"var(--nice-text-secondary, #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."}),t.jsxs("div",{style:ke,children:[t.jsx("label",{style:Ce,children:"Storage provider"}),t.jsxs("select",{value:i.provider,onChange:s=>e({...i,provider:s.target.value}),style:ve,children:[t.jsx("option",{value:"indexeddb",children:"IndexedDB (browser)"}),t.jsx("option",{value:"localstorage",children:"LocalStorage (browser)"}),t.jsx("option",{value:"server",children:"Server"}),t.jsx("option",{value:"custom",children:"Custom adapter"})]})]}),i.provider==="server"&&t.jsxs("div",{style:ke,children:[t.jsx("label",{style:Ce,children:"Server URL"}),t.jsx("input",{type:"url",value:i.serverUrl??"",onChange:s=>e({...i,serverUrl:s.target.value}),placeholder:"https://your-api.example.com/storage",style:ve})]}),t.jsx("hr",{style:{border:"none",borderTop:"1px solid var(--nice-border, #e5e7eb)",margin:"4px 0"}}),t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{background:"var(--nice-bg-secondary, #f9fafb)"},children:[t.jsx("th",{style:Se,children:"Data type"}),t.jsx("th",{style:Se,children:"Active period"}),t.jsx("th",{style:Se,children:"Archive after"}),t.jsx("th",{style:Se,children:"Auto-delete"}),t.jsx("th",{style:Se,children:"User can delete"}),t.jsx("th",{style:Se,children:"Legal hold"})]})}),t.jsx("tbody",{children:n.map(s=>t.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)"},children:[t.jsx("td",{style:{...je,fontWeight:500,color:"var(--nice-text, #374151)"},children:wn[s.dataType]}),t.jsx("td",{style:je,children:t.jsx(gt,{value:s.activePeriod,onChange:a=>r(s.dataType,{activePeriod:a})})}),t.jsx("td",{style:je,children:s.archivePeriod?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[t.jsx(gt,{value:s.archivePeriod,onChange:a=>r(s.dataType,{archivePeriod:a})}),t.jsx("button",{onClick:()=>r(s.dataType,{archivePeriod:void 0}),style:{border:"none",background:"none",cursor:"pointer",color:"var(--nice-danger, #ef4444)",display:"inline-flex",alignItems:"center"},title:"Remove archive period","aria-label":"Remove archive period",children:t.jsx(b.NiceIcon,{name:"close",size:14})})]}):t.jsxs("button",{onClick:()=>r(s.dataType,{archivePeriod:{value:1,unit:"years"}}),style:{fontSize:11,padding:"2px 8px",border:"1px dashed var(--nice-border, #d1d5db)",borderRadius:4,cursor:"pointer",background:"none",color:"var(--nice-text-secondary, #6b7280)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(b.NiceIcon,{name:"plus",size:11})," Add"]})}),t.jsx("td",{style:{...je,textAlign:"center"},children:t.jsx("input",{type:"checkbox",checked:s.deleteAfterArchive,disabled:!s.archivePeriod,onChange:a=>r(s.dataType,{deleteAfterArchive:a.target.checked})})}),t.jsx("td",{style:{...je,textAlign:"center"},children:t.jsx("input",{type:"checkbox",checked:s.userCanDelete,onChange:a=>r(s.dataType,{userCanDelete:a.target.checked})})}),t.jsx("td",{style:{...je,textAlign:"center"},children:t.jsx("input",{type:"checkbox",checked:s.legalHoldEnabled??!1,onChange:a=>r(s.dataType,{legalHoldEnabled:a.target.checked})})})]},s.dataType))})]}),t.jsxs("div",{style:ke,children:[t.jsx("label",{style:Ce,children:"Storage quota"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("input",{type:"number",min:0,value:i.quota?Math.round(i.quota/1024/1024):0,onChange:s=>e({...i,quota:Number(s.target.value)*1024*1024}),style:{...ve,width:90},placeholder:"0"}),t.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:"MB (0 = unlimited)"})]})]})]})}function Cn({config:i,onChange:e}){const n=["messages","attachments","whiteboard","recordings","documents","calls","presence"];return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx("p",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",margin:0},children:"Configure encryption at rest and in transit. E2E-ECDH ensures only participants can read conversations — the server never sees plaintext."}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsxs("label",{style:{position:"relative",display:"inline-block",width:42,height:22},children:[t.jsx("input",{type:"checkbox",checked:i.enabled,onChange:r=>e({...i,enabled:r.target.checked}),style:{opacity:0,width:0,height:0}}),t.jsx("span",{style:{position:"absolute",inset:0,borderRadius:22,background:i.enabled?"var(--nice-info, #6366f1)":"var(--nice-border, #d1d5db)",transition:"background 0.2s",cursor:"pointer"},children:t.jsx("span",{style:{position:"absolute",width:16,height:16,top:3,left:i.enabled?23:3,background:"var(--nice-bg, #fff)",borderRadius:"50%",transition:"left 0.2s"}})})]}),t.jsxs("span",{style:{fontSize:13,fontWeight:500,color:"var(--nice-text, #374151)",display:"inline-flex",alignItems:"center",gap:5},children:[t.jsx(b.NiceIcon,{name:"lock",size:14})," ",i.enabled?"Encryption enabled":"Encryption disabled"]})]}),i.enabled&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:ke,children:[t.jsx("label",{style:Ce,children:"Default algorithm"}),t.jsx("select",{value:i.defaultAlgorithm,onChange:r=>e({...i,defaultAlgorithm:r.target.value}),style:ve,children:Object.entries(ft).map(([r,s])=>t.jsx("option",{value:r,children:s},r))})]}),i.defaultAlgorithm==="E2E-ECDH-P384"&&t.jsxs("div",{style:ke,children:[t.jsx("label",{style:Ce,children:"Key exchange URL"}),t.jsx("input",{type:"url",value:i.keyExchangeUrl??"",onChange:r=>e({...i,keyExchangeUrl:r.target.value}),placeholder:"wss://your-server/e2e-key-exchange",style:ve}),t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginTop:2},children:"WebSocket endpoint for ECDH public key exchange between participants."})]}),t.jsxs("div",{style:ke,children:[t.jsx("label",{style:Ce,children:"External key (base64, optional)"}),t.jsx("input",{type:"password",value:i.keyMaterial??"",onChange:r=>e({...i,keyMaterial:r.target.value||void 0}),placeholder:"Leave empty to auto-generate",style:ve}),t.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginTop:2},children:"Provide a pre-shared key for symmetric algorithms. Leave empty for automatic key generation."})]}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:i.showIndicator??!0,onChange:r=>e({...i,showIndicator:r.target.checked})}),t.jsx("span",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:"Show lock indicator in messages"})]}),t.jsx("hr",{style:{border:"none",borderTop:"1px solid var(--nice-border, #e5e7eb)",margin:"4px 0"}}),t.jsx("strong",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:"Per-scope overrides"}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:n.map(r=>{var c;const s=(c=i.scopeOverrides)==null?void 0:c.find(f=>f.scope===r),a=(s==null?void 0:s.enabled)??!1,o=(s==null?void 0:s.algorithm)??i.defaultAlgorithm;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 8px",background:"var(--nice-bg-secondary, #f9fafb)",borderRadius:6},children:[t.jsx("input",{type:"checkbox",checked:a,onChange:f=>{const d=[...(i.scopeOverrides??[]).filter(g=>g.scope!==r),{scope:r,algorithm:o,enabled:f.target.checked}];e({...i,scopeOverrides:d})}}),t.jsx("span",{style:{minWidth:120,fontSize:12,color:"var(--nice-text, #374151)"},children:Sn[r]}),t.jsx("select",{value:o,disabled:!a,onChange:f=>{const d=[...(i.scopeOverrides??[]).filter(g=>g.scope!==r),{scope:r,algorithm:f.target.value,enabled:a}];e({...i,scopeOverrides:d})},style:{...ve,flex:1,opacity:a?1:.4},children:Object.entries(ft).map(([f,d])=>t.jsx("option",{value:f,children:d},f))})]},r)})})]})]})}function In({storageConfig:i,defaultStorageConfig:e,encryptionConfig:n,onStorageConfigChange:r,onEncryptionConfigChange:s,currentUsageBytes:a=0,showEncryption:o=!0,showRetention:c=!0,showQuota:f=!0,className:d,style:g,"data-testid":p}){const[m,h]=l.useState("retention"),[w,z]=b.useControllableState({value:i,defaultValue:e,fallbackValue:{provider:"indexeddb",retentionRules:[]},onChange:r,componentName:"NiceStorageSettings"}),u=n??{enabled:!1,defaultAlgorithm:"AES-GCM-256",showIndicator:!0},I={...w,retentionRules:w.retentionRules.length>0?w.retentionRules:nt};return t.jsxs("div",{className:d,"data-testid":p,style:{display:"flex",flexDirection:"column",gap:16,padding:20,background:"var(--nice-bg, #fff)",borderRadius:10,border:"1px solid var(--nice-border, #e5e7eb)",fontFamily:"system-ui, sans-serif",maxWidth:800,...g},children:[t.jsxs("div",{children:[t.jsx("h3",{style:{margin:0,fontSize:16,color:"var(--nice-text, #111827)"},children:"Storage & Privacy"}),t.jsx("p",{style:{margin:"4px 0 0",fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:"Manage data retention, encryption, and storage settings."})]}),f&&w.quota&&w.quota>0&&t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:12,color:"var(--nice-text-secondary, #6b7280)",marginBottom:4},children:[t.jsx("span",{children:"Storage used"}),t.jsxs("span",{children:[ht(a)," / ",ht(w.quota)]})]}),t.jsx("div",{style:{height:6,background:"var(--nice-border, #e5e7eb)",borderRadius:3},children:t.jsx("div",{style:{width:`${Math.min(100,a/w.quota*100)}%`,height:"100%",background:a/w.quota>.9?"var(--nice-danger, #ef4444)":"var(--nice-info, #6366f1)",borderRadius:3,transition:"width 0.3s"}})})]}),c&&o&&t.jsx("div",{style:{display:"flex",gap:0,borderBottom:"1px solid var(--nice-border, #e5e7eb)"},children:["retention","encryption"].map(A=>t.jsx("button",{onClick:()=>h(A),style:{padding:"8px 18px",border:"none",borderBottom:`2px solid ${m===A?"var(--nice-info, #6366f1)":"transparent"}`,background:"none",cursor:"pointer",fontSize:13,fontWeight:m===A?600:400,color:m===A?"var(--nice-accent, #4f46e5)":"var(--nice-text-secondary, #6b7280)",marginBottom:-1,display:"inline-flex",alignItems:"center",gap:6},children:A==="retention"?t.jsxs(t.Fragment,{children:[t.jsx(b.NiceIcon,{name:"archive",size:13})," Retention"]}):t.jsxs(t.Fragment,{children:[t.jsx(b.NiceIcon,{name:"lock",size:13})," Encryption"]})},A))}),t.jsxs("div",{children:[(m==="retention"||!o)&&c&&t.jsx(kn,{config:I,onChange:z}),(m==="encryption"||!c)&&o&&t.jsx(Cn,{config:u,onChange:s??(()=>{})})]})]})}const ke={display:"flex",flexDirection:"column",gap:4},Ce={fontSize:12,fontWeight:500,color:"var(--nice-text, #374151)"},ve={padding:"6px 8px",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6,fontSize:13,color:"var(--nice-text, #111827)",background:"var(--nice-bg, #fff)"},Se={padding:"6px 8px",textAlign:"left",fontSize:11,fontWeight:600,color:"var(--nice-text-secondary, #6b7280)",borderBottom:"1px solid var(--nice-border, #e5e7eb)"},je={padding:"8px 8px",verticalAlign:"middle"};function Le(i){const e=Math.floor(i/1e3),n=Math.floor(e/60),r=Math.floor(n/60);return r>0?`${r}:${String(n%60).padStart(2,"0")}:${String(e%60).padStart(2,"0")}`:`${String(n).padStart(2,"0")}:${String(e%60).padStart(2,"0")}`}function zn(i){if(i===0)return"0 B";const e=1024,n=["B","KB","MB","GB"],r=Math.floor(Math.log(i)/Math.log(e));return`${(i/Math.pow(e,r)).toFixed(1)} ${n[r]}`}function Tn(i,e){return new Intl.DateTimeFormat(e,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(i))}const Rn=(i,e)=>i(`recording.state.${e}`,Pt[e].label),Pt={idle:{label:"Idle",icon:null,bg:"var(--nice-bg-secondary, #f3f4f6)",fg:"var(--nice-text-secondary, #6b7280)"},recording:{label:"Recording",icon:"circle",bg:"var(--nice-danger-bg, #fee2e2)",fg:"var(--nice-danger-dark, #dc2626)"},paused:{label:"Paused",icon:"pause",bg:"var(--nice-warning-bg, #fef3c7)",fg:"var(--nice-warning-dark, #d97706)"},processing:{label:"Processing",icon:"clock",bg:"var(--nice-accent-tint-10, #ede9fe)",fg:"var(--nice-accent, #7c3aed)"},ready:{label:"Ready",icon:"check",bg:"var(--nice-success-bg, #dcfce7)",fg:"var(--nice-success-dark, #16a34a)"},failed:{label:"Failed",icon:"close",bg:"var(--nice-danger-bg, #fee2e2)",fg:"var(--nice-danger-dark, #dc2626)"}};function Nn({segments:i,onClose:e,currentTimeMs:n=0}){const{t:r}=b.useNiceTranslation();return t.jsx("div",{style:{position:"fixed",inset:0,zIndex:9999,background:"var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsxs("div",{style:{background:"var(--nice-bg, #fff)",borderRadius:12,width:"90%",maxWidth:640,maxHeight:"80vh",display:"flex",flexDirection:"column",boxShadow:"0 20px 40px var(--nice-overlay-20, rgba(0, 0, 0, 0.2))",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"14px 18px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsx("strong",{style:{fontSize:14,color:"var(--nice-text, #111827)"},children:r("recording.transcript","Transcript")}),t.jsx("button",{onClick:e,style:En,"aria-label":r("recording.close","Close"),children:t.jsx(b.NiceIcon,{name:"close",size:16})})]}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"12px 18px"},children:i.length===0?t.jsx("p",{style:{fontSize:13,color:"var(--nice-text-muted, #9ca3af)",textAlign:"center",padding:"32px 0"},children:r("recording.noTranscript","No transcript available.")}):i.map(s=>{const a=n>=s.startMs&&n<s.endMs;return t.jsxs("div",{style:{marginBottom:12,padding:"8px 10px",borderRadius:6,background:a?"var(--nice-primary-bg, #eff6ff)":"transparent",borderLeft:`3px solid ${a?"var(--nice-primary, #3b82f6)":"transparent"}`,transition:"background 0.2s"},children:[t.jsxs("div",{style:{display:"flex",gap:10,alignItems:"baseline",marginBottom:3},children:[t.jsx("span",{style:{fontSize:11,fontWeight:600,color:"var(--nice-accent, #4f46e5)"},children:s.speakerName}),t.jsxs("span",{style:{fontSize:10,color:"var(--nice-text-muted, #9ca3af)"},children:[Le(s.startMs)," – ",Le(s.endMs)]}),t.jsxs("span",{style:{fontSize:10,color:"var(--nice-text-secondary, #d1d5db)"},children:[Math.round(s.confidence*100),"% conf."]})]}),t.jsx("p",{style:{margin:0,fontSize:13,color:"var(--nice-text, #374151)",lineHeight:1.5},children:s.text})]},s.id)})})]})})}function At({startedAt:i}){const[e,n]=l.useState(0);return l.useEffect(()=>{const r=new Date(i).getTime(),s=setInterval(()=>n(Date.now()-r),500);return()=>clearInterval(s)},[i]),t.jsx(t.Fragment,{children:Le(e)})}function Pn({rec:i,onDelete:e,onDownload:n}){const{t:r,lang:s}=b.useNiceTranslation(),[a,o]=l.useState(!1),[c,f]=l.useState(0),d=l.useRef(null),g=Pt[i.state],p=Rn(r,i.state),m=i.state==="recording"||i.state==="paused";return t.jsxs(t.Fragment,{children:[a&&i.transcript&&t.jsx(Nn,{segments:i.transcript,currentTimeMs:c,onClose:()=>o(!1)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",flexWrap:"wrap"},children:[t.jsx("div",{style:{display:"flex",alignItems:"center"},children:t.jsx(b.NiceIcon,{name:i.sessionType==="call"?"phone":i.sessionType==="meeting"?"video":i.sessionType==="whiteboard"?"image":"monitor",size:20})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:13,fontWeight:500,color:"var(--nice-text, #111827)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.title??`Recording ${i.id.slice(0,8)}`}),t.jsxs("div",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",marginTop:2,display:"flex",gap:8},children:[t.jsx("span",{children:Tn(i.startedAt,s)}),t.jsx("span",{children:m?t.jsx(At,{startedAt:i.startedAt}):i.durationMs!=null?Le(i.durationMs):"—"}),i.size!=null&&t.jsx("span",{children:zn(i.size)}),t.jsxs("span",{children:[i.participants.length," participants"]})]})]}),t.jsxs("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:20,background:g.bg,color:g.fg,fontWeight:500,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[g.icon&&t.jsx(b.NiceIcon,{name:g.icon,size:11}),p]}),i.url&&i.state==="ready"&&t.jsx("audio",{ref:d,src:i.url,controls:!0,onTimeUpdate:()=>{d.current&&f(d.current.currentTime*1e3)},style:{height:32,maxWidth:180}}),t.jsxs("div",{style:{display:"flex",gap:4},children:[i.transcript&&i.transcript.length>0&&t.jsx("button",{onClick:()=>o(!0),style:Ke,title:r("recording.viewTranscript","View transcript"),"aria-label":r("recording.viewTranscript","View transcript"),children:t.jsx(b.NiceIcon,{name:"type",size:14})}),i.state==="ready"&&t.jsx("button",{onClick:()=>n(i),style:Ke,title:r("recording.download","Download"),"aria-label":r("recording.download","Download"),children:t.jsx(b.NiceIcon,{name:"download",size:14})}),t.jsx("button",{onClick:()=>e(i.id),style:{...Ke,color:"var(--nice-danger, #ef4444)"},title:r("recording.delete","Delete"),"aria-label":r("recording.delete","Delete"),children:t.jsx(b.NiceIcon,{name:"trash",size:14})})]})]})]})}function An({recordings:i,onRecordingStart:e,onRecordingStop:n,onRecordingPause:r,onRecordingResume:s,onRecordingDelete:a,onRecordingDownload:o,activeRecordingId:c,sessionType:f="meeting",className:d,style:g,"data-testid":p}){const{t:m}=b.useNiceTranslation(),[h,w]=l.useState(i??[]),[z,u]=l.useState(""),[I,A]=l.useState("all");l.useEffect(()=>{i&&w(i)},[i]);const N=h.find($=>$.id===c),H=(N==null?void 0:N.state)==="recording",E=(N==null?void 0:N.state)==="paused",B=h.filter($=>{const C=I==="all"||$.sessionType===I,j=!z||($.title??"").toLowerCase().includes(z.toLowerCase())||$.id.includes(z);return C&&j}),K=l.useCallback($=>{w(C=>C.filter(j=>j.id!==$)),a==null||a($)},[a]),J=l.useCallback($=>{if(o){o($.id);return}if($.url){const C=document.createElement("a");C.href=$.url,C.download=`${$.title??$.id}.${$.mimeType.includes("mp4")?"mp4":"webm"}`,C.click()}else if($.blob){const C=URL.createObjectURL($.blob),j=document.createElement("a");j.href=C,j.download=`${$.title??$.id}.webm`,j.click(),setTimeout(()=>URL.revokeObjectURL(C),5e3)}},[o]);return t.jsxs("div",{className:d,"data-testid":p,style:{display:"flex",flexDirection:"column",background:"var(--nice-bg, #fff)",borderRadius:10,border:"1px solid var(--nice-border, #e5e7eb)",fontFamily:"system-ui, sans-serif",overflow:"hidden",...g},children:[t.jsxs("div",{style:{padding:"14px 16px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",display:"flex",gap:8,alignItems:"center"},children:[t.jsx(b.NiceIcon,{name:"mic",size:16}),t.jsx("strong",{style:{fontSize:14,color:"var(--nice-text, #111827)",flex:1},children:"Recordings"}),t.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-muted, #9ca3af)"},children:[h.length," total"]})]}),t.jsxs("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[t.jsxs("select",{value:f,disabled:H||E,onChange:()=>{},style:{...mt,flex:0},children:[t.jsx("option",{value:"call",children:m("recording.type.call","Call")}),t.jsx("option",{value:"meeting",children:m("recording.type.meeting","Meeting")}),t.jsx("option",{value:"whiteboard",children:m("recording.type.whiteboard","Whiteboard")}),t.jsx("option",{value:"screen",children:m("recording.type.screen","Screen")})]}),!H&&!E?t.jsxs("button",{onClick:e,style:{...De,background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)"},children:[t.jsx(b.NiceIcon,{name:"circle",size:12})," ",m("recording.start","Start recording")]}):t.jsxs(t.Fragment,{children:[E?t.jsxs("button",{onClick:s,style:{...De,background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)"},children:[t.jsx(b.NiceIcon,{name:"play",size:12})," ",m("recording.resume","Resume")]}):t.jsxs("button",{onClick:r,style:{...De,background:"var(--nice-warning, #f59e0b)",color:"var(--nice-text-on-primary, #fff)"},children:[t.jsx(b.NiceIcon,{name:"pause",size:12})," ",m("recording.pause","Pause")]}),t.jsxs("button",{onClick:n,style:{...De,background:"var(--nice-text, #374151)",color:"var(--nice-text-inverse, #fff)"},children:[t.jsx(b.NiceIcon,{name:"stop",size:12})," ",m("recording.stop","Stop")]}),N&&t.jsx("span",{style:{fontSize:12,color:"var(--nice-text-muted, #9ca3af)",marginLeft:4},children:t.jsx(At,{startedAt:N.startedAt})})]})]}),t.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",display:"flex",gap:6,alignItems:"center"},children:[t.jsx("input",{type:"search",value:z,onChange:$=>u($.target.value),placeholder:m("recording.searchPlaceholder","Search recordings…"),style:{flex:1,padding:"4px 8px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,fontSize:12}}),t.jsxs("select",{value:I,onChange:$=>A($.target.value),style:mt,children:[t.jsx("option",{value:"all",children:m("recording.filter.all","All types")}),t.jsx("option",{value:"call",children:m("recording.filter.calls","Calls")}),t.jsx("option",{value:"meeting",children:m("recording.filter.meetings","Meetings")}),t.jsx("option",{value:"whiteboard",children:m("recording.type.whiteboard","Whiteboard")}),t.jsx("option",{value:"screen",children:m("recording.type.screen","Screen")})]})]}),t.jsx("div",{style:{flex:1,overflowY:"auto"},children:B.length===0?t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:32,gap:8,color:"var(--nice-text-muted, #9ca3af)"},children:[t.jsx(b.NiceIcon,{name:"mic",size:32}),t.jsx("span",{style:{fontSize:13},children:m("recording.empty","No recordings found")}),t.jsx("span",{style:{fontSize:11},children:m("recording.emptyHint","Start a recording above or adjust your search filters.")})]}):B.map($=>t.jsx(Pn,{rec:$,onDelete:K,onDownload:J},$.id))})]})}const Ke={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,background:"var(--nice-bg, #fff)",cursor:"pointer",padding:"4px 8px",fontSize:14,lineHeight:1},De={border:"none",borderRadius:6,cursor:"pointer",padding:"6px 14px",fontSize:12,fontWeight:500,display:"inline-flex",alignItems:"center",gap:4},mt={padding:"4px 6px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,fontSize:12,color:"var(--nice-text, #374151)",background:"var(--nice-bg, #fff)"},En={border:"none",background:"none",cursor:"pointer",fontSize:16,color:"var(--nice-text-muted, #9ca3af)",lineHeight:1,padding:4};function yt({participant:i,isFollowing:e,onClick:n}){const r=i.user.displayName??i.user.name,s=r.split(" ").map(a=>a[0]).slice(0,2).join("").toUpperCase();return t.jsxs("button",{onClick:n,title:`${r}${e?" (following)":""} — ${i.editingRegion??"viewing"}`,style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:"50%",background:i.color,color:"var(--nice-text-on-primary, #fff)",fontSize:11,fontWeight:600,border:`2px solid ${e?"var(--nice-bg, #fff)":i.color}`,boxShadow:e?`0 0 0 2px ${i.color}`:"none",cursor:"pointer",flexShrink:0,transition:"transform 0.15s",position:"relative",overflow:"visible"},children:[i.user.avatarUrl?t.jsx("img",{src:i.user.avatarUrl,alt:s,style:{width:"100%",height:"100%",borderRadius:"50%",objectFit:"cover"}}):s,i.isActive&&t.jsx("span",{style:{position:"absolute",bottom:-1,right:-1,width:9,height:9,borderRadius:"50%",background:"var(--nice-success, #22c55e)",border:"2px solid var(--nice-bg, #FFF)"}})]})}function Dn({participant:i,containerRect:e}){if(!i.cursorX||!i.cursorY||!e)return null;const n=i.cursorX,r=i.cursorY;return t.jsxs("div",{style:{position:"absolute",left:n,top:r,pointerEvents:"none",zIndex:9e3,transform:"translate(-2px, -2px)"},children:[t.jsx("svg",{width:16,height:20,style:{display:"block"},children:t.jsx("path",{d:"M2 2 L2 16 L6 12 L10 18 L12 17 L8 11 L14 11 Z",fill:i.color,stroke:"var(--nice-bg, #fff)",strokeWidth:1.5})}),t.jsx("div",{style:{background:i.color,color:"var(--nice-text-on-primary, #fff)",fontSize:10,padding:"1px 5px",borderRadius:3,whiteSpace:"nowrap",marginTop:-2,marginLeft:10},children:i.user.displayName??i.user.name})]})}function Mn({count:i}){return i===0?null:t.jsxs("div",{style:{position:"absolute",top:8,left:"50%",transform:"translateX(-50%)",zIndex:8e3,background:"var(--nice-warning-bg, #fef3c7)",border:"1px solid var(--nice-warning-light, #fbbf24)",borderRadius:6,padding:"4px 12px",fontSize:12,color:"var(--nice-warning-dark, #92400e)",display:"flex",alignItems:"center",gap:6,boxShadow:"0 2px 8px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",pointerEvents:"none"},children:[t.jsx(b.NiceIcon,{name:"warning",size:12})," ",i," edit conflict",i>1?"s":""," — auto-merging…"]})}function $n(){return t.jsx("div",{style:{position:"absolute",inset:0,zIndex:7e3,background:"var(--nice-overlay-3, rgba(0, 0, 0, 0.03))",cursor:"not-allowed",display:"flex",alignItems:"flex-end",justifyContent:"center",paddingBottom:12,pointerEvents:"none"},children:t.jsxs("div",{style:{background:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",color:"var(--nice-text-on-primary, #fff)",fontSize:12,padding:"4px 14px",borderRadius:20,display:"inline-flex",alignItems:"center",gap:4},children:[t.jsx(b.NiceIcon,{name:"eye",size:12})," View only"]})})}function On({pending:i}){return i===0?t.jsxs("span",{style:{fontSize:11,color:"var(--nice-success, #22c55e)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(b.NiceIcon,{name:"check",size:11})," Synced"]}):t.jsxs("span",{style:{fontSize:11,color:"var(--nice-warning, #f59e0b)",display:"inline-flex",alignItems:"center",gap:3},children:[t.jsx(b.NiceIcon,{name:"upload",size:11})," ",i," pending…"]})}function Ln({participant:i,isFollowing:e,onClick:n}){return t.jsxs("button",{onClick:n,style:{fontSize:11,padding:"2px 8px",border:`1px solid ${e?i.color:"var(--nice-border, #e5e7eb)"}`,borderRadius:20,background:e?i.color:"var(--nice-bg, #fff)",color:e?"var(--nice-text-on-primary, #fff)":"var(--nice-text-secondary, #6b7280)",cursor:"pointer",display:"flex",alignItems:"center",gap:4},children:[t.jsx(b.NiceIcon,{name:"eye",size:11})," ",e?"Unfollow":`Follow ${(i.user.displayName??i.user.name).split(" ")[0]}`]})}function Wn({editorType:i,sessionId:e,currentUser:n,participants:r=[],onOperation:s,onParticipantJoin:a,onParticipantLeave:o,onCursorMove:c,isReadOnly:f=!1,showParticipants:d=!0,showCursors:g=!0,pendingOperations:p=0,conflictCount:m=0,className:h,style:w,children:z,"data-testid":u}){const I=l.useRef(null),[A,N]=l.useState(null),[H,E]=l.useState(null),[B,K]=l.useState(!1);l.useEffect(()=>{const P=I.current;if(!P)return;const T=new ResizeObserver(()=>N(P.getBoundingClientRect()));return T.observe(P),N(P.getBoundingClientRect()),()=>T.disconnect()},[]);const J=l.useCallback(P=>{if(!I.current||!c)return;const T=I.current.getBoundingClientRect();c(P.clientX-T.left,P.clientY-T.top)},[c]),$=l.useCallback(P=>{E(T=>T===P?null:P)},[]),C={vector:{icon:"pen",label:"Vector"},pixel:{icon:"image",label:"Pixel"},diagram:{icon:"bar-chart",label:"Diagram"},document:{icon:"file",label:"Document"},whiteboard:{icon:"edit",label:"Whiteboard"}},j=t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",background:"var(--nice-bg-secondary, #f9fafb)",minHeight:40},children:[t.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",fontWeight:500,display:"inline-flex",alignItems:"center",gap:4},children:[t.jsx(b.NiceIcon,{name:C[i].icon,size:12}),C[i].label]}),t.jsx("span",{style:{flex:1}}),t.jsx(On,{pending:p}),d&&r.length>0&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:-4},children:[r.slice(0,5).map((P,T)=>t.jsx("div",{style:{marginLeft:T>0?-8:0,zIndex:10-T},children:t.jsx(yt,{participant:P,isFollowing:H===P.user.id,onClick:()=>{K(!0),$(P.user.id)}})},P.user.id)),r.length>5&&t.jsxs("button",{onClick:()=>K(!B),style:{marginLeft:-4,zIndex:5,width:30,height:30,borderRadius:"50%",background:"var(--nice-border, #e5e7eb)",border:"2px solid var(--nice-bg, #FFF)",fontSize:10,fontWeight:600,color:"var(--nice-text, #374151)",cursor:"pointer"},children:["+",r.length-5]})]}),d&&r.length>0&&t.jsxs("button",{onClick:()=>K(!B),style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:5,background:B?"var(--nice-primary-bg, #eff6ff)":"var(--nice-bg, #fff)",padding:"3px 8px",cursor:"pointer",fontSize:11,color:B?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #6b7280)"},children:[r.length," online"]})]}),O=t.jsxs("div",{ref:I,onMouseMove:J,style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},children:[z??t.jsxs("div",{id:`collab-editor-${i}-${e}`,style:{width:"100%",height:"100%",minHeight:400,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-bg-secondary, #f9fafb)",color:"var(--nice-text-muted, #9ca3af)",fontSize:13},children:["Drop your ",i," editor here or use the"," ",t.jsx("code",{style:{background:"var(--nice-border, #e5e7eb)",padding:"1px 5px",borderRadius:3,margin:"0 4px"},children:`#collab-editor-${i}-${e}`})," ","mount point."]}),g&&r.filter(P=>P.user.id!==n.id&&P.cursorX!=null&&P.cursorY!=null).map(P=>t.jsx(Dn,{participant:P,containerRect:A},P.user.id)),t.jsx(Mn,{count:m}),f&&t.jsx($n,{})]}),U=B&&r.length>0?t.jsxs("div",{style:{width:220,height:"100%",borderLeft:"1px solid var(--nice-border, #e5e7eb)",background:"var(--nice-bg-secondary, #f9fafb)",overflowY:"auto",padding:10,display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[t.jsx("strong",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:"Participants"}),t.jsx("button",{onClick:()=>K(!1),style:{border:"none",background:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",fontSize:14},"aria-label":"Close",children:t.jsx(b.NiceIcon,{name:"close",size:14})})]}),r.map(P=>t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"8px",borderRadius:6,background:"var(--nice-bg, #fff)",border:"1px solid var(--nice-bg-secondary, #f3f4f6)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx(yt,{participant:P,isFollowing:H===P.user.id,onClick:()=>$(P.user.id)}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:12,fontWeight:500,color:"var(--nice-text, #111827)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:P.user.displayName??P.user.name}),t.jsx("div",{style:{fontSize:10,color:"var(--nice-text-muted, #9ca3af)"},children:P.editingRegion??"viewing"})]})]}),P.user.id!==n.id&&t.jsx(Ln,{participant:P,isFollowing:H===P.user.id,onClick:()=>$(P.user.id)})]},P.user.id))]}):void 0;return t.jsx(b.NiceAppShell,{flush:!0,className:h,"data-testid":u,style:{background:"var(--nice-bg, #fff)",fontFamily:"system-ui, sans-serif",...w},menubar:j,rightSidebar:U,children:O})}function rt(i){let e="";for(let n=0;n<i.length;n++)e+=String.fromCharCode(i[n]);return btoa(e)}function st(i){const e=atob(i),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Fn(i){return new TextEncoder().encode(i)}function _n(i){return new TextDecoder().decode(i)}async function Bn(i){return crypto.subtle.generateKey({name:"AES-GCM",length:i},!0,["encrypt","decrypt"])}async function Un(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-384"},!0,["deriveKey"])}async function Hn(i,e){return crypto.subtle.deriveKey({name:"ECDH",public:e},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Kn(i,e){const n=crypto.getRandomValues(new Uint8Array(12)),r=Fn(e),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},i,r),a=new Uint8Array(s),o=new Uint8Array(12+a.length);return o.set(n,0),o.set(a,12),rt(o)}async function Yn(i,e){const n=st(e),r=n.slice(0,12),s=n.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},i,s);return _n(new Uint8Array(a))}async function xt(i,e){const n=st(i);return crypto.subtle.importKey("raw",n,{name:"AES-GCM",length:e},!1,["encrypt","decrypt"])}async function Gn(i){const e=await crypto.subtle.exportKey("raw",i);return rt(new Uint8Array(e))}async function qn(i){const e=await crypto.subtle.exportKey("spki",i);return rt(new Uint8Array(e))}async function Vn(i){const e=st(i);return crypto.subtle.importKey("spki",e,{name:"ECDH",namedCurve:"P-384"},!0,[])}class Et{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 xt(this.config.keyMaterial,128):this.keys.aes256=await xt(this.config.keyMaterial,256);else if(e==="AES-GCM-256"||e==="AES-GCM-128"){const n=e==="AES-GCM-256"?256:128,r=await Bn(n);n===128?this.keys.aes128=r:this.keys.aes256=r}else if(e==="E2E-ECDH-P384"){const n=await Un();this.keys.ecdhPrivate=n.privateKey,this.keys.ecdhPublic=n.publicKey,this.keys.ecdhSessionKeys=new Map}this.ready=!0}async getPublicKeyForPeer(){return this.keys.ecdhPublic?qn(this.keys.ecdhPublic):null}async registerPeerPublicKey(e,n){var a;if(!this.keys.ecdhPrivate)return;const r=await Vn(n),s=await Hn(this.keys.ecdhPrivate,r);(a=this.keys.ecdhSessionKeys)==null||a.set(e,s)}resolveAlgorithm(e){if(e&&this.config.scopeOverrides){const n=this.config.scopeOverrides.find(r=>(r.scope===e||r.scope==="all")&&r.enabled);if(n)return n.algorithm}return this.config.defaultAlgorithm}getKey(e,n){var r;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 n?((r=this.keys.ecdhSessionKeys)==null?void 0:r.get(n))??null:null;default:return null}}async encrypt(e,n,r){if(!this.config.enabled)return e;if(!this.ready)throw new Error("EncryptionService not initialised — call init() first");const s=this.resolveAlgorithm(n);if(s==="none")return e;const a=this.getKey(s,r);return a?Kn(a,e):(console.warn(`EncryptionService: no key found for algorithm "${s}" — returning plaintext`),e)}async decrypt(e,n,r){if(!this.config.enabled)return e;if(!this.ready)throw new Error("EncryptionService not initialised — call init() first");const s=this.resolveAlgorithm(n);if(s==="none")return e;const a=this.getKey(s,r);return a?Yn(a,e):(console.warn(`EncryptionService: no key found for algorithm "${s}" — returning as-is`),e)}async exportSymmetricKey(e){const n=e??this.config.defaultAlgorithm,r=this.getKey(n);return r?Gn(r):null}isEnabled(){return this.config.enabled}getConfig(){return this.config}updateConfig(e){this.config=e,this.ready=!1}}const $e=new Map;function Xn(i,e){return $e.has(i)||$e.set(i,new Et(e)),$e.get(i)}function Jn(i){$e.delete(i)}class Dt{constructor(e={}){this.recorder=null,this.chunks=[],this.session=null,this.recognition=null,this.segmentCounter=0,this.callbacks=e}start(e,n){var c,f,d;if(((c=this.recorder)==null?void 0:c.state)==="recording")throw new Error("Recording already in progress");const r=n.mimeType??this.chooseMimeType(),s=new MediaRecorder(e,{mimeType:r});this.chunks=[];const a=new Date,o=`rec_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return this.session={id:o,sessionType:n.sessionType,startedAt:a,state:"recording",mimeType:r,participants:[n.speakerId??"unknown"],title:n.title??`Recording ${a.toLocaleString()}`},s.ondataavailable=g=>{g.data&&g.data.size>0&&this.chunks.push(g.data)},s.onstop=()=>{var p,m,h,w;const g=new Blob(this.chunks,{type:r});this.session&&(this.session.blob=g,this.session.endedAt=new Date,this.session.durationMs=this.session.endedAt.getTime()-this.session.startedAt.getTime(),this.session.size=g.size,this.session.state="ready"),(m=(p=this.callbacks).onDataAvailable)==null||m.call(p,g),(w=(h=this.callbacks).onStateChange)==null||w.call(h,"ready")},s.onerror=g=>{var p,m,h,w;(m=(p=this.callbacks).onError)==null||m.call(p,new Error(String(g))),this.session&&(this.session.state="failed"),(w=(h=this.callbacks).onStateChange)==null||w.call(h,"failed")},s.start(n.timesliceMs??1e3),this.recorder=s,n.transcribe&&this.startTranscription(n.speakerId??"unknown",n.speakerName??"Participant"),(d=(f=this.callbacks).onStateChange)==null||d.call(f,"recording"),this.session}pause(){var e,n,r;((e=this.recorder)==null?void 0:e.state)==="recording"&&(this.recorder.pause(),this.session&&(this.session.state="paused"),(r=(n=this.callbacks).onStateChange)==null||r.call(n,"paused"))}resume(){var e,n,r;((e=this.recorder)==null?void 0:e.state)==="paused"&&(this.recorder.resume(),this.session&&(this.session.state="recording"),(r=(n=this.callbacks).onStateChange)==null||r.call(n,"recording"))}stop(){var e,n;return this.stopTranscription(),this.recorder&&this.recorder.state!=="inactive"&&(this.recorder.stop(),this.session&&(this.session.state="processing"),(n=(e=this.callbacks).onStateChange)==null||n.call(e,"processing")),this.session}startTranscription(e,n){const r=window,s=r.SpeechRecognition??r.webkitSpeechRecognition;if(!s)return;const a=new s;a.continuous=!0,a.interimResults=!1,a.lang="en-US";const o=Date.now();a.onresult=c=>{var d,g;const f=c.results;for(let p=c.resultIndex;p<f.length;p++){const m=f[p];if(!m.isFinal)continue;const h=m[0],w=Date.now(),z={id:`seg_${++this.segmentCounter}`,speakerId:e,speakerName:n,text:h.transcript.trim(),startMs:w-o-1500,endMs:w-o,confidence:h.confidence??.9};this.session&&(this.session.transcript=[...this.session.transcript??[],z]),(g=(d=this.callbacks).onTranscriptSegment)==null||g.call(d,z)}},a.onerror=()=>{};try{a.start(),this.recognition=a}catch{}}stopTranscription(){var e;try{(e=this.recognition)==null||e.stop()}catch{}this.recognition=null}chooseMimeType(){const e=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm","audio/webm;codecs=opus","audio/ogg;codecs=opus"];for(const n of e)if(MediaRecorder.isTypeSupported(n))return n;return""}getState(){var e;return((e=this.session)==null?void 0:e.state)??"idle"}getSession(){return this.session}download(e){var a,o;const n=(a=this.session)==null?void 0:a.blob;if(!n)return;const r=URL.createObjectURL(n),s=document.createElement("a");s.href=r,s.download=e??`${((o=this.session)==null?void 0:o.title)??"recording"}.webm`,s.click(),setTimeout(()=>URL.revokeObjectURL(r),3e4)}}const Oe=new Map;function Qn(i,e){return Oe.has(i)||Oe.set(i,new Dt(e)),Oe.get(i)}function Zn(i){Oe.delete(i)}class Mt{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 n=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,metadata:e.metadata}),r=e.width??1,s=e.height??1,a=`${this.config.serverUrl}${this.config.pixelPath}?${n}`;return`<img src="${this.escapeHtml(a)}" width="${r}" height="${s}" alt="" style="display:block;width:${r}px;height:${s}px;border:0;" />`}generateTrackingPixelUrl(e){const n=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,metadata:e.metadata});return`${this.config.serverUrl}${this.config.pixelPath}?${n}`}wrapLink(e){const n=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,url:e.url,linkName:e.linkName});return`${this.config.serverUrl}${this.config.redirectPath}?${n}`}wrapLinksForTracking(e,n){const r=n.excludePatterns??[/^mailto:/i,/^tel:/i,/^#/,/unsubscribe/i],s=/<a\s+([^>]*?)href=["']([^"']+)["']([^>]*?)>/gi;return e.replace(s,(a,o,c,f)=>{if(r.some(m=>m.test(c)))return a;const g=this.extractLinkName(o+f)??c,p=this.wrapLink({url:c,messageId:n.messageId,recipientId:n.recipientId,campaignId:n.campaignId,linkName:g});return`<a ${o}href="${this.escapeHtml(p)}"${f}>`})}recordEvent(e){const n={...e,id:this.generateEventId(),timestamp:new Date,ipAddress:this.config.anonymizeIp?this.anonymizeIpAddress(e.ipAddress):e.ipAddress};return this.events.push(n),this.notifyListeners(n),n}parseTrackingParams(e){const n=e.get("mid"),r=e.get("rid");if(!n||!r)return null;const s={};return e.forEach((a,o)=>{o.startsWith("m_")&&(s[o.substring(2)]=a)}),{messageId:n,recipientHash:r,campaignId:e.get("cid")??void 0,url:e.get("url")??void 0,linkName:e.get("ln")??void 0,metadata:Object.keys(s).length>0?s:void 0}}getStats(e){let n=this.events;e&&(n=this.events.filter(m=>!(e.campaignId&&m.campaignId!==e.campaignId||e.messageId&&m.messageId!==e.messageId||e.startDate&&m.timestamp<e.startDate||e.endDate&&m.timestamp>e.endDate)));const r=new Set(n.map(m=>m.recipientHash)),s=n.filter(m=>m.type==="open"),a=n.filter(m=>m.type==="click"),o=n.filter(m=>m.type==="bounce"),c=n.filter(m=>m.type==="unsubscribe"),f=n.filter(m=>m.type==="complaint"),d=new Set(s.map(m=>m.recipientHash)).size,g=new Set(a.map(m=>m.recipientHash)).size,p=r.size;return{sent:p+o.length,delivered:p,opens:s.length,uniqueOpens:d,clicks:a.length,uniqueClicks:g,bounces:o.length,unsubscribes:c.length,complaints:f.length,openRate:p>0?d/p:0,clickRate:p>0?g/p:0,clickToOpenRate:d>0?g/d:0,bounceRate:p>0?o.length/(p+o.length):0}}getLinkStats(e){let n=this.events.filter(o=>o.type==="click"&&o.url);e&&(n=n.filter(o=>!(e.campaignId&&o.campaignId!==e.campaignId||e.messageId&&o.messageId!==e.messageId)));const r=new Map;for(const o of n){const c=o.url;r.has(c)||r.set(c,{url:c,linkName:void 0,total:0,unique:new Set});const f=r.get(c);f.total++,f.unique.add(o.recipientHash)}const s=n.length,a=[];for(const[,o]of r)a.push({url:o.url,linkName:o.linkName,totalClicks:o.total,uniqueClicks:o.unique.size,clickShare:s>0?o.total/s:0});return a.sort((o,c)=>c.totalClicks-o.totalClicks)}getDeviceStats(e){let n=this.events.filter(s=>s.type==="open");e!=null&&e.campaignId&&(n=n.filter(s=>s.campaignId===e.campaignId));const r={desktop:0,mobile:0,tablet:0,unknown:0};for(const s of n){const a=s.device??"unknown";r[a]=(r[a]??0)+1}return r}on(e,n){return this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(n),()=>{var r;(r=this.eventListeners.get(e))==null||r.delete(n)}}onAny(e){const n=["open","click","bounce","unsubscribe","complaint"].map(r=>this.on(r,e));return()=>{n.forEach(r=>r())}}generateUnsubscribeLink(e){const n=new URLSearchParams;return n.set("rid",this.hashRecipientId(e.recipientId)),e.listId&&n.set("lid",e.listId),n.set("action","unsubscribe"),`${this.config.serverUrl}/unsubscribe?${n.toString()}`}generateListUnsubscribeHeader(e){return`<${this.generateUnsubscribeLink(e)}>`}clearEvents(){this.events=[]}exportEvents(e){return e!=null&&e.anonymize?this.events.map(n=>({...n,recipientHash:"anonymized",ipAddress:void 0,userAgent:void 0})):[...this.events]}buildTrackingParams(e){const n=new URLSearchParams;if(n.set("mid",e.messageId),n.set("rid",this.hashRecipientId(e.recipientId)),e.campaignId&&n.set("cid",e.campaignId),e.url&&n.set("url",e.url),e.linkName&&n.set("ln",e.linkName),e.metadata)for(const[r,s]of Object.entries(e.metadata))n.set(`m_${r}`,s);return n.toString()}hashRecipientId(e){let n=0;for(let r=0;r<e.length;r++){const s=e.charCodeAt(r);n=(n<<5)-n+s,n=n&n}return Math.abs(n).toString(36)}anonymizeIpAddress(e){if(e){if(e.includes(".")){const n=e.split(".");return n[3]="0",n.join(".")}return e.includes(":")?e.split(":").slice(0,3).join(":")+"::":e}}extractLinkName(e){const n=e.match(/title=["']([^"']+)["']/i);if(n)return n[1];const r=e.match(/data-link-name=["']([^"']+)["']/i);if(r)return r[1]}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}generateEventId(){return`evt_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}notifyListeners(e){const n=this.eventListeners.get(e.type);if(n)for(const r of n)try{r(e)}catch(s){console.error("Tracking event listener error:",s)}}}let me=null;function Ve(i){if(!me&&i&&(me=new Mt(i)),!me)throw new Error("EmailTrackingService not initialized. Call with config first.");return me}function ei(){me==null||me.clearEvents(),me=null}function ti(i){const{config:e,campaignId:n,autoRefreshInterval:r}=i,s=l.useMemo(()=>{if(e)return Ve(e);try{return Ve()}catch{return null}},[e]),[a,o]=l.useState(null),[c,f]=l.useState([]),d=l.useCallback(()=>{s&&(o(s.getStats({campaignId:n})),f(s.getLinkStats({campaignId:n})))},[s,n]);l.useEffect(()=>{if(d(),r&&s){const h=setInterval(d,r);return()=>clearInterval(h)}},[d,r,s]),l.useEffect(()=>{if(s)return s.onAny(()=>{d()})},[s,d]);const g=l.useCallback((h,w)=>s?s.generateTrackingPixel({messageId:h,recipientId:w,campaignId:n}):"",[s,n]),p=l.useCallback((h,w,z)=>s?s.wrapLinksForTracking(h,{messageId:w,recipientId:z,campaignId:n}):h,[s,n]),m=l.useCallback(h=>{s==null||s.recordEvent(h)},[s]);return{generatePixel:g,wrapLinks:p,stats:a,linkStats:c,recordEvent:m,refreshStats:d}}class $t{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 n={...e,id:this.generateId("tpl"),createdAt:new Date,updatedAt:new Date};return this.templates.set(n.id,n),n}updateTemplate(e,n){const r=this.templates.get(e);if(!r)throw new Error(`Template not found: ${e}`);const s={...r,...n,updatedAt:new Date};return this.templates.set(e,s),s}getTemplate(e){return this.templates.get(e)}deleteTemplate(e){return this.templates.delete(e)}listTemplates(){return Array.from(this.templates.values())}extractFields(e){const n=/\{\{([^}]+)\}\}/g,r=new Set;let s;for(;(s=n.exec(e))!==null;){const a=s[1].trim();if(a.startsWith("#if "))r.add(a.substring(4).trim());else if(a.startsWith("#unless "))r.add(a.substring(8).trim());else if(a.startsWith("#each "))r.add(a.substring(6).trim());else if(!a.startsWith("/")&&!a.startsWith("else")){const[o]=a.split("|");r.add(o.trim())}}return Array.from(r)}createCampaign(e){if(!this.templates.has(e.templateId))throw new Error(`Template not found: ${e.templateId}`);const n={...e,id:this.generateId("cmp"),status:"draft",recipients:e.recipients.map(r=>({...r,status:"pending"})),createdAt:new Date};return this.campaigns.set(n.id,n),n}getCampaign(e){return this.campaigns.get(e)}updateCampaign(e,n){const r=this.campaigns.get(e);if(!r)throw new Error(`Campaign not found: ${e}`);if(r.status==="sending")throw new Error("Cannot update campaign while sending");const s={...r,...n};return this.campaigns.set(e,s),s}addRecipients(e,n){const r=this.campaigns.get(e);if(!r)throw new Error(`Campaign not found: ${e}`);if(r.status==="sending")throw new Error("Cannot add recipients while sending");const s=n.map(a=>({...a,status:"pending"}));r.recipients.push(...s),this.campaigns.set(e,r)}removeRecipient(e,n){const r=this.campaigns.get(e);if(!r)return!1;const s=r.recipients.findIndex(a=>a.id===n);return s===-1?!1:(r.recipients.splice(s,1),!0)}listCampaigns(){return Array.from(this.campaigns.values())}validateCampaign(e){const n=this.campaigns.get(e);if(!n)return{isValid:!1,errors:[{type:"syntax_error",message:"Campaign not found"}],warnings:[],missingFields:new Map};const r=this.templates.get(n.templateId);if(!r)return{isValid:!1,errors:[{type:"syntax_error",message:"Template not found"}],warnings:[],missingFields:new Map};const s=[],a=[],o=new Map;n.recipients.length===0&&s.push({type:"empty_recipient",message:"No recipients in campaign"});for(const d of n.recipients){if(!d.email){s.push({type:"empty_recipient",recipientId:d.id,message:`Recipient ${d.id} has no email address`});continue}const g=[];for(const p of r.fields)p.required&&!(p.name in d.data)&&(g.push(p.name),s.push({type:"missing_field",field:p.name,recipientId:d.id,message:`Required field "${p.name}" missing for ${d.email}`}));g.length>0&&o.set(d.id,g)}const c=this.extractFields(r.subject+r.htmlBody+(r.textBody??"")),f=r.fields.map(d=>d.name);for(const d of c)f.includes(d)||a.push({type:"unused_field",field:d,message:`Field "${d}" used in template but not defined`});return{isValid:s.length===0,errors:s,warnings:a,missingFields:o}}previewMerge(e,n){const r=this.templates.get(e);if(!r)throw new Error(`Template not found: ${e}`);return{subject:this.processTemplate(r.subject,n,r.fields),html:this.processTemplate(r.htmlBody,n,r.fields),text:r.textBody?this.processTemplate(r.textBody,n,r.fields):void 0}}async*sendCampaign(e){const n=this.campaigns.get(e);if(!n)throw new Error(`Campaign not found: ${e}`);const r=this.templates.get(n.templateId);if(!r)throw new Error(`Template not found: ${n.templateId}`);const s=this.validateCampaign(e);if(!s.isValid)throw new Error(`Campaign validation failed: ${s.errors.map(m=>m.message).join(", ")}`);n.status="sending",n.startedAt=new Date,this.campaigns.set(e,n);const a=new AbortController;this.abortControllers.set(e,a);const o=n.recipients.filter(m=>m.status==="pending"),c=o.length;let f=0,d=0;const g=Date.now(),p=60*1e3/(n.rateLimit??this.config.rateLimit);try{for(let m=0;m<o.length;m++){if(a.signal.aborted){n.status="paused";break}const h=o[m];try{const N=this.previewMerge(r.id,h.data),H=await this.config.sendEmail({to:h.email,cc:h.cc,bcc:h.bcc,from:n.fromEmail,fromName:n.fromName,replyTo:n.replyTo,subject:h.subjectOverride??N.subject,html:N.html,text:N.text});H.success?(h.status="sent",f++):(h.status="failed",h.error=H.error,d++)}catch(N){h.status="failed",h.error=N instanceof Error?N.message:"Unknown error",d++}const w=f+d,z=Date.now()-g,u=w>0?z/w:p,I=c-w,A=Math.round(I*u/1e3);yield{campaignId:e,total:c,sent:f,failed:d,pending:c-w,current:h.email,percentage:Math.round(w/c*100),estimatedTimeRemaining:A,isComplete:!1},m<o.length-1&&await this.delay(p)}n.status="completed",n.completedAt=new Date,this.campaigns.set(e,n),yield{campaignId:e,total:c,sent:f,failed:d,pending:0,percentage:100,isComplete:!0}}finally{this.abortControllers.delete(e)}}pauseCampaign(e){const n=this.abortControllers.get(e);n&&n.abort();const r=this.campaigns.get(e);r&&r.status==="sending"&&(r.status="paused",this.campaigns.set(e,r))}async*resumeCampaign(e){const n=this.campaigns.get(e);if(!n)throw new Error(`Campaign not found: ${e}`);if(n.status!=="paused")throw new Error("Campaign is not paused");n.status="draft",this.campaigns.set(e,n),yield*this.sendCampaign(e)}cancelCampaign(e){this.pauseCampaign(e);const n=this.campaigns.get(e);n&&(n.status="cancelled",this.campaigns.set(e,n))}async*retryFailed(e){const n=this.campaigns.get(e);if(!n)throw new Error(`Campaign not found: ${e}`);for(const r of n.recipients)r.status==="failed"&&(r.status="pending",r.error=void 0);n.status="draft",this.campaigns.set(e,n),yield*this.sendCampaign(e)}processTemplate(e,n,r){const s=new Map(r.map(a=>[a.name,a]));return e=this.processConditionals(e,n),e=this.processLoops(e,n),e=e.replace(/\{\{([^}#/]+)\}\}/g,(a,o)=>{const[c,...f]=o.trim().split("|").map(p=>p.trim());let d=this.getNestedValue(n,c);const g=s.get(c);d==null&&(d=(g==null?void 0:g.defaultValue)??""),g&&d!==""&&(d=this.formatValue(d,g));for(const p of f)d=this.applyFormatter(d,p);return String(d)}),e}processConditionals(e,n){const r=/\{\{#if\s+([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g;return e.replace(r,(s,a,o,c="")=>{const f=this.getNestedValue(n,a.trim());return this.isTruthy(f)?o:c})}processLoops(e,n){const r=/\{\{#each\s+([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g;return e.replace(r,(s,a,o)=>{const c=this.getNestedValue(n,a.trim());return Array.isArray(c)?c.map((f,d)=>{let g=o;return typeof f!="object"&&(g=g.replace(/\{\{this\}\}/g,String(f))),g=g.replace(/\{\{this\.([^}]+)\}\}/g,(p,m)=>String(this.getNestedValue(f,m)??"")),g=g.replace(/\{\{@index\}\}/g,String(d)),g=g.replace(/\{\{@first\}\}/g,String(d===0)),g=g.replace(/\{\{@last\}\}/g,String(d===c.length-1)),g}).join(""):""})}formatValue(e,n){switch(n.type){case"date":return e instanceof Date?this.config.dateFormatter(e,n.format??"short"):typeof e=="string"||typeof e=="number"?this.config.dateFormatter(new Date(e),n.format??"short"):String(e);case"number":return typeof e=="number"?this.config.numberFormatter(e,n.format??""):String(e);case"currency":if(typeof e=="number"){const[r="USD",s="en-US"]=(n.format??"USD|en-US").split("|");return this.config.currencyFormatter(e,r,s)}return String(e);case"boolean":return e?"Yes":"No";case"list":return Array.isArray(e)?e.join(n.format??", "):String(e);default:return String(e)}}applyFormatter(e,n){const r=String(e);switch(n.toLowerCase()){case"uppercase":return r.toUpperCase();case"lowercase":return r.toLowerCase();case"capitalize":return r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();case"titlecase":return r.replace(/\b\w/g,s=>s.toUpperCase());case"trim":return r.trim();case"escape":return this.escapeHtml(r);default:return r}}getNestedValue(e,n){const r=n.split(".");let s=e;for(const a of r){if(s==null)return;s=s[a]}return s}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,n){const r={};switch(n){case"short":r.dateStyle="short";break;case"medium":r.dateStyle="medium";break;case"long":r.dateStyle="long";break;case"full":r.dateStyle="full";break;case"iso":return e.toISOString();default:r.dateStyle="medium"}return new Intl.DateTimeFormat("en-US",r).format(e)}defaultNumberFormatter(e,n){if(!n)return new Intl.NumberFormat().format(e);const r=parseInt(n,10);return isNaN(r)?String(e):new Intl.NumberFormat("en-US",{minimumFractionDigits:r,maximumFractionDigits:r}).format(e)}defaultCurrencyFormatter(e,n,r){return new Intl.NumberFormat(r,{style:"currency",currency:n}).format(e)}generateId(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}delay(e){return new Promise(n=>setTimeout(n,e))}}let Te=null;function Xe(i){if(!Te&&i&&(Te=new $t(i)),!Te)throw new Error("MailMergeService not initialized. Call with config first.");return Te}function ni(){Te=null}function ii(i={}){const{config:e}=i,n=l.useMemo(()=>{if(e)return Xe(e);try{return Xe()}catch{return null}},[e]),[r,s]=l.useState(null),[a,o]=l.useState(!1),[c,f]=l.useState([]),[d,g]=l.useState([]),p=l.useCallback(()=>{n&&(f(n.listTemplates()),g(n.listCampaigns()))},[n]),m=l.useCallback(A=>{if(!n)throw new Error("Service not initialized");const N=n.createTemplate(A);return p(),N},[n,p]),h=l.useCallback(A=>{if(!n)throw new Error("Service not initialized");const N=n.createCampaign(A);return p(),N},[n,p]),w=l.useCallback((A,N)=>{if(!n)throw new Error("Service not initialized");return n.previewMerge(A,N)},[n]),z=l.useCallback(A=>{if(!n)throw new Error("Service not initialized");return n.validateCampaign(A)},[n]),u=l.useCallback(async function*(A){if(!n)throw new Error("Service not initialized");o(!0);try{for await(const N of n.sendCampaign(A))s(N),yield N}finally{o(!1),p()}},[n,p]),I=l.useCallback(A=>{n==null||n.pauseCampaign(A),o(!1),p()},[n,p]);return{createTemplate:m,createCampaign:h,preview:w,validate:z,send:u,pause:I,progress:r,isSending:a,templates:c,campaigns:d}}class Ot{constructor(e){this.abortController=null,this.mapping={users:new Map,channels:new Map,files:new Map},this.config=e}async parseSlackExport(e){const n=await this.extractZipContents(e),r=n.get("users.json"),s=r?JSON.parse(r):[],a=n.get("channels.json"),o=a?JSON.parse(a):[],c=n.get("groups.json");if(c){const g=JSON.parse(c);o.push(...g.map(p=>({...p,is_private:!0})))}const f=n.get("dms.json");if(f){const g=JSON.parse(f);o.push(...g.map(p=>({...p,is_im:!0})))}const d=new Map;for(const g of o){const p=[],m=g.name;for(const[h,w]of n)if(h.startsWith(m+"/")&&h.endsWith(".json"))try{const z=JSON.parse(w);p.push(...z)}catch(z){console.warn(`Failed to parse messages from ${h}:`,z)}p.length>0&&d.set(g.id,p)}return{users:s,channels:o,messages:d}}parseSlackExportFromJson(e){return{users:e.users??[],channels:e.channels??[],messages:new Map(Object.entries(e.messages??{})),files:e.files}}previewImport(e,n={}){const r=e.users.filter(p=>n.importUsers!==!1&&!p.deleted),s=r.map(p=>this.mapUser(p)),a=e.channels.filter(p=>!(n.skipArchived&&p.is_archived||n.skipDirectMessages&&(p.is_im||p.is_mpim)||n.channelFilter&&!n.channelFilter.includes(p.id)&&!n.channelFilter.includes(p.name))),o=a.map(p=>this.mapChannel(p,new Map));let c=0;const f=new Map;for(const[p,m]of e.messages){const h=e.channels.find(u=>u.id===p);if(!h||!a.some(u=>u.id===p))continue;const z=this.filterMessages(m,n);f.set(h.name,z.length),c+=z.length}let d=0,g=0;for(const p of e.messages.values())for(const m of p)m.files&&(d+=m.files.length,g+=m.files.reduce((h,w)=>h+(w.size||0),0));return{users:{total:e.users.length,filtered:r.length,items:s},channels:{total:e.channels.length,filtered:a.length,items:o},messages:{total:c,perChannel:f},files:{total:d,totalSize:g}}}async*import(e,n={}){this.abortController=new AbortController,this.mapping={users:new Map,channels:new Map,files:new Map};const r=[],s={usersImported:0,channelsImported:0,messagesImported:0,filesImported:0,reactionsImported:0,threadsImported:0},a=new Date,c=1e3/(this.config.rateLimit??10);try{if(n.importUsers!==!1){const d=e.users.filter(p=>!p.deleted);let g=0;for(const p of d){if(this.abortController.signal.aborted)break;const m=this.mapUser(p),h=await this.config.createUser(m);h.success&&h.id?(this.mapping.users.set(p.id,h.id),s.usersImported++):r.push({phase:"users",itemId:p.id,itemType:"user",message:h.error??"Failed to create user"}),g++,yield{phase:"users",total:d.length,processed:g,failed:r.filter(w=>w.phase==="users").length,current:p.name,percentage:Math.round(g/d.length*100),isComplete:!1,errors:r},await this.delay(c)}}if(n.importChannels!==!1){const d=e.channels.filter(p=>{var m;return n.skipArchived&&p.is_archived||n.skipDirectMessages&&(p.is_im||p.is_mpim)?!1:(m=n.channelFilter)!=null&&m.length?n.channelFilter.includes(p.id)||n.channelFilter.includes(p.name):!0});let g=0;for(const p of d){if(this.abortController.signal.aborted)break;const m=this.mapChannel(p,this.mapping.users),h=await this.config.createChannel(m);h.success&&h.id?(this.mapping.channels.set(p.id,h.id),s.channelsImported++):r.push({phase:"channels",itemId:p.id,itemType:"channel",message:h.error??"Failed to create channel"}),g++,yield{phase:"channels",total:d.length,processed:g,failed:r.filter(w=>w.phase==="channels").length,current:p.name,percentage:Math.round(g/d.length*100),isComplete:!1,errors:r},await this.delay(c)}}if(n.importMessages!==!1){const d=[];for(const[m,h]of e.messages){if(!this.mapping.channels.has(m))continue;const w=this.filterMessages(h,n);for(const z of w)d.push({channelId:m,message:z})}d.sort((m,h)=>parseFloat(m.message.ts)-parseFloat(h.message.ts));const g=new Map;let p=0;for(const{channelId:m,message:h}of d){if(this.abortController.signal.aborted)break;const w=this.mapMessage(h,m,this.mapping,g),z=await this.config.createMessage(w);z.success&&z.id?((!h.thread_ts||h.thread_ts===h.ts)&&g.set(h.ts,z.id),s.messagesImported++,w.isThreadReply&&s.threadsImported++,s.reactionsImported+=w.reactions.length):r.push({phase:"messages",itemId:h.ts,itemType:"message",message:z.error??"Failed to create message"}),p++,yield{phase:"messages",total:d.length,processed:p,failed:r.filter(u=>u.phase==="messages").length,current:`${p}/${d.length}`,percentage:Math.round(p/d.length*100),isComplete:!1,errors:r},await this.delay(c)}}if(n.importFiles&&n.downloadFiles&&this.config.uploadFile&&this.config.downloadFile){const d=[];for(const p of e.messages.values())for(const m of p)m.files&&d.push(...m.files);let g=0;for(const p of d){if(this.abortController.signal.aborted)break;try{const m=p.url_private_download??p.url_private;if(m&&this.config.slackToken){const h=await this.config.downloadFile(m,this.config.slackToken),w=await this.config.uploadFile(p,h);w.success&&w.url?(this.mapping.files.set(p.id,w.url),s.filesImported++):r.push({phase:"files",itemId:p.id,itemType:"file",message:w.error??"Failed to upload file"})}}catch(m){r.push({phase:"files",itemId:p.id,itemType:"file",message:m instanceof Error?m.message:"File download failed"})}g++,yield{phase:"files",total:d.length,processed:g,failed:r.filter(m=>m.phase==="files").length,current:p.name,percentage:Math.round(g/d.length*100),isComplete:!1,errors:r},await this.delay(c)}}const f=new Date;return yield{phase:"complete",total:0,processed:0,failed:r.length,percentage:100,isComplete:!0,errors:r},{status:(r.length>0,"completed"),stats:s,mapping:this.mapping,errors:r,startedAt:a,completedAt:f,duration:f.getTime()-a.getTime()}}finally{this.abortController=null}}cancel(){var e;(e=this.abortController)==null||e.abort()}mapUser(e){var n,r,s,a,o;return{slackId:e.id,email:e.email,displayName:((n=e.profile)==null?void 0:n.display_name)||e.name,realName:e.real_name,avatarUrl:((r=e.profile)==null?void 0:r.image_192)||((s=e.profile)==null?void 0:s.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,n){var s,a;let r="public";return e.is_private&&(r="private"),e.is_im&&(r="dm"),e.is_mpim&&(r="mpim"),{slackId:e.id,name:e.name,type:r,description:(s=e.purpose)==null?void 0:s.value,topic:(a=e.topic)==null?void 0:a.value,isArchived:e.is_archived??!1,creatorId:e.creator?n.get(e.creator):void 0,memberIds:(e.members??[]).map(o=>n.get(o)).filter(o=>!!o),createdAt:e.created?new Date(e.created*1e3):void 0}}mapMessage(e,n,r,s){const a=r.channels.get(n)??n,o=e.user?r.users.get(e.user):void 0,{text:c,html:f}=this.convertSlackMessage(e.text,r.users),d=e.thread_ts!==void 0&&e.thread_ts!==e.ts,g=e.thread_ts?s.get(e.thread_ts):void 0,p=[];if(e.files)for(const h of e.files)p.push({type:h.mimetype.startsWith("image/")?"image":"file",url:r.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?p.push({type:"image",url:h.image_url}):h.title_link&&p.push({type:"link",url:h.title_link,name:h.title});const m=(e.reactions??[]).map(h=>({emoji:h.name,userIds:h.users.map(w=>r.users.get(w)).filter(w=>!!w),count:h.count}));return{channelId:a,senderId:o,content:c,htmlContent:f,threadId:g,isThreadReply:d,attachments:p,reactions:m,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,n){let r=e,s=this.escapeHtml(e);const a=/<@([A-Z0-9]+)(?:\|([^>]+))?>/g;return r=r.replace(a,(o,c,f)=>f?`@${f}`:"@user"),s=s.replace(/&lt;@([A-Z0-9]+)(?:\|([^&]+))?&gt;/g,(o,c,f)=>`<span class="mention" data-user-id="${n.get(c)??c}">@${f??"user"}</span>`),r=r.replace(/<#([A-Z0-9]+)\|([^>]+)>/g,"#$2"),s=s.replace(/&lt;#([A-Z0-9]+)\|([^&]+)&gt;/g,'<span class="channel-mention">#$2</span>'),r=r.replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)"),r=r.replace(/<(https?:\/\/[^>]+)>/g,"$1"),s=s.replace(/&lt;(https?:\/\/[^|&]+)\|([^&]+)&gt;/g,'<a href="$1">$2</a>'),s=s.replace(/&lt;(https?:\/\/[^&]+)&gt;/g,'<a href="$1">$1</a>'),r=this.convertEmoji(r),s=this.convertEmoji(s),s=s.replace(/\*([^*]+)\*/g,"<strong>$1</strong>"),s=s.replace(/\b_([^_]+)_\b/g,"<em>$1</em>"),s=s.replace(/~([^~]+)~/g,"<del>$1</del>"),s=s.replace(/`([^`]+)`/g,"<code>$1</code>"),s=s.replace(/```([^`]+)```/g,"<pre>$1</pre>"),s=s.replace(/\n/g,"<br>"),{text:r,html:s}}convertEmoji(e){const n={":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,(r,s)=>n[r]??r)}filterMessages(e,n){return e.filter(r=>r.subtype==="bot_message"?!0:!(n.messagesAfter&&new Date(parseFloat(r.ts)*1e3)<n.messagesAfter||n.messagesBefore&&new Date(parseFloat(r.ts)*1e3)>n.messagesBefore||!n.importThreads&&r.thread_ts&&r.thread_ts!==r.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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}delay(e){return new Promise(n=>setTimeout(n,e))}}let Re=null;function Je(i){if(!Re&&i&&(Re=new Ot(i)),!Re)throw new Error("SlackImportService not initialized. Call with config first.");return Re}function ri(){Re=null}function si(i={}){const{config:e}=i,n=l.useMemo(()=>{if(e)return Je(e);try{return Je()}catch{return null}},[e]),[r,s]=l.useState(null),[a,o]=l.useState(!1),[c,f]=l.useState(null),d=l.useCallback(h=>{if(!n)throw new Error("Service not initialized");return n.parseSlackExportFromJson(h)},[n]),g=l.useCallback((h,w)=>{if(!n)throw new Error("Service not initialized");return n.previewImport(h,w)},[n]),p=l.useCallback(async function*(h,w){var z,u;if(!n)throw new Error("Service not initialized");o(!0),f(null);try{for await(const H of n.import(h,w))s(H),yield H;const I=n.import(h,w);let A;for await(const H of I)A=H;const N=(u=(z=I.next)==null?void 0:z.call(I))==null?void 0:u.value;return N&&f(N),N}finally{o(!1)}},[n]),m=l.useCallback(()=>{n==null||n.cancel(),o(!1)},[n]);return{parseJson:d,preview:g,import:p,cancel:m,progress:r,isImporting:a,result:c}}const Lt={toggleMute:"*6",raiseHand:"*9",leave:"#",help:"*0",hostMuteAll:"*1",hostUnmuteAll:"*2",hostEndMeeting:"*#"},Wt={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."},Qe={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 at{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=Lt,this.ivrText={...Wt,...e.ivrText}}on(e,n){this.eventHandlers[e]=n}off(e){delete this.eventHandlers[e]}emit(e,...n){const r=this.eventHandlers[e];r&&r(...n)}generateDialInInfo(e,n){const r=this.getAvailableNumbers(),s=this.generateAccessPin(),a=this.generateAccessPin(8),o={meetingId:e,dialInNumbers:r,accessPin:s,hostPin:a,meetingTitle:n,expiresAt:Date.now()+1440*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 n=Qe[e],r=Math.floor(1e9+Math.random()*9e9).toString();return`${n}${r}`}formatPhoneNumber(e){const n=Qe[e],r=this.generatePhoneNumber(e).slice(n.length);return e==="US"||e==="CA"?`${n} (${r.slice(0,3)}) ${r.slice(3,6)}-${r.slice(6)}`:`${n} ${r}`}generateAccessPin(e=6){return Math.floor(Math.random()*Math.pow(10,e)).toString().padStart(e,"0")}async handleIncomingCall(e,n,r){const s={callId:e,callerNumber:n,callerName:r,state:"connecting",joinedAt:Date.now(),audioStats:{volume:0,isMuted:!1,packetLoss:0,quality:5},isHost:!1,isModerator:!1};return this.participants.set(e,s),this.updateParticipantState(e,"waiting-pin"),await this.playIvr(e,"welcome"),await this.playIvr(e,"enterPin"),s}async validatePinAndJoin(e,n,r){const s=this.participants.get(e);if(!s)return{success:!1,isHost:!1};const a=this.meetingDialIns.get(n);if(!a)return await this.playIvr(e,"invalidPin"),{success:!1,isHost:!1};const o=r===a.hostPin;return r===a.accessPin||o?(s.isHost=o,s.isModerator=o,this.updateParticipantState(e,"joined"),await this.playIvr(e,"joined"),this.emit("onParticipantJoined",{...s}),{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,n){const r=this.participants.get(e);if(!r)return;const s=r.state;r.state=n,this.emit("onParticipantStateChanged",{...r},s)}async muteParticipant(e){const n=this.participants.get(e);n&&(n.audioStats.isMuted=!0,this.updateParticipantState(e,"muted"),await this.playIvr(e,"muted"))}async unmuteParticipant(e){const n=this.participants.get(e);n&&(n.audioStats.isMuted=!1,this.updateParticipantState(e,"joined"),await this.playIvr(e,"unmuted"))}async toggleMute(e){const n=this.participants.get(e);return n?n.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 n of this.participants.values())e&&(n.isHost||n.isModerator)||await this.muteParticipant(n.callId)}async unmuteAll(){for(const e of this.participants.values())await this.unmuteParticipant(e.callId)}async handleDtmf(e,n){const r=this.participants.get(e);r&&(this.emit("onDtmfReceived",{...r},n),n===this.dtmfCommands.toggleMute?await this.toggleMute(e):n===this.dtmfCommands.raiseHand?console.log(`Participant ${e} raised hand`):n===this.dtmfCommands.leave?await this.disconnectParticipant(e):n===this.dtmfCommands.help?await this.playHelp(e):(r.isHost||r.isModerator)&&(n===this.dtmfCommands.hostMuteAll?await this.muteAll():n===this.dtmfCommands.hostUnmuteAll?await this.unmuteAll():n===this.dtmfCommands.hostEndMeeting&&await this.endMeeting()))}setDtmfCommands(e){this.dtmfCommands={...this.dtmfCommands,...e}}async playIvr(e,n){const r=this.ivrText[n];console.log(`[IVR -> ${e}] ${r}`),await new Promise(s=>setTimeout(s,r.length*50))}async playCustomMessage(e,n){console.log(`[TTS -> ${e}] ${n}`),await new Promise(r=>setTimeout(r,n.length*50))}async playHelp(e){await this.playCustomMessage(e,`
7
7
  To mute or unmute yourself, press star 6.
8
8
  To raise your hand, press star 9.
9
9
  To leave the meeting, press pound.
@@ -18,4 +18,4 @@ a=rtpmap:0 PCMU/8000
18
18
  a=rtpmap:8 PCMA/8000
19
19
  a=rtpmap:101 telephone-event/8000
20
20
  a=fmtp:101 0-16
21
- `}processSdpAnswer(e){console.log("[PstnGateway] Processing SDP answer")}}let He=null;function Ot(s){return He||(He=new st(s)),He}function ii(s){return new st(s)}function si(s){const e=l.useMemo(()=>Ot(s),[]),[n,i]=l.useState("disconnected"),[r,a]=l.useState([]);l.useEffect(()=>{const v=()=>{a(e.getParticipants())};return e.on("onStatusChanged",i),e.on("onParticipantJoined",v),e.on("onParticipantLeft",v),e.on("onParticipantStateChanged",v),()=>{e.off("onStatusChanged"),e.off("onParticipantJoined"),e.off("onParticipantLeft"),e.off("onParticipantStateChanged")}},[e]);const o=l.useCallback((v,z)=>e.generateDialInInfo(v,z),[e]),c=l.useCallback(v=>e.getDialInInfo(v),[e]),u=l.useCallback(v=>e.muteParticipant(v),[e]),p=l.useCallback(v=>e.unmuteParticipant(v),[e]),m=l.useCallback(v=>e.disconnectParticipant(v),[e]),f=l.useCallback(()=>e.muteAll(),[e]),y=l.useCallback(()=>e.endMeeting(),[e]),h=l.useCallback(()=>e.connect(),[e]);return{status:n,participants:r,generateDialIn:o,getDialIn:c,mute:u,unmute:p,disconnect:m,muteAll:f,endMeeting:y,connect:h}}exports.DEFAULT_DTMF_COMMANDS=Mt;exports.DEFAULT_IVR_TEXT=$t;exports.DEFAULT_RETENTION_RULES=et;exports.EmailTrackingService=At;exports.EncryptionService=Nt;exports.MailMergeService=Et;exports.MockTransport=bt;exports.NiceCallScreen=Qe;exports.NiceChannelView=jt;exports.NiceChatWindow=Ne;exports.NiceCollaborativeEditor=$n;exports.NiceCommunication=Tt;exports.NiceCommunicationDefault=Tt;exports.NiceMessenger=St;exports.NicePresenceIndicator=pe;exports.NiceRecordingPanel=Rn;exports.NiceStorageSettings=jn;exports.NiceTeamsWorkspace=zt;exports.NiceVideoConference=Ze;exports.NiceWhiteboard=tt;exports.PstnGatewayService=st;exports.REGION_CODES=Xe;exports.RecordingService=Pt;exports.SlackImportService=Dt;exports.StorageService=kt;exports.WebRTCTransport=xt;exports.buildOptimisticMessage=Ft;exports.createPstnGateway=ii;exports.createTransport=vt;exports.disposeEmailTrackingService=Jn;exports.disposeEncryptionService=qn;exports.disposeMailMergeService=Zn;exports.disposeRecordingService=Xn;exports.disposeSlackImportService=ti;exports.disposeStorageService=Xt;exports.findConversationPartner=Ke;exports.getDefaultMode=Bt;exports.getEmailTrackingService=Ge;exports.getEncryptionService=Gn;exports.getMailMergeService=qe;exports.getMentionCount=_t;exports.getPstnGateway=Ot;exports.getRecordingService=Vn;exports.getSlackImportService=Ve;exports.getStorageService=Ct;exports.getUnreadCount=Je;exports.useCommunication=wt;exports.useEmailTracking=Qn;exports.useMailMerge=ei;exports.usePstnGateway=si;exports.useSlackImport=ni;exports.useWhiteboard=It;
21
+ `}processSdpAnswer(e){console.log("[PstnGateway] Processing SDP answer")}}let Ye=null;function Ft(i){return Ye||(Ye=new at(i)),Ye}function ai(i){return new at(i)}function oi(i){const e=l.useMemo(()=>Ft(i),[]),[n,r]=l.useState("disconnected"),[s,a]=l.useState([]);l.useEffect(()=>{const w=()=>{a(e.getParticipants())};return e.on("onStatusChanged",r),e.on("onParticipantJoined",w),e.on("onParticipantLeft",w),e.on("onParticipantStateChanged",w),()=>{e.off("onStatusChanged"),e.off("onParticipantJoined"),e.off("onParticipantLeft"),e.off("onParticipantStateChanged")}},[e]);const o=l.useCallback((w,z)=>e.generateDialInInfo(w,z),[e]),c=l.useCallback(w=>e.getDialInInfo(w),[e]),f=l.useCallback(w=>e.muteParticipant(w),[e]),d=l.useCallback(w=>e.unmuteParticipant(w),[e]),g=l.useCallback(w=>e.disconnectParticipant(w),[e]),p=l.useCallback(()=>e.muteAll(),[e]),m=l.useCallback(()=>e.endMeeting(),[e]),h=l.useCallback(()=>e.connect(),[e]);return{status:n,participants:s,generateDialIn:o,getDialIn:c,mute:f,unmute:d,disconnect:g,muteAll:p,endMeeting:m,connect:h}}exports.DEFAULT_DTMF_COMMANDS=Lt;exports.DEFAULT_IVR_TEXT=Wt;exports.DEFAULT_RETENTION_RULES=nt;exports.EmailTrackingService=Mt;exports.EncryptionService=Et;exports.MailMergeService=$t;exports.MockTransport=wt;exports.NiceCallScreen=et;exports.NiceChannelView=Ct;exports.NiceChatWindow=Ne;exports.NiceCollaborativeEditor=Wn;exports.NiceCommunication=Nt;exports.NiceCommunicationDefault=Nt;exports.NiceMessenger=kt;exports.NicePresenceIndicator=ue;exports.NiceRecordingPanel=An;exports.NiceStorageSettings=In;exports.NiceTeamsWorkspace=Rt;exports.NiceVideoConference=tt;exports.NiceWhiteboard=it;exports.PstnGatewayService=at;exports.REGION_CODES=Qe;exports.RecordingService=Dt;exports.SlackImportService=Ot;exports.StorageService=It;exports.WebRTCTransport=vt;exports.buildOptimisticMessage=Ut;exports.createPstnGateway=ai;exports.createTransport=St;exports.disposeEmailTrackingService=ei;exports.disposeEncryptionService=Jn;exports.disposeMailMergeService=ni;exports.disposeRecordingService=Zn;exports.disposeSlackImportService=ri;exports.disposeStorageService=Zt;exports.findConversationPartner=Ge;exports.getDefaultMode=Kt;exports.getEmailTrackingService=Ve;exports.getEncryptionService=Xn;exports.getMailMergeService=Xe;exports.getMentionCount=Ht;exports.getPstnGateway=Ft;exports.getRecordingService=Qn;exports.getSlackImportService=Je;exports.getStorageService=zt;exports.getUnreadCount=Ze;exports.useCommunication=jt;exports.useEmailTracking=ti;exports.useMailMerge=ii;exports.usePstnGateway=oi;exports.useSlackImport=si;exports.useWhiteboard=Tt;