@nice2dev/ui-communication 1.1.5 → 1.1.7

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 d=c.getParameters();d.encodings||(d.encodings=[{}]),c.track.kind==="audio"&&this.config.maxBitrate.audio?d.encodings[0].maxBitrate=this.config.maxBitrate.audio:c.track.kind==="video"&&this.config.maxBitrate.video&&(d.encodings[0].maxBitrate=this.config.maxBitrate.video),await c.setParameters(d)}}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),d=[...a.getTracks(),...c.getTracks()];return this.localStream=new MediaStream(d),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:d,onStreamRemoved:u,onError:m}=s,f=l.useRef(null),[y,h]=l.useState({isConnected:!1,activeCall:null,incomingCall:null,localStream:null,isMicMuted:!1,isCameraMuted:!1,isScreenSharing:!1,screenStream:null,isHandRaised:!1,connectionError:null}),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,z={callId:M,callType:K,caller:{id:P,name:P,presence:{status:"online"}},startedAt:new Date};h(W=>({...W,incomingCall:z})),c==null||c(z)}),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;d==null||d(M,K)}),C.on("stream:removed",k=>{const{participantId:M}=k;u==null||u(M)}),f.current=C,C},[n,i,o,c,d,u,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 I=l.useCallback(async C=>{await v().connect(C,e.id)},[v,e.id]),p=l.useCallback(()=>{var C;(C=f.current)==null||C.disconnect(),f.current=null,h(k=>({...k,isConnected:!1}))},[]),R=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),z=await M.startCall(C,k);return h(W=>({...W,activeCall:z,localStream:P})),z},[v]),N=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(z=>({...z,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:I,disconnect:p,startCall:R,acceptCall:N,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 ue({status:s,size:e="sm",showLabel:n=!1,showTooltip:i=!1,className:r,style:a,id:o,"data-testid":c}){const d=Kt[e],u=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:d,height:d,borderRadius:"50%",backgroundColor:u,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:d+4,color:u},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:d,onStopScreenShare:u,onRaiseHand:m,className:f,style:y,id:h,"data-testid":v}){var S,J;const I=l.useRef(null),p=l.useRef(null),[R,N]=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(()=>{I.current&&n&&(I.current.srcObject=n)},[n]),l.useEffect(()=>{p.current&&(k!=null&&k.stream)&&(p.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=!R;N(X),o==null||o(X)},P=()=>{const X=!D;_(X),c==null||c(X)},z=async()=>{$?(B(!1),u==null||u()):(B(!0),await(d==null?void 0:d()))},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:p,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(ue,{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:I,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:R?"Unmute":"Mute",onClick:K,active:!R,style:{background:R?"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:()=>{z()},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"),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:`
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:d,onPin:u,onOpenThread:m}){var R,N,D,_;const[f,y]=l.useState(!1),[h,v]=l.useState(!1),I=s.isDeleted,p=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)&&(((N=(R=e==null?void 0:e.name)==null?void 0:R[0])==null?void 0:N.toUpperCase())??"?")}),t.jsx(ue,{status:((D=e==null?void 0:e.presence)==null?void 0:D.status)??"unknown",size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),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:I?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})}),!I&&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:p}),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&&!I&&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})}),u&&t.jsx("button",{title:s.isPinned?"Unpin":"Pin","aria-label":s.isPinned?"Unpin":"Pin",onClick:()=>u(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&&d&&t.jsx("button",{title:"Delete","aria-label":"Delete",onClick:()=>d(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,d]=l.useState(""),u=l.useRef(null);l.useEffect(()=>{n&&u.current&&u.current.focus()},[n]);const m=h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),f())},f=()=>{const h=c.trim();h&&(r(h),d(""),u.current&&(u.current.style.height="auto"))},y=h=>{d(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:u,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:d=!0,enableThreads:u=!0,enableAttachments:m=!0,placeholder:f,maxMessageLength:y,onSendMessage:h,onEditMessage:v,onDeleteMessage:I,onReactToMessage:p,onPinMessage:R,onLoadMoreMessages:N,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 z=l.useCallback(()=>{const S=G.current;!S||!a||r||S.scrollTop===0&&e.length>0&&(N==null||N(s.id,e[0].id))},[a,r,e,s.id,N]),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(ue,{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:z,style:{flex:1,overflowY:"auto",padding:"8px 0",display:"flex",flexDirection:"column"},children:[a&&t.jsx("button",{onClick:()=>e.length>0&&(N==null?void 0:N(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:d,onReact:(q,ae)=>p==null?void 0:p(q,ae),onReply:q=>k(q),onEdit:v?q=>v(q.id,q.content):void 0,onDelete:I?q=>I(q.id):void 0,onPin:R?q=>R(q.id):void 0,onOpenThread:u?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:d,onReact:(S,J)=>p==null?void 0:p(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:d,onReact:(J,X)=>p==null?void 0:p(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,d=i?i.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"",u=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(ue,{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:d})]}),t.jsx("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:u})]}),(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:d=!0,onSendMessage:u,onEditMessage:m,onDeleteMessage:f,onReactToMessage:y,onPinMessage:h,onLoadMoreMessages:v,onMarkAsRead:I,onStartCall:p,onCreateConversation:R,className:N,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]),z=l.useCallback(g=>{Y(g),I==null||I(g)},[I]),W=l.useMemo(()=>Je(s),[s]),U=a??[];return t.jsxs("div",{id:_,"data-testid":$,className:`nice-messenger${N?` ${N}`:""}`,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&&R&&t.jsx("button",{onClick:()=>R([],"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})})]}),d&&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(ue,{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:()=>z(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(ue,{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:u,onEditMessage:m,onDeleteMessage:f,onReactToMessage:y,onPinMessage:h,onLoadMoreMessages:v,onStartCall:p,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,I,p;const[d,u]=l.useState(!1),[m,f]=l.useState(!1),y=s.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),h=s.timestamp.toLocaleDateString([],{month:"short",day:"numeric"});return t.jsxs("div",{className:`nice-channel-msg${d?" nice-channel-msg--hovered":""}${n?" nice-channel-msg--mine":""}`,onMouseEnter:()=>u(!0),onMouseLeave:()=>{u(!1),f(!1)},style:{display:"flex",gap:10,padding:"4px 16px",position:"relative",background:d?"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)&&(((I=(v=e==null?void 0:e.name)==null?void 0:v[0])==null?void 0:I.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," ",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"&&((p=s.attachments)!=null&&p[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(R=>t.jsxs("a",{href:R.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})," ",R.name]},R.id))}),s.reactions&&s.reactions.length>0&&t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:s.reactions.map(R=>t.jsxs("button",{onClick:()=>a(s.id,R.emoji),style:{background:R.mine?"var(--nice-accent-bg, #ede9fe)":"var(--nice-bg-secondary, #f3f4f6)",border:R.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:[R.emoji," ",R.count]},R.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})]})]}),d&&!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(R=>!R),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(R=>t.jsx("button",{onClick:()=>{a(s.id,R),f(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:R},R))})]}),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:d=!0,enableAttachments:u=!0,onSendMessage:m,onEditMessage:f,onDeleteMessage:y,onReactToMessage:h,onPinMessage:v,onLoadMoreMessages:I,onStartCall:p,className:R,style:N,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&&(I==null||I(s.id,e[0].id))},[o,a,e,s.id,I]),z=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(),z())},U=n.filter(g=>g.presence.status==="online").length;return t.jsxs("div",{id:D,"data-testid":_,className:`nice-channel-view${R?` ${R}`:""}`,style:{display:"flex",height:"100%",background:"var(--nice-bg, #fff)",overflow:"hidden",...N},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"]}),p&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>p(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:()=>p(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&&(I==null?void 0:I(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:d,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:[u&&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:z,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:d,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:d,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 I;const a=l.useRef(null),{user:o,isMuted:c,isCameraOff:d,isScreenSharing:u,isSpeaking:m,isHandRaised:f,stream:y,screenStream:h}=s;l.useEffect(()=>{if(!a.current)return;const p=u?h:y;p&&(a.current.srcObject=p)},[y,h,u]);const v=!d&&!!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&&!u?"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&&((I=o.name[0])==null?void 0:I.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}),u&&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(p=>t.jsx("div",{style:{flex:1,background:s.connectionQuality==="excellent"||s.connectionQuality==="good"&&p<=2||s.connectionQuality==="fair"&&p<=1?"var(--nice-success, #22c55e)":"var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))",height:`${p*30}%`,borderRadius:1}},p))})]})}function Ze({session:s,currentUser:e,localStream:n,enableScreenSharing:i=!0,enableRecording:r=!1,enableTranscription:a=!1,enableRaiseHand:o=!0,maxGridCols:c=4,onEndCall:d,onMuteAudio:u,onMuteVideo:m,onStartScreenShare:f,onStopScreenShare:y,onRaiseHand:h,className:v,style:I,id:p,"data-testid":R}){const[N,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,z]=l.useState(0),[W,U]=l.useState(!1);l.useEffect(()=>{if(s.status!=="active")return;const F=setInterval(()=>z(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=!N;D(F),u==null||u(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:N,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:p,"data-testid":R,className:`nice-video-conference${v?` ${v}`:""}`,style:{position:"relative",width:"100%",height:"100%",background:"var(--nice-text, #111827)",display:"flex",flexDirection:"column",overflow:"hidden",...I},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(ue,{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:N?"Unmute":"Mute",onClick:g,danger:N}),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:()=>d==null?void 0:d(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 u=r.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:e,data:n,expiresAt:i==null?void 0:i.toISOString()});u.onsuccess=()=>a(),u.onerror=()=>o(u.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 d=c.result;if(!d){i(void 0);return}if(d.expiresAt&&new Date(d.expiresAt)<new Date){this.delete(e),i(void 0);return}i(d.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(d=>d.startsWith(e))),c.onerror=()=>r(c.error)})}async clear(e){if(!e){const i=await this.openDb();return new Promise((r,a)=>{const d=i.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();d.onsuccess=()=>r(),d.onerror=()=>a(d.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 d=await this.adapter.list(a);for(const u of d){const m=await this.adapter.load(u);if(m){if(Ye(c.activePeriod),c.archivePeriod){const f=`archive:${u}`,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:${u}`),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},d=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:d,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,[d,u]=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(z=>{z&&u({type:"LOAD_SESSION",session:z})}))},[e.id,o]),l.useEffect(()=>{if(!c||!y.current||!d.isDirty)return;const z=setTimeout(()=>{var W;(W=y.current)==null||W.saveWhiteboardSnapshot(d.session.id,d.session).then(()=>{u({type:"MARK_SAVED"})})},c);return()=>clearTimeout(z)},[d.isDirty,d.session,c]);const h=l.useRef(new Set);l.useEffect(()=>{for(const z of r)if(!h.current.has(z.id)&&z.userId!==n.id)if(h.current.add(z.id),z.type==="cursor:move"){const{x:W,y:U}=z.payload;u({type:"UPDATE_CURSOR",userId:z.userId,x:W,y:U})}else z.type==="viewport:sync"||u({type:"APPLY_OP",op:z,local:!1})},[r,n.id]);function v(z,W){return{id:`${n.id}_${++m.current}_${Date.now()}`,sessionId:d.session.id,type:z,userId:n.id,timestamp:new Date,payload:W}}const I=l.useCallback(z=>{a||u({type:"SET_TOOL",tool:z})},[a]),p=l.useCallback(z=>{if(a)return;const W=v("object:add",z);u({type:"APPLY_OP",op:W,local:!0}),i==null||i(W)},[a,i,d.session.id]),R=l.useCallback(z=>{if(a)return;const W=v("object:update",z);u({type:"APPLY_OP",op:W,local:!0}),i==null||i(W)},[a,i,d.session.id]),N=l.useCallback(z=>{if(!a){for(const W of z){const U=v("object:delete",{id:W});u({type:"APPLY_OP",op:U,local:!0}),i==null||i(U)}u({type:"SET_SELECTION",ids:[]})}},[a,i,d.session.id]),D=l.useCallback(z=>{if(!a)for(const{id:W,x:U,y:H}of z){const g=v("object:move",{id:W,x:U,y:H});u({type:"APPLY_OP",op:g,local:!0}),i==null||i(g)}},[a,i,d.session.id]),_=l.useCallback(z=>{u({type:"SET_SELECTION",ids:z})},[]),$=l.useCallback(()=>{a||u({type:"UNDO"})},[a]),B=l.useCallback(()=>{a||u({type:"REDO"})},[a]),Y=l.useCallback(z=>{u({type:"SET_VIEWPORT",viewport:z});const W=v("viewport:sync",z);i==null||i(W)},[i,d.session.id]),O=l.useCallback((z,W)=>{if(f.current)return;f.current=setTimeout(()=>{f.current=null},50);const U=v("cursor:move",{x:z,y:W});i==null||i(U)},[i,d.session.id]),G=l.useCallback(z=>{if(a)return;const W={id:`layer_${Date.now()}`,name:z,visible:!0,locked:!1,objectIds:[]},U=v("layer:add",W);u({type:"APPLY_OP",op:U,local:!0}),i==null||i(U)},[a,i,d.session.id]),C=l.useCallback(z=>{if(a)return;const W=v("layer:update",z);u({type:"APPLY_OP",op:W,local:!0}),i==null||i(W)},[a,i,d.session.id]),k=l.useCallback(z=>{if(a)return;const W=v("layer:delete",{id:z});u({type:"APPLY_OP",op:W,local:!0}),i==null||i(W)},[a,i,d.session.id]),M=l.useCallback(z=>{const W={user:z,cursorX:0,cursorY:0,color:Jt(z.id),selectedObjectIds:[],activeTool:"pen",lastSeenAt:new Date};u({type:"APPLY_OP",op:v("cursor:move",W),local:!1})},[]),K=l.useCallback(z=>{u({type:"REMOVE_COLLABORATOR",userId:z})},[]),P=l.useCallback(async()=>{y.current&&(await y.current.saveWhiteboardSnapshot(d.session.id,d.session),u({type:"MARK_SAVED"}))},[d.session]);return{session:d.session,activeTool:d.activeTool,selectedObjectIds:d.selectedObjectIds,isDrawing:d.isDrawing,isPanning:d.isPanning,isDirty:d.isDirty,lastSavedAt:d.lastSavedAt,canUndo:d.undoStack.length>0,canRedo:d.redoStack.length>0,collaborators:Object.values(d.session.collaborators),objects:Object.values(d.session.objects),layers:d.session.layers,viewport:d.session.viewport,setTool:I,addObject:p,updateObject:R,deleteObjects:N,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 d of a){const u=o?`${o} ${d}`:d;s.measureText(u).width>i&&o?(s.fillText(o,n,c),o=d,c+=r):o=u}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({session:s,currentUser:e,onOperation:n,remoteOperations:i=[],readonly:r=!1,enableLayers:a=!0,enableExport:o=!0,enableLaserPointer:c=!0,enableVectorEditor:d=!1,enableDiagramEditor:u=!1,onExport:m,onSessionUpdate:f,storageConfig:y,className:h,style:v,"data-testid":I}){const p=It({session:s,currentUser:e,onOperation:n,remoteOperations:i,readonly:r,storageConfig:y,autoSaveMs:3e4}),R=l.useRef(null);l.useRef(null);const N=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)"),[z,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(!p.session.gridEnabled)return;const A=p.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()},[p.session.gridEnabled,p.session.gridSize]),J=l.useCallback((x,b)=>{for(const E of p.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()}},[p.collaborators,e.id]),X=l.useCallback((x,b)=>{if(p.selectedObjectIds.length!==0)for(const E of p.selectedObjectIds){const L=p.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)}},[p.selectedObjectIds,p.session.objects]),Z=l.useCallback(()=>{const x=R.current;if(!x)return;const b=x.getContext("2d");if(!b)return;const{width:E,height:L}=x,A=p.viewport;b.clearRect(0,0,E,L),b.fillStyle=p.session.backgroundColor,b.fillRect(0,0,E,L),S(b,A,E,L),b.save();const V=Object.values(p.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&&p.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)},[p.session,p.viewport,p.activeTool,S,J,X,$,Y]);l.useLayoutEffect(()=>{function x(){Z(),N.current=requestAnimationFrame(x)}return N.current=requestAnimationFrame(x),()=>cancelAnimationFrame(N.current)},[Z]),l.useEffect(()=>{const x=R.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(),p.undo()),b.key==="y"&&(b.preventDefault(),p.redo()),b.key==="s"&&(b.preventDefault(),p.saveNow()),b.key==="a"&&(b.preventDefault(),p.setSelection(Object.keys(p.session.objects)))),(b.key==="Delete"||b.key==="Backspace")&&p.selectedObjectIds.length>0&&p.deleteObjects(p.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]&&p.setTool(E[b.key])}return window.addEventListener("keydown",x),window.addEventListener("keyup",x),()=>{window.removeEventListener("keydown",x),window.removeEventListener("keyup",x)}},[p]);const q=l.useCallback(x=>{const b=R.current.getBoundingClientRect(),E=x.clientX-b.left,L=x.clientY-b.top,{wx:A,wy:V}=en(E,L,p.viewport);return{x:A,y:V,pressure:x.pressure??.5}},[p.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:p.viewport.x,vpY:p.viewport.y};return}const E=p.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(p.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?p.setSelection([...p.selectedObjectIds,L.id]):p.setSelection([L.id]):p.setSelection([])}},[r,q,p]),oe=l.useCallback(x=>{const b=q(x);if(p.broadcastCursor(b.x,b.y),g.current.panStart){const{x:L,y:A,vpX:V,vpY:j}=g.current.panStart;p.setViewport({...p.viewport,x:V+(x.clientX-L),y:j+(x.clientY-A)});return}if(!g.current.active)return;const E=p.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"&&p.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,p.moveObjects(p.selectedObjectIds.map(V=>{const j=p.session.objects[V];return{id:V,x:j.x+L,y:j.y+A}}))}},[q,p]),fe=l.useCallback(x=>{if(g.current.panStart){g.current.panStart=null;return}if(!g.current.active)return;const b=q(x),E=p.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(p.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:j,points:T,color:$,strokeWidth:Y,opacity:E==="highlighter"?.4:1,tool:E};p.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(p.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:j,shape:de[E],fillColor:G,strokeColor:$,strokeWidth:Y,opacity:1};p.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(p.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};p.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(p.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:$};p.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(p.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};p.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(p.session.objects).length+1}`,childIds:[],borderColor:"#8888"};p.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(p.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:ye,dataUrl:ye,originalWidth:he.width,originalHeight:he.height};p.addObject(xe)},he.src=ye},ee.readAsDataURL(te)},T.click();break}}},[q,p,e.id,$,Y,G,k,K]),le=l.useCallback(x=>{if(x.preventDefault(),!x.ctrlKey&&!x.metaKey){p.setViewport({...p.viewport,x:p.viewport.x-x.deltaX,y:p.viewport.y-x.deltaY});return}const b=R.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,p.viewport.scale*V));p.setViewport({scale:j,x:E-(E-p.viewport.x)*(j/p.viewport.scale),y:L-(L-p.viewport.y)*(j/p.viewport.scale)})},[p]),F=l.useCallback(x=>{if(x==="json"){const A=JSON.stringify(p.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=`${p.session.title}.json`,V.click();return}const b=R.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=`${p.session.title}.png`,L.click()},[p.session,m]);l.useEffect(()=>{f==null||f(p.session)},[p.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(p.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:j,dataUrl:j,originalWidth:T.width,originalHeight:T.height};p.addObject(de)},T.src=j},A.readAsDataURL(L);break}}}return window.addEventListener("paste",x),()=>window.removeEventListener("paste",x)},[p,e.id]);const Q=z?p.session.objects[z]:null,ie=l.useMemo(()=>Q?Be(Q.x,Q.y,p.viewport):null,[Q,p.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":I,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:()=>p.setTool(E.id),title:`${E.label}`,style:{padding:"4px 7px",border:`1.5px solid ${p.activeTool===E.id?"var(--nice-info, #6366f1)":"transparent"}`,borderRadius:6,background:p.activeTool===E.id?"var(--nice-primary-bg, #eef2ff)":"transparent",cursor:"pointer",fontSize:15,minWidth:30,color:p.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})]}),p.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:p.undo,disabled:!p.canUndo,title:"Undo (Ctrl+Z)","aria-label":"Undo",style:pe(!p.canUndo),children:t.jsx(w.NiceIcon,{name:"reply",size:13})}),t.jsx("button",{onClick:p.redo,disabled:!p.canRedo,title:"Redo (Ctrl+Y)","aria-label":"Redo",style:pe(!p.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(p.viewport.scale*100),"%"]}),t.jsx("button",{onClick:()=>p.setViewport({x:0,y:0,scale:1}),style:pe(),title:"Reset zoom","aria-label":"Reset zoom",children:t.jsx(w.NiceIcon,{name:"target",size:13})}),a&&t.jsx("button",{onClick:()=>_(x=>!x),style:pe(!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:p.session.id,type:"object:update",userId:e.id,timestamp:new Date,payload:{...p.session,gridEnabled:!p.session.gridEnabled}};n==null||n(x)},style:pe(!1,p.session.gridEnabled),title:"Toggle grid","aria-label":"Toggle grid",children:t.jsx(w.NiceIcon,{name:"hash",size:13})}),d&&t.jsx("button",{onClick:()=>H(x=>x==="vector"?null:"vector"),style:pe(!1,U==="vector"),title:"Vector Editor panel","aria-label":"Vector Editor panel",children:t.jsx(w.NiceIcon,{name:"pen",size:13})}),u&&t.jsx("button",{onClick:()=>H(x=>x==="diagram"?null:"diagram"),style:pe(!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 p.saveNow(),style:pe(),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}),p.isDirty&&"*"]})}),o&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>F("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(w.NiceIcon,{name:"download",size:12})]})}),t.jsx("button",{onClick:()=>F("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(w.NiceIcon,{name:"download",size:12})]})})]})]}),t.jsxs("div",{style:{display:"flex",flex:1,overflow:"hidden",position:"relative"},children:[t.jsx("canvas",{ref:R,style:{flex:1,display:"block",cursor:pn(p.activeTool,g.current.spaceDown)},onPointerDown:ae,onPointerMove:oe,onPointerUp:fe,onWheel:le,onContextMenu:x=>x.preventDefault()}),a&&D&&t.jsx(dn,{layers:p.layers,objects:p.session.objects,onAdd:()=>p.addLayer(`Layer ${p.layers.length+1}`),onUpdate:x=>p.updateLayer(x),onDelete:x=>p.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}})]})]}),p.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:"}),p.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)),p.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"]}),p.lastSavedAt&&!p.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 ",p.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};p.updateObject(b),W(null)},style:{position:"absolute",left:ie.sx,top:ie.sy,minWidth:Q.width*p.viewport.scale,minHeight:Q.height*p.viewport.scale,fontSize:(Q.fontSize??14)*p.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 dn({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 pe(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 un({team:s,activeChannelId:e,onSelectChannel:n}){var o;const[i,r]=l.useState(!1),a=s.channels.reduce((c,d)=>c+d.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 fn({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(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: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:d,rtcConfig:u,enableCalls:m=!0,enableMeetings:f=!0,enableScreenSharing:y=!0,enableWhiteboard:h=!1,storageConfig:v,onSendMessage:I,onEditMessage:p,onDeleteMessage:R,onReactToMessage:N,onPinMessage:D,onLoadMoreMessages:_,onMarkAsRead:$,onStartCall:B,onAcceptCall:Y,onDeclineCall:O,onEndCall:G,onMuteAudio:C,onMuteVideo:k,onStartScreenShare:M,onStopScreenShare:K,className:P,style:z,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%",...z},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(un,{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(fn,{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:I,onEditMessage:p,onDeleteMessage:R,onReactToMessage:N,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:I,onEditMessage:p,onDeleteMessage:R,onReactToMessage:N,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 hn={"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 gn({props:s,onExpand:e}){const[n,i]=l.useState(!1),{bubblePosition:r="bottom-right",bubbleLabel:a,currentUser:o,users:c,conversations:d=[],messages:u={},onSendMessage:m,onReactToMessage:f,onPinMessage:y,onDeleteMessage:h,onEditMessage:v,onLoadMoreMessages:I,onStartCall:p}=s,R=hn[r],N=d[0]??null,D=N?u[N.id]??[]:[];return t.jsxs("div",{style:{position:"fixed",zIndex:9999,...R},children:[n&&N&&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:N,messages:D,users:c,currentUser:o,showHeader:!1,onSendMessage:m,onEditMessage:v,onDeleteMessage:h,onReactToMessage:f,onPinMessage:y,onLoadMoreMessages:I,onStartCall:p,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 mn({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:d,incomingCall:u,transport:m="webrtc",rtcConfig:f,onSendMessage:y,onEditMessage:h,onDeleteMessage:v,onReactToMessage:I,onPinMessage:p,onLoadMoreMessages:R,onMarkAsRead:N,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:z=!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(d??null),[F,Q]=l.useState(u??null),ie=d??fe,re=u??F;l.useEffect(()=>{Z(e)},[e]),l.useEffect(()=>{d!==void 0&&le(d)},[d]),l.useEffect(()=>{u!==void 0&&Q(u)},[u]);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:I,onPinMessage:p,onLoadMoreMessages:R,onMarkAsRead:N,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(mn,{call:re,onAccept:se,onDecline:de}),ge==="bubble"&&t.jsx(gn,{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"&&z&&t.jsx(tt,{session:q??oe,currentUser:n,storageConfig:W,onSessionUpdate:ne=>ae(ne),style:{height:"100%"}})]})}const yn={messages:"Messages",attachments:"Attachments","whiteboard-snapshots":"Whiteboard snapshots",recordings:"Recordings",transcripts:"Transcripts",documents:"Documents","call-logs":"Call logs","audit-logs":"Audit logs"},pt={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"},xn={messages:"Messages",attachments:"Attachments",whiteboard:"Whiteboard",recordings:"Recordings",documents:"Documents",calls:"Calls (metadata)",presence:"Presence data",all:"Everything"},bn=["days","weeks","months","years","forever"];function ut(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:bn.map(i=>t.jsx("option",{value:i,children:i},i))})]})}function vn({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:yn[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 wn({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(pt).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(d=>d.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:d=>{const u=[...(s.scopeOverrides??[]).filter(m=>m.scope!==i),{scope:i,algorithm:o,enabled:d.target.checked}];e({...s,scopeOverrides:u})}}),t.jsx("span",{style:{minWidth:120,fontSize:12,color:"var(--nice-text, #374151)"},children:xn[i]}),t.jsx("select",{value:o,disabled:!a,onChange:d=>{const u=[...(s.scopeOverrides??[]).filter(m=>m.scope!==i),{scope:i,algorithm:d.target.value,enabled:a}];e({...s,scopeOverrides:u})},style:{...we,flex:1,opacity:a?1:.4},children:Object.entries(pt).map(([d,u])=>t.jsx("option",{value:d,children:u},d))})]},i)})})]})]})}function Sn({storageConfig:s,encryptionConfig:e,onStorageConfigChange:n,onEncryptionConfigChange:i,currentUsageBytes:r=0,showEncryption:a=!0,showRetention:o=!0,showQuota:c=!0,className:d,style:u,"data-testid":m}){const[f,y]=l.useState("retention"),h=e??{enabled:!1,defaultAlgorithm:"AES-GCM-256",showIndicator:!0},v={...s,retentionRules:s.retentionRules.length>0?s.retentionRules:et};return t.jsxs("div",{className:d,"data-testid":m,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,...u},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."})]}),c&&s.quota&&s.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:[ut(r)," / ",ut(s.quota)]})]}),t.jsx("div",{style:{height:6,background:"var(--nice-border, #e5e7eb)",borderRadius:3},children:t.jsx("div",{style:{width:`${Math.min(100,r/s.quota*100)}%`,height:"100%",background:r/s.quota>.9?"var(--nice-danger, #ef4444)":"var(--nice-info, #6366f1)",borderRadius:3,transition:"width 0.3s"}})})]}),o&&a&&t.jsx("div",{style:{display:"flex",gap:0,borderBottom:"1px solid var(--nice-border, #e5e7eb)"},children:["retention","encryption"].map(I=>t.jsx("button",{onClick:()=>y(I),style:{padding:"8px 18px",border:"none",borderBottom:`2px solid ${f===I?"var(--nice-info, #6366f1)":"transparent"}`,background:"none",cursor:"pointer",fontSize:13,fontWeight:f===I?600:400,color:f===I?"var(--nice-accent, #4f46e5)":"var(--nice-text-secondary, #6b7280)",marginBottom:-1,display:"inline-flex",alignItems:"center",gap:6},children:I==="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"]})},I))}),t.jsxs("div",{children:[(f==="retention"||!a)&&o&&t.jsx(vn,{config:v,onChange:n??(()=>{})}),(f==="encryption"||!o)&&a&&t.jsx(wn,{config:h,onChange:i??(()=>{})})]})]})}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 jn(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 kn(s){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(s))}const Cn={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 In({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:Rn,"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 zn({rec:s,onDelete:e,onDownload:n}){const[i,r]=l.useState(!1),[a,o]=l.useState(0),c=l.useRef(null),d=Cn[s.state],u=s.state==="recording"||s.state==="paused";return t.jsxs(t.Fragment,{children:[i&&s.transcript&&t.jsx(In,{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:kn(s.startedAt)}),t.jsx("span",{children:u?t.jsx(Rt,{startedAt:s.startedAt}):s.durationMs!=null?Le(s.durationMs):"—"}),s.size!=null&&t.jsx("span",{children:jn(s.size)}),t.jsxs("span",{children:[s.participants.length," participants"]})]})]}),t.jsxs("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:20,background:d.bg,color:d.fg,fontWeight:500,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[d.icon&&t.jsx(w.NiceIcon,{name:d.icon,size:11}),d.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 Tn({recordings:s,onRecordingStart:e,onRecordingStop:n,onRecordingPause:i,onRecordingResume:r,onRecordingDelete:a,onRecordingDownload:o,activeRecordingId:c,sessionType:d="meeting",className:u,style:m,"data-testid":f}){const[y,h]=l.useState(s??[]),[v,I]=l.useState(""),[p,R]=l.useState("all");l.useEffect(()=>{s&&h(s)},[s]);const N=y.find(O=>O.id===c),D=(N==null?void 0:N.state)==="recording",_=(N==null?void 0:N.state)==="paused",$=y.filter(O=>{const G=p==="all"||O.sessionType===p,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:u,"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:d,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"]}),N&&t.jsx("span",{style:{fontSize:12,color:"var(--nice-text-muted, #9ca3af)",marginLeft:4},children:t.jsx(Rt,{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:v,onChange:O=>I(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:p,onChange:O=>R(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(zn,{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)"},Rn={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 Nn({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 Pn({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 An(){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 En({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 Dn({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 Mn({editorType:s,sessionId:e,currentUser:n,participants:i=[],onOperation:r,onParticipantJoin:a,onParticipantLeave:o,onCursorMove:c,isReadOnly:d=!1,showParticipants:u=!0,showCursors:m=!0,pendingOperations:f=0,conflictCount:y=0,className:h,style:v,children:I,"data-testid":p}){const R=l.useRef(null),[N,D]=l.useState(null),[_,$]=l.useState(null),[B,Y]=l.useState(!1);l.useEffect(()=>{const P=R.current;if(!P)return;const z=new ResizeObserver(()=>D(P.getBoundingClientRect()));return z.observe(P),D(P.getBoundingClientRect()),()=>z.disconnect()},[]);const O=l.useCallback(P=>{if(!R.current||!c)return;const z=R.current.getBoundingClientRect();c(P.clientX-z.left,P.clientY-z.top)},[c]),G=l.useCallback(P=>{$(z=>z===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(En,{pending:f}),u&&i.length>0&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:-4},children:[i.slice(0,5).map((P,z)=>t.jsx("div",{style:{marginLeft:z>0?-8:0,zIndex:10-z},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]})]}),u&&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:R,onMouseMove:O,style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},children:[I??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(Nn,{participant:P,containerRect:N},P.user.id)),t.jsx(Pn,{count:y}),d&&t.jsx(An,{})]}),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(Dn,{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":p,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 $n(s){return new TextEncoder().encode(s)}function On(s){return new TextDecoder().decode(s)}async function Ln(s){return crypto.subtle.generateKey({name:"AES-GCM",length:s},!0,["encrypt","decrypt"])}async function Wn(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-384"},!0,["deriveKey"])}async function Fn(s,e){return crypto.subtle.deriveKey({name:"ECDH",public:e},s,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function _n(s,e){const n=crypto.getRandomValues(new Uint8Array(12)),i=$n(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 Bn(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 On(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 Un(s){const e=await crypto.subtle.exportKey("raw",s);return nt(new Uint8Array(e))}async function Hn(s){const e=await crypto.subtle.exportKey("spki",s);return nt(new Uint8Array(e))}async function Kn(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 Ln(n);n===128?this.keys.aes128=i:this.keys.aes256=i}else if(e==="E2E-ECDH-P384"){const n=await Wn();this.keys.ecdhPrivate=n.privateKey,this.keys.ecdhPublic=n.publicKey,this.keys.ecdhSessionKeys=new Map}this.ready=!0}async getPublicKeyForPeer(){return this.keys.ecdhPublic?Hn(this.keys.ecdhPublic):null}async registerPeerPublicKey(e,n){var a;if(!this.keys.ecdhPrivate)return;const i=await Kn(n),r=await Fn(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?_n(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?Bn(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?Un(i):null}isEnabled(){return this.config.enabled}getConfig(){return this.config}updateConfig(e){this.config=e,this.ready=!1}}const $e=new Map;function Yn(s,e){return $e.has(s)||$e.set(s,new Nt(e)),$e.get(s)}function Gn(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,d,u;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"),(u=(d=this.callbacks).onStateChange)==null||u.call(d,"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 u,m;const d=c.results;for(let f=c.resultIndex;f<d.length;f++){const y=d[f];if(!y.isFinal)continue;const h=y[0],v=Date.now(),I={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??[],I]),(m=(u=this.callbacks).onTranscriptSegment)==null||m.call(u,I)}},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 qn(s,e){return Oe.has(s)||Oe.set(s,new Pt(e)),Oe.get(s)}function Vn(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,d)=>{if(i.some(y=>y.test(c)))return a;const m=this.extractLinkName(o+d)??c,f=this.wrapLink({url:c,messageId:n.messageId,recipientId:n.recipientId,campaignId:n.campaignId,linkName:m});return`<a ${o}href="${this.escapeHtml(f)}"${d}>`})}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"),d=n.filter(y=>y.type==="complaint"),u=new Set(r.map(y=>y.recipientHash)).size,m=new Set(a.map(y=>y.recipientHash)).size,f=i.size;return{sent:f+o.length,delivered:f,opens:r.length,uniqueOpens:u,clicks:a.length,uniqueClicks:m,bounces:o.length,unsubscribes:c.length,complaints:d.length,openRate:f>0?u/f:0,clickRate:f>0?m/f:0,clickToOpenRate:u>0?m/u:0,bounceRate:f>0?o.length/(f+o.length):0}}getLinkStats(e){let 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 d=i.get(c);d.total++,d.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 Xn(){me==null||me.clearEvents(),me=null}function Jn(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,d]=l.useState([]),u=l.useCallback(()=>{r&&(o(r.getStats({campaignId:n})),d(r.getLinkStats({campaignId:n})))},[r,n]);l.useEffect(()=>{if(u(),i&&r){const h=setInterval(u,i);return()=>clearInterval(h)}},[u,i,r]),l.useEffect(()=>{if(r)return r.onAny(()=>{u()})},[r,u]);const m=l.useCallback((h,v)=>r?r.generateTrackingPixel({messageId:h,recipientId:v,campaignId:n}):"",[r,n]),f=l.useCallback((h,v,I)=>r?r.wrapLinksForTracking(h,{messageId:v,recipientId:I,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:u}}class Et{constructor(e){this.templates=new Map,this.campaigns=new Map,this.abortControllers=new Map,this.config={sendEmail:e.sendEmail,rateLimit:e.rateLimit??60,batchSize:e.batchSize??10,retryOnFail:e.retryOnFail??!0,maxRetries:e.maxRetries??3,dateFormatter:e.dateFormatter??this.defaultDateFormatter,numberFormatter:e.numberFormatter??this.defaultNumberFormatter,currencyFormatter:e.currencyFormatter??this.defaultCurrencyFormatter}}createTemplate(e){const 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 u of n.recipients){if(!u.email){r.push({type:"empty_recipient",recipientId:u.id,message:`Recipient ${u.id} has no email address`});continue}const m=[];for(const f of i.fields)f.required&&!(f.name in u.data)&&(m.push(f.name),r.push({type:"missing_field",field:f.name,recipientId:u.id,message:`Required field "${f.name}" missing for ${u.email}`}));m.length>0&&o.set(u.id,m)}const c=this.extractFields(i.subject+i.htmlBody+(i.textBody??"")),d=i.fields.map(u=>u.name);for(const u of c)d.includes(u)||a.push({type:"unused_field",field:u,message:`Field "${u}" used in template but not defined`});return{isValid:r.length===0,errors:r,warnings:a,missingFields:o}}previewMerge(e,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 d=0,u=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",d++):(h.status="failed",h.error=_.error,u++)}catch(D){h.status="failed",h.error=D instanceof Error?D.message:"Unknown error",u++}const v=d+u,I=Date.now()-m,p=v>0?I/v:f,R=c-v,N=Math.round(R*p/1e3);yield{campaignId:e,total:c,sent:d,failed:u,pending:c-v,current:h.email,percentage:Math.round(v/c*100),estimatedTimeRemaining:N,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:d,failed:u,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,...d]=o.trim().split("|").map(f=>f.trim());let u=this.getNestedValue(n,c);const m=r.get(c);u==null&&(u=(m==null?void 0:m.defaultValue)??""),m&&u!==""&&(u=this.formatValue(u,m));for(const f of d)u=this.applyFormatter(u,f);return String(u)}),e}processConditionals(e,n){const i=/\{\{#if\s+([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g;return e.replace(i,(r,a,o,c="")=>{const d=this.getNestedValue(n,a.trim());return this.isTruthy(d)?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((d,u)=>{let m=o;return typeof d!="object"&&(m=m.replace(/\{\{this\}\}/g,String(d))),m=m.replace(/\{\{this\.([^}]+)\}\}/g,(f,y)=>String(this.getNestedValue(d,y)??"")),m=m.replace(/\{\{@index\}\}/g,String(u)),m=m.replace(/\{\{@first\}\}/g,String(u===0)),m=m.replace(/\{\{@last\}\}/g,String(u===c.length-1)),m}).join(""):""})}formatValue(e,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 Qn(){Te=null}function Zn(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,d]=l.useState([]),[u,m]=l.useState([]),f=l.useCallback(()=>{n&&(d(n.listTemplates()),m(n.listCampaigns()))},[n]),y=l.useCallback(N=>{if(!n)throw new Error("Service not initialized");const D=n.createTemplate(N);return f(),D},[n,f]),h=l.useCallback(N=>{if(!n)throw new Error("Service not initialized");const D=n.createCampaign(N);return f(),D},[n,f]),v=l.useCallback((N,D)=>{if(!n)throw new Error("Service not initialized");return n.previewMerge(N,D)},[n]),I=l.useCallback(N=>{if(!n)throw new Error("Service not initialized");return n.validateCampaign(N)},[n]),p=l.useCallback(async function*(N){if(!n)throw new Error("Service not initialized");o(!0);try{for await(const D of n.sendCampaign(N))r(D),yield D}finally{o(!1),f()}},[n,f]),R=l.useCallback(N=>{n==null||n.pauseCampaign(N),o(!1),f()},[n,f]);return{createTemplate:y,createCampaign:h,preview:v,validate:I,send:p,pause:R,progress:i,isSending:a,templates:c,campaigns:u}}class Dt{constructor(e){this.abortController=null,this.mapping={users:new Map,channels:new Map,files:new Map},this.config=e}async parseSlackExport(e){const 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 d=n.get("dms.json");if(d){const m=JSON.parse(d);o.push(...m.map(f=>({...f,is_im:!0})))}const u=new Map;for(const m of o){const f=[],y=m.name;for(const[h,v]of n)if(h.startsWith(y+"/")&&h.endsWith(".json"))try{const I=JSON.parse(v);f.push(...I)}catch(I){console.warn(`Failed to parse messages from ${h}:`,I)}f.length>0&&u.set(m.id,f)}return{users:r,channels:o,messages:u}}parseSlackExportFromJson(e){return{users:e.users??[],channels:e.channels??[],messages:new Map(Object.entries(e.messages??{})),files:e.files}}previewImport(e,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 d=new Map;for(const[f,y]of e.messages){const h=e.channels.find(p=>p.id===f);if(!h||!a.some(p=>p.id===f))continue;const I=this.filterMessages(y,n);d.set(h.name,I.length),c+=I.length}let u=0,m=0;for(const f of e.messages.values())for(const y of f)y.files&&(u+=y.files.length,m+=y.files.reduce((h,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:d},files:{total:u,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 u=e.users.filter(f=>!f.deleted);let m=0;for(const f of u){if(this.abortController.signal.aborted)break;const y=this.mapUser(f),h=await this.config.createUser(y);h.success&&h.id?(this.mapping.users.set(f.id,h.id),r.usersImported++):i.push({phase:"users",itemId:f.id,itemType:"user",message:h.error??"Failed to create user"}),m++,yield{phase:"users",total:u.length,processed:m,failed:i.filter(v=>v.phase==="users").length,current:f.name,percentage:Math.round(m/u.length*100),isComplete:!1,errors:i},await this.delay(c)}}if(n.importChannels!==!1){const u=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 u){if(this.abortController.signal.aborted)break;const y=this.mapChannel(f,this.mapping.users),h=await this.config.createChannel(y);h.success&&h.id?(this.mapping.channels.set(f.id,h.id),r.channelsImported++):i.push({phase:"channels",itemId:f.id,itemType:"channel",message:h.error??"Failed to create channel"}),m++,yield{phase:"channels",total:u.length,processed:m,failed:i.filter(v=>v.phase==="channels").length,current:f.name,percentage:Math.round(m/u.length*100),isComplete:!1,errors:i},await this.delay(c)}}if(n.importMessages!==!1){const u=[];for(const[y,h]of e.messages){if(!this.mapping.channels.has(y))continue;const v=this.filterMessages(h,n);for(const I of v)u.push({channelId:y,message:I})}u.sort((y,h)=>parseFloat(y.message.ts)-parseFloat(h.message.ts));const m=new Map;let f=0;for(const{channelId:y,message:h}of u){if(this.abortController.signal.aborted)break;const v=this.mapMessage(h,y,this.mapping,m),I=await this.config.createMessage(v);I.success&&I.id?((!h.thread_ts||h.thread_ts===h.ts)&&m.set(h.ts,I.id),r.messagesImported++,v.isThreadReply&&r.threadsImported++,r.reactionsImported+=v.reactions.length):i.push({phase:"messages",itemId:h.ts,itemType:"message",message:I.error??"Failed to create message"}),f++,yield{phase:"messages",total:u.length,processed:f,failed:i.filter(p=>p.phase==="messages").length,current:`${f}/${u.length}`,percentage:Math.round(f/u.length*100),isComplete:!1,errors:i},await this.delay(c)}}if(n.importFiles&&n.downloadFiles&&this.config.uploadFile&&this.config.downloadFile){const u=[];for(const f of e.messages.values())for(const y of f)y.files&&u.push(...y.files);let m=0;for(const f of u){if(this.abortController.signal.aborted)break;try{const y=f.url_private_download??f.url_private;if(y&&this.config.slackToken){const h=await this.config.downloadFile(y,this.config.slackToken),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:u.length,processed:m,failed:i.filter(y=>y.phase==="files").length,current:f.name,percentage:Math.round(m/u.length*100),isComplete:!1,errors:i},await this.delay(c)}}const d=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:d,duration:d.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:d}=this.convertSlackMessage(e.text,i.users),u=e.thread_ts!==void 0&&e.thread_ts!==e.ts,m=e.thread_ts?r.get(e.thread_ts):void 0,f=[];if(e.files)for(const h of e.files)f.push({type:h.mimetype.startsWith("image/")?"image":"file",url:i.files.get(h.id)??h.url_private,name:h.name,size:h.size});if(e.attachments)for(const h of e.attachments)h.image_url?f.push({type:"image",url:h.image_url}):h.title_link&&f.push({type:"link",url:h.title_link,name:h.title});const y=(e.reactions??[]).map(h=>({emoji:h.name,userIds:h.users.map(v=>i.users.get(v)).filter(v=>!!v),count:h.count}));return{channelId:a,senderId:o,content:c,htmlContent:d,threadId:m,isThreadReply:u,attachments:f,reactions:y,createdAt:e.ts?new Date(parseFloat(e.ts)*1e3):void 0,editedAt:e.edited?new Date(parseFloat(e.edited.ts)*1e3):void 0}}convertSlackMessage(e,n){let i=e,r=this.escapeHtml(e);const a=/<@([A-Z0-9]+)(?:\|([^>]+))?>/g;return i=i.replace(a,(o,c,d)=>d?`@${d}`:"@user"),r=r.replace(/&lt;@([A-Z0-9]+)(?:\|([^&]+))?&gt;/g,(o,c,d)=>`<span class="mention" data-user-id="${n.get(c)??c}">@${d??"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 ei(){Re=null}function ti(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,d]=l.useState(null),u=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 I,p;if(!n)throw new Error("Service not initialized");o(!0),d(null);try{for await(const _ of n.import(h,v))r(_),yield _;const R=n.import(h,v);let N;for await(const _ of R)N=_;const D=(p=(I=R.next)==null?void 0:I.call(R))==null?void 0:p.value;return D&&d(D),D}finally{o(!1)}},[n]),y=l.useCallback(()=>{n==null||n.cancel(),o(!1)},[n]);return{parseJson:u,preview:m,import:f,cancel:y,progress:i,isImporting:a,result:c}}const Mt={toggleMute:"*6",raiseHand:"*9",leave:"#",help:"*0",hostMuteAll:"*1",hostUnmuteAll:"*2",hostEndMeeting:"*#"},$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 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,`
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 ni(s){return new st(s)}function ii(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,I)=>e.generateDialInInfo(v,I),[e]),c=l.useCallback(v=>e.getDialInInfo(v),[e]),d=l.useCallback(v=>e.muteParticipant(v),[e]),u=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:d,unmute:u,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=Mn;exports.NiceCommunication=Tt;exports.NiceCommunicationDefault=Tt;exports.NiceMessenger=St;exports.NicePresenceIndicator=ue;exports.NiceRecordingPanel=Tn;exports.NiceStorageSettings=Sn;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=ni;exports.createTransport=vt;exports.disposeEmailTrackingService=Xn;exports.disposeEncryptionService=Gn;exports.disposeMailMergeService=Qn;exports.disposeRecordingService=Vn;exports.disposeSlackImportService=ei;exports.disposeStorageService=Xt;exports.findConversationPartner=Ke;exports.getDefaultMode=Bt;exports.getEmailTrackingService=Ge;exports.getEncryptionService=Yn;exports.getMailMergeService=qe;exports.getMentionCount=_t;exports.getPstnGateway=Ot;exports.getRecordingService=qn;exports.getSlackImportService=Ve;exports.getStorageService=Ct;exports.getUnreadCount=Je;exports.useCommunication=wt;exports.useEmailTracking=Jn;exports.useMailMerge=Zn;exports.usePstnGateway=ii;exports.useSlackImport=ti;exports.useWhiteboard=It;
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;