@nice2dev/ui-communication 1.2.2 โ 1.3.1
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 +1 -1
- package/dist/index.mjs +0 -5
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
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 transparent; }
|
|
5
5
|
}
|
|
6
|
-
`})]})}function Se({icon:i,label:e,onClick:t,active:r,style:s}){return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[n.jsx("button",{onClick:t,title:e,style:{width:44,height:44,borderRadius:"50%",border:"none",background:r?"var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))":"var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",color:"var(--nice-color-white, #fff)",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.2s",...s},children:n.jsx(y.NiceIcon,{name:i,size:18})}),n.jsx("span",{style:{fontSize:9,color:"var(--nice-overlay-light-50, rgba(255, 255, 255, 0.5))",textAlign:"center",maxWidth:50},children:e})]})}const Xt=[],Zt=[],Qt=["๐","โค๏ธ","๐","๐ฎ","๐ข","๐"];function Be({message:i,author:e,isMine:t,showAvatar:r,enableReactions:s,onReact:a,onReply:o,onEdit:d,onDelete:u,onPin:p,onOpenThread:g}){var C,A,U,M;const{t:c}=y.useNiceTranslation(),[f,m]=l.useState(!1),[w,k]=l.useState(!1),T=i.isDeleted,h=i.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.jsxs("div",{className:`nice-chat-message${t?" nice-chat-message--mine":""}${i.isPinned?" nice-chat-message--pinned":""}`,onMouseEnter:()=>m(!0),onMouseLeave:()=>{m(!1),k(!1)},children:[r&&!t&&n.jsxs("div",{style:{position:"relative",flexShrink:0},children:[n.jsx("div",{className:"nice-chat-avatar",style:{width:32,height:32,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontSize:13,fontWeight:600,flexShrink:0},children:!(e!=null&&e.avatarUrl)&&(((A=(C=e==null?void 0:e.name)==null?void 0:C[0])==null?void 0:A.toUpperCase())??"?")}),n.jsx(he,{status:((U=e==null?void 0:e.presence)==null?void 0:U.status)??"unknown",size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),n.jsxs("div",{style:{maxWidth:"70%",display:"flex",flexDirection:"column",alignItems:t?"flex-end":"flex-start"},children:[!t&&e&&n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginBottom:2,paddingLeft:2},children:e.displayName??e.name}),i.replyTo&&n.jsx("div",{className:"nice-chat-reply-preview",style:{borderLeft:"3px solid var(--nice-info, #6366f1)",paddingLeft:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)",marginBottom:4,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.replyTo.content}),n.jsx("div",{className:`nice-chat-bubble${t?" nice-chat-bubble--mine":""}`,style:{padding:"8px 12px",borderRadius:t?"18px 18px 4px 18px":"18px 18px 18px 4px",background:t?"var(--nice-info, #6366f1)":"var(--nice-bg-secondary, #f3f4f6)",color:t?"var(--nice-color-white, #fff)":"var(--nice-text, #111827)",fontSize:14,lineHeight:1.5,wordBreak:"break-word"},children:T?n.jsx("span",{style:{fontStyle:"italic",opacity:.6},children:c("chatWindow.thisMessageWasDeleted","This message was deleted")}):i.contentType==="image"&&((M=i.attachments)!=null&&M[0])?n.jsx("img",{src:i.attachments[0].url,alt:i.attachments[0].name,style:{maxWidth:280,maxHeight:280,borderRadius:8,display:"block"}}):n.jsx("span",{children:i.content})}),!T&&i.attachments&&i.attachments.length>0&&i.contentType!=="image"&&n.jsx("div",{className:"nice-chat-attachments",style:{marginTop:4},children:i.attachments.map(P=>n.jsxs("a",{href:P.url,target:"_blank",rel:"noreferrer",className:"nice-chat-attachment",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:12,color:t?"var(--nice-overlay-light-85, rgba(255, 255, 255, 0.85))":"var(--nice-info, #6366f1)",textDecoration:"none",background:t?"var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))":"var(--nice-primary-bg, #e0e7ff)",borderRadius:6,padding:"3px 8px",marginTop:2},children:[n.jsx(y.NiceIcon,{name:"paperclip",size:14})," ",P.name]},P.id))}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:2},children:[n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:h}),i.editedAt&&n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:c("chatWindow.edited","(edited)")}),t&&n.jsx("span",{style:{display:"inline-flex",alignItems:"center",color:i.status==="read"?"var(--nice-info, #6366f1)":"var(--nice-text-muted, #9ca3af)"},children:i.status==="sending"?n.jsx(y.NiceIcon,{name:"circle",size:12}):i.status==="sent"?n.jsx(y.NiceIcon,{name:"check",size:12}):n.jsxs("span",{style:{display:"inline-flex",marginRight:-6},children:[n.jsx(y.NiceIcon,{name:"check",size:12}),n.jsx(y.NiceIcon,{name:"check",size:12})]})})]}),i.reactions&&i.reactions.length>0&&n.jsx("div",{className:"nice-chat-reactions",style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:i.reactions.map(P=>n.jsxs("button",{onClick:()=>a(i.id,P.emoji),style:{background:P.mine?"var(--nice-primary-bg, #e0e7ff)":"var(--nice-bg-secondary, #f3f4f6)",border:P.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:[P.emoji," ",P.count]},P.emoji))}),(i.threadCount??0)>0&&n.jsxs("button",{className:"nice-chat-thread-btn",onClick:()=>g==null?void 0:g(i),style:{background:"none",border:"none",color:"var(--nice-info, #6366f1)",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:2,display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(y.NiceIcon,{name:"message",size:14})," ",i.threadCount===1?c("chatWindow.repliesOne","{threadCount} reply").replace("{threadCount}",String(i.threadCount??"")):c("chatWindow.repliesMany","{threadCount} replies").replace("{threadCount}",String(i.threadCount??""))]})]}),f&&!T&&n.jsxs("div",{className:"nice-chat-actions",style:{position:"absolute",top:-16,[t?"left":"right"]:16,display:"flex",gap:2,background:"var(--nice-bg, #fff)",borderRadius:8,boxShadow:"0 2px 8px var(--nice-overlay-12, rgba(0, 0, 0, 0.12))",padding:"3px 6px",zIndex:10},children:[s&&n.jsxs("div",{style:{position:"relative"},children:[n.jsx("button",{title:c("chatWindow.react","React"),"aria-label":c("chatWindow.react","React"),onClick:()=>k(P=>!P),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:n.jsx(y.NiceIcon,{name:"heart",size:16})}),w&&n.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:Qt.map(P=>n.jsx("button",{onClick:()=>{a(i.id,P),k(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:P},P))})]}),n.jsx("button",{title:c("chatWindow.reply","Reply"),"aria-label":c("chatWindow.reply","Reply"),onClick:()=>o(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:n.jsx(y.NiceIcon,{name:"reply",size:16})}),t&&d&&n.jsx("button",{title:c("chatWindow.edit","Edit"),"aria-label":c("chatWindow.edit","Edit"),onClick:()=>d(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:n.jsx(y.NiceIcon,{name:"edit",size:16})}),p&&n.jsx("button",{title:i.isPinned?c("chatWindow.unpin","Unpin"):c("chatWindow.pin","Pin"),"aria-label":i.isPinned?c("chatWindow.unpin","Unpin"):c("chatWindow.pin","Pin"),onClick:()=>p(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:n.jsx(y.NiceIcon,{name:"map-pin",size:16})}),t&&u&&n.jsx("button",{title:c("chatWindow.delete","Delete"),"aria-label":c("chatWindow.delete","Delete"),onClick:()=>u(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px",color:"var(--nice-danger, #ef4444)"},children:n.jsx(y.NiceIcon,{name:"trash",size:16})})]})]})}function dt({placeholder:i,maxLength:e,replyTo:t,onCancelReply:r,onSend:s,onAttach:a,disabled:o}){const{t:d}=y.useNiceTranslation(),u=i??d("chatWindow.typeAMessage","Type a messageโฆ"),[p,g]=l.useState(""),c=l.useRef(null);l.useEffect(()=>{t&&c.current&&c.current.focus()},[t]);const f=k=>{k.key==="Enter"&&!k.shiftKey&&(k.preventDefault(),m())},m=()=>{const k=p.trim();k&&(s(k),g(""),c.current&&(c.current.style.height="auto"))},w=k=>{g(k.target.value),k.target.style.height="auto",k.target.style.height=`${Math.min(k.target.scrollHeight,120)}px`};return n.jsxs("div",{className:"nice-chat-input-area",style:{padding:"8px 12px",borderTop:"1px solid var(--nice-border, #e5e7eb)",background:"var(--nice-bg, #fff)"},children:[t&&n.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:[n.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d("chatWindow.replying","Replying: {content}").replace("{content}",String(t.content))}),n.jsx("button",{onClick:r,title:d("chatWindow.cancelReply","Cancel reply"),"aria-label":d("chatWindow.cancelReply","Cancel reply"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",marginLeft:8,display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"close",size:16})})]}),n.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:8},children:[a&&n.jsx("button",{onClick:a,title:d("chatWindow.attachFile","Attach file"),"aria-label":d("chatWindow.attachFile","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:n.jsx(y.NiceIcon,{name:"paperclip",size:18})}),n.jsx("textarea",{ref:c,value:p,onChange:w,onKeyDown:f,placeholder:u,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"}}),n.jsx("button",{onClick:m,disabled:!p.trim()||o,title:d("chatWindow.send","Send"),"aria-label":d("chatWindow.send","Send"),style:{background:p.trim()?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)",border:"none",borderRadius:"50%",width:36,height:36,cursor:p.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--nice-color-white, #fff)",transition:"background 0.15s"},children:n.jsx(y.NiceIcon,{name:"send",size:16})})]}),e&&p.length>e*.8&&n.jsxs("div",{style:{textAlign:"right",fontSize:11,color:p.length>=e?"var(--nice-danger, #ef4444)":"var(--nice-text-muted, #9ca3af)",marginTop:2},children:[p.length,"/",e]})]})}function Re({conversation:i,messages:e=Xt,users:t=Zt,currentUser:r,isLoading:s=!1,hasMore:a=!1,showHeader:o=!0,showUserAvatars:d=!0,enableReactions:u=!0,enableThreads:p=!0,enableAttachments:g=!0,placeholder:c,maxMessageLength:f,onSendMessage:m,onEditMessage:w,onDeleteMessage:k,onReactToMessage:T,onPinMessage:h,onLoadMoreMessages:C,onStartCall:A,className:U,style:M,id:P,"data-testid":G}){var H,S;const{t:F}=y.useNiceTranslation(),L=l.useRef(null),N=l.useRef(null),[z,E]=l.useState(null),[V,J]=l.useState(null),j=l.useMemo(()=>{const b=new Map;return t.forEach(Y=>b.set(Y.id,Y)),b},[t]);l.useEffect(()=>{var b;(b=L.current)==null||b.scrollIntoView({behavior:"smooth"})},[e]);const O=l.useCallback(()=>{const b=N.current;!b||!a||s||b.scrollTop===0&&e.length>0&&(C==null||C(i.id,e[0].id))},[a,s,e,i.id,C]),Z=l.useCallback(b=>{m==null||m(i.id,b,"text"),E(null)},[i.id,m]),D=i.type==="dm"?j.get(i.participantIds.find(b=>b!==r.id)??""):void 0;return n.jsxs("div",{id:P,"data-testid":G,className:`nice-chat-window${U?` ${U}`:""}`,style:{display:"flex",flexDirection:"column",height:"100%",background:"var(--nice-bg, #fff)",...M},children:[o&&n.jsxs("div",{className:"nice-chat-header",style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:(D??i).avatarUrl?`url(${(D??i).avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:15,flexShrink:0},children:!(D??i).avatarUrl&&((H=((D==null?void 0:D.name)??i.name??"?")[0])==null?void 0:H.toUpperCase())}),n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600,fontSize:15},children:(D==null?void 0:D.displayName)??(D==null?void 0:D.name)??i.name??F("chatWindow.chat","Chat")}),D&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:1},children:[n.jsx(he,{status:D.presence.status,size:"xs"}),n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:D.presence.statusMessage??D.presence.status})]}),i.type!=="dm"&&n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:F("chatWindow.members","{participantIds} members").replace("{participantIds}",String(i.participantIds.length))})]})]}),i.type==="dm"&&A&&D&&n.jsxs("div",{style:{display:"flex",gap:4},children:[n.jsx("button",{onClick:()=>A([D.id],"audio"),title:F("chatWindow.audioCall","Audio call"),"aria-label":F("chatWindow.audioCall","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:n.jsx(y.NiceIcon,{name:"phone",size:16})}),n.jsx("button",{onClick:()=>A([D.id],"video"),title:F("chatWindow.videoCall","Video call"),"aria-label":F("chatWindow.videoCall","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:n.jsx(y.NiceIcon,{name:"video",size:16})})]})]}),n.jsxs("div",{ref:N,className:"nice-chat-messages",onScroll:O,style:{flex:1,overflowY:"auto",padding:"8px 0",display:"flex",flexDirection:"column"},children:[a&&n.jsx("button",{onClick:()=>e.length>0&&(C==null?void 0:C(i.id,e[0].id)),disabled:s,style:{display:"block",margin:"8px auto",background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,padding:"4px 16px",fontSize:12,color:"var(--nice-text-secondary, #6b7280)",cursor:"pointer"},children:s?F("chatWindow.loading","Loadingโฆ"):F("chatWindow.loadOlderMessages","Load older messages")}),e.map((b,Y)=>{const X=e[Y-1],Q=d&&(!X||X.authorId!==b.authorId);return n.jsx(Be,{message:b,author:j.get(b.authorId),isMine:b.authorId===r.id,showAvatar:Q,enableReactions:u,onReact:(K,ie)=>T==null?void 0:T(K,ie),onReply:K=>E(K),onEdit:w?K=>w(K.id,K.content):void 0,onDelete:k?K=>k(K.id):void 0,onPin:h?K=>h(K.id):void 0,onOpenThread:p?K=>J(K):void 0},b.id)}),n.jsx("div",{ref:L})]}),V&&n.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:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid var(--nice-border, #e5e7eb)"},children:[n.jsx("span",{style:{fontWeight:600,fontSize:14},children:F("chatWindow.thread","Thread")}),n.jsx("button",{onClick:()=>J(null),title:F("chatWindow.closeThread","Close thread"),"aria-label":F("chatWindow.closeThread","Close thread"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"close",size:18})})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[n.jsx(Be,{message:V,author:j.get(V.authorId),isMine:V.authorId===r.id,showAvatar:!0,enableReactions:u,onReact:(b,Y)=>T==null?void 0:T(b,Y),onReply:()=>{}}),(S=V.thread)==null?void 0:S.map(b=>n.jsx(Be,{message:b,author:j.get(b.authorId),isMine:b.authorId===r.id,showAvatar:!0,enableReactions:u,onReact:(Y,X)=>T==null?void 0:T(Y,X),onReply:()=>{}},b.id))]}),n.jsx(dt,{placeholder:F("chatWindow.replyInThread","Reply in threadโฆ"),onSend:b=>m==null?void 0:m(i.id,b,"text")})]}),n.jsx(dt,{placeholder:c,maxLength:f,replyTo:z,onCancelReply:()=>E(null),onSend:Z,onAttach:g?()=>{}:void 0})]})}const en=[],tn=[];function nn({conversation:i,partner:e,isActive:t,lastMessage:r,onClick:s}){var c;const{t:a}=y.useNiceTranslation(),o=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??i.name??"Group",d=((c=o[0])==null?void 0:c.toUpperCase())??"?",u=(e==null?void 0:e.avatarUrl)??i.avatarUrl,p=r?r.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"",g=r?r.isDeleted?"Message deleted":r.content.slice(0,50):"";return n.jsxs("button",{className:`nice-messenger-conv-item${t?" nice-messenger-conv-item--active":""}`,onClick:s,style:{display:"flex",alignItems:"center",gap:10,padding:"10px 14px",background:t?"var(--nice-accent-tint-10, #ede9fe)":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",position:"relative"},children:[n.jsxs("div",{style:{position:"relative",flexShrink:0},children:[n.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:u?`url(${u}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-color-white, #fff)",fontWeight:700,fontSize:16},children:!u&&d}),e&&n.jsx(he,{status:e.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}}),i.type!=="dm"&&n.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:n.jsx(y.NiceIcon,{name:"hash",size:10})})]}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline"},children:[n.jsx("span",{style:{fontWeight:i.unreadCount>0?700:500,fontSize:14,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o}),n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",flexShrink:0,marginLeft:4},children:p})]}),n.jsx("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:g})]}),(i.unreadCount>0||i.mentionCount>0)&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,alignItems:"flex-end",flexShrink:0},children:[i.mentionCount>0&&n.jsxs("span",{style:{background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:["@",i.mentionCount]}),i.unreadCount>0&&n.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:i.unreadCount>99?"99+":i.unreadCount})]}),i.isMuted&&n.jsx("span",{style:{position:"absolute",bottom:8,right:8,color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex"},children:n.jsx(y.NiceIcon,{name:"mic",size:12,title:a("messenger.muted","Muted")})})]})}function Ct({conversations:i=en,messages:e,users:t=tn,currentUser:r,activeConversationId:s,teams:a,enableGroupConversations:o=!0,showPresence:d=!0,enableSearch:u=!0,onSendMessage:p,onEditMessage:g,onDeleteMessage:c,onReactToMessage:f,onPinMessage:m,onLoadMoreMessages:w,onMarkAsRead:k,onStartCall:T,onCreateConversation:h,className:C,style:A,id:U,"data-testid":M}){var S;const{t:P}=y.useNiceTranslation(),[G,F]=l.useState(s??null),[L,N]=l.useState(""),[z,E]=l.useState("all");l.useMemo(()=>{const b=new Map;return t.forEach(Y=>b.set(Y.id,Y)),b},[t]);const V=l.useMemo(()=>{let b=i;if(z==="unread"&&(b=b.filter(Y=>Y.unreadCount>0)),z==="groups"&&(b=b.filter(Y=>Y.type!=="dm")),L.trim()){const Y=L.toLowerCase();b=b.filter(X=>{var K,ie;const Q=Ge(X,r.id,t);return(Q==null?void 0:Q.name.toLowerCase().includes(Y))||((K=X.name)==null?void 0:K.toLowerCase().includes(Y))||((ie=X.lastMessage)==null?void 0:ie.content.toLowerCase().includes(Y))})}return[...b].sort((Y,X)=>{var ie,de;if(Y.isPinned!==X.isPinned)return Y.isPinned?-1:1;const Q=((ie=Y.lastMessage)==null?void 0:ie.timestamp.getTime())??Y.updatedAt.getTime();return(((de=X.lastMessage)==null?void 0:de.timestamp.getTime())??X.updatedAt.getTime())-Q})},[i,z,L,r.id,t]),J=l.useMemo(()=>i.find(b=>b.id===G)??null,[i,G]),j=l.useMemo(()=>G?e[G]??[]:[],[e,G]),O=l.useCallback(b=>{F(b),k==null||k(b)},[k]),Z=l.useMemo(()=>et(i),[i]),D=a??[],H=t.filter(b=>b.id!==r.id&&b.presence.status==="online").slice(0,6);return n.jsxs("div",{id:U,"data-testid":M,className:`nice-messenger${C?` ${C}`:""}`,style:{display:"flex",height:"100%",background:"var(--nice-bg, #fff)",overflow:"hidden",...A},children:[n.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:[n.jsxs("div",{style:{padding:"14px 14px 8px",borderBottom:"1px solid var(--nice-border, #e5e7eb)"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("span",{style:{fontWeight:700,fontSize:16},children:[P("messenger.messages","Messages")," ",Z>0&&n.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:10,padding:"1px 6px",fontWeight:700,marginLeft:4},children:Z})]}),o&&h&&n.jsx("button",{onClick:()=>h([],"group"),title:P("messenger.newConversation","New conversation"),"aria-label":P("messenger.newConversation","New conversation"),style:{background:"var(--nice-info, #6366f1)",border:"none",borderRadius:6,padding:"5px 8px",cursor:"pointer",color:"var(--nice-text-on-primary, #fff)",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"plus",size:13})})]}),u&&n.jsx("input",{type:"search",value:L,onChange:b=>N(b.target.value),placeholder:P("messenger.searchConversations","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)"}}),n.jsx("div",{style:{display:"flex",gap:2,marginTop:8},children:["all","unread","groups"].map(b=>n.jsx("button",{onClick:()=>E(b),style:{flex:1,padding:"4px 0",border:"none",borderRadius:6,background:z===b?"var(--nice-info, #6366f1)":"transparent",color:z===b?"var(--nice-color-white, #fff)":"var(--nice-text-secondary, #6b7280)",cursor:"pointer",fontSize:12,textTransform:"capitalize",fontWeight:z===b?600:400},children:b},b))})]}),d&&H.length>0&&n.jsxs("div",{style:{padding:"8px 14px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",overflowX:"auto"},children:[n.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",marginBottom:6},children:P("messenger.onlineNow","ONLINE NOW")}),n.jsx("div",{style:{display:"flex",gap:10},children:H.map(b=>{var Y;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:3},children:[n.jsxs("div",{style:{position:"relative"},children:[n.jsx("div",{style:{width:34,height:34,borderRadius:"50%",background:b.avatarUrl?`url(${b.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:13,cursor:"pointer"},title:b.name,children:!b.avatarUrl&&((Y=b.name[0])==null?void 0:Y.toUpperCase())}),n.jsx(he,{status:b.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),n.jsx("span",{style:{fontSize:10,color:"var(--nice-text-secondary, #6b7280)",maxWidth:36,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.displayName??b.name.split(" ")[0]})]},b.id)})})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[D.length>0&&z==="all"&&n.jsx("div",{style:{padding:"8px 14px 4px",fontSize:11,color:"var(--nice-text-muted, #9ca3af)",fontWeight:600,letterSpacing:"0.05em"},children:P("messenger.directMessages","DIRECT MESSAGES")}),V.length===0?n.jsx("div",{style:{padding:24,textAlign:"center",color:"var(--nice-text-muted, #9ca3af)",fontSize:13},children:P("messenger.noConversations","No conversations")}):V.map(b=>n.jsx(nn,{conversation:b,partner:Ge(b,r.id,t),isActive:b.id===G,lastMessage:b.lastMessage,onClick:()=>O(b.id)},b.id))]}),n.jsxs("div",{style:{padding:"10px 14px",borderTop:"1px solid var(--nice-border, #e5e7eb)",display:"flex",alignItems:"center",gap:8},children:[n.jsxs("div",{style:{position:"relative"},children:[n.jsx("div",{style:{width:32,height:32,borderRadius:"50%",background:r.avatarUrl?`url(${r.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:13},children:!r.avatarUrl&&((S=r.name[0])==null?void 0:S.toUpperCase())}),n.jsx(he,{status:r.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontWeight:600,fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.displayName??r.name}),n.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.presence.statusMessage??r.presence.status})]})]})]}),n.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:J?n.jsx(Re,{conversation:J,messages:j,users:t,currentUser:r,onSendMessage:p,onEditMessage:g,onDeleteMessage:c,onReactToMessage:f,onPinMessage:m,onLoadMoreMessages:w,onStartCall:T,style:{height:"100%"}}):n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"var(--nice-text-muted, #9ca3af)",gap:12},children:[n.jsx(y.NiceIcon,{name:"message",size:48}),n.jsx("span",{style:{fontSize:15},children:P("messenger.selectAConversationToStart","Select a conversation to start messaging")})]})})]})}const rn=[],sn=[],an=["๐","โค๏ธ","๐","๐","๐ฎ","๐ข"];function Ue({message:i,author:e,isMine:t,enableReactions:r,enableThreads:s,onReact:a,onOpenThread:o,onReply:d}){var k,T,h;const{t:u}=y.useNiceTranslation(),[p,g]=l.useState(!1),[c,f]=l.useState(!1),m=i.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),w=i.timestamp.toLocaleDateString([],{month:"short",day:"numeric"});return n.jsxs("div",{className:`nice-channel-msg${p?" nice-channel-msg--hovered":""}${t?" nice-channel-msg--mine":""}`,onMouseEnter:()=>g(!0),onMouseLeave:()=>{g(!1),f(!1)},children:[n.jsx("div",{style:{width:36,flexShrink:0},children:n.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:14},children:!(e!=null&&e.avatarUrl)&&(((T=(k=e==null?void 0:e.name)==null?void 0:k[0])==null?void 0:T.toUpperCase())??"?")})}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:2},children:[n.jsx("span",{style:{fontWeight:600,fontSize:14,color:"var(--nice-text, #111827)"},children:(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??u("channelView.unknown","Unknown")}),e&&n.jsx(he,{status:e.presence.status,size:"xs"}),n.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:[w," ",m]}),i.editedAt&&n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:u("channelView.edited","(edited)")}),i.isPinned&&n.jsxs("span",{style:{fontSize:11,color:"var(--nice-info, #6366f1)",display:"inline-flex",alignItems:"center",gap:3},children:[n.jsx(y.NiceIcon,{name:"map-pin",size:12})," ",u("channelView.pinned","Pinned")]})]}),i.isDeleted?n.jsx("span",{style:{fontStyle:"italic",color:"var(--nice-text-muted, #9ca3af)",fontSize:14},children:u("channelView.thisMessageWasDeleted","This message was deleted")}):n.jsx("div",{style:{fontSize:14,lineHeight:1.6,color:"var(--nice-text, #1f2937)",wordBreak:"break-word"},children:i.contentType==="image"&&((h=i.attachments)!=null&&h[0])?n.jsx("img",{src:i.attachments[0].url,alt:i.attachments[0].name,style:{maxWidth:400,maxHeight:300,borderRadius:8,display:"block",marginTop:4}}):i.content}),!i.isDeleted&&i.attachments&&i.attachments.length>0&&i.contentType!=="image"&&n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:4},children:i.attachments.map(C=>n.jsxs("a",{href:C.url,target:"_blank",rel:"noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:12,color:"var(--nice-info, #6366f1)",background:"var(--nice-accent-tint-10, #ede9fe)",borderRadius:6,padding:"3px 8px",textDecoration:"none"},children:[n.jsx(y.NiceIcon,{name:"paperclip",size:14})," ",C.name]},C.id))}),i.reactions&&i.reactions.length>0&&n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:i.reactions.map(C=>n.jsxs("button",{onClick:()=>a(i.id,C.emoji),style:{background:C.mine?"var(--nice-accent-tint-10, #ede9fe)":"var(--nice-bg-secondary, #f3f4f6)",border:C.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:[C.emoji," ",C.count]},C.emoji))}),s&&(i.threadCount??0)>0&&n.jsxs("button",{onClick:()=>o(i),style:{background:"none",border:"none",color:"var(--nice-info, #6366f1)",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:3,display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(y.NiceIcon,{name:"message",size:14})," ",i.threadCount===1?u("channelView.repliesOne","{threadCount} reply").replace("{threadCount}",String(i.threadCount??"")):u("channelView.repliesMany","{threadCount} replies").replace("{threadCount}",String(i.threadCount??""))," ",n.jsx(y.NiceIcon,{name:"arrow-right",size:12})]})]}),p&&!i.isDeleted&&n.jsxs("div",{style:{position:"absolute",top:-16,right:16,display:"flex",gap:2,background:"var(--nice-bg, #fff)",borderRadius:8,boxShadow:"0 2px 8px var(--nice-overlay-12, rgba(0, 0, 0, 0.12))",padding:"3px 6px",zIndex:10},children:[r&&n.jsxs("div",{style:{position:"relative"},children:[n.jsx("button",{onClick:()=>f(C=>!C),title:u("channelView.react","React"),"aria-label":u("channelView.react","React"),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:n.jsx(y.NiceIcon,{name:"heart",size:16})}),c&&n.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:an.map(C=>n.jsx("button",{onClick:()=>{a(i.id,C),f(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:C},C))})]}),n.jsx("button",{onClick:()=>d(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},title:u("channelView.reply","Reply"),"aria-label":u("channelView.reply","Reply"),children:n.jsx(y.NiceIcon,{name:"reply",size:16})}),s&&n.jsx("button",{onClick:()=>o(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},title:u("channelView.openThread","Open thread"),"aria-label":u("channelView.openThread","Open thread"),children:n.jsx(y.NiceIcon,{name:"message",size:16})})]})]})}function It({channel:i,messages:e=rn,users:t=sn,currentUser:r,team:s,isLoading:a=!1,hasMore:o=!1,enableThreads:d=!0,enableReactions:u=!0,enableAttachments:p=!0,onSendMessage:g,onEditMessage:c,onDeleteMessage:f,onReactToMessage:m,onPinMessage:w,onLoadMoreMessages:k,onStartCall:T,className:h,style:C,id:A,"data-testid":U}){var H;const{t:M}=y.useNiceTranslation(),P=l.useRef(null),G=l.useRef(null),[F,L]=l.useState(""),[N,z]=l.useState(null),[E,V]=l.useState(null),J=l.useMemo(()=>{const S=new Map;return t.forEach(b=>S.set(b.id,b)),S},[t]);l.useEffect(()=>{var S;(S=P.current)==null||S.scrollIntoView({behavior:"smooth"})},[e]);const j=l.useCallback(()=>{const S=G.current;!S||!o||a||S.scrollTop===0&&e.length>0&&(k==null||k(i.id,e[0].id))},[o,a,e,i.id,k]),O=l.useCallback(()=>{const S=F.trim();S&&(g==null||g(i.id,S,"text"),L(""),z(null))},[F,i.id,g]),Z=S=>{S.key==="Enter"&&!S.shiftKey&&(S.preventDefault(),O())},D=t.filter(S=>S.presence.status==="online").length;return n.jsxs("div",{id:A,"data-testid":U,className:`nice-channel-view${h?` ${h}`:""}`,style:{display:"flex",height:"100%",background:"var(--nice-bg, #fff)",overflow:"hidden",...C},children:[n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsx(y.NiceIcon,{name:"hash",size:20,style:{color:"var(--nice-text-secondary, #6b7280)"}}),n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:700,fontSize:16},children:i.name}),(i.topic||i.description)&&n.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",marginTop:1},children:[i.topic&&n.jsx("span",{className:"nice-channel-view__topic",style:{fontWeight:600,color:"var(--nice-text-primary, #111827)"},children:i.topic}),i.topic&&i.description&&" ยท ",i.description]})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:[n.jsx("span",{style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:"var(--nice-success, #22c55e)",marginRight:4,verticalAlign:"middle"}}),M("channelView.online","{onlineCount} online").replace("{onlineCount}",String(D))]}),T&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>T(t.map(S=>S.id),"audio"),style:{background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"5px 8px",cursor:"pointer",display:"inline-flex",alignItems:"center"},title:M("channelView.audioCall","Audio call"),"aria-label":M("channelView.audioCall","Audio call"),children:n.jsx(y.NiceIcon,{name:"phone",size:15})}),n.jsx("button",{onClick:()=>T(t.map(S=>S.id),"video"),style:{background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"5px 8px",cursor:"pointer",display:"inline-flex",alignItems:"center"},title:M("channelView.videoMeet","Video meet"),"aria-label":M("channelView.videoMeet","Video meet"),children:n.jsx(y.NiceIcon,{name:"video",size:15})})]})]})]}),n.jsxs("div",{ref:G,onScroll:j,style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[o&&n.jsx("button",{onClick:()=>e.length>0&&(k==null?void 0:k(i.id,e[0].id)),disabled:a,style:{display:"block",margin:"8px auto",background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,padding:"4px 16px",fontSize:12,color:"var(--nice-text-secondary, #6b7280)",cursor:"pointer"},children:a?M("channelView.loading","Loadingโฆ"):M("channelView.loadOlderMessages","Load older messages")}),e.map(S=>n.jsx(Ue,{message:S,author:J.get(S.authorId),isMine:S.authorId===r.id,enableReactions:u,enableThreads:d,onReact:(b,Y)=>m==null?void 0:m(b,Y),onOpenThread:b=>V(b),onReply:b=>z(b)},S.id)),n.jsx("div",{ref:P})]}),n.jsxs("div",{style:{padding:"8px 16px",borderTop:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[N&&n.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:[n.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M("channelView.replyingTo","Replying to: {content}").replace("{content}",String(N.content))}),n.jsx("button",{onClick:()=>z(null),title:M("channelView.cancelReply","Cancel reply"),"aria-label":M("channelView.cancelReply","Cancel reply"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"close",size:16})})]}),n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-end"},children:[p&&n.jsx("button",{title:M("channelView.attach","Attach"),"aria-label":M("channelView.attach","Attach"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",padding:"6px 4px",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"paperclip",size:18})}),n.jsx("textarea",{value:F,onChange:S=>L(S.target.value),onKeyDown:Z,placeholder:M("channelView.message","Message #{name}").replace("{name}",String(i.name)),rows:1,style:{flex:1,resize:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:"8px 12px",fontSize:14,outline:"none",fontFamily:"inherit",lineHeight:1.5,overflow:"hidden",maxHeight:100}}),n.jsx("button",{onClick:O,disabled:!F.trim(),title:M("channelView.send","Send"),"aria-label":M("channelView.send","Send"),style:{background:F.trim()?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)",border:"none",borderRadius:"50%",width:36,height:36,cursor:F.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--nice-color-white, #fff)",transition:"background 0.15s"},children:n.jsx(y.NiceIcon,{name:"send",size:15})})]})]})]}),E&&n.jsxs("div",{style:{width:340,flexShrink:0,borderLeft:"1px solid var(--nice-border, #e5e7eb)",display:"flex",flexDirection:"column",overflow:"hidden"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[n.jsx("span",{style:{fontWeight:600,fontSize:14},children:M("channelView.thread","Thread")}),n.jsx("button",{onClick:()=>V(null),title:M("channelView.closeThread","Close thread"),"aria-label":M("channelView.closeThread","Close thread"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"close",size:18})})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[n.jsx(Ue,{message:E,author:J.get(E.authorId),isMine:E.authorId===r.id,enableReactions:u,enableThreads:!1,onReact:(S,b)=>m==null?void 0:m(S,b),onOpenThread:()=>{},onReply:()=>{}}),n.jsx("div",{style:{padding:"6px 14px",color:"var(--nice-text-muted, #9ca3af)",fontSize:12,borderTop:"1px solid var(--nice-bg-secondary, #f3f4f6)"},children:E.threadCount===1?M("channelView.repliesOne","{threadCount} reply").replace("{threadCount}",String(E.threadCount??0)):M("channelView.repliesMany","{threadCount} replies").replace("{threadCount}",String(E.threadCount??0))}),(H=E.thread)==null?void 0:H.map(S=>n.jsx(Ue,{message:S,author:J.get(S.authorId),isMine:S.authorId===r.id,enableReactions:u,enableThreads:!1,onReact:(b,Y)=>m==null?void 0:m(b,Y),onOpenThread:()=>{},onReply:()=>{}},S.id))]}),n.jsx("div",{style:{padding:"8px 12px",borderTop:"1px solid var(--nice-border, #e5e7eb)"},children:n.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-end"},children:[n.jsx("textarea",{placeholder:M("channelView.replyInThread","Reply in threadโฆ"),rows:1,onKeyDown:S=>{if(S.key==="Enter"&&!S.shiftKey){S.preventDefault();const b=S.target.value.trim();b&&(g==null||g(i.id,b,"text"),S.target.value="")}},style:{flex:1,resize:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:"7px 10px",fontSize:13,outline:"none",fontFamily:"inherit",overflow:"hidden"}}),n.jsx("button",{title:M("channelView.send","Send"),"aria-label":M("channelView.send","Send"),style:{background:"var(--nice-info, #6366f1)",border:"none",borderRadius:"50%",width:32,height:32,cursor:"pointer",color:"var(--nice-text-on-primary, #fff)",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsx(y.NiceIcon,{name:"send",size:14})})]})})]})]})}function He({participant:i,isLocal:e,isPinned:t,onPin:r,size:s="medium",fill:a=!1}){var h;const{t:o}=y.useNiceTranslation(),d=l.useRef(null),{user:u,isMuted:p,isCameraOff:g,isScreenSharing:c,isSpeaking:f,isHandRaised:m,stream:w,screenStream:k}=i;l.useEffect(()=>{if(!d.current)return;const C=c?k:w;C&&(d.current.srcObject=C)},[w,k,c]);const T=!g&&!!w;return n.jsxs("div",{className:`nice-conference-tile${f?" nice-conference-tile--speaking":""}${t?" nice-conference-tile--pinned":""}`,style:a?{height:"100%",minHeight:0}:{aspectRatio:"16/9"},children:[T?n.jsx("video",{ref:d,autoPlay:!0,muted:e,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"cover",transform:e&&!c?"scaleX(-1)":"none"}}):n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:8},children:[n.jsx("div",{style:{width:s==="large"?64:s==="small"?28:44,height:s==="large"?64:s==="small"?28:44,borderRadius:"50%",background:u.avatarUrl?`url(${u.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:s==="large"?28:s==="small"?12:18},children:!u.avatarUrl&&((h=u.name[0])==null?void 0:h.toUpperCase())}),s!=="small"&&n.jsx("span",{style:{color:"var(--nice-text-primary, #fff)",fontSize:12},children:u.displayName??u.name})]}),n.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:[n.jsxs("span",{style:{color:"var(--nice-color-white, #fff)",fontSize:11,fontWeight:500},children:[u.displayName??u.name,e&&o("videoConference.you"," (You)")]}),n.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[m&&n.jsx(y.NiceIcon,{name:"cursor",size:13}),p&&n.jsx(y.NiceIcon,{name:"mic",size:12}),c&&n.jsx(y.NiceIcon,{name:"monitor",size:12}),s!=="small"&&n.jsx("div",{style:{width:6,height:6,borderRadius:"50%",background:f?"var(--nice-success, #22c55e)":"transparent",border:"1px solid var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))"}})]})]}),s!=="small"&&n.jsx("button",{onClick:r,style:{position:"absolute",top:6,right:6,background:"var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",border:"none",borderRadius:4,padding:"2px 5px",color:t?"var(--nice-info, #6366f1)":"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))",cursor:"pointer",fontSize:12},title:t?o("videoConference.unpin","Unpin"):o("videoConference.pin","Pin"),"aria-label":t?o("videoConference.unpin","Unpin"):o("videoConference.pin","Pin"),children:n.jsx(y.NiceIcon,{name:"map-pin",size:12})}),i.connectionQuality!=="none"&&s!=="small"&&n.jsx("div",{style:{position:"absolute",top:6,left:6,width:14,height:10,display:"flex",gap:2,alignItems:"flex-end"},children:[1,2,3].map(C=>n.jsx("div",{style:{flex:1,background:i.connectionQuality==="excellent"||i.connectionQuality==="good"&&C<=2||i.connectionQuality==="fair"&&C<=1?"var(--nice-success, #22c55e)":"var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))",height:`${C*30}%`,borderRadius:1}},C))})]})}function nt({session:i,currentUser:e,localStream:t,enableScreenSharing:r=!0,enableRecording:s=!1,enableTranscription:a=!1,enableRaiseHand:o=!0,maxGridCols:d=4,onEndCall:u,onMuteAudio:p,onMuteVideo:g,onStartScreenShare:c,onStopScreenShare:f,onRaiseHand:m,className:w,style:k,id:T,"data-testid":h}){const{t:C}=y.useNiceTranslation(),[A,U]=l.useState(!1),[M,P]=l.useState(!1),[G,F]=l.useState(!1),[L,N]=l.useState(!1),[z,E]=l.useState(i.pinnedParticipantId??null),[V,J]=l.useState(i.layout==="sidebar"?"grid":i.layout??"grid"),[j,O]=l.useState(0),[Z,D]=l.useState(!1);l.useEffect(()=>{J(i.layout==="spotlight"?"spotlight":"grid")},[i.layout]),l.useEffect(()=>{if(i.status!=="active")return;const _=setInterval(()=>O(ee=>ee+1),1e3);return()=>clearInterval(_)},[i.status]);const H=_=>{const ee=Math.floor(_/3600),ae=Math.floor(_%3600/60),oe=_%60;return ee>0?`${ee}:${String(ae).padStart(2,"0")}:${String(oe).padStart(2,"0")}`:`${String(ae).padStart(2,"0")}:${String(oe).padStart(2,"0")}`},S=()=>{const _=!A;U(_),p==null||p(_)},b=()=>{const _=!M;P(_),g==null||g(_)},Y=async()=>{G?(F(!1),f==null||f()):(F(!0),await(c==null?void 0:c()))},X=()=>{const _=!L;N(_),m==null||m(_)},Q=[{user:e,isMuted:A,isCameraOff:M,isScreenSharing:G,isSpeaking:!1,isHandRaised:L,stream:t,connectionQuality:"excellent"},...i.participants.filter(_=>_.user.id!==e.id)],K=z?Q.find(_=>_.user.id===z):null,ie=K??(V==="spotlight"?Q.find(_=>_.isSpeaking)??Q[1]??Q[0]:null),de=Q.filter(_=>_.user.id!==(ie==null?void 0:ie.user.id)),ce=Q.length,xe=Math.min(d,ce<=1?1:ce<=2||ce<=4?2:ce<=9?3:4);return n.jsxs("div",{id:T,"data-testid":h,className:`nice-video-conference${w?` ${w}`:""}`,style:{position:"relative",width:"100%",height:"100%",background:"var(--nice-bg-primary, #111827)",display:"flex",flexDirection:"column",overflow:"hidden",...k},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 16px",flexShrink:0,color:"var(--nice-text-primary, #fff)"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[n.jsxs("span",{style:{fontSize:15,fontWeight:600},children:[i.id.slice(0,8),"โฆ"]}),n.jsx("span",{style:{fontSize:12,color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"},children:H(j)}),i.isRecording&&n.jsxs("span",{style:{fontSize:11,color:"var(--nice-danger, #ef4444)",display:"flex",alignItems:"center",gap:4},children:[n.jsx(y.NiceIcon,{name:"circle",size:11})," ",C("videoConference.recording","Recording")]})]}),n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[n.jsx("button",{onClick:()=>J(V==="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-color-white, #fff)",cursor:"pointer",fontSize:12},children:V==="grid"?n.jsxs(n.Fragment,{children:[n.jsx(y.NiceIcon,{name:"grid",size:14})," ",C("videoConference.grid","Grid")]}):n.jsxs(n.Fragment,{children:[n.jsx(y.NiceIcon,{name:"square",size:14})," ",C("videoConference.spotlight","Spotlight")]})}),n.jsxs("button",{onClick:()=>D(_=>!_),style:{display:"flex",alignItems:"center",gap:4,background:Z?"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-color-white, #fff)",cursor:"pointer",fontSize:12},children:[n.jsx(y.NiceIcon,{name:"users",size:14})," ",Q.length]})]})]}),n.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden",gap:4,padding:"0 8px 8px"},children:[n.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:4,overflow:"hidden"},children:ie?n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{flex:1,minHeight:0},children:n.jsx(He,{participant:ie,isLocal:ie.user.id===e.id,isPinned:K!=null,onPin:()=>E(K?null:ie.user.id),size:"large",fill:!0})}),n.jsx("div",{style:{display:"flex",gap:4,height:90,flexShrink:0,overflowX:"auto"},children:de.map(_=>n.jsx("div",{style:{width:140,flexShrink:0},children:n.jsx(He,{participant:_,isLocal:_.user.id===e.id,isPinned:!1,onPin:()=>E(_.user.id),size:"small"})},_.user.id))})]}):n.jsx("div",{style:{flex:1,display:"grid",gridTemplateColumns:`repeat(${xe}, 1fr)`,gridAutoRows:"minmax(0, 1fr)",gap:6,overflow:"hidden"},children:Q.map(_=>n.jsx(He,{participant:_,isLocal:_.user.id===e.id,isPinned:_.user.id===z,onPin:()=>E(ee=>ee===_.user.id?null:_.user.id),size:ce<=4?"large":"medium",fill:!0},_.user.id))})}),Z&&n.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:[n.jsx("div",{style:{padding:"10px 12px",fontWeight:600,fontSize:13,color:"var(--nice-text-primary, #fff)",borderBottom:"1px solid var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))"},children:C("videoConference.participants","Participants ({allParticipants})").replace("{allParticipants}",String(Q.length))}),n.jsx("div",{style:{flex:1,overflowY:"auto",padding:8},children:Q.map(_=>{var ee;return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px"},children:[n.jsx("div",{style:{width:28,height:28,borderRadius:"50%",background:_.user.avatarUrl?`url(${_.user.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontSize:11,fontWeight:700},children:!_.user.avatarUrl&&((ee=_.user.name[0])==null?void 0:ee.toUpperCase())}),n.jsx("div",{style:{flex:1,minWidth:0},children:n.jsxs("div",{style:{color:"var(--nice-text-primary, #fff)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[_.user.displayName??_.user.name,_.user.id===e.id&&C("videoConference.you"," (You)")]})}),n.jsxs("div",{style:{display:"flex",gap:3,alignItems:"center"},children:[_.isHandRaised&&n.jsx(y.NiceIcon,{name:"cursor",size:11}),_.isMuted&&n.jsx(y.NiceIcon,{name:"mic",size:11}),n.jsx(he,{status:_.user.presence.status,size:"xs"})]})]},_.user.id)})})]})]}),n.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:[n.jsx(be,{icon:"mic",label:A?C("videoConference.unmute","Unmute"):C("videoConference.mute","Mute"),onClick:S,danger:A}),n.jsx(be,{icon:M?"camera":"video",label:M?C("videoConference.startVideo","Start video"):C("videoConference.stopVideo","Stop video"),onClick:b,danger:M}),r&&n.jsx(be,{icon:"monitor",label:G?C("videoConference.stopShare","Stop share"):C("videoConference.share","Share"),onClick:()=>{Y()},active:G}),o&&n.jsx(be,{icon:"cursor",label:C("videoConference.raiseHand","Raise hand"),onClick:X,active:L}),s&&n.jsx(be,{icon:"circle",label:i.isRecording?C("videoConference.stopRec","Stop rec"):C("videoConference.record","Record"),onClick:()=>{},active:i.isRecording,danger:i.isRecording}),a&&n.jsx(be,{icon:"type",label:i.isTranscribing?C("videoConference.stopCaptions","Stop captions"):C("videoConference.captions","Captions"),onClick:()=>{},active:i.isTranscribing}),n.jsx(be,{icon:"phone",label:C("videoConference.leave","Leave"),onClick:()=>u==null?void 0:u(i.id),end:!0})]})]})}function be({icon:i,label:e,onClick:t,active:r,danger:s,end:a}){return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[n.jsx("button",{title:e,onClick:t,style:{width:46,height:46,borderRadius:"50%",border:"none",background:a?"var(--nice-danger, #ef4444)":s?"var(--nice-danger-dark, #450a0a)":r?"var(--nice-info, #6366f1)":"var(--nice-overlay-light-12, rgba(255, 255, 255, 0.12))",color:"var(--nice-color-white, #fff)",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.15s"},children:n.jsx(y.NiceIcon,{name:i,size:18})}),n.jsx("span",{style:{fontSize:9,color:"var(--nice-overlay-light-50, rgba(255, 255, 255, 0.5))",textAlign:"center",maxWidth:52},children:e})]})}function qe(i){const e={days:864e5,weeks:6048e5,months:2592e6,years:31536e6,forever:Number.MAX_SAFE_INTEGER};return i.unit==="forever"?e.forever:e[i.unit]*i.value}function ze(i,e=new Date){if(i.unit!=="forever")return new Date(e.getTime()+qe(i))}class pt{constructor(e="nice2dev-communication"){this.storeName="nice_comm_store",this.db=null,this.dbName=e}async openDb(){return this.db?this.db:new Promise((e,t)=>{const r=indexedDB.open(this.dbName,1);r.onupgradeneeded=s=>{const a=s.target.result;a.objectStoreNames.contains(this.storeName)||a.createObjectStore(this.storeName,{keyPath:"key"})},r.onsuccess=s=>{this.db=s.target.result,e(this.db)},r.onerror=()=>t(r.error)})}async save(e,t,r){const s=await this.openDb();return new Promise((a,o)=>{const p=s.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:e,data:t,expiresAt:r==null?void 0:r.toISOString()});p.onsuccess=()=>a(),p.onerror=()=>o(p.error)})}async load(e){const t=await this.openDb();return new Promise((r,s)=>{const d=t.transaction(this.storeName,"readonly").objectStore(this.storeName).get(e);d.onsuccess=()=>{const u=d.result;if(!u){r(void 0);return}if(u.expiresAt&&new Date(u.expiresAt)<new Date){this.delete(e),r(void 0);return}r(u.data)},d.onerror=()=>s(d.error)})}async delete(e){const t=await this.openDb();return new Promise((r,s)=>{const d=t.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(e);d.onsuccess=()=>r(),d.onerror=()=>s(d.error)})}async list(e){const t=await this.openDb();return new Promise((r,s)=>{const d=t.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();d.onsuccess=()=>r((d.result??[]).filter(u=>u.startsWith(e))),d.onerror=()=>s(d.error)})}async clear(e){if(!e){const r=await this.openDb();return new Promise((s,a)=>{const u=r.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();u.onsuccess=()=>s(),u.onerror=()=>a(u.error)})}const t=await this.list(e);await Promise.all(t.map(r=>this.delete(r)))}}class on{constructor(e="nice_comm__"){this.prefix=e}async save(e,t,r){const s={data:t,expiresAt:r==null?void 0:r.toISOString()};localStorage.setItem(this.prefix+e,JSON.stringify(s))}async load(e){const t=localStorage.getItem(this.prefix+e);if(t)try{const r=JSON.parse(t);if(r.expiresAt&&new Date(r.expiresAt)<new Date){await this.delete(e);return}return r.data}catch{return}}async delete(e){localStorage.removeItem(this.prefix+e)}async list(e){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&s.startsWith(this.prefix+e)&&t.push(s.slice(this.prefix.length))}return t}async clear(e){(await this.list(e??"")).forEach(r=>localStorage.removeItem(this.prefix+r))}}class Tt{constructor(e,t){this.config=e,this.encryption=t,this.adapter=this.buildAdapter()}buildAdapter(){switch(this.config.provider){case"localstorage":return new on;case"custom":return this.config.customAdapter??new pt;default:return new pt}}getRuleFor(e){return this.config.retentionRules.find(t=>t.dataType===e)}async encode(e){var r;const t=JSON.stringify(e);return(r=this.encryption)!=null&&r.isEnabled()?this.encryption.encrypt(t,"messages"):t}async decode(e){var t;if(typeof e!="string")return e;if(!((t=this.encryption)!=null&&t.isEnabled()))try{return JSON.parse(e)}catch{return e}try{const r=await this.encryption.decrypt(e,"messages");return JSON.parse(r)}catch{return e}}async saveMessages(e,t){const r=this.getRuleFor("messages"),s=r?ze(r.activePeriod):void 0,a=await this.encode(t);await this.adapter.save(`msg:${e}`,a,s)}async loadMessages(e){const t=await this.adapter.load(`msg:${e}`);if(!t)return[];const r=await this.decode(t);return Array.isArray(r)?r:[]}async appendMessage(e,t){const r=await this.loadMessages(e);await this.saveMessages(e,[...r,t])}async saveWhiteboardSnapshot(e,t){const r=this.getRuleFor("whiteboard-snapshots"),s=r?ze(r.activePeriod):void 0,a=await this.encode(t);await this.adapter.save(`wb:${e}`,a,s)}async loadWhiteboardSnapshot(e){const t=await this.adapter.load(`wb:${e}`);return t?await this.decode(t):null}async saveRecordingMeta(e){const t=this.getRuleFor("recordings"),r=t?ze(t.activePeriod):void 0,s=await this.encode(e);await this.adapter.save(`rec:${e.id}`,s,r)}async loadRecordingMeta(e){const t=await this.adapter.load(`rec:${e}`);return t?await this.decode(t):null}async listRecordings(){const e=await this.adapter.list("rec:");return(await Promise.all(e.map(r=>this.loadRecordingMeta(r.slice(4))))).filter(Boolean)}async deleteRecording(e){await this.adapter.delete(`rec:${e}`)}async saveDocument(e,t){const r=this.getRuleFor("documents"),s=r?ze(r.activePeriod):void 0,a=await this.encode(t);await this.adapter.save(`doc:${e}`,a,s)}async loadDocument(e){const t=await this.adapter.load(`doc:${e}`);return t?this.decode(t):null}async enforceRetention(){let e=0,t=0;const r=new Date,s=[{prefix:"msg:",type:"messages"},{prefix:"wb:",type:"whiteboard-snapshots"},{prefix:"rec:",type:"recordings"},{prefix:"doc:",type:"documents"}];for(const{prefix:a,type:o}of s){const d=this.getRuleFor(o);if(!d)continue;const u=await this.adapter.list(a);for(const p of u){const g=await this.adapter.load(p);if(g){if(qe(d.activePeriod),d.archivePeriod){const c=`archive:${p}`,f=ze(d.archivePeriod,r);await this.adapter.save(c,g,f),e++}if(d.deleteAfterArchive&&d.archivePeriod){const c=qe(d.archivePeriod);new Date(r.getTime()+c)<r&&(await this.adapter.delete(`archive:${p}`),t++)}}}}return{archived:e,deleted:t}}async estimateUsageBytes(){return typeof window<"u"&&"storage"in navigator&&"estimate"in navigator.storage?(await navigator.storage.estimate()).usage??0:0}updateConfig(e){this.config=e,this.adapter=this.buildAdapter()}getConfig(){return this.config}}const it=[{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}],We=new Map;function zt(i,e,t){return We.has(i)||We.set(i,new Tt(e,t)),We.get(i)}function ln(i){We.delete(i)}const ut=["var(--nice-color-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-accent, #3f51b5)","var(--nice-primary, #2196f3)","var(--nice-info, #00bcd4)","var(--nice-success, #4caf50)","var(--nice-warning, #ff9800)","var(--nice-danger, #ff5722)","var(--nice-warning-dark, #795548)","var(--nice-text-secondary, #607d8b)"];function cn(i){let e=0;for(let t=0;t<i.length;t++)e=e*31+i.charCodeAt(t)>>>0;return ut[e%ut.length]}function ht(i,e,t){const r={...i},s=[...e];switch(t.type){case"object:add":case"object:update":{const a=t.payload;if(r[a.id]=a,s.length>0&&!s[0].objectIds.includes(a.id)){const o=a.layerId?s.find(d=>d.id===a.layerId)??s[0]:s[0];o.objectIds=[...o.objectIds,a.id]}break}case"object:delete":{const{id:a}=t.payload;delete r[a],s.forEach(o=>{o.objectIds=o.objectIds.filter(d=>d!==a)});break}case"object:move":{const{id:a,x:o,y:d}=t.payload;r[a]&&(r[a]={...r[a],x:o,y:d,updatedAt:t.timestamp});break}case"layer:add":{const a=t.payload;s.find(o=>o.id===a.id)||s.push(a);break}case"layer:update":{const a=t.payload,o=s.findIndex(d=>d.id===a.id);o!==-1&&(s[o]={...s[o],...a});break}case"layer:delete":{const{id:a}=t.payload,o=s.findIndex(d=>d.id===a);o!==-1&&s.splice(o,1);break}}return{objects:r,layers:s}}function dn(i,e){switch(e.type){case"LOAD_SESSION":return{...i,session:e.session,undoStack:[],redoStack:[],isDirty:!1};case"SET_TOOL":return{...i,activeTool:e.tool};case"APPLY_OP":{const{op:t,local:r}=e,{objects:s,layers:a}=ht(i.session.objects,i.session.layers,t),o={...i.session,objects:s,layers:a,updatedAt:t.timestamp},u=r&&["object:add","object:update","object:delete","object:move","layer:add","layer:update","layer:delete"].includes(t.type)?[...i.undoStack,[t]]:i.undoStack;return{...i,session:o,undoStack:u,redoStack:r?[]:i.redoStack,isDirty:!0}}case"UNDO":{if(i.undoStack.length===0)return i;const t=i.undoStack[i.undoStack.length-1],r=t.filter(o=>o.type==="object:add").map(o=>o.payload.id),s={...i.session.objects};r.forEach(o=>delete s[o]);const a=i.session.layers.map(o=>({...o,objectIds:o.objectIds.filter(d=>!r.includes(d))}));return{...i,session:{...i.session,objects:s,layers:a},undoStack:i.undoStack.slice(0,-1),redoStack:[t,...i.redoStack],isDirty:!0}}case"REDO":{if(i.redoStack.length===0)return i;const t=i.redoStack[0];let{objects:r,layers:s}={objects:i.session.objects,layers:i.session.layers};for(const a of t)({objects:r,layers:s}=ht(r,s,a));return{...i,session:{...i.session,objects:r,layers:s},undoStack:[...i.undoStack,t],redoStack:i.redoStack.slice(1),isDirty:!0}}case"SET_SELECTION":return{...i,selectedObjectIds:e.ids};case"SET_DRAWING":return{...i,isDrawing:e.value};case"SET_PANNING":return{...i,isPanning:e.value};case"UPDATE_CURSOR":{const{userId:t,x:r,y:s}=e,a=i.session.collaborators[t];return a?{...i,session:{...i.session,collaborators:{...i.session.collaborators,[t]:{...a,cursorX:r,cursorY:s,lastSeenAt:new Date}}}}:i}case"REMOVE_COLLABORATOR":{const t={...i.session.collaborators};return delete t[e.userId],{...i,session:{...i.session,collaborators:t}}}case"SET_VIEWPORT":return{...i,session:{...i.session,viewport:e.viewport}};case"MARK_SAVED":return{...i,isDirty:!1,lastSavedAt:new Date};default:return i}}function Nt(i){const{session:e,currentUser:t,onOperation:r,remoteOperations:s=[],readonly:a=!1,storageConfig:o,autoSaveMs:d=3e4}=i,[u,p]=l.useReducer(dn,{session:e,activeTool:a?"select":"pen",selectedObjectIds:[],undoStack:[],redoStack:[],isDrawing:!1,isPanning:!1,isDirty:!1}),g=l.useRef(0),c=l.useRef(null),f=l.useRef(null);l.useEffect(()=>{o&&(f.current=zt(`wb_${e.id}`,o),f.current.loadWhiteboardSnapshot(e.id).then(j=>{j&&p({type:"LOAD_SESSION",session:j})}))},[e.id,o]),l.useEffect(()=>{if(!d||!f.current||!u.isDirty)return;const j=setTimeout(()=>{var O;(O=f.current)==null||O.saveWhiteboardSnapshot(u.session.id,u.session).then(()=>{p({type:"MARK_SAVED"})})},d);return()=>clearTimeout(j)},[u.isDirty,u.session,d]);const m=l.useRef(new Set);l.useEffect(()=>{for(const j of s)if(!m.current.has(j.id)&&j.userId!==t.id)if(m.current.add(j.id),j.type==="cursor:move"){const{x:O,y:Z}=j.payload;p({type:"UPDATE_CURSOR",userId:j.userId,x:O,y:Z})}else j.type==="viewport:sync"||p({type:"APPLY_OP",op:j,local:!1})},[s,t.id]);const w=l.useCallback((j,O)=>({id:`${t.id}_${++g.current}_${Date.now()}`,sessionId:u.session.id,type:j,userId:t.id,timestamp:new Date,payload:O}),[t.id,u.session.id]),k=l.useCallback(j=>{a||p({type:"SET_TOOL",tool:j})},[a]),T=l.useCallback(j=>{if(a)return;const O=w("object:add",j);p({type:"APPLY_OP",op:O,local:!0}),r==null||r(O)},[a,r,w]),h=l.useCallback(j=>{if(a)return;const O=w("object:update",j);p({type:"APPLY_OP",op:O,local:!0}),r==null||r(O)},[a,r,w]),C=l.useCallback(j=>{if(!a){for(const O of j){const Z=w("object:delete",{id:O});p({type:"APPLY_OP",op:Z,local:!0}),r==null||r(Z)}p({type:"SET_SELECTION",ids:[]})}},[a,r,w]),A=l.useCallback(j=>{if(!a)for(const{id:O,x:Z,y:D}of j){const H=w("object:move",{id:O,x:Z,y:D});p({type:"APPLY_OP",op:H,local:!0}),r==null||r(H)}},[a,r,w]),U=l.useCallback(j=>{p({type:"SET_SELECTION",ids:j})},[]),M=l.useCallback(()=>{a||p({type:"UNDO"})},[a]),P=l.useCallback(()=>{a||p({type:"REDO"})},[a]),G=l.useCallback(j=>{p({type:"SET_VIEWPORT",viewport:j});const O=w("viewport:sync",j);r==null||r(O)},[r,w]),F=l.useCallback((j,O)=>{if(c.current)return;c.current=setTimeout(()=>{c.current=null},50);const Z=w("cursor:move",{x:j,y:O});r==null||r(Z)},[r,w]),L=l.useCallback(j=>{if(a)return;const O={id:`layer_${Date.now()}`,name:j,visible:!0,locked:!1,objectIds:[]},Z=w("layer:add",O);p({type:"APPLY_OP",op:Z,local:!0}),r==null||r(Z)},[a,r,w]),N=l.useCallback(j=>{if(a)return;const O=w("layer:update",j);p({type:"APPLY_OP",op:O,local:!0}),r==null||r(O)},[a,r,w]),z=l.useCallback(j=>{if(a)return;const O=w("layer:delete",{id:j});p({type:"APPLY_OP",op:O,local:!0}),r==null||r(O)},[a,r,w]),E=l.useCallback(j=>{const O={user:j,cursorX:0,cursorY:0,color:cn(j.id),selectedObjectIds:[],activeTool:"pen",lastSeenAt:new Date};p({type:"APPLY_OP",op:w("cursor:move",O),local:!1})},[]),V=l.useCallback(j=>{p({type:"REMOVE_COLLABORATOR",userId:j})},[]),J=l.useCallback(async()=>{f.current&&(await f.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:k,addObject:T,updateObject:h,deleteObjects:C,moveObjects:A,setSelection:U,undo:M,redo:P,setViewport:G,broadcastCursor:F,addLayer:L,updateLayer:N,deleteLayer:z,registerCollaborator:E,removeCollaborator:V,saveNow:J}}const pn=[{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 De(){return`${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Ve(i,e,t){return{sx:i*t.scale+t.x,sy:e*t.scale+t.y}}function un(i,e,t){return{wx:(i-t.x)/t.scale,wy:(e-t.y)/t.scale}}function hn(i,e){return Math.hypot(e.x-i.x,e.y-i.y)}function fn(i,e){if(!(e.points.length<2)){i.save(),i.globalAlpha=e.opacity,i.strokeStyle=y.resolveCssColor(e.color,i.canvas),i.lineWidth=e.strokeWidth,i.lineCap="round",i.lineJoin="round",e.tool==="highlighter"&&(i.globalCompositeOperation="multiply"),i.beginPath(),i.moveTo(e.points[0].x,e.points[0].y);for(let t=1;t<e.points.length;t++){const r={x:(e.points[t-1].x+e.points[t].x)/2,y:(e.points[t-1].y+e.points[t].y)/2};i.quadraticCurveTo(e.points[t-1].x,e.points[t-1].y,r.x,r.y)}i.stroke(),i.restore()}}function gn(i,e){switch(i.save(),i.globalAlpha=e.opacity,i.strokeStyle=y.resolveCssColor(e.strokeColor,i.canvas),i.lineWidth=e.strokeWidth,e.fillColor&&(i.fillStyle=y.resolveCssColor(e.fillColor,i.canvas)),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(e.rotation*Math.PI/180),i.beginPath(),e.shape){case"rect":i.rect(-e.width/2,-e.height/2,e.width,e.height);break;case"ellipse":i.ellipse(0,0,e.width/2,e.height/2,0,0,Math.PI*2);break;case"triangle":{const t=e.width/2,r=e.height/2;i.moveTo(0,-r),i.lineTo(t,r),i.lineTo(-t,r),i.closePath();break}case"diamond":{const t=e.width/2,r=e.height/2;i.moveTo(0,-r),i.lineTo(t,0),i.lineTo(0,r),i.lineTo(-t,0),i.closePath();break}}e.fillColor&&i.fill(),i.stroke(),i.restore()}function mn(i,e){if(i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(e.rotation*Math.PI/180),i.font=`${e.fontStyle} ${e.fontWeight} ${e.fontSize}px ${e.fontFamily}`,i.fillStyle=y.resolveCssColor(e.color,i.canvas),i.textAlign=e.textAlign,i.textBaseline="middle",e.backgroundColor){const t=i.measureText(e.text),r=4;i.fillStyle=y.resolveCssColor(e.backgroundColor,i.canvas),i.fillRect(-t.width/2-r,-e.fontSize/2-r,t.width+r*2,e.fontSize+r*2),i.fillStyle=y.resolveCssColor(e.color,i.canvas)}i.fillText(e.text,0,0),i.restore()}function yn(i,e){i.save(),i.translate(e.x,e.y),i.rotate(e.rotation*Math.PI/180),i.shadowColor=y.resolveCssColor("var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",i.canvas),i.shadowBlur=8,i.shadowOffsetY=3,i.fillStyle=y.resolveCssColor(e.backgroundColor,i.canvas),i.fillRect(0,0,e.width,e.height),i.shadowColor="transparent",i.fillStyle=y.resolveCssColor(e.textColor,i.canvas),i.font=`${e.fontSize}px sans-serif`,i.textAlign="left",i.textBaseline="top";const t=10,r=e.width-t*2,s=e.fontSize*1.4,a=e.text.split(" ");let o="",d=t;for(const u of a){const p=o?`${o} ${u}`:u;i.measureText(p).width>r&&o?(i.fillText(o,t,d),o=u,d+=s):o=p}o&&i.fillText(o,t,d),i.restore()}function xn(i,e){if(!(e.points.length<2)){if(i.save(),i.strokeStyle=y.resolveCssColor(e.strokeColor,i.canvas),i.lineWidth=e.strokeWidth,i.lineCap="round",i.beginPath(),i.moveTo(e.points[0].x,e.points[0].y),e.curved&&e.points.length>2){for(let t=1;t<e.points.length-1;t++){const r=e.points[t],s={x:(r.x+e.points[t+1].x)/2,y:(r.y+e.points[t+1].y)/2};i.quadraticCurveTo(r.x,r.y,s.x,s.y)}i.lineTo(e.points[e.points.length-1].x,e.points[e.points.length-1].y)}else for(let t=1;t<e.points.length;t++)i.lineTo(e.points[t].x,e.points[t].y);if(i.stroke(),e.arrowEnd==="arrow"){const t=e.points[e.points.length-1],r=e.points[e.points.length-2],s=Math.atan2(t.y-r.y,t.x-r.x),a=12;i.beginPath(),i.moveTo(t.x,t.y),i.lineTo(t.x-a*Math.cos(s-Math.PI/6),t.y-a*Math.sin(s-Math.PI/6)),i.moveTo(t.x,t.y),i.lineTo(t.x-a*Math.cos(s+Math.PI/6),t.y-a*Math.sin(s+Math.PI/6)),i.stroke()}i.restore()}}function bn(i,e){i.save(),i.strokeStyle=y.resolveCssColor(e.borderColor??"var(--nice-text-muted, #aaa)",i.canvas),i.lineWidth=2,i.setLineDash([8,4]),e.backgroundColor&&(i.fillStyle=y.resolveCssColor(e.backgroundColor,i.canvas),i.fillRect(e.x,e.y,e.width,e.height)),i.strokeRect(e.x,e.y,e.width,e.height),i.setLineDash([]),i.fillStyle=y.resolveCssColor("var(--nice-text-secondary, #555)",i.canvas),i.font="bold 13px sans-serif",i.fillText(e.name,e.x+8,e.y-6),i.restore()}function vn(i,e){if(e.visible)switch(e.type){case"stroke":return fn(i,e);case"shape":return gn(i,e);case"text":return mn(i,e);case"sticky":return yn(i,e);case"connector":return xn(i,e);case"frame":return bn(i,e);case"image":{const t=e,r=new Image;r.src=t.dataUrl??t.url,i.save(),i.translate(t.x+t.width/2,t.y+t.height/2),i.rotate(t.rotation*Math.PI/180),i.drawImage(r,-t.width/2,-t.height/2,t.width,t.height),i.restore();break}}}function rt(i){const{t:e}=y.useNiceTranslation();return i.session?n.jsx(wn,{...i,session:i.session}):n.jsx("div",{className:i.className,style:i.style,"data-testid":i["data-testid"],children:n.jsx(y.NiceEmpty,{title:e("whiteboard.noSession","No whiteboard session")})})}function wn({session:i,currentUser:e,onOperation:t,remoteOperations:r=[],readonly:s=!1,enableLayers:a=!0,enableExport:o=!0,enableLaserPointer:d=!0,enableVectorEditor:u=!1,enableDiagramEditor:p=!1,onExport:g,onSessionUpdate:c,storageConfig:f,className:m,style:w,"data-testid":k}){const{t:T}=y.useNiceTranslation(),h=Nt({session:i,currentUser:e,onOperation:t,remoteOperations:r,readonly:s,storageConfig:f,autoSaveMs:3e4}),C=l.useRef(null);l.useRef(null);const A=l.useRef(0),[U,M]=l.useState(!1),[P,G]=l.useState("#1a1a1a"),[F,L]=l.useState(3),[N,z]=l.useState(void 0),[E,V]=l.useState(18),[J,j]=l.useState("var(--nice-warning-bg, #fef08a)"),[O,Z]=l.useState(null),[D,H]=l.useState(null),S=l.useRef({active:!1,startX:0,startY:0,currentPoints:[],currentId:"",spaceDown:!1,panStart:null,laserPoints:[]}),b=l.useCallback((x,v,$,B)=>{if(!h.session.gridEnabled)return;const W=h.session.gridSize*v.scale,q=(v.x%W+W)%W,I=(v.y%W+W)%W;x.strokeStyle=y.resolveCssColor("var(--nice-border-color, rgba(180,180,200,0.35))",x.canvas),x.lineWidth=1,x.beginPath();for(let R=q;R<$;R+=W)x.moveTo(R,0),x.lineTo(R,B);for(let R=I;R<B;R+=W)x.moveTo(0,R),x.lineTo($,R);x.stroke()},[h.session.gridEnabled,h.session.gridSize]),Y=l.useCallback((x,v)=>{for(const $ of h.collaborators){if($.user.id===e.id)continue;const{sx:B,sy:W}=Ve($.cursorX,$.cursorY,v);x.save(),x.fillStyle=$.color,x.beginPath(),x.moveTo(B,W),x.lineTo(B+14,W+5),x.lineTo(B+5,W+14),x.closePath(),x.fill(),x.fillStyle=$.color,x.font="bold 11px sans-serif",x.fillText($.user.name,B+16,W+14),x.restore()}},[h.collaborators,e.id]),X=l.useCallback((x,v)=>{if(h.selectedObjectIds.length!==0)for(const $ of h.selectedObjectIds){const B=h.session.objects[$];if(!B)continue;const{sx:W,sy:q}=Ve(B.x,B.y,v),I=B.width*v.scale,R=B.height*v.scale;x.strokeStyle=y.resolveCssColor("var(--nice-primary, #4f8df9)",x.canvas),x.lineWidth=1.5,x.setLineDash([4,2]),x.strokeRect(W-2,q-2,I+4,R+4),x.setLineDash([]);const ne=[[W-2,q-2],[W+I+2,q-2],[W-2,q+R+2],[W+I+2,q+R+2]];x.fillStyle=y.resolveCssColor("var(--nice-bg, #fff)",x.canvas),x.strokeStyle=y.resolveCssColor("var(--nice-primary, #4f8df9)",x.canvas),x.lineWidth=1.5;for(const[te,se]of ne)x.fillRect(te-4,se-4,8,8),x.strokeRect(te-4,se-4,8,8)}},[h.selectedObjectIds,h.session.objects]),Q=l.useCallback(()=>{const x=C.current;if(!x)return;const v=x.getContext("2d");if(!v)return;const{width:$,height:B}=x,W=h.viewport;v.clearRect(0,0,$,B),v.fillStyle=y.resolveCssColor(h.session.backgroundColor,x),v.fillRect(0,0,$,B),b(v,W,$,B),v.save();const q=Object.values(h.session.objects).filter(I=>I.visible).sort((I,R)=>I.zIndex-R.zIndex);v.translate(W.x,W.y),v.scale(W.scale,W.scale);for(const I of q)vn(v,I);if(S.current.active&&S.current.currentPoints.length>1){const I=S.current.currentPoints;v.strokeStyle=y.resolveCssColor(P,x),v.lineWidth=F,v.lineCap="round",v.lineJoin="round",v.beginPath(),v.moveTo(I[0].x,I[0].y);for(let R=1;R<I.length;R++)v.lineTo(I[R].x,I[R].y);v.stroke()}if(S.current.laserPoints.length>1&&h.activeTool==="laser"){const I=S.current.laserPoints;v.strokeStyle="#ff2c2c",v.lineWidth=3,v.globalAlpha=.7,v.beginPath(),v.moveTo(I[0].x,I[0].y);for(let R=1;R<I.length;R++)v.lineTo(I[R].x,I[R].y);v.stroke(),v.globalAlpha=1}v.restore(),X(v,W),Y(v,W)},[h.session,h.viewport,h.activeTool,b,Y,X,P,F]);l.useLayoutEffect(()=>{function x(){Q(),A.current=requestAnimationFrame(x)}return A.current=requestAnimationFrame(x),()=>cancelAnimationFrame(A.current)},[Q]),l.useEffect(()=>{const x=C.current;if(!x)return;const v=new ResizeObserver(()=>{x.width=x.offsetWidth,x.height=x.offsetHeight});return v.observe(x),x.width=x.offsetWidth,x.height=x.offsetHeight,()=>v.disconnect()},[]),l.useEffect(()=>{function x(v){if(v.target.tagName==="INPUT"||v.target.tagName==="TEXTAREA"||(v.code==="Space"&&(S.current.spaceDown=v.type==="keydown",v.preventDefault()),v.type!=="keydown"))return;(v.ctrlKey||v.metaKey)&&(v.key==="z"&&(v.preventDefault(),h.undo()),v.key==="y"&&(v.preventDefault(),h.redo()),v.key==="s"&&(v.preventDefault(),h.saveNow()),v.key==="a"&&(v.preventDefault(),h.setSelection(Object.keys(h.session.objects)))),(v.key==="Delete"||v.key==="Backspace")&&h.selectedObjectIds.length>0&&h.deleteObjects(h.selectedObjectIds);const $={v:"select",p:"pen",h:"highlighter",e:"eraser",r:"rect",c:"ellipse",t:"text",s:"sticky",i:"image",a:"arrow",l:"laser"};!v.ctrlKey&&!v.metaKey&&$[v.key]&&h.setTool($[v.key])}return window.addEventListener("keydown",x),window.addEventListener("keyup",x),()=>{window.removeEventListener("keydown",x),window.removeEventListener("keyup",x)}},[h]);const K=l.useCallback(x=>{const v=C.current.getBoundingClientRect(),$=x.clientX-v.left,B=x.clientY-v.top,{wx:W,wy:q}=un($,B,h.viewport);return{x:W,y:q,pressure:x.pressure??.5}},[h.viewport]),ie=l.useCallback(x=>{if(s)return;x.target.setPointerCapture(x.pointerId);const v=K(x);if(x.button===1||S.current.spaceDown){S.current.panStart={x:x.clientX,y:x.clientY,vpX:h.viewport.x,vpY:h.viewport.y};return}const $=h.activeTool;if(S.current.active=!0,S.current.startX=v.x,S.current.startY=v.y,S.current.currentId=De(),$==="pen"||$==="highlighter")S.current.currentPoints=[v];else if($==="laser")S.current.laserPoints=[v];else if($==="select"){const B=Object.values(h.session.objects).filter(W=>W.visible&&W.x<=v.x&&W.y<=v.y&&W.x+W.width>=v.x&&W.y+W.height>=v.y).sort((W,q)=>q.zIndex-W.zIndex)[0];B?x.shiftKey?h.setSelection([...h.selectedObjectIds,B.id]):h.setSelection([B.id]):h.setSelection([])}},[s,K,h]),de=l.useCallback(x=>{const v=K(x);if(h.broadcastCursor(v.x,v.y),S.current.panStart){const{x:B,y:W,vpX:q,vpY:I}=S.current.panStart;h.setViewport({...h.viewport,x:q+(x.clientX-B),y:I+(x.clientY-W)});return}if(!S.current.active)return;const $=h.activeTool;if($==="pen"||$==="highlighter"){const B=S.current.currentPoints;(B.length===0||hn(B[B.length-1],v)>2)&&(S.current.currentPoints=[...B,v])}else if($==="laser"){const B=S.current.laserPoints;S.current.laserPoints=[...B.slice(-40),v]}else if($==="select"&&h.selectedObjectIds.length>0){const B=v.x-S.current.startX,W=v.y-S.current.startY;S.current.startX=v.x,S.current.startY=v.y,h.moveObjects(h.selectedObjectIds.map(q=>{const I=h.session.objects[q];return{id:q,x:I.x+B,y:I.y+W}}))}},[K,h]),ce=l.useCallback(x=>{if(S.current.panStart){S.current.panStart=null;return}if(!S.current.active)return;const v=K(x),$=h.activeTool,B=S.current.startX,W=S.current.startY,q=S.current.currentId,I=new Date;switch(S.current.active=!1,$){case"pen":case"highlighter":{const R=S.current.currentPoints;if(R.length<2)break;const ne={id:q,type:"stroke",x:Math.min(...R.map(te=>te.x)),y:Math.min(...R.map(te=>te.y)),width:Math.max(...R.map(te=>te.x))-Math.min(...R.map(te=>te.x)),height:Math.max(...R.map(te=>te.y))-Math.min(...R.map(te=>te.y)),rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:I,points:R,color:P,strokeWidth:F,opacity:$==="highlighter"?.4:1,tool:$};h.addObject(ne),S.current.currentPoints=[];break}case"rect":case"ellipse":case"triangle":{const R=Math.min(B,v.x),ne=Math.min(W,v.y),te=Math.abs(v.x-B),se=Math.abs(v.y-W);if(te<5||se<5)break;const pe={rect:"rect",ellipse:"ellipse",triangle:"triangle"},me={id:q,type:"shape",x:R,y:ne,width:te,height:se,rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:I,shape:pe[$],fillColor:N,strokeColor:P,strokeWidth:F,opacity:1};h.addObject(me);break}case"arrow":case"line":{const R={id:q,type:"connector",x:Math.min(B,v.x),y:Math.min(W,v.y),width:Math.abs(v.x-B),height:Math.abs(v.y-W),rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:I,points:[{x:B,y:W},{x:v.x,y:v.y}],strokeColor:P,strokeWidth:F,arrowStart:"none",arrowEnd:$==="arrow"?"arrow":"none",curved:!1};h.addObject(R);break}case"text":{const R={id:q,type:"text",x:v.x,y:v.y,width:200,height:E+10,rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:I,text:T("whiteboard.clickToEdit","Click to edit"),fontSize:E,fontFamily:"sans-serif",fontWeight:"normal",fontStyle:"normal",textAlign:"left",color:P};h.addObject(R),Z(q);break}case"sticky":{const R={id:q,type:"sticky",x:v.x,y:v.y,width:180,height:150,rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:I,text:T("whiteboard.note","Note..."),backgroundColor:J,textColor:"var(--nice-text, #333)",fontSize:14,authorId:e.id};h.addObject(R),Z(q);break}case"frame":{const R=Math.min(B,v.x),ne=Math.min(W,v.y),te=Math.abs(v.x-B),se=Math.abs(v.y-W);if(te<20||se<20)break;const pe={id:q,type:"frame",x:R,y:ne,width:te,height:se,rotation:0,zIndex:0,locked:!1,visible:!0,createdBy:e.id,createdAt:I,name:`Frame ${Object.keys(h.session.objects).length+1}`,childIds:[],borderColor:"#8888"};h.addObject(pe);break}case"image":{const R=document.createElement("input");R.type="file",R.accept="image/*",R.onchange=()=>{var se;const ne=(se=R.files)==null?void 0:se[0];if(!ne)return;const te=new FileReader;te.onload=pe=>{var Pe;const me=(Pe=pe.target)==null?void 0:Pe.result,fe=new Image;fe.onload=()=>{const Ae=400/fe.width,Fe={id:De(),type:"image",x:v.x,y:v.y,width:fe.width*Ae,height:fe.height*Ae,rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:me,dataUrl:me,originalWidth:fe.width,originalHeight:fe.height};h.addObject(Fe)},fe.src=me},te.readAsDataURL(ne)},R.click();break}}},[K,h,e.id,P,F,N,E,J,T]),xe=l.useCallback(x=>{if(x.preventDefault(),!x.ctrlKey&&!x.metaKey){h.setViewport({...h.viewport,x:h.viewport.x-x.deltaX,y:h.viewport.y-x.deltaY});return}const v=C.current.getBoundingClientRect(),$=x.clientX-v.left,B=x.clientY-v.top,q=-x.deltaY>0?1.1:.9,I=Math.min(8,Math.max(.1,h.viewport.scale*q));h.setViewport({scale:I,x:$-($-h.viewport.x)*(I/h.viewport.scale),y:B-(B-h.viewport.y)*(I/h.viewport.scale)})},[h]),_=l.useCallback(x=>{if(x==="json"){const W=JSON.stringify(h.session,null,2);g==null||g("json",W);const q=document.createElement("a");q.href=URL.createObjectURL(new Blob([W],{type:"application/json"})),q.download=`${h.session.title}.json`,q.click();return}const v=C.current;if(!v)return;const $=v.toDataURL("image/png");g==null||g("png",$);const B=document.createElement("a");B.href=$,B.download=`${h.session.title}.png`,B.click()},[h.session,g]);l.useEffect(()=>{c==null||c(h.session)},[h.session,c]),l.useEffect(()=>{function x(v){if(v.clipboardData){for(const $ of Array.from(v.clipboardData.items))if($.type.startsWith("image/")){const B=$.getAsFile();if(!B)continue;const W=new FileReader;W.onload=q=>{var ne;const I=(ne=q.target)==null?void 0:ne.result,R=new Image;R.onload=()=>{const se=400/R.width,pe={id:De(),type:"image",x:100,y:100,width:R.width*se,height:R.height*se,rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:I,dataUrl:I,originalWidth:R.width,originalHeight:R.height};h.addObject(pe)},R.src=I},W.readAsDataURL(B);break}}}return window.addEventListener("paste",x),()=>window.removeEventListener("paste",x)},[h,e.id]);const ee=O?h.session.objects[O]:null,ae=l.useMemo(()=>ee?Ve(ee.x,ee.y,h.viewport):null,[ee,h.viewport]),oe=["var(--nice-warning-bg, #fef08a)","var(--nice-primary-bg, #bfdbfe)","var(--nice-success-bg, #bbf7d0)","var(--nice-danger-bg, #fecaca)","var(--nice-accent-tint-10, #e9d5ff)","var(--nice-warning-bg, #fed7aa)"],le=l.useMemo(()=>{var v;const x={};for(const $ of pn)(x[v=$.group]??(x[v]=[])).push($);return Object.values(x)},[]);return n.jsxs("div",{className:m,"data-testid":k,style:{position:"relative",display:"flex",flexDirection:"column",width:"100%",height:"100%",overflow:"hidden",background:"var(--nice-bg-secondary, #f5f5f5)",fontFamily:"system-ui, sans-serif",...w},children:[n.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:[le.map((x,v)=>n.jsxs(l.Fragment,{children:[v>0&&n.jsx("div",{style:{width:1,height:24,background:"var(--nice-border, #e5e7eb)",margin:"0 2px"}}),x.map($=>n.jsx("button",{onClick:()=>h.setTool($.id),title:`${$.label}`,style:{padding:"4px 7px",border:`1.5px solid ${h.activeTool===$.id?"var(--nice-info, #6366f1)":"transparent"}`,borderRadius:6,background:h.activeTool===$.id?"var(--nice-primary-bg, #eef2ff)":"transparent",cursor:"pointer",fontSize:15,minWidth:30,color:h.activeTool===$.id?"var(--nice-accent, #4f46e5)":"var(--nice-text, #374151)",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:n.jsx(y.NiceIcon,{name:$.icon,size:15})},$.id))]},v)),n.jsx("div",{style:{width:1,height:24,background:"var(--nice-border, #e5e7eb)",margin:"0 4px"}}),n.jsxs("label",{title:T("whiteboard.strokeColor","Stroke color"),style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:T("whiteboard.color","Color")}),n.jsx("input",{type:"color",value:P,onChange:x=>G(x.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}})]}),n.jsxs("label",{title:T("whiteboard.fillColor","Fill color"),style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:T("whiteboard.fill","Fill")}),n.jsx("input",{type:"color",value:N??"#ffffff",onChange:x=>z(x.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}}),n.jsx("button",{onClick:()=>z(void 0),style:{fontSize:11,padding:"1px 5px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:4,cursor:"pointer",background:N?"var(--nice-bg, #fff)":"var(--nice-bg-secondary, #f3f4f6)"},children:T("whiteboard.noFill","No fill")})]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:T("whiteboard.width","Width")}),n.jsx("input",{type:"range",min:1,max:24,step:1,value:F,onChange:x=>L(Number(x.target.value)),style:{width:70}}),n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",minWidth:20},children:F})]}),h.activeTool==="sticky"&&n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:T("whiteboard.note2","Note:")}),oe.map(x=>n.jsx("button",{onClick:()=>j(x),style:{width:20,height:20,background:x,border:`2px solid ${J===x?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)"}`,borderRadius:4,cursor:"pointer"}},x))]}),n.jsx("div",{style:{flex:1}}),n.jsx("button",{onClick:h.undo,disabled:!h.canUndo,title:T("whiteboard.undoCtrlZ","Undo (Ctrl+Z)"),"aria-label":T("whiteboard.undo","Undo"),style:ue(!h.canUndo),children:n.jsx(y.NiceIcon,{name:"reply",size:13})}),n.jsx("button",{onClick:h.redo,disabled:!h.canRedo,title:T("whiteboard.redoCtrlY","Redo (Ctrl+Y)"),"aria-label":T("whiteboard.redo","Redo"),style:ue(!h.canRedo),children:n.jsx(y.NiceIcon,{name:"forward",size:13})}),n.jsx("div",{style:{width:1,height:24,background:"var(--nice-border, #e5e7eb)"}}),n.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",minWidth:42,textAlign:"center"},children:[Math.round(h.viewport.scale*100),"%"]}),n.jsx("button",{onClick:()=>h.setViewport({x:0,y:0,scale:1}),style:ue(),title:T("whiteboard.resetZoom","Reset zoom"),"aria-label":T("whiteboard.resetZoom","Reset zoom"),children:n.jsx(y.NiceIcon,{name:"target",size:13})}),a&&n.jsx("button",{onClick:()=>M(x=>!x),style:ue(!1,U),title:T("whiteboard.layers","Layers"),"aria-label":T("whiteboard.layers","Layers"),children:n.jsx(y.NiceIcon,{name:"layers",size:13})}),n.jsx("button",{onClick:()=>{const x={id:De(),sessionId:h.session.id,type:"object:update",userId:e.id,timestamp:new Date,payload:{...h.session,gridEnabled:!h.session.gridEnabled}};t==null||t(x)},style:ue(!1,h.session.gridEnabled),title:T("whiteboard.toggleGrid","Toggle grid"),"aria-label":T("whiteboard.toggleGrid","Toggle grid"),children:n.jsx(y.NiceIcon,{name:"hash",size:13})}),u&&n.jsx("button",{onClick:()=>H(x=>x==="vector"?null:"vector"),style:ue(!1,D==="vector"),title:T("whiteboard.vectorEditorPanel","Vector Editor panel"),"aria-label":T("whiteboard.vectorEditorPanel","Vector Editor panel"),children:n.jsx(y.NiceIcon,{name:"pen",size:13})}),p&&n.jsx("button",{onClick:()=>H(x=>x==="diagram"?null:"diagram"),style:ue(!1,D==="diagram"),title:T("whiteboard.diagramEditorPanel","Diagram Editor panel"),"aria-label":T("whiteboard.diagramEditorPanel","Diagram Editor panel"),children:n.jsx(y.NiceIcon,{name:"hexagon",size:13})}),n.jsx("button",{onClick:()=>void h.saveNow(),style:ue(),title:T("whiteboard.saveCtrlS","Save (Ctrl+S)"),"aria-label":T("whiteboard.save","Save"),children:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center"},children:[n.jsx(y.NiceIcon,{name:"save",size:13}),h.isDirty&&"*"]})}),o&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>_("png"),style:ue(),title:T("whiteboard.exportPng","Export PNG"),"aria-label":T("whiteboard.exportPng","Export PNG"),children:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:2},children:["PNG",n.jsx(y.NiceIcon,{name:"download",size:12})]})}),n.jsx("button",{onClick:()=>_("json"),style:ue(),title:T("whiteboard.exportJson","Export JSON"),"aria-label":T("whiteboard.exportJson","Export JSON"),children:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:2},children:[T("whiteboard.json","JSON"),n.jsx(y.NiceIcon,{name:"download",size:12})]})})]})]}),n.jsxs("div",{style:{display:"flex",flex:1,overflow:"hidden",position:"relative"},children:[n.jsx("canvas",{ref:C,style:{flex:1,display:"block",cursor:kn(h.activeTool,S.current.spaceDown)},onPointerDown:ie,onPointerMove:de,onPointerUp:ce,onWheel:xe,onContextMenu:x=>x.preventDefault()}),a&&U&&n.jsx(Sn,{layers:h.layers,objects:h.session.objects,onAdd:()=>h.addLayer(`Layer ${h.layers.length+1}`),onUpdate:x=>h.updateLayer(x),onDelete:x=>h.deleteLayer(x)}),D&&n.jsxs("div",{style:{position:"absolute",right:U?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:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[n.jsx("strong",{style:{fontSize:13},children:D==="vector"?T("whiteboard.vectorEditor","Vector Editor"):T("whiteboard.diagramEditor","Diagram Editor")}),n.jsx("button",{onClick:()=>H(null),style:{border:"none",background:"none",cursor:"pointer",fontSize:16},"aria-label":T("whiteboard.close","Close"),children:n.jsx(y.NiceIcon,{name:"close",size:16})})]}),n.jsx("p",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:D==="vector"?T("whiteboard.renderTheFullNice2devUi","Render the full @nice2dev/ui-graphics VectorEditor here. Pass the whiteboard's StorageConfig to persist edits and onOperation to broadcast strokes in real time."):T("whiteboard.renderTheFullNice2devUi2","Render the full @nice2dev/ui-diagrams NiceDiagramEditor here. Pass the collaborativeDiagram YDoc to enable simultaneous multi-user editing.")}),n.jsx("div",{id:`wb-integration-${D}`,style:{width:"100%",height:400}})]})]}),h.collaborators.length>1&&n.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:[n.jsx("span",{children:T("whiteboard.collaborators","Collaborators:")}),h.collaborators.map(x=>n.jsxs("span",{style:{display:"flex",alignItems:"center",gap:3},children:[n.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:x.color,display:"inline-block"}}),x.user.name]},x.user.id)),h.isDirty&&n.jsxs("span",{style:{marginLeft:"auto",color:"var(--nice-warning, #f59e0b)",display:"inline-flex",alignItems:"center",gap:3},children:[n.jsx(y.NiceIcon,{name:"circle",size:10})," ",T("whiteboard.unsaved","unsaved")]}),h.lastSavedAt&&!h.isDirty&&n.jsxs("span",{style:{marginLeft:"auto",color:"var(--nice-success, #10b981)",display:"inline-flex",alignItems:"center",gap:3},children:[n.jsx(y.NiceIcon,{name:"check",size:10})," ",T("whiteboard.saved","Saved {lastSavedAt}").replace("{lastSavedAt}",String(h.lastSavedAt.toLocaleTimeString()))]})]}),ee&&ae&&n.jsx("textarea",{autoFocus:!0,defaultValue:ee.text,onBlur:x=>{const v={...ee,text:x.target.value,updatedAt:new Date,updatedBy:e.id};h.updateObject(v),Z(null)},style:{position:"absolute",left:ae.sx,top:ae.sy,minWidth:ee.width*h.viewport.scale,minHeight:ee.height*h.viewport.scale,fontSize:(ee.fontSize??14)*h.viewport.scale,fontFamily:"sans-serif",background:ee.type==="sticky"?ee.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:ee.type==="sticky"?ee.textColor:ee.color}})]})}function Sn({layers:i,objects:e,onAdd:t,onUpdate:r,onDelete:s}){const{t:a}=y.useNiceTranslation();return n.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:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[n.jsx("strong",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:a("whiteboard.layers","Layers")}),n.jsx("button",{onClick:t,style:{fontSize:16,border:"none",background:"none",cursor:"pointer",color:"var(--nice-info, #6366f1)",display:"inline-flex",alignItems:"center"},title:a("whiteboard.addLayer","Add layer"),"aria-label":a("whiteboard.addLayer","Add layer"),children:n.jsx(y.NiceIcon,{name:"plus",size:16})})]}),[...i].reverse().map(o=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",borderRadius:5,background:"var(--nice-bg-secondary, #f9fafb)",opacity:o.visible?1:.5},children:[n.jsx("button",{onClick:()=>r({id:o.id,visible:!o.visible}),title:a("whiteboard.toggleVisibility","Toggle visibility"),"aria-label":a("whiteboard.toggleVisibility","Toggle visibility"),style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,display:"inline-flex",alignItems:"center",color:o.visible?"var(--nice-text, #374151)":"var(--nice-text-muted, #9ca3af)"},children:n.jsx(y.NiceIcon,{name:o.visible?"eye":"eye-off",size:13})}),n.jsx("button",{onClick:()=>r({id:o.id,locked:!o.locked}),title:a("whiteboard.toggleLock","Toggle lock"),"aria-label":a("whiteboard.toggleLock","Toggle lock"),style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,display:"inline-flex",alignItems:"center",opacity:o.locked?1:.5},children:n.jsx(y.NiceIcon,{name:"lock",size:13})}),n.jsx("span",{style:{flex:1,fontSize:11,color:"var(--nice-text, #374151)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o.name}),n.jsx("span",{style:{fontSize:10,color:"var(--nice-text-muted, #9ca3af)"},children:o.objectIds.filter(d=>d in e).length}),i.length>1&&n.jsx("button",{onClick:()=>s(o.id),title:a("whiteboard.deleteLayer","Delete layer"),"aria-label":a("whiteboard.deleteLayer","Delete layer"),style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,display:"inline-flex",alignItems:"center",color:"var(--nice-danger, #ef4444)"},children:n.jsx(y.NiceIcon,{name:"trash",size:13})})]},o.id))]})}function ue(i=!1,e=!1){return{padding:"4px 8px",border:`1.5px solid ${e?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)"}`,borderRadius:6,background:e?"var(--nice-primary-bg, #eef2ff)":"var(--nice-bg, #fff)",cursor:i?"default":"pointer",opacity:i?.35:1,fontSize:13,color:e?"var(--nice-accent, #4f46e5)":"var(--nice-text, #374151)",fontWeight:e?600:400}}function kn(i,e){if(e)return"grab";switch(i){case"pen":case"highlighter":return"crosshair";case"eraser":return"cell";case"select":return"default";case"text":return"text";case"laser":return"none";default:return"crosshair"}}const jn=[],Cn=[],In=[];function ve({icon:i,label:e,active:t,badge:r,onClick:s}){return n.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[n.jsxs("button",{title:e,onClick:s,style:{width:44,height:44,borderRadius:10,border:"none",background:t?"var(--nice-overlay-light-20, rgba(255, 255, 255, 0.2))":"transparent",color:"var(--nice-color-white, #fff)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",position:"relative"},children:[n.jsx(y.NiceIcon,{name:i,size:20}),r!=null&&r>0&&n.jsx("span",{style:{position:"absolute",top:4,right:4,background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700,lineHeight:1.4},children:r>99?"99+":r})]}),n.jsx("span",{style:{fontSize:9,color:"var(--nice-overlay-light-70, rgba(255, 255, 255, 0.7))",letterSpacing:"0.03em"},children:e})]})}function Tn({team:i,activeChannelId:e,onSelectChannel:t}){var o;const[r,s]=l.useState(!1),a=i.channels.reduce((d,u)=>d+u.unreadCount,0);return n.jsxs("div",{className:"nice-workspace-team",children:[n.jsxs("button",{onClick:()=>s(d=>!d),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:[n.jsx("span",{style:{color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:r?"chevron-right":"chevron-down",size:12})}),n.jsx("div",{style:{width:20,height:20,borderRadius:4,background:i.avatarUrl?`url(${i.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:9,flexShrink:0},children:!i.avatarUrl&&((o=i.name[0])==null?void 0:o.toUpperCase())}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.name}),!r&&a>0&&n.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:a})]}),!r&&i.channels.map(d=>n.jsxs("button",{onClick:()=>t(i.id,d.id),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 10px 5px 34px",background:d.id===e?"var(--nice-accent-tint-10, #ede9fe)":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:d.unreadCount>0?"var(--nice-text, #111827)":"var(--nice-text-secondary, #4b5563)",fontSize:13,fontWeight:d.unreadCount>0?600:400},children:[n.jsx("span",{style:{color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:d.isPrivate?"lock":"hash",size:12})}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d.name}),d.mentionCount>0&&n.jsxs("span",{style:{background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:["@",d.mentionCount]}),d.unreadCount>0&&d.mentionCount===0&&n.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700},children:d.unreadCount})]},d.id))]})}function zn({conversation:i,partner:e,isActive:t,onClick:r}){var a;const s=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??i.name??"Group";return n.jsxs("button",{onClick:r,style:{display:"flex",alignItems:"center",gap:8,padding:"5px 10px",background:t?"var(--nice-accent-tint-10, #ede9fe)":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:i.unreadCount>0?"var(--nice-text, #111827)":"var(--nice-text-secondary, #4b5563)",fontWeight:i.unreadCount>0?600:400,fontSize:13},children:[n.jsxs("div",{style:{position:"relative",flexShrink:0},children:[n.jsx("div",{style:{width:24,height:24,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:10},children:!(e!=null&&e.avatarUrl)&&((a=s[0])==null?void 0:a.toUpperCase())}),e&&n.jsx(he,{status:e.presence.status,size:"xs",style:{position:"absolute",bottom:-1,right:-1}})]}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),i.unreadCount>0&&n.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700,flexShrink:0},children:i.unreadCount})]})}function Et({currentUser:i,users:e=jn,teams:t=Cn,conversations:r=In,messages:s,activeCall:a,incomingCall:o,meetings:d,transport:u,rtcConfig:p,enableCalls:g=!0,enableMeetings:c=!0,enableScreenSharing:f=!0,enableWhiteboard:m=!1,storageConfig:w,onSendMessage:k,onEditMessage:T,onDeleteMessage:h,onReactToMessage:C,onPinMessage:A,onLoadMoreMessages:U,onMarkAsRead:M,onStartCall:P,onAcceptCall:G,onDeclineCall:F,onEndCall:L,onMuteAudio:N,onMuteVideo:z,onStartScreenShare:E,onStopScreenShare:V,className:J,style:j,id:O,"data-testid":Z}){var W,q;const{t:D}=y.useNiceTranslation(),[H,S]=l.useState("teams"),[b,Y]=l.useState(null),[X,Q]=l.useState(""),[K,ie]=l.useState(null),de=()=>{K||ie({id:`wb-workspace-${Date.now()}`,title:D("teamsWorkspace.teamWhiteboard","Team Whiteboard"),objects:{},layers:[{id:"layer-0",name:"Layer 1",visible:!0,locked:!1,objectIds:[]}],collaborators:{},viewport:{x:0,y:0,scale:1},width:4e3,height:3e3,backgroundColor:"#ffffff",gridEnabled:!0,gridSize:20,snapEnabled:!0,createdAt:new Date,updatedAt:new Date,ownerId:i.id,permissions:"edit"})},ce=l.useMemo(()=>{const I=new Map;return e.forEach(R=>I.set(R.id,R)),I},[e]),xe=l.useMemo(()=>et(r),[r]),_=l.useMemo(()=>r.reduce((I,R)=>I+R.mentionCount,0),[r]),ee=l.useMemo(()=>{if(b!=null&&b.channelId)for(const I of t){const R=I.channels.find(ne=>ne.id===b.channelId);if(R)return R}},[t,b]),ae=l.useMemo(()=>{if(b!=null&&b.teamId)return t.find(I=>I.id===b.teamId)},[t,b]),oe=l.useMemo(()=>r.find(I=>I.id===(b==null?void 0:b.conversationId))??null,[r,b]),le=l.useMemo(()=>{const I=(b==null?void 0:b.channelId)??(b==null?void 0:b.conversationId);return I?s[I]??[]:[]},[s,b]),x=!!o&&!a,v=!!a,$=l.useMemo(()=>r.filter(I=>I.type==="dm"||I.type==="group"),[r]),B=l.useMemo(()=>{if(!X)return $;const I=X.toLowerCase();return $.filter(R=>{var te;const ne=ce.get(R.participantIds.find(se=>se!==i.id)??"");return(ne==null?void 0:ne.name.toLowerCase().includes(I))||((te=R.name)==null?void 0:te.toLowerCase().includes(I))})},[$,X,ce,i.id]);return n.jsxs("div",{id:O,"data-testid":Z,className:`nice-teams-workspace${J?` ${J}`:""}`,style:{position:"relative",height:"100%",...j},children:[n.jsx(y.NiceAppShell,{flush:!0,height:"100%",className:"nice-teams-workspace__shell",style:{background:"var(--nice-bg, #fff)",overflow:"hidden"},sidebar:n.jsxs("div",{style:{display:"flex",height:"100%",minHeight:0},children:[n.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:[n.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:i.avatarUrl?`url(${i.avatarUrl}) center/cover`:"var(--nice-accent, #818cf8)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:14,marginBottom:8,flexShrink:0},children:!i.avatarUrl&&((W=i.name[0])==null?void 0:W.toUpperCase())}),n.jsx(ve,{icon:"zap",label:D("teamsWorkspace.activity","Activity"),active:H==="activity",badge:_,onClick:()=>S("activity")}),n.jsx(ve,{icon:"message",label:D("teamsWorkspace.chat","Chat"),active:H==="chat",badge:xe,onClick:()=>S("chat")}),n.jsx(ve,{icon:"users",label:D("teamsWorkspace.teams","Teams"),active:H==="teams",onClick:()=>S("teams")}),g&&n.jsx(ve,{icon:"phone",label:D("teamsWorkspace.calls","Calls"),active:H==="calls",onClick:()=>S("calls")}),c&&n.jsx(ve,{icon:"calendar",label:D("teamsWorkspace.meetings","Meetings"),active:H==="meetings",onClick:()=>S("meetings")}),n.jsx(ve,{icon:"folder",label:D("teamsWorkspace.files","Files"),active:H==="files",onClick:()=>S("files")}),m&&n.jsx(ve,{icon:"edit",label:D("teamsWorkspace.board","Board"),active:H==="whiteboard",onClick:()=>{S("whiteboard"),de()}})]}),n.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:[n.jsxs("div",{style:{padding:"12px 10px 8px",flexShrink:0},children:[n.jsx("div",{style:{fontWeight:700,fontSize:15,color:"var(--nice-text, #374151)",marginBottom:8,textTransform:"capitalize"},children:H}),n.jsx("input",{type:"search",value:X,onChange:I=>Q(I.target.value),placeholder:D("teamsWorkspace.search","Search {navSection}โฆ").replace("{navSection}",String(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)"}})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[H==="teams"&&n.jsx(n.Fragment,{children:t.map(I=>n.jsx(Tn,{team:I,activeChannelId:b==null?void 0:b.channelId,onSelectChannel:(R,ne)=>{Y({type:"channel",teamId:R,channelId:ne}),M==null||M(ne)}},I.id))}),H==="chat"&&n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:"var(--nice-text-muted, #9ca3af)",fontWeight:600,letterSpacing:"0.05em"},children:D("teamsWorkspace.directMessages","DIRECT MESSAGES")}),B.map(I=>{const R=ce.get(I.participantIds.find(ne=>ne!==i.id)??"");return n.jsx(zn,{conversation:I,partner:R,isActive:(b==null?void 0:b.conversationId)===I.id,onClick:()=>{Y({type:I.type==="dm"?"dm":"group",conversationId:I.id}),M==null||M(I.id)}},I.id)})]}),H==="activity"&&n.jsxs("div",{style:{padding:12},children:[r.filter(I=>I.unreadCount>0).map(I=>n.jsxs("button",{onClick:()=>{S(I.type==="channel"?"teams":"chat"),Y({type:I.type==="channel"?"channel":"dm",conversationId:I.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:[n.jsx("strong",{children:I.name??D("teamsWorkspace.conversation","Conversation")})," ",D("teamsWorkspace.unread","โ {unreadCount} unread").replace("{unreadCount}",String(I.unreadCount))]},I.id)),r.every(I=>I.unreadCount===0)&&n.jsxs("p",{style:{color:"var(--nice-text-muted, #9ca3af)",fontSize:13,textAlign:"center",marginTop:24,display:"flex",alignItems:"center",justifyContent:"center",gap:4},children:[D("teamsWorkspace.allCaughtUp","All caught up")," ",n.jsx(y.NiceIcon,{name:"check",size:13})]})]}),H==="calls"&&n.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8},children:[n.jsxs("button",{onClick:()=>P==null?void 0:P(e.map(I=>I.id).filter(I=>I!==i.id),"audio"),style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[n.jsx(y.NiceIcon,{name:"phone",size:14})," ",D("teamsWorkspace.newAudioCall","New audio call")]}),n.jsxs("button",{onClick:()=>P==null?void 0:P(e.map(I=>I.id).filter(I=>I!==i.id),"video"),style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[n.jsx(y.NiceIcon,{name:"video",size:14})," ",D("teamsWorkspace.newVideoCall","New video call")]})]}),H==="meetings"&&n.jsxs("div",{style:{padding:12},children:[(d??[]).map(I=>n.jsxs("div",{style:{padding:"8px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,marginBottom:8},children:[n.jsx("div",{style:{fontWeight:600,fontSize:13},children:I.title}),n.jsx("div",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginTop:2},children:I.scheduledStart.toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}),n.jsx("button",{onClick:()=>{},style:{marginTop:6,background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:6,padding:"3px 10px",fontSize:12,cursor:"pointer"},children:D("teamsWorkspace.join","Join")})]},I.id)),(d??[]).length===0&&n.jsx("p",{style:{color:"var(--nice-text-muted, #9ca3af)",fontSize:13,textAlign:"center",marginTop:24},children:D("teamsWorkspace.noUpcomingMeetings","No upcoming meetings")})]}),H==="files"&&n.jsx("div",{style:{padding:12},children:n.jsx("p",{style:{color:"var(--nice-text-muted, #9ca3af)",fontSize:13,textAlign:"center",marginTop:24},children:D("teamsWorkspace.noFilesSharedYet","No files shared yet")})}),H==="whiteboard"&&n.jsxs("div",{style:{padding:12},children:[n.jsxs("button",{onClick:()=>de(),style:{width:"100%",background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,marginBottom:8,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[n.jsx(y.NiceIcon,{name:"edit",size:14})," ",K?D("teamsWorkspace.openWhiteboard","Open whiteboard"):D("teamsWorkspace.newWhiteboard","New whiteboard")]}),K&&n.jsxs("div",{style:{padding:"6px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,fontSize:12,color:"var(--nice-text, #374151)"},children:[n.jsx("div",{style:{fontWeight:500},children:K.title}),n.jsx("div",{style:{color:"var(--nice-text-muted, #9ca3af)",marginTop:2},children:D("teamsWorkspace.objects","{objects} objects").replace("{objects}",String(Object.keys(K.objects).length))})]})]})]})]})]}),children:n.jsxs("div",{style:{flex:1,height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[(b==null?void 0:b.type)==="channel"&&ee?n.jsx(It,{channel:ee,messages:le,users:(ae==null?void 0:ae.members)??e,currentUser:i,team:ae,onSendMessage:k,onEditMessage:T,onDeleteMessage:h,onReactToMessage:C,onPinMessage:A,onLoadMoreMessages:U,onStartCall:g?P:void 0,style:{height:"100%"}}):((b==null?void 0:b.type)==="dm"||(b==null?void 0:b.type)==="group")&&oe?n.jsx(Re,{conversation:oe,messages:le,users:e,currentUser:i,onSendMessage:k,onEditMessage:T,onDeleteMessage:h,onReactToMessage:C,onPinMessage:A,onLoadMoreMessages:U,onStartCall:g?P:void 0,style:{height:"100%"}}):H==="whiteboard"&&K?n.jsx(rt,{session:K,currentUser:i,storageConfig:w,onSessionUpdate:I=>ie(I),style:{height:"100%"}}):n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"var(--nice-text-muted, #9ca3af)",gap:12},children:[n.jsx(y.NiceIcon,{name:H==="teams"?"users":H==="chat"?"message":H==="calls"?"phone":H==="whiteboard"?"edit":"zap",size:56}),n.jsx("span",{style:{fontSize:17,fontWeight:500},children:H==="teams"?D("teamsWorkspace.selectAChannelToGet","Select a channel to get started"):H==="chat"?D("teamsWorkspace.selectAConversation","Select a conversation"):H==="calls"?D("teamsWorkspace.startOrJoinACall","Start or join a call"):H==="whiteboard"?D("teamsWorkspace.clickNewWhiteboardToStart",'Click "New whiteboard" to start'):D("teamsWorkspace.nothingSelected","Nothing selected")})]}),v&&a&&n.jsx("div",{style:{position:"absolute",inset:0,zIndex:50},children:a.participants.length>2?n.jsx(nt,{session:a,currentUser:i,enableScreenSharing:f,onEndCall:L,onMuteAudio:N,onMuteVideo:z,onStartScreenShare:E,onStopScreenShare:V}):n.jsx(tt,{session:a,currentUser:i,enableScreenSharing:f,onEndCall:L,onMuteAudio:N,onMuteVideo:z,onStartScreenShare:E,onStopScreenShare:V})})]})}),x&&o&&n.jsxs("div",{style:{position:"absolute",top:16,right:16,width:300,background:"var(--nice-text, #1f2937)",borderRadius:12,padding:16,boxShadow:"0 8px 32px var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",zIndex:100,color:"var(--nice-text-inverse, #fff)"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:12},children:[n.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:o.caller.avatarUrl?`url(${o.caller.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:16},children:!o.caller.avatarUrl&&((q=o.caller.name[0])==null?void 0:q.toUpperCase())}),n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:o.caller.displayName??o.caller.name}),n.jsx("div",{style:{fontSize:12,color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"},children:D("teamsWorkspace.incomingCall","Incoming {callType} call").replace("{callType}",String(o.callType))})]})]}),n.jsxs("div",{style:{display:"flex",gap:8},children:[n.jsxs("button",{onClick:()=>F==null?void 0:F(o.callId),style:{flex:1,background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[n.jsx(y.NiceIcon,{name:"phone",size:14})," ",D("teamsWorkspace.decline","Decline")]}),n.jsxs("button",{onClick:()=>G==null?void 0:G(o.callId),style:{flex:1,background:"var(--nice-success, #22c55e)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[n.jsx(y.NiceIcon,{name:"phone",size:14})," ",D("teamsWorkspace.accept","Accept")]})]})]})]})}const Rt=[],Nn={"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 En({props:i,onExpand:e}){const{t}=y.useNiceTranslation(),[r,s]=l.useState(!1),{bubblePosition:a="bottom-right",bubbleLabel:o,currentUser:d,users:u=Rt,conversations:p=[],messages:g={},activeConversationId:c,onSendMessage:f,onReactToMessage:m,onPinMessage:w,onDeleteMessage:k,onEditMessage:T,onLoadMoreMessages:h,onStartCall:C}=i,A=Nn[a],U=p.find(P=>P.id===c)??p[0]??null,M=U?g[U.id]??[]:[];return n.jsxs("div",{style:{position:"fixed",zIndex:9999,...A},children:[r&&U&&n.jsxs("div",{style:{position:"absolute",bottom:a.startsWith("bottom")?64:void 0,top:a.startsWith("top")?64:void 0,right:a.endsWith("right")?0:void 0,left:a.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:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",flexShrink:0},children:[n.jsx("span",{style:{fontWeight:700,fontSize:15},children:o??t("communication.chat","Chat")}),n.jsxs("div",{style:{display:"flex",gap:4},children:[n.jsx("button",{onClick:()=>e("messenger"),title:t("communication.openFullChat","Open full chat"),"aria-label":t("communication.openFullChat","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-color-white, #fff)",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"expand",size:13})}),n.jsx("button",{onClick:()=>s(!1),title:t("communication.close","Close"),"aria-label":t("communication.close","Close"),style:{background:"none",border:"none",color:"var(--nice-text-primary, #fff)",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"close",size:18})})]})]}),n.jsx(Re,{conversation:U,messages:M,users:u,currentUser:d,showHeader:!1,onSendMessage:f,onEditMessage:T,onDeleteMessage:k,onReactToMessage:m,onPinMessage:w,onLoadMoreMessages:h,onStartCall:C,style:{flex:1}})]}),n.jsx("button",{onClick:()=>s(P=>!P),style:{width:56,height:56,borderRadius:"50%",background:"var(--nice-info, #6366f1)",border:"none",boxShadow:"0 4px 16px var(--nice-accent-tint-40, rgba(99, 102, 241, 0.4))",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-on-primary, #fff)",transition:"transform 0.15s"},title:r?t("communication.closeChat","Close chat"):o??t("communication.openChat","Open chat"),"aria-label":r?t("communication.closeChat","Close chat"):o??t("communication.openChat","Open chat"),children:n.jsx(y.NiceIcon,{name:r?"close":"message",size:24})})]})}function Rn({call:i,onAccept:e,onDecline:t}){const{t:r}=y.useNiceTranslation();return n.jsxs("div",{style:{position:"fixed",top:16,left:"50%",transform:"translateX(-50%)",zIndex:9998,background:"var(--nice-text, #1f2937)",color:"var(--nice-text-inverse, #fff)",borderRadius:12,padding:"12px 20px",boxShadow:"0 8px 32px var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",display:"flex",alignItems:"center",gap:16,minWidth:280},children:[n.jsx("div",{style:{display:"flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:i.callType==="video"?"video":"phone",size:28})}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:600,fontSize:14},children:i.caller.displayName??i.caller.name}),n.jsx("div",{style:{fontSize:12,color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"},children:r("communication.incomingCall","Incoming {callType} callโฆ").replace("{callType}",String(i.callType))})]}),n.jsx("button",{onClick:t,style:{background:"var(--nice-danger, #ef4444)",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",color:"var(--nice-text-on-primary, #fff)",display:"inline-flex",alignItems:"center",justifyContent:"center"},title:r("communication.decline","Decline"),"aria-label":r("communication.decline","Decline"),children:n.jsx(y.NiceIcon,{name:"phone",size:18})}),n.jsx("button",{onClick:e,style:{background:"var(--nice-success, #22c55e)",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",color:"var(--nice-text-on-primary, #fff)",display:"inline-flex",alignItems:"center",justifyContent:"center"},title:r("communication.accept","Accept"),"aria-label":r("communication.accept","Accept"),children:n.jsx(y.NiceIcon,{name:"phone",size:18})})]})}function Pt(i){const{t:e}=y.useNiceTranslation(),{mode:t,currentUser:r,users:s=Rt,conversations:a=[],messages:o={},activeConversationId:d,teams:u=[],meetings:p,activeCall:g,incomingCall:c,transport:f="webrtc",rtcConfig:m,onSendMessage:w,onEditMessage:k,onDeleteMessage:T,onReactToMessage:h,onPinMessage:C,onLoadMoreMessages:A,onMarkAsRead:U,onStartCall:M,onAcceptCall:P,onDeclineCall:G,onEndCall:F,onMuteAudio:L,onMuteVideo:N,onStartScreenShare:z,onStopScreenShare:E,onRaiseHand:V,onModeChange:J,enableScreenSharing:j=!0,enableMeetings:O=!0,enableWhiteboard:Z=!1,storageConfig:D,encryptionConfig:H,className:S,style:b,id:Y,"data-testid":X}=i,[Q,K]=l.useState(t),[ie,de]=l.useState(null),ce=l.useMemo(()=>({id:`wb-${r.id}-${Date.now()}`,title:e("communication.whiteboard","Whiteboard"),objects:{},layers:[{id:"layer-0",name:"Layer 1",visible:!0,locked:!1,objectIds:[]}],collaborators:{},viewport:{x:0,y:0,scale:1},width:4e3,height:3e3,backgroundColor:"#ffffff",gridEnabled:!0,gridSize:20,snapEnabled:!0,createdAt:new Date,updatedAt:new Date,ownerId:r.id,permissions:"edit"}),[r.id,e]),[xe,_]=l.useState(g??null),[ee,ae]=l.useState(c??null),oe=g??xe,le=c??ee;l.useEffect(()=>{K(t)},[t]),l.useEffect(()=>{g!==void 0&&_(g)},[g]),l.useEffect(()=>{c!==void 0&&ae(c)},[c]);const{state:x,startCall:v,acceptCall:$,declineCall:B,endCall:W,toggleMic:q,toggleCamera:I,startScreenShare:R,stopScreenShare:ne}=jt({currentUser:r,transport:f,rtcConfig:m,onCallEnded:re=>{_(null),F==null||F(re)},onIncomingCall:re=>{ae(re)}}),te=l.useCallback(re=>{K(re),J==null||J(re)},[J]),se=l.useCallback(async(re,ct)=>{if(M){await M(re,ct);return}const Ht=await v(re,ct);_(Ht),K(re.length>2?"conference":"call")},[M,v]),pe=l.useCallback(async()=>{var re;P&&le?await P(le.callId):await $(),ae(null),K((re=x.activeCall)!=null&&re.participants&&x.activeCall.participants.length>2?"conference":"call")},[P,le,$,x.activeCall]),me=l.useCallback(()=>{G&&le?G(le.callId):B(),ae(null)},[G,le,B]),fe=l.useCallback(re=>{F?F(re):W(),_(null),K(t)},[F,W,t]),Pe=l.useCallback(re=>{q(),L==null||L(re)},[q,L]),lt=l.useCallback(re=>{I(),N==null||N(re)},[I,N]),Ae=l.useCallback(async()=>{await R(),await(z==null?void 0:z())},[R,z]),Fe=l.useCallback(()=>{ne(),E==null||E()},[ne,E]),Te={onSendMessage:w,onEditMessage:k,onDeleteMessage:T,onReactToMessage:h,onPinMessage:C,onLoadMoreMessages:A,onMarkAsRead:U,onStartCall:se,onEndCall:fe,onMuteAudio:Pe,onMuteVideo:lt,onStartScreenShare:Ae,onStopScreenShare:Fe,onRaiseHand:V},_e=a.find(re=>re.id===d)??a[0],ge=oe?oe.participants.length>2?"conference":"call":Q,Ut={width:"100%",height:"100%",position:"relative",...b};return n.jsxs("div",{id:Y,"data-testid":X,className:`nice-communication nice-communication--${ge}${S?` ${S}`:""}`,style:Ut,children:[le&&ge!=="workspace"&&n.jsx(Rn,{call:le,onAccept:pe,onDecline:me}),ge==="bubble"&&n.jsx(En,{props:i,onExpand:te}),ge==="chat"&&_e&&n.jsx(Re,{conversation:_e,messages:o[_e.id]??[],users:s,currentUser:r,...Te,style:{height:"100%"}}),ge==="messenger"&&n.jsx(Ct,{conversations:a,messages:o,activeConversationId:d,users:s,currentUser:r,teams:u,...Te,onAcceptCall:P,onDeclineCall:G,style:{height:"100%"}}),ge==="workspace"&&n.jsx(Et,{currentUser:r,users:s,teams:u,conversations:a,messages:o,meetings:p,activeCall:oe??void 0,incomingCall:le??void 0,transport:f,rtcConfig:m,enableCalls:!0,enableMeetings:O,enableScreenSharing:j,...Te,onAcceptCall:pe,onDeclineCall:me,style:{height:"100%"}}),ge==="call"&&oe&&n.jsx(tt,{session:oe,currentUser:r,localStream:x.localStream??void 0,enableScreenSharing:j,...Te,style:{height:"100%"}}),ge==="conference"&&oe&&n.jsx(nt,{session:oe,currentUser:r,localStream:x.localStream??void 0,enableScreenSharing:j,...Te,style:{height:"100%"}}),ge==="whiteboard"&&Z&&n.jsx(rt,{session:ie??ce,currentUser:r,storageConfig:D,onSessionUpdate:re=>de(re),style:{height:"100%"}})]})}const Pn={messages:"Messages",attachments:"Attachments","whiteboard-snapshots":"Whiteboard snapshots",recordings:"Recordings",transcripts:"Transcripts",documents:"Documents","call-logs":"Call logs","audit-logs":"Audit logs"},ft={none:"No encryption","AES-GCM-128":"AES-GCM 128-bit","AES-GCM-256":"AES-GCM 256-bit (recommended)","ChaCha20-Poly1305":"ChaCha20-Poly1305","E2E-ECDH-P384":"End-to-End ECDH P-384"},An={messages:"Messages",attachments:"Attachments",whiteboard:"Whiteboard",recordings:"Recordings",documents:"Documents",calls:"Calls (metadata)",presence:"Presence data",all:"Everything"},Dn=["days","weeks","months","years","forever"];function gt(i){if(i===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],r=Math.floor(Math.log(i)/Math.log(e));return`${(i/Math.pow(e,r)).toFixed(1)} ${t[r]}`}function mt({value:i,onChange:e,disabled:t=!1}){return n.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[n.jsx("input",{type:"number",min:1,max:9999,value:i.unit==="forever"?"":i.value,disabled:t||i.unit==="forever",onChange:r=>e({...i,value:Math.max(1,Number(r.target.value))}),style:{width:60,padding:"3px 6px",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:5,fontSize:12}}),n.jsx("select",{value:i.unit,disabled:t,onChange:r=>e({...i,unit:r.target.value}),style:{padding:"3px 6px",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:5,fontSize:12},children:Dn.map(r=>n.jsx("option",{value:r,children:r},r))})]})}function Mn({config:i,onChange:e}){const{t}=y.useNiceTranslation(),r=i.retentionRules.length>0?i.retentionRules:it;function s(a,o){const d=r.map(u=>u.dataType===a?{...u,...o}:u);e({...i,retentionRules:d})}return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[n.jsx("p",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",margin:0},children:t("storageSettings.configureHowLongEachData","Configure how long each data type is retained before archiving and eventual deletion. Legal-hold prevents deletion regardless of retention rules.")}),n.jsxs("div",{style:Ce,children:[n.jsx("label",{style:Ie,children:t("storageSettings.storageProvider","Storage provider")}),n.jsxs("select",{value:i.provider,onChange:a=>e({...i,provider:a.target.value}),style:we,children:[n.jsx("option",{value:"indexeddb",children:t("storageSettings.indexeddbBrowser","IndexedDB (browser)")}),n.jsx("option",{value:"localstorage",children:t("storageSettings.localstorageBrowser","LocalStorage (browser)")}),n.jsx("option",{value:"server",children:t("storageSettings.server","Server")}),n.jsx("option",{value:"custom",children:t("storageSettings.customAdapter","Custom adapter")})]})]}),i.provider==="server"&&n.jsxs("div",{style:Ce,children:[n.jsx("label",{style:Ie,children:t("storageSettings.serverUrl","Server URL")}),n.jsx("input",{type:"url",value:i.serverUrl??"",onChange:a=>e({...i,serverUrl:a.target.value}),placeholder:"https://your-api.example.com/storage",style:we})]}),n.jsx("hr",{style:{border:"none",borderTop:"1px solid var(--nice-border, #e5e7eb)",margin:"4px 0"}}),n.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12},children:[n.jsx("thead",{children:n.jsxs("tr",{style:{background:"var(--nice-bg-secondary, #f9fafb)"},children:[n.jsx("th",{style:ke,children:t("storageSettings.dataType","Data type")}),n.jsx("th",{style:ke,children:t("storageSettings.activePeriod","Active period")}),n.jsx("th",{style:ke,children:t("storageSettings.archiveAfter","Archive after")}),n.jsx("th",{style:ke,children:t("storageSettings.autoDelete","Auto-delete")}),n.jsx("th",{style:ke,children:t("storageSettings.userCanDelete","User can delete")}),n.jsx("th",{style:ke,children:t("storageSettings.legalHold","Legal hold")})]})}),n.jsx("tbody",{children:r.map(a=>n.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)"},children:[n.jsx("td",{style:{...je,fontWeight:500,color:"var(--nice-text, #374151)"},children:Pn[a.dataType]}),n.jsx("td",{style:je,children:n.jsx(mt,{value:a.activePeriod,onChange:o=>s(a.dataType,{activePeriod:o})})}),n.jsx("td",{style:je,children:a.archivePeriod?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx(mt,{value:a.archivePeriod,onChange:o=>s(a.dataType,{archivePeriod:o})}),n.jsx("button",{onClick:()=>s(a.dataType,{archivePeriod:void 0}),style:{border:"none",background:"none",cursor:"pointer",color:"var(--nice-danger, #ef4444)",display:"inline-flex",alignItems:"center"},title:t("storageSettings.removeArchivePeriod","Remove archive period"),"aria-label":t("storageSettings.removeArchivePeriod","Remove archive period"),children:n.jsx(y.NiceIcon,{name:"close",size:14})})]}):n.jsxs("button",{onClick:()=>s(a.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:[n.jsx(y.NiceIcon,{name:"plus",size:11})," ",t("storageSettings.add","Add")]})}),n.jsx("td",{style:{...je,textAlign:"center"},children:n.jsx("input",{type:"checkbox",checked:a.deleteAfterArchive,disabled:!a.archivePeriod,onChange:o=>s(a.dataType,{deleteAfterArchive:o.target.checked})})}),n.jsx("td",{style:{...je,textAlign:"center"},children:n.jsx("input",{type:"checkbox",checked:a.userCanDelete,onChange:o=>s(a.dataType,{userCanDelete:o.target.checked})})}),n.jsx("td",{style:{...je,textAlign:"center"},children:n.jsx("input",{type:"checkbox",checked:a.legalHoldEnabled??!1,onChange:o=>s(a.dataType,{legalHoldEnabled:o.target.checked})})})]},a.dataType))})]}),n.jsxs("div",{style:Ce,children:[n.jsx("label",{style:Ie,children:t("storageSettings.storageQuota","Storage quota")}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx("input",{type:"number",min:0,value:i.quota?Math.round(i.quota/1024/1024):0,onChange:a=>e({...i,quota:Number(a.target.value)*1024*1024}),style:{...we,width:90},placeholder:"0"}),n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:t("storageSettings.mb0Unlimited","MB (0 = unlimited)")})]})]})]})}function Wn({config:i,onChange:e}){const{t}=y.useNiceTranslation(),r=["messages","attachments","whiteboard","recordings","documents","calls","presence"];return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[n.jsx("p",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",margin:0},children:t("storageSettings.configureEncryptionAtRestAnd","Configure encryption at rest and in transit. E2E-ECDH ensures only participants can read conversations โ the server never sees plaintext.")}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsxs("label",{style:{position:"relative",display:"inline-block",width:42,height:22},children:[n.jsx("input",{type:"checkbox",checked:i.enabled,onChange:s=>e({...i,enabled:s.target.checked}),style:{opacity:0,width:0,height:0}}),n.jsx("span",{style:{position:"absolute",inset:0,borderRadius:22,background:i.enabled?"var(--nice-info, #6366f1)":"var(--nice-border, #d1d5db)",transition:"background 0.2s",cursor:"pointer"},children:n.jsx("span",{style:{position:"absolute",width:16,height:16,top:3,left:i.enabled?23:3,background:"var(--nice-bg, #fff)",borderRadius:"50%",transition:"left 0.2s"}})})]}),n.jsxs("span",{style:{fontSize:13,fontWeight:500,color:"var(--nice-text, #374151)",display:"inline-flex",alignItems:"center",gap:5},children:[n.jsx(y.NiceIcon,{name:"lock",size:14})," ",i.enabled?t("storageSettings.encryptionEnabled","Encryption enabled"):t("storageSettings.encryptionDisabled","Encryption disabled")]})]}),i.enabled&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:Ce,children:[n.jsx("label",{style:Ie,children:t("storageSettings.defaultAlgorithm","Default algorithm")}),n.jsx("select",{value:i.defaultAlgorithm,onChange:s=>e({...i,defaultAlgorithm:s.target.value}),style:we,children:Object.entries(ft).map(([s,a])=>n.jsx("option",{value:s,children:a},s))})]}),i.defaultAlgorithm==="E2E-ECDH-P384"&&n.jsxs("div",{style:Ce,children:[n.jsx("label",{style:Ie,children:t("storageSettings.keyExchangeUrl","Key exchange URL")}),n.jsx("input",{type:"url",value:i.keyExchangeUrl??"",onChange:s=>e({...i,keyExchangeUrl:s.target.value}),placeholder:t("storageSettings.wssYourServerE2eKey","wss://your-server/e2e-key-exchange"),style:we}),n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginTop:2},children:t("storageSettings.websocketEndpointForEcdhPublic","WebSocket endpoint for ECDH public key exchange between participants.")})]}),n.jsxs("div",{style:Ce,children:[n.jsx("label",{style:Ie,children:t("storageSettings.externalKeyBase64Optional","External key (base64, optional)")}),n.jsx("input",{type:"password",value:i.keyMaterial??"",onChange:s=>e({...i,keyMaterial:s.target.value||void 0}),placeholder:t("storageSettings.leaveEmptyToAutoGenerate","Leave empty to auto-generate"),style:we}),n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginTop:2},children:t("storageSettings.provideAPreSharedKey","Provide a pre-shared key for symmetric algorithms. Leave empty for automatic key generation.")})]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:i.showIndicator??!0,onChange:s=>e({...i,showIndicator:s.target.checked})}),n.jsx("span",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:t("storageSettings.showLockIndicatorInMessages","Show lock indicator in messages")})]}),n.jsx("hr",{style:{border:"none",borderTop:"1px solid var(--nice-border, #e5e7eb)",margin:"4px 0"}}),n.jsx("strong",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:t("storageSettings.perScopeOverrides","Per-scope overrides")}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:r.map(s=>{var u;const a=(u=i.scopeOverrides)==null?void 0:u.find(p=>p.scope===s),o=(a==null?void 0:a.enabled)??!1,d=(a==null?void 0:a.algorithm)??i.defaultAlgorithm;return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 8px",background:"var(--nice-bg-secondary, #f9fafb)",borderRadius:6},children:[n.jsx("input",{type:"checkbox",checked:o,onChange:p=>{const g=[...(i.scopeOverrides??[]).filter(c=>c.scope!==s),{scope:s,algorithm:d,enabled:p.target.checked}];e({...i,scopeOverrides:g})}}),n.jsx("span",{style:{minWidth:120,fontSize:12,color:"var(--nice-text, #374151)"},children:An[s]}),n.jsx("select",{value:d,disabled:!o,onChange:p=>{const g=[...(i.scopeOverrides??[]).filter(c=>c.scope!==s),{scope:s,algorithm:p.target.value,enabled:o}];e({...i,scopeOverrides:g})},style:{...we,flex:1,opacity:o?1:.4},children:Object.entries(ft).map(([p,g])=>n.jsx("option",{value:p,children:g},p))})]},s)})})]})]})}function On({storageConfig:i,defaultStorageConfig:e,encryptionConfig:t,onStorageConfigChange:r,onEncryptionConfigChange:s,currentUsageBytes:a=0,showEncryption:o=!0,showRetention:d=!0,showQuota:u=!0,className:p,style:g,"data-testid":c}){const{t:f}=y.useNiceTranslation(),[m,w]=l.useState("retention"),[k,T]=y.useControllableState({value:i,defaultValue:e,fallbackValue:{provider:"indexeddb",retentionRules:[]},onChange:r,componentName:"NiceStorageSettings"}),h=t??{enabled:!1,defaultAlgorithm:"AES-GCM-256",showIndicator:!0},C={...k,retentionRules:k.retentionRules.length>0?k.retentionRules:it};return n.jsxs("div",{className:p,"data-testid":c,style:{display:"flex",flexDirection:"column",gap:16,padding:20,background:"var(--nice-bg, #fff)",borderRadius:10,border:"1px solid var(--nice-border, #e5e7eb)",fontFamily:"system-ui, sans-serif",maxWidth:800,...g},children:[n.jsxs("div",{children:[n.jsx("h3",{style:{margin:0,fontSize:16,color:"var(--nice-text, #111827)"},children:f("storageSettings.storagePrivacy","Storage & Privacy")}),n.jsx("p",{style:{margin:"4px 0 0",fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:f("storageSettings.manageDataRetentionEncryptionAnd","Manage data retention, encryption, and storage settings.")})]}),u&&k.quota&&k.quota>0&&n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:12,color:"var(--nice-text-secondary, #6b7280)",marginBottom:4},children:[n.jsx("span",{children:f("storageSettings.storageUsed","Storage used")}),n.jsxs("span",{children:[gt(a)," / ",gt(k.quota)]})]}),n.jsx("div",{style:{height:6,background:"var(--nice-border, #e5e7eb)",borderRadius:3},children:n.jsx("div",{style:{width:`${Math.min(100,a/k.quota*100)}%`,height:"100%",background:a/k.quota>.9?"var(--nice-danger, #ef4444)":"var(--nice-info, #6366f1)",borderRadius:3,transition:"width 0.3s"}})})]}),d&&o&&n.jsx("div",{style:{display:"flex",gap:0,borderBottom:"1px solid var(--nice-border, #e5e7eb)"},children:["retention","encryption"].map(A=>n.jsx("button",{onClick:()=>w(A),style:{padding:"8px 18px",border:"none",borderBottom:`2px solid ${m===A?"var(--nice-info, #6366f1)":"transparent"}`,background:"none",cursor:"pointer",fontSize:13,fontWeight:m===A?600:400,color:m===A?"var(--nice-accent, #4f46e5)":"var(--nice-text-secondary, #6b7280)",marginBottom:-1,display:"inline-flex",alignItems:"center",gap:6},children:A==="retention"?n.jsxs(n.Fragment,{children:[n.jsx(y.NiceIcon,{name:"archive",size:13})," ",f("storageSettings.retention","Retention")]}):n.jsxs(n.Fragment,{children:[n.jsx(y.NiceIcon,{name:"lock",size:13})," ",f("storageSettings.encryption","Encryption")]})},A))}),n.jsxs("div",{children:[(m==="retention"||!o)&&d&&n.jsx(Mn,{config:C,onChange:T}),(m==="encryption"||!d)&&o&&n.jsx(Wn,{config:h,onChange:s??(()=>{})})]})]})}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)"},ke={padding:"6px 8px",textAlign:"left",fontSize:11,fontWeight:600,color:"var(--nice-text-secondary, #6b7280)",borderBottom:"1px solid var(--nice-border, #e5e7eb)"},je={padding:"8px 8px",verticalAlign:"middle"};function Le(i){const e=Math.floor(i/1e3),t=Math.floor(e/60),r=Math.floor(t/60);return r>0?`${r}:${String(t%60).padStart(2,"0")}:${String(e%60).padStart(2,"0")}`:`${String(t).padStart(2,"0")}:${String(e%60).padStart(2,"0")}`}function $n(i){if(i===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],r=Math.floor(Math.log(i)/Math.log(e));return`${(i/Math.pow(e,r)).toFixed(1)} ${t[r]}`}function Ln(i,e){return new Intl.DateTimeFormat(e,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(i))}const Fn=(i,e)=>i(`recording.state.${e}`,At[e].label),At={idle:{label:"Idle",icon:null,bg:"var(--nice-bg-secondary, #f3f4f6)",fg:"var(--nice-text-secondary, #6b7280)"},recording:{label:"Recording",icon:"circle",bg:"var(--nice-danger-bg, #fee2e2)",fg:"var(--nice-danger-dark, #dc2626)"},paused:{label:"Paused",icon:"pause",bg:"var(--nice-warning-bg, #fef3c7)",fg:"var(--nice-warning-dark, #d97706)"},processing:{label:"Processing",icon:"clock",bg:"var(--nice-accent-tint-10, #ede9fe)",fg:"var(--nice-accent, #7c3aed)"},ready:{label:"Ready",icon:"check",bg:"var(--nice-success-bg, #dcfce7)",fg:"var(--nice-success-dark, #16a34a)"},failed:{label:"Failed",icon:"close",bg:"var(--nice-danger-bg, #fee2e2)",fg:"var(--nice-danger-dark, #dc2626)"}};function _n({segments:i,onClose:e,currentTimeMs:t=0}){const{t:r}=y.useNiceTranslation();return n.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:n.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:[n.jsxs("div",{style:{padding:"14px 18px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("strong",{style:{fontSize:14,color:"var(--nice-text, #111827)"},children:r("recording.transcript","Transcript")}),n.jsx("button",{onClick:e,style:Hn,"aria-label":r("recording.close","Close"),children:n.jsx(y.NiceIcon,{name:"close",size:16})})]}),n.jsx("div",{style:{flex:1,overflowY:"auto",padding:"12px 18px"},children:i.length===0?n.jsx("p",{style:{fontSize:13,color:"var(--nice-text-muted, #9ca3af)",textAlign:"center",padding:"32px 0"},children:r("recording.noTranscript","No transcript available.")}):i.map(s=>{const a=t>=s.startMs&&t<s.endMs;return n.jsxs("div",{style:{marginBottom:12,padding:"8px 10px",borderRadius:6,background:a?"var(--nice-primary-bg, #eff6ff)":"transparent",borderLeft:`3px solid ${a?"var(--nice-primary, #3b82f6)":"transparent"}`,transition:"background 0.2s"},children:[n.jsxs("div",{style:{display:"flex",gap:10,alignItems:"baseline",marginBottom:3},children:[n.jsx("span",{style:{fontSize:11,fontWeight:600,color:"var(--nice-accent, #4f46e5)"},children:s.speakerName}),n.jsxs("span",{style:{fontSize:10,color:"var(--nice-text-muted, #9ca3af)"},children:[Le(s.startMs)," โ ",Le(s.endMs)]}),n.jsx("span",{style:{fontSize:10,color:"var(--nice-text-secondary, #d1d5db)"},children:r("recording.conf","{confidence}% conf.").replace("{confidence}",String(Math.round(s.confidence*100)))})]}),n.jsx("p",{style:{margin:0,fontSize:13,color:"var(--nice-text, #374151)",lineHeight:1.5},children:s.text})]},s.id)})})]})})}function Dt({startedAt:i}){const[e,t]=l.useState(0);return l.useEffect(()=>{const r=new Date(i).getTime(),s=setInterval(()=>t(Date.now()-r),500);return()=>clearInterval(s)},[i]),n.jsx(n.Fragment,{children:Le(e)})}function Bn({rec:i,onDelete:e,onDownload:t}){const{t:r,lang:s}=y.useNiceTranslation(),[a,o]=l.useState(!1),[d,u]=l.useState(0),p=l.useRef(null),g=At[i.state],c=Fn(r,i.state),f=i.state==="recording"||i.state==="paused";return n.jsxs(n.Fragment,{children:[a&&i.transcript&&n.jsx(_n,{segments:i.transcript,currentTimeMs:d,onClose:()=>o(!1)}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",flexWrap:"wrap"},children:[n.jsx("div",{style:{display:"flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:i.sessionType==="call"?"phone":i.sessionType==="meeting"?"video":i.sessionType==="whiteboard"?"image":"monitor",size:20})}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontSize:13,fontWeight:500,color:"var(--nice-text, #111827)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.title??r("recording.recording","Recording {id}").replace("{id}",String(i.id.slice(0,8)))}),n.jsxs("div",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",marginTop:2,display:"flex",gap:8},children:[n.jsx("span",{children:Ln(i.startedAt,s)}),n.jsx("span",{children:f?n.jsx(Dt,{startedAt:i.startedAt}):i.durationMs!=null?Le(i.durationMs):"โ"}),i.size!=null&&n.jsx("span",{children:$n(i.size)}),n.jsx("span",{children:r("recording.participants","{participants} participants").replace("{participants}",String(i.participants.length))})]})]}),n.jsxs("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:20,background:g.bg,color:g.fg,fontWeight:500,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[g.icon&&n.jsx(y.NiceIcon,{name:g.icon,size:11}),c]}),i.url&&i.state==="ready"&&n.jsx("audio",{ref:p,src:i.url,controls:!0,onTimeUpdate:()=>{p.current&&u(p.current.currentTime*1e3)},style:{height:32,maxWidth:180}}),n.jsxs("div",{style:{display:"flex",gap:4},children:[i.transcript&&i.transcript.length>0&&n.jsx("button",{onClick:()=>o(!0),style:Ye,title:r("recording.viewTranscript","View transcript"),"aria-label":r("recording.viewTranscript","View transcript"),children:n.jsx(y.NiceIcon,{name:"type",size:14})}),i.state==="ready"&&n.jsx("button",{onClick:()=>t(i),style:Ye,title:r("recording.download","Download"),"aria-label":r("recording.download","Download"),children:n.jsx(y.NiceIcon,{name:"download",size:14})}),n.jsx("button",{onClick:()=>e(i.id),style:{...Ye,color:"var(--nice-danger, #ef4444)"},title:r("recording.delete","Delete"),"aria-label":r("recording.delete","Delete"),children:n.jsx(y.NiceIcon,{name:"trash",size:14})})]})]})]})}function Un({recordings:i,onRecordingStart:e,onRecordingStop:t,onRecordingPause:r,onRecordingResume:s,onRecordingDelete:a,onRecordingDownload:o,activeRecordingId:d,sessionType:u="meeting",className:p,style:g,"data-testid":c}){const{t:f}=y.useNiceTranslation(),[m,w]=l.useState(i??[]),[k,T]=l.useState(""),[h,C]=l.useState("all");l.useEffect(()=>{i&&w(i)},[i]);const A=m.find(L=>L.id===d),U=(A==null?void 0:A.state)==="recording",M=(A==null?void 0:A.state)==="paused",P=m.filter(L=>{const N=h==="all"||L.sessionType===h,z=!k||(L.title??"").toLowerCase().includes(k.toLowerCase())||L.id.includes(k);return N&&z}),G=l.useCallback(L=>{w(N=>N.filter(z=>z.id!==L)),a==null||a(L)},[a]),F=l.useCallback(L=>{if(o){o(L.id);return}if(L.url){const N=document.createElement("a");N.href=L.url,N.download=`${L.title??L.id}.${L.mimeType.includes("mp4")?"mp4":"webm"}`,N.click()}else if(L.blob){const N=URL.createObjectURL(L.blob),z=document.createElement("a");z.href=N,z.download=`${L.title??L.id}.webm`,z.click(),setTimeout(()=>URL.revokeObjectURL(N),5e3)}},[o]);return n.jsxs("div",{className:p,"data-testid":c,style:{display:"flex",flexDirection:"column",background:"var(--nice-bg, #fff)",borderRadius:10,border:"1px solid var(--nice-border, #e5e7eb)",fontFamily:"system-ui, sans-serif",overflow:"hidden",...g},children:[n.jsxs("div",{style:{padding:"14px 16px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",display:"flex",gap:8,alignItems:"center"},children:[n.jsx(y.NiceIcon,{name:"mic",size:16}),n.jsx("strong",{style:{fontSize:14,color:"var(--nice-text, #111827)",flex:1},children:f("recording.recordings","Recordings")}),n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-muted, #9ca3af)"},children:f("recording.total","{recordings} total").replace("{recordings}",String(m.length))})]}),n.jsxs("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[n.jsxs("select",{value:u,disabled:U||M,onChange:()=>{},style:{...yt,flex:0},children:[n.jsx("option",{value:"call",children:f("recording.type.call","Call")}),n.jsx("option",{value:"meeting",children:f("recording.type.meeting","Meeting")}),n.jsx("option",{value:"whiteboard",children:f("recording.type.whiteboard","Whiteboard")}),n.jsx("option",{value:"screen",children:f("recording.type.screen","Screen")})]}),!U&&!M?n.jsxs("button",{onClick:e,style:{...Me,background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)"},children:[n.jsx(y.NiceIcon,{name:"circle",size:12})," ",f("recording.start","Start recording")]}):n.jsxs(n.Fragment,{children:[M?n.jsxs("button",{onClick:s,style:{...Me,background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)"},children:[n.jsx(y.NiceIcon,{name:"play",size:12})," ",f("recording.resume","Resume")]}):n.jsxs("button",{onClick:r,style:{...Me,background:"var(--nice-warning, #f59e0b)",color:"var(--nice-text-on-primary, #fff)"},children:[n.jsx(y.NiceIcon,{name:"pause",size:12})," ",f("recording.pause","Pause")]}),n.jsxs("button",{onClick:t,style:{...Me,background:"var(--nice-text, #374151)",color:"var(--nice-text-inverse, #fff)"},children:[n.jsx(y.NiceIcon,{name:"stop",size:12})," ",f("recording.stop","Stop")]}),A&&n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-muted, #9ca3af)",marginLeft:4},children:n.jsx(Dt,{startedAt:A.startedAt})})]})]}),n.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",display:"flex",gap:6,alignItems:"center"},children:[n.jsx("input",{type:"search",value:k,onChange:L=>T(L.target.value),placeholder:f("recording.searchPlaceholder","Search recordingsโฆ"),style:{flex:1,padding:"4px 8px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,fontSize:12}}),n.jsxs("select",{value:h,onChange:L=>C(L.target.value),style:yt,children:[n.jsx("option",{value:"all",children:f("recording.filter.all","All types")}),n.jsx("option",{value:"call",children:f("recording.filter.calls","Calls")}),n.jsx("option",{value:"meeting",children:f("recording.filter.meetings","Meetings")}),n.jsx("option",{value:"whiteboard",children:f("recording.type.whiteboard","Whiteboard")}),n.jsx("option",{value:"screen",children:f("recording.type.screen","Screen")})]})]}),n.jsx("div",{style:{flex:1,overflowY:"auto"},children:P.length===0?n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:32,gap:8,color:"var(--nice-text-muted, #9ca3af)"},children:[n.jsx(y.NiceIcon,{name:"mic",size:32}),n.jsx("span",{style:{fontSize:13},children:f("recording.empty","No recordings found")}),n.jsx("span",{style:{fontSize:11},children:f("recording.emptyHint","Start a recording above or adjust your search filters.")})]}):P.map(L=>n.jsx(Bn,{rec:L,onDelete:G,onDownload:F},L.id))})]})}const Ye={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,background:"var(--nice-bg, #fff)",cursor:"pointer",padding:"4px 8px",fontSize:14,lineHeight:1},Me={border:"none",borderRadius:6,cursor:"pointer",padding:"6px 14px",fontSize:12,fontWeight:500,display:"inline-flex",alignItems:"center",gap:4},yt={padding:"4px 6px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,fontSize:12,color:"var(--nice-text, #374151)",background:"var(--nice-bg, #fff)"},Hn={border:"none",background:"none",cursor:"pointer",fontSize:16,color:"var(--nice-text-muted, #9ca3af)",lineHeight:1,padding:4};function xt({participant:i,isFollowing:e,onClick:t}){const r=i.user.displayName??i.user.name,s=r.split(" ").map(a=>a[0]).slice(0,2).join("").toUpperCase();return n.jsxs("button",{onClick:t,title:`${r}${e?" (following)":""} โ ${i.editingRegion??"viewing"}`,style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:"50%",background:i.color,color:"var(--nice-color-white, #fff)",fontSize:11,fontWeight:600,border:`2px solid ${e?"var(--nice-bg, #fff)":i.color}`,boxShadow:e?`0 0 0 2px ${i.color}`:"none",cursor:"pointer",flexShrink:0,transition:"transform 0.15s",position:"relative",overflow:"visible"},children:[i.user.avatarUrl?n.jsx("img",{src:i.user.avatarUrl,alt:s,style:{width:"100%",height:"100%",borderRadius:"50%",objectFit:"cover"}}):s,i.isActive&&n.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 Vn({participant:i,containerRect:e}){if(!i.cursorX||!i.cursorY||!e)return null;const t=i.cursorX,r=i.cursorY;return n.jsxs("div",{style:{position:"absolute",left:t,top:r,pointerEvents:"none",zIndex:9e3,transform:"translate(-2px, -2px)"},children:[n.jsx("svg",{width:16,height:20,style:{display:"block"},children:n.jsx("path",{d:"M2 2 L2 16 L6 12 L10 18 L12 17 L8 11 L14 11 Z",fill:i.color,stroke:"var(--nice-bg, #fff)",strokeWidth:1.5})}),n.jsx("div",{style:{background:i.color,color:"var(--nice-color-white, #fff)",fontSize:10,padding:"1px 5px",borderRadius:3,whiteSpace:"nowrap",marginTop:-2,marginLeft:10},children:i.user.displayName??i.user.name})]})}function Yn({count:i}){const{t:e}=y.useNiceTranslation();return i===0?null:n.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:[n.jsx(y.NiceIcon,{name:"warning",size:12})," ",i>1?e("collaborativeEditor.editConflictsAutoMergingMany","{count} edit conflicts โ auto-mergingโฆ").replace("{count}",String(i)):e("collaborativeEditor.editConflictsAutoMergingOne","{count} edit conflict โ auto-mergingโฆ").replace("{count}",String(i))]})}function Kn(){const{t:i}=y.useNiceTranslation();return n.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:n.jsxs("div",{style:{background:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",color:"var(--nice-color-white, #fff)",fontSize:12,padding:"4px 14px",borderRadius:20,display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(y.NiceIcon,{name:"eye",size:12})," ",i("collaborativeEditor.viewOnly","View only")]})})}function Gn({pending:i}){const{t:e}=y.useNiceTranslation();return i===0?n.jsxs("span",{style:{fontSize:11,color:"var(--nice-success, #22c55e)",display:"inline-flex",alignItems:"center",gap:3},children:[n.jsx(y.NiceIcon,{name:"check",size:11})," ",e("collaborativeEditor.synced","Synced")]}):n.jsxs("span",{style:{fontSize:11,color:"var(--nice-warning, #f59e0b)",display:"inline-flex",alignItems:"center",gap:3},children:[n.jsx(y.NiceIcon,{name:"upload",size:11})," ",e("collaborativeEditor.pending","{pending} pendingโฆ").replace("{pending}",String(i))]})}function qn({participant:i,isFollowing:e,onClick:t}){const{t:r}=y.useNiceTranslation();return n.jsxs("button",{onClick:t,style:{fontSize:11,padding:"2px 8px",border:`1px solid ${e?i.color:"var(--nice-border, #e5e7eb)"}`,borderRadius:20,background:e?i.color:"var(--nice-bg, #fff)",color:e?"var(--nice-color-white, #fff)":"var(--nice-text-secondary, #6b7280)",cursor:"pointer",display:"flex",alignItems:"center",gap:4},children:[n.jsx(y.NiceIcon,{name:"eye",size:11})," ",e?r("collaborativeEditor.unfollow","Unfollow"):r("collaborativeEditor.follow","Follow {name}").replace("{name}",String((i.user.displayName??i.user.name).split(" ")[0]))]})}function Jn({editorType:i,sessionId:e,currentUser:t,participants:r=[],onOperation:s,onParticipantJoin:a,onParticipantLeave:o,onCursorMove:d,isReadOnly:u=!1,showParticipants:p=!0,showCursors:g=!0,pendingOperations:c=0,conflictCount:f=0,className:m,style:w,children:k,"data-testid":T}){const{t:h}=y.useNiceTranslation(),C=l.useRef(null),[A,U]=l.useState(null),[M,P]=l.useState(null),[G,F]=l.useState(!1);l.useEffect(()=>{const j=C.current;if(!j)return;const O=new ResizeObserver(()=>U(j.getBoundingClientRect()));return O.observe(j),U(j.getBoundingClientRect()),()=>O.disconnect()},[]);const L=l.useCallback(j=>{if(!C.current||!d)return;const O=C.current.getBoundingClientRect();d(j.clientX-O.left,j.clientY-O.top)},[d]),N=l.useCallback(j=>{P(O=>O===j?null:j)},[]),z={vector:{icon:"pen",label:h("collaborativeEditor.vector","Vector")},pixel:{icon:"image",label:h("collaborativeEditor.pixel","Pixel")},diagram:{icon:"bar-chart",label:h("collaborativeEditor.diagram","Diagram")},document:{icon:"file",label:h("collaborativeEditor.document","Document")},whiteboard:{icon:"edit",label:h("collaborativeEditor.whiteboard","Whiteboard")}},E=n.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:[n.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",fontWeight:500,display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(y.NiceIcon,{name:z[i].icon,size:12}),z[i].label]}),n.jsx("span",{style:{flex:1}}),n.jsx(Gn,{pending:c}),p&&r.length>0&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:-4},children:[r.slice(0,5).map((j,O)=>n.jsx("div",{style:{marginLeft:O>0?-8:0,zIndex:10-O},children:n.jsx(xt,{participant:j,isFollowing:M===j.user.id,onClick:()=>{F(!0),N(j.user.id)}})},j.user.id)),r.length>5&&n.jsxs("button",{onClick:()=>F(!G),style:{marginLeft:-4,zIndex:5,width:30,height:30,borderRadius:"50%",background:"var(--nice-border, #e5e7eb)",border:"2px solid var(--nice-bg, #FFF)",fontSize:10,fontWeight:600,color:"var(--nice-text, #374151)",cursor:"pointer"},children:["+",r.length-5]})]}),p&&r.length>0&&n.jsx("button",{onClick:()=>F(!G),style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:5,background:G?"var(--nice-primary-bg, #eff6ff)":"var(--nice-bg, #fff)",padding:"3px 8px",cursor:"pointer",fontSize:11,color:G?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #6b7280)"},children:h("collaborativeEditor.online","{propParticipants} online").replace("{propParticipants}",String(r.length))})]}),V=n.jsxs("div",{ref:C,onMouseMove:L,style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},children:[k??n.jsxs("div",{id:`collab-editor-${i}-${e}`,style:{width:"100%",height:"100%",minHeight:400,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-bg-secondary, #f9fafb)",color:"var(--nice-text-muted, #9ca3af)",fontSize:13},children:[h("collaborativeEditor.dropYourEditorHereOr","Drop your {editorType} editor here or use the").replace("{editorType}",String(i))," ",n.jsx("code",{style:{background:"var(--nice-border, #e5e7eb)",padding:"1px 5px",borderRadius:3,margin:"0 4px"},children:`#collab-editor-${i}-${e}`})," ",h("collaborativeEditor.mountPoint","mount point.")]}),g&&r.filter(j=>j.user.id!==t.id&&j.cursorX!=null&&j.cursorY!=null).map(j=>n.jsx(Vn,{participant:j,containerRect:A},j.user.id)),n.jsx(Yn,{count:f}),u&&n.jsx(Kn,{})]}),J=G&&r.length>0?n.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:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[n.jsx("strong",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:h("collaborativeEditor.participants","Participants")}),n.jsx("button",{onClick:()=>F(!1),style:{border:"none",background:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",fontSize:14},"aria-label":h("collaborativeEditor.close","Close"),children:n.jsx(y.NiceIcon,{name:"close",size:14})})]}),r.map(j=>n.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:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx(xt,{participant:j,isFollowing:M===j.user.id,onClick:()=>N(j.user.id)}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontSize:12,fontWeight:500,color:"var(--nice-text, #111827)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j.user.displayName??j.user.name}),n.jsx("div",{style:{fontSize:10,color:"var(--nice-text-muted, #9ca3af)"},children:j.editingRegion??h("collaborativeEditor.viewing","viewing")})]})]}),j.user.id!==t.id&&n.jsx(qn,{participant:j,isFollowing:M===j.user.id,onClick:()=>N(j.user.id)})]},j.user.id))]}):void 0;return n.jsx(y.NiceAppShell,{flush:!0,className:m,"data-testid":T,style:{background:"var(--nice-bg, #fff)",fontFamily:"system-ui, sans-serif",...w},menubar:E,rightSidebar:J,children:V})}function st(i){let e="";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return btoa(e)}function at(i){const e=atob(i),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Xn(i){return new TextEncoder().encode(i)}function Zn(i){return new TextDecoder().decode(i)}async function Qn(i){return crypto.subtle.generateKey({name:"AES-GCM",length:i},!0,["encrypt","decrypt"])}async function ei(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-384"},!0,["deriveKey"])}async function ti(i,e){return crypto.subtle.deriveKey({name:"ECDH",public:e},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function ni(i,e){const t=crypto.getRandomValues(new Uint8Array(12)),r=Xn(e),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},i,r),a=new Uint8Array(s),o=new Uint8Array(12+a.length);return o.set(t,0),o.set(a,12),st(o)}async function ii(i,e){const t=at(e),r=t.slice(0,12),s=t.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},i,s);return Zn(new Uint8Array(a))}async function bt(i,e){const t=at(i);return crypto.subtle.importKey("raw",t,{name:"AES-GCM",length:e},!1,["encrypt","decrypt"])}async function ri(i){const e=await crypto.subtle.exportKey("raw",i);return st(new Uint8Array(e))}async function si(i){const e=await crypto.subtle.exportKey("spki",i);return st(new Uint8Array(e))}async function ai(i){const e=at(i);return crypto.subtle.importKey("spki",e,{name:"ECDH",namedCurve:"P-384"},!0,[])}class Mt{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 bt(this.config.keyMaterial,128):this.keys.aes256=await bt(this.config.keyMaterial,256);else if(e==="AES-GCM-256"||e==="AES-GCM-128"){const t=e==="AES-GCM-256"?256:128,r=await Qn(t);t===128?this.keys.aes128=r:this.keys.aes256=r}else if(e==="E2E-ECDH-P384"){const t=await ei();this.keys.ecdhPrivate=t.privateKey,this.keys.ecdhPublic=t.publicKey,this.keys.ecdhSessionKeys=new Map}this.ready=!0}async getPublicKeyForPeer(){return this.keys.ecdhPublic?si(this.keys.ecdhPublic):null}async registerPeerPublicKey(e,t){var a;if(!this.keys.ecdhPrivate)return;const r=await ai(t),s=await ti(this.keys.ecdhPrivate,r);(a=this.keys.ecdhSessionKeys)==null||a.set(e,s)}resolveAlgorithm(e){if(e&&this.config.scopeOverrides){const t=this.config.scopeOverrides.find(r=>(r.scope===e||r.scope==="all")&&r.enabled);if(t)return t.algorithm}return this.config.defaultAlgorithm}getKey(e,t){var r;switch(e){case"AES-GCM-256":return this.keys.aes256??null;case"AES-GCM-128":return this.keys.aes128??null;case"E2E-ECDH-P384":return t?((r=this.keys.ecdhSessionKeys)==null?void 0:r.get(t))??null:null;default:return null}}async encrypt(e,t,r){if(!this.config.enabled)return e;if(!this.ready)throw new Error("EncryptionService not initialised โ call init() first");const s=this.resolveAlgorithm(t);if(s==="none")return e;const a=this.getKey(s,r);return a?ni(a,e):(console.warn(`EncryptionService: no key found for algorithm "${s}" โ returning plaintext`),e)}async decrypt(e,t,r){if(!this.config.enabled)return e;if(!this.ready)throw new Error("EncryptionService not initialised โ call init() first");const s=this.resolveAlgorithm(t);if(s==="none")return e;const a=this.getKey(s,r);return a?ii(a,e):(console.warn(`EncryptionService: no key found for algorithm "${s}" โ returning as-is`),e)}async exportSymmetricKey(e){const t=e??this.config.defaultAlgorithm,r=this.getKey(t);return r?ri(r):null}isEnabled(){return this.config.enabled}getConfig(){return this.config}updateConfig(e){this.config=e,this.ready=!1}}const Oe=new Map;function oi(i,e){return Oe.has(i)||Oe.set(i,new Mt(e)),Oe.get(i)}function li(i){Oe.delete(i)}class Wt{constructor(e={}){this.recorder=null,this.chunks=[],this.session=null,this.recognition=null,this.segmentCounter=0,this.callbacks=e}start(e,t){var d,u,p;if(((d=this.recorder)==null?void 0:d.state)==="recording")throw new Error("Recording already in progress");const r=t.mimeType??this.chooseMimeType(),s=new MediaRecorder(e,{mimeType:r});this.chunks=[];const a=new Date,o=`rec_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return this.session={id:o,sessionType:t.sessionType,startedAt:a,state:"recording",mimeType:r,participants:[t.speakerId??"unknown"],title:t.title??`Recording ${a.toLocaleString()}`},s.ondataavailable=g=>{g.data&&g.data.size>0&&this.chunks.push(g.data)},s.onstop=()=>{var c,f,m,w;const g=new Blob(this.chunks,{type:r});this.session&&(this.session.blob=g,this.session.endedAt=new Date,this.session.durationMs=this.session.endedAt.getTime()-this.session.startedAt.getTime(),this.session.size=g.size,this.session.state="ready"),(f=(c=this.callbacks).onDataAvailable)==null||f.call(c,g),(w=(m=this.callbacks).onStateChange)==null||w.call(m,"ready")},s.onerror=g=>{var c,f,m,w;(f=(c=this.callbacks).onError)==null||f.call(c,new Error(String(g))),this.session&&(this.session.state="failed"),(w=(m=this.callbacks).onStateChange)==null||w.call(m,"failed")},s.start(t.timesliceMs??1e3),this.recorder=s,t.transcribe&&this.startTranscription(t.speakerId??"unknown",t.speakerName??"Participant"),(p=(u=this.callbacks).onStateChange)==null||p.call(u,"recording"),this.session}pause(){var e,t,r;((e=this.recorder)==null?void 0:e.state)==="recording"&&(this.recorder.pause(),this.session&&(this.session.state="paused"),(r=(t=this.callbacks).onStateChange)==null||r.call(t,"paused"))}resume(){var e,t,r;((e=this.recorder)==null?void 0:e.state)==="paused"&&(this.recorder.resume(),this.session&&(this.session.state="recording"),(r=(t=this.callbacks).onStateChange)==null||r.call(t,"recording"))}stop(){var e,t;return this.stopTranscription(),this.recorder&&this.recorder.state!=="inactive"&&(this.recorder.stop(),this.session&&(this.session.state="processing"),(t=(e=this.callbacks).onStateChange)==null||t.call(e,"processing")),this.session}startTranscription(e,t){const r=window,s=r.SpeechRecognition??r.webkitSpeechRecognition;if(!s)return;const a=new s;a.continuous=!0,a.interimResults=!1,a.lang="en-US";const o=Date.now();a.onresult=d=>{var p,g;const u=d.results;for(let c=d.resultIndex;c<u.length;c++){const f=u[c];if(!f.isFinal)continue;const m=f[0],w=Date.now(),k={id:`seg_${++this.segmentCounter}`,speakerId:e,speakerName:t,text:m.transcript.trim(),startMs:w-o-1500,endMs:w-o,confidence:m.confidence??.9};this.session&&(this.session.transcript=[...this.session.transcript??[],k]),(g=(p=this.callbacks).onTranscriptSegment)==null||g.call(p,k)}},a.onerror=()=>{};try{a.start(),this.recognition=a}catch{}}stopTranscription(){var e;try{(e=this.recognition)==null||e.stop()}catch{}this.recognition=null}chooseMimeType(){const e=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm","audio/webm;codecs=opus","audio/ogg;codecs=opus"];for(const t of e)if(MediaRecorder.isTypeSupported(t))return t;return""}getState(){var e;return((e=this.session)==null?void 0:e.state)??"idle"}getSession(){return this.session}download(e){var a,o;const t=(a=this.session)==null?void 0:a.blob;if(!t)return;const r=URL.createObjectURL(t),s=document.createElement("a");s.href=r,s.download=e??`${((o=this.session)==null?void 0:o.title)??"recording"}.webm`,s.click(),setTimeout(()=>URL.revokeObjectURL(r),3e4)}}const $e=new Map;function ci(i,e){return $e.has(i)||$e.set(i,new Wt(e)),$e.get(i)}function di(i){$e.delete(i)}class Ot{constructor(e){this.events=[],this.eventListeners=new Map,this.config={serverUrl:e.serverUrl,apiKey:e.apiKey??"",anonymizeIp:e.anonymizeIp??!0,enableGeoLocation:e.enableGeoLocation??!1,pixelPath:e.pixelPath??"/pixel",redirectPath:e.redirectPath??"/redirect",hashAlgorithm:e.hashAlgorithm??"sha256"}}generateTrackingPixel(e){const t=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,metadata:e.metadata}),r=e.width??1,s=e.height??1,a=`${this.config.serverUrl}${this.config.pixelPath}?${t}`;return`<img src="${this.escapeHtml(a)}" width="${r}" height="${s}" alt="" style="display:block;width:${r}px;height:${s}px;border:0;" />`}generateTrackingPixelUrl(e){const t=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,metadata:e.metadata});return`${this.config.serverUrl}${this.config.pixelPath}?${t}`}wrapLink(e){const t=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,url:e.url,linkName:e.linkName});return`${this.config.serverUrl}${this.config.redirectPath}?${t}`}wrapLinksForTracking(e,t){const r=t.excludePatterns??[/^mailto:/i,/^tel:/i,/^#/,/unsubscribe/i],s=/<a\s+([^>]*?)href=["']([^"']+)["']([^>]*?)>/gi;return e.replace(s,(a,o,d,u)=>{if(r.some(f=>f.test(d)))return a;const g=this.extractLinkName(o+u)??d,c=this.wrapLink({url:d,messageId:t.messageId,recipientId:t.recipientId,campaignId:t.campaignId,linkName:g});return`<a ${o}href="${this.escapeHtml(c)}"${u}>`})}recordEvent(e){const t={...e,id:this.generateEventId(),timestamp:new Date,ipAddress:this.config.anonymizeIp?this.anonymizeIpAddress(e.ipAddress):e.ipAddress};return this.events.push(t),this.notifyListeners(t),t}parseTrackingParams(e){const t=e.get("mid"),r=e.get("rid");if(!t||!r)return null;const s={};return e.forEach((a,o)=>{o.startsWith("m_")&&(s[o.substring(2)]=a)}),{messageId:t,recipientHash:r,campaignId:e.get("cid")??void 0,url:e.get("url")??void 0,linkName:e.get("ln")??void 0,metadata:Object.keys(s).length>0?s:void 0}}getStats(e){let t=this.events;e&&(t=this.events.filter(f=>!(e.campaignId&&f.campaignId!==e.campaignId||e.messageId&&f.messageId!==e.messageId||e.startDate&&f.timestamp<e.startDate||e.endDate&&f.timestamp>e.endDate)));const r=new Set(t.map(f=>f.recipientHash)),s=t.filter(f=>f.type==="open"),a=t.filter(f=>f.type==="click"),o=t.filter(f=>f.type==="bounce"),d=t.filter(f=>f.type==="unsubscribe"),u=t.filter(f=>f.type==="complaint"),p=new Set(s.map(f=>f.recipientHash)).size,g=new Set(a.map(f=>f.recipientHash)).size,c=r.size;return{sent:c+o.length,delivered:c,opens:s.length,uniqueOpens:p,clicks:a.length,uniqueClicks:g,bounces:o.length,unsubscribes:d.length,complaints:u.length,openRate:c>0?p/c:0,clickRate:c>0?g/c:0,clickToOpenRate:p>0?g/p:0,bounceRate:c>0?o.length/(c+o.length):0}}getLinkStats(e){let t=this.events.filter(o=>o.type==="click"&&o.url);e&&(t=t.filter(o=>!(e.campaignId&&o.campaignId!==e.campaignId||e.messageId&&o.messageId!==e.messageId)));const r=new Map;for(const o of t){const d=o.url;r.has(d)||r.set(d,{url:d,linkName:void 0,total:0,unique:new Set});const u=r.get(d);u.total++,u.unique.add(o.recipientHash)}const s=t.length,a=[];for(const[,o]of r)a.push({url:o.url,linkName:o.linkName,totalClicks:o.total,uniqueClicks:o.unique.size,clickShare:s>0?o.total/s:0});return a.sort((o,d)=>d.totalClicks-o.totalClicks)}getDeviceStats(e){let t=this.events.filter(s=>s.type==="open");e!=null&&e.campaignId&&(t=t.filter(s=>s.campaignId===e.campaignId));const r={desktop:0,mobile:0,tablet:0,unknown:0};for(const s of t){const a=s.device??"unknown";r[a]=(r[a]??0)+1}return r}on(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t),()=>{var r;(r=this.eventListeners.get(e))==null||r.delete(t)}}onAny(e){const t=["open","click","bounce","unsubscribe","complaint"].map(r=>this.on(r,e));return()=>{t.forEach(r=>r())}}generateUnsubscribeLink(e){const t=new URLSearchParams;return t.set("rid",this.hashRecipientId(e.recipientId)),e.listId&&t.set("lid",e.listId),t.set("action","unsubscribe"),`${this.config.serverUrl}/unsubscribe?${t.toString()}`}generateListUnsubscribeHeader(e){return`<${this.generateUnsubscribeLink(e)}>`}clearEvents(){this.events=[]}exportEvents(e){return e!=null&&e.anonymize?this.events.map(t=>({...t,recipientHash:"anonymized",ipAddress:void 0,userAgent:void 0})):[...this.events]}buildTrackingParams(e){const t=new URLSearchParams;if(t.set("mid",e.messageId),t.set("rid",this.hashRecipientId(e.recipientId)),e.campaignId&&t.set("cid",e.campaignId),e.url&&t.set("url",e.url),e.linkName&&t.set("ln",e.linkName),e.metadata)for(const[r,s]of Object.entries(e.metadata))t.set(`m_${r}`,s);return t.toString()}hashRecipientId(e){let t=0;for(let r=0;r<e.length;r++){const s=e.charCodeAt(r);t=(t<<5)-t+s,t=t&t}return Math.abs(t).toString(36)}anonymizeIpAddress(e){if(e){if(e.includes(".")){const t=e.split(".");return t[3]="0",t.join(".")}return e.includes(":")?e.split(":").slice(0,3).join(":")+"::":e}}extractLinkName(e){const t=e.match(/title=["']([^"']+)["']/i);if(t)return t[1];const r=e.match(/data-link-name=["']([^"']+)["']/i);if(r)return r[1]}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}generateEventId(){return`evt_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}notifyListeners(e){const t=this.eventListeners.get(e.type);if(t)for(const r of t)try{r(e)}catch(s){console.error("Tracking event listener error:",s)}}}let ye=null;function Je(i){if(!ye&&i&&(ye=new Ot(i)),!ye)throw new Error("EmailTrackingService not initialized. Call with config first.");return ye}function pi(){ye==null||ye.clearEvents(),ye=null}function ui(i){const{config:e,campaignId:t,autoRefreshInterval:r}=i,s=l.useMemo(()=>{if(e)return Je(e);try{return Je()}catch{return null}},[e]),[a,o]=l.useState(null),[d,u]=l.useState([]),p=l.useCallback(()=>{s&&(o(s.getStats({campaignId:t})),u(s.getLinkStats({campaignId:t})))},[s,t]);l.useEffect(()=>{if(p(),r&&s){const m=setInterval(p,r);return()=>clearInterval(m)}},[p,r,s]),l.useEffect(()=>{if(s)return s.onAny(()=>{p()})},[s,p]);const g=l.useCallback((m,w)=>s?s.generateTrackingPixel({messageId:m,recipientId:w,campaignId:t}):"",[s,t]),c=l.useCallback((m,w,k)=>s?s.wrapLinksForTracking(m,{messageId:w,recipientId:k,campaignId:t}):m,[s,t]),f=l.useCallback(m=>{s==null||s.recordEvent(m)},[s]);return{generatePixel:g,wrapLinks:c,stats:a,linkStats:d,recordEvent:f,refreshStats:p}}class $t{constructor(e){this.templates=new Map,this.campaigns=new Map,this.abortControllers=new Map,this.config={sendEmail:e.sendEmail,rateLimit:e.rateLimit??60,batchSize:e.batchSize??10,retryOnFail:e.retryOnFail??!0,maxRetries:e.maxRetries??3,dateFormatter:e.dateFormatter??this.defaultDateFormatter,numberFormatter:e.numberFormatter??this.defaultNumberFormatter,currencyFormatter:e.currencyFormatter??this.defaultCurrencyFormatter}}createTemplate(e){const t={...e,id:this.generateId("tpl"),createdAt:new Date,updatedAt:new Date};return this.templates.set(t.id,t),t}updateTemplate(e,t){const r=this.templates.get(e);if(!r)throw new Error(`Template not found: ${e}`);const s={...r,...t,updatedAt:new Date};return this.templates.set(e,s),s}getTemplate(e){return this.templates.get(e)}deleteTemplate(e){return this.templates.delete(e)}listTemplates(){return Array.from(this.templates.values())}extractFields(e){const t=/\{\{([^}]+)\}\}/g,r=new Set;let s;for(;(s=t.exec(e))!==null;){const a=s[1].trim();if(a.startsWith("#if "))r.add(a.substring(4).trim());else if(a.startsWith("#unless "))r.add(a.substring(8).trim());else if(a.startsWith("#each "))r.add(a.substring(6).trim());else if(!a.startsWith("/")&&!a.startsWith("else")){const[o]=a.split("|");r.add(o.trim())}}return Array.from(r)}createCampaign(e){if(!this.templates.has(e.templateId))throw new Error(`Template not found: ${e.templateId}`);const t={...e,id:this.generateId("cmp"),status:"draft",recipients:e.recipients.map(r=>({...r,status:"pending"})),createdAt:new Date};return this.campaigns.set(t.id,t),t}getCampaign(e){return this.campaigns.get(e)}updateCampaign(e,t){const r=this.campaigns.get(e);if(!r)throw new Error(`Campaign not found: ${e}`);if(r.status==="sending")throw new Error("Cannot update campaign while sending");const s={...r,...t};return this.campaigns.set(e,s),s}addRecipients(e,t){const r=this.campaigns.get(e);if(!r)throw new Error(`Campaign not found: ${e}`);if(r.status==="sending")throw new Error("Cannot add recipients while sending");const s=t.map(a=>({...a,status:"pending"}));r.recipients.push(...s),this.campaigns.set(e,r)}removeRecipient(e,t){const r=this.campaigns.get(e);if(!r)return!1;const s=r.recipients.findIndex(a=>a.id===t);return s===-1?!1:(r.recipients.splice(s,1),!0)}listCampaigns(){return Array.from(this.campaigns.values())}validateCampaign(e){const t=this.campaigns.get(e);if(!t)return{isValid:!1,errors:[{type:"syntax_error",message:"Campaign not found"}],warnings:[],missingFields:new Map};const r=this.templates.get(t.templateId);if(!r)return{isValid:!1,errors:[{type:"syntax_error",message:"Template not found"}],warnings:[],missingFields:new Map};const s=[],a=[],o=new Map;t.recipients.length===0&&s.push({type:"empty_recipient",message:"No recipients in campaign"});for(const p of t.recipients){if(!p.email){s.push({type:"empty_recipient",recipientId:p.id,message:`Recipient ${p.id} has no email address`});continue}const g=[];for(const c of r.fields)c.required&&!(c.name in p.data)&&(g.push(c.name),s.push({type:"missing_field",field:c.name,recipientId:p.id,message:`Required field "${c.name}" missing for ${p.email}`}));g.length>0&&o.set(p.id,g)}const d=this.extractFields(r.subject+r.htmlBody+(r.textBody??"")),u=r.fields.map(p=>p.name);for(const p of d)u.includes(p)||a.push({type:"unused_field",field:p,message:`Field "${p}" used in template but not defined`});return{isValid:s.length===0,errors:s,warnings:a,missingFields:o}}previewMerge(e,t){const r=this.templates.get(e);if(!r)throw new Error(`Template not found: ${e}`);return{subject:this.processTemplate(r.subject,t,r.fields),html:this.processTemplate(r.htmlBody,t,r.fields),text:r.textBody?this.processTemplate(r.textBody,t,r.fields):void 0}}async*sendCampaign(e){const t=this.campaigns.get(e);if(!t)throw new Error(`Campaign not found: ${e}`);const r=this.templates.get(t.templateId);if(!r)throw new Error(`Template not found: ${t.templateId}`);const s=this.validateCampaign(e);if(!s.isValid)throw new Error(`Campaign validation failed: ${s.errors.map(f=>f.message).join(", ")}`);t.status="sending",t.startedAt=new Date,this.campaigns.set(e,t);const a=new AbortController;this.abortControllers.set(e,a);const o=t.recipients.filter(f=>f.status==="pending"),d=o.length;let u=0,p=0;const g=Date.now(),c=60*1e3/(t.rateLimit??this.config.rateLimit);try{for(let f=0;f<o.length;f++){if(a.signal.aborted){t.status="paused";break}const m=o[f];try{const A=this.previewMerge(r.id,m.data),U=await this.config.sendEmail({to:m.email,cc:m.cc,bcc:m.bcc,from:t.fromEmail,fromName:t.fromName,replyTo:t.replyTo,subject:m.subjectOverride??A.subject,html:A.html,text:A.text});U.success?(m.status="sent",u++):(m.status="failed",m.error=U.error,p++)}catch(A){m.status="failed",m.error=A instanceof Error?A.message:"Unknown error",p++}const w=u+p,k=Date.now()-g,T=w>0?k/w:c,h=d-w,C=Math.round(h*T/1e3);yield{campaignId:e,total:d,sent:u,failed:p,pending:d-w,current:m.email,percentage:Math.round(w/d*100),estimatedTimeRemaining:C,isComplete:!1},f<o.length-1&&await this.delay(c)}t.status="completed",t.completedAt=new Date,this.campaigns.set(e,t),yield{campaignId:e,total:d,sent:u,failed:p,pending:0,percentage:100,isComplete:!0}}finally{this.abortControllers.delete(e)}}pauseCampaign(e){const t=this.abortControllers.get(e);t&&t.abort();const r=this.campaigns.get(e);r&&r.status==="sending"&&(r.status="paused",this.campaigns.set(e,r))}async*resumeCampaign(e){const t=this.campaigns.get(e);if(!t)throw new Error(`Campaign not found: ${e}`);if(t.status!=="paused")throw new Error("Campaign is not paused");t.status="draft",this.campaigns.set(e,t),yield*this.sendCampaign(e)}cancelCampaign(e){this.pauseCampaign(e);const t=this.campaigns.get(e);t&&(t.status="cancelled",this.campaigns.set(e,t))}async*retryFailed(e){const t=this.campaigns.get(e);if(!t)throw new Error(`Campaign not found: ${e}`);for(const r of t.recipients)r.status==="failed"&&(r.status="pending",r.error=void 0);t.status="draft",this.campaigns.set(e,t),yield*this.sendCampaign(e)}processTemplate(e,t,r){const s=new Map(r.map(a=>[a.name,a]));return e=this.processConditionals(e,t),e=this.processLoops(e,t),e=e.replace(/\{\{([^}#/]+)\}\}/g,(a,o)=>{const[d,...u]=o.trim().split("|").map(c=>c.trim());let p=this.getNestedValue(t,d);const g=s.get(d);p==null&&(p=(g==null?void 0:g.defaultValue)??""),g&&p!==""&&(p=this.formatValue(p,g));for(const c of u)p=this.applyFormatter(p,c);return String(p)}),e}processConditionals(e,t){const r=/\{\{#if\s+([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g;return e.replace(r,(s,a,o,d="")=>{const u=this.getNestedValue(t,a.trim());return this.isTruthy(u)?o:d})}processLoops(e,t){const r=/\{\{#each\s+([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g;return e.replace(r,(s,a,o)=>{const d=this.getNestedValue(t,a.trim());return Array.isArray(d)?d.map((u,p)=>{let g=o;return typeof u!="object"&&(g=g.replace(/\{\{this\}\}/g,String(u))),g=g.replace(/\{\{this\.([^}]+)\}\}/g,(c,f)=>String(this.getNestedValue(u,f)??"")),g=g.replace(/\{\{@index\}\}/g,String(p)),g=g.replace(/\{\{@first\}\}/g,String(p===0)),g=g.replace(/\{\{@last\}\}/g,String(p===d.length-1)),g}).join(""):""})}formatValue(e,t){switch(t.type){case"date":return e instanceof Date?this.config.dateFormatter(e,t.format??"short"):typeof e=="string"||typeof e=="number"?this.config.dateFormatter(new Date(e),t.format??"short"):String(e);case"number":return typeof e=="number"?this.config.numberFormatter(e,t.format??""):String(e);case"currency":if(typeof e=="number"){const[r="USD",s="en-US"]=(t.format??"USD|en-US").split("|");return this.config.currencyFormatter(e,r,s)}return String(e);case"boolean":return e?"Yes":"No";case"list":return Array.isArray(e)?e.join(t.format??", "):String(e);default:return String(e)}}applyFormatter(e,t){const r=String(e);switch(t.toLowerCase()){case"uppercase":return r.toUpperCase();case"lowercase":return r.toLowerCase();case"capitalize":return r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();case"titlecase":return r.replace(/\b\w/g,s=>s.toUpperCase());case"trim":return r.trim();case"escape":return this.escapeHtml(r);default:return r}}getNestedValue(e,t){const r=t.split(".");let s=e;for(const a of r){if(s==null)return;s=s[a]}return s}isTruthy(e){return e==null?!1:typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"||Array.isArray(e)?e.length>0:!0}defaultDateFormatter(e,t){const r={};switch(t){case"short":r.dateStyle="short";break;case"medium":r.dateStyle="medium";break;case"long":r.dateStyle="long";break;case"full":r.dateStyle="full";break;case"iso":return e.toISOString();default:r.dateStyle="medium"}return new Intl.DateTimeFormat("en-US",r).format(e)}defaultNumberFormatter(e,t){if(!t)return new Intl.NumberFormat().format(e);const r=parseInt(t,10);return isNaN(r)?String(e):new Intl.NumberFormat("en-US",{minimumFractionDigits:r,maximumFractionDigits:r}).format(e)}defaultCurrencyFormatter(e,t,r){return new Intl.NumberFormat(r,{style:"currency",currency:t}).format(e)}generateId(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}delay(e){return new Promise(t=>setTimeout(t,e))}}let Ne=null;function Xe(i){if(!Ne&&i&&(Ne=new $t(i)),!Ne)throw new Error("MailMergeService not initialized. Call with config first.");return Ne}function hi(){Ne=null}function fi(i={}){const{config:e}=i,t=l.useMemo(()=>{if(e)return Xe(e);try{return Xe()}catch{return null}},[e]),[r,s]=l.useState(null),[a,o]=l.useState(!1),[d,u]=l.useState([]),[p,g]=l.useState([]),c=l.useCallback(()=>{t&&(u(t.listTemplates()),g(t.listCampaigns()))},[t]),f=l.useCallback(C=>{if(!t)throw new Error("Service not initialized");const A=t.createTemplate(C);return c(),A},[t,c]),m=l.useCallback(C=>{if(!t)throw new Error("Service not initialized");const A=t.createCampaign(C);return c(),A},[t,c]),w=l.useCallback((C,A)=>{if(!t)throw new Error("Service not initialized");return t.previewMerge(C,A)},[t]),k=l.useCallback(C=>{if(!t)throw new Error("Service not initialized");return t.validateCampaign(C)},[t]),T=l.useCallback(async function*(C){if(!t)throw new Error("Service not initialized");o(!0);try{for await(const A of t.sendCampaign(C))s(A),yield A}finally{o(!1),c()}},[t,c]),h=l.useCallback(C=>{t==null||t.pauseCampaign(C),o(!1),c()},[t,c]);return{createTemplate:f,createCampaign:m,preview:w,validate:k,send:T,pause:h,progress:r,isSending:a,templates:d,campaigns:p}}class Lt{constructor(e){this.abortController=null,this.mapping={users:new Map,channels:new Map,files:new Map},this.config=e}async parseSlackExport(e){const t=await this.extractZipContents(e),r=t.get("users.json"),s=r?JSON.parse(r):[],a=t.get("channels.json"),o=a?JSON.parse(a):[],d=t.get("groups.json");if(d){const g=JSON.parse(d);o.push(...g.map(c=>({...c,is_private:!0})))}const u=t.get("dms.json");if(u){const g=JSON.parse(u);o.push(...g.map(c=>({...c,is_im:!0})))}const p=new Map;for(const g of o){const c=[],f=g.name;for(const[m,w]of t)if(m.startsWith(f+"/")&&m.endsWith(".json"))try{const k=JSON.parse(w);c.push(...k)}catch(k){console.warn(`Failed to parse messages from ${m}:`,k)}c.length>0&&p.set(g.id,c)}return{users:s,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,t={}){const r=e.users.filter(c=>t.importUsers!==!1&&!c.deleted),s=r.map(c=>this.mapUser(c)),a=e.channels.filter(c=>!(t.skipArchived&&c.is_archived||t.skipDirectMessages&&(c.is_im||c.is_mpim)||t.channelFilter&&!t.channelFilter.includes(c.id)&&!t.channelFilter.includes(c.name))),o=a.map(c=>this.mapChannel(c,new Map));let d=0;const u=new Map;for(const[c,f]of e.messages){const m=e.channels.find(T=>T.id===c);if(!m||!a.some(T=>T.id===c))continue;const k=this.filterMessages(f,t);u.set(m.name,k.length),d+=k.length}let p=0,g=0;for(const c of e.messages.values())for(const f of c)f.files&&(p+=f.files.length,g+=f.files.reduce((m,w)=>m+(w.size||0),0));return{users:{total:e.users.length,filtered:r.length,items:s},channels:{total:e.channels.length,filtered:a.length,items:o},messages:{total:d,perChannel:u},files:{total:p,totalSize:g}}}async*import(e,t={}){this.abortController=new AbortController,this.mapping={users:new Map,channels:new Map,files:new Map};const r=[],s={usersImported:0,channelsImported:0,messagesImported:0,filesImported:0,reactionsImported:0,threadsImported:0},a=new Date,d=1e3/(this.config.rateLimit??10);try{if(t.importUsers!==!1){const p=e.users.filter(c=>!c.deleted);let g=0;for(const c of p){if(this.abortController.signal.aborted)break;const f=this.mapUser(c),m=await this.config.createUser(f);m.success&&m.id?(this.mapping.users.set(c.id,m.id),s.usersImported++):r.push({phase:"users",itemId:c.id,itemType:"user",message:m.error??"Failed to create user"}),g++,yield{phase:"users",total:p.length,processed:g,failed:r.filter(w=>w.phase==="users").length,current:c.name,percentage:Math.round(g/p.length*100),isComplete:!1,errors:r},await this.delay(d)}}if(t.importChannels!==!1){const p=e.channels.filter(c=>{var f;return t.skipArchived&&c.is_archived||t.skipDirectMessages&&(c.is_im||c.is_mpim)?!1:(f=t.channelFilter)!=null&&f.length?t.channelFilter.includes(c.id)||t.channelFilter.includes(c.name):!0});let g=0;for(const c of p){if(this.abortController.signal.aborted)break;const f=this.mapChannel(c,this.mapping.users),m=await this.config.createChannel(f);m.success&&m.id?(this.mapping.channels.set(c.id,m.id),s.channelsImported++):r.push({phase:"channels",itemId:c.id,itemType:"channel",message:m.error??"Failed to create channel"}),g++,yield{phase:"channels",total:p.length,processed:g,failed:r.filter(w=>w.phase==="channels").length,current:c.name,percentage:Math.round(g/p.length*100),isComplete:!1,errors:r},await this.delay(d)}}if(t.importMessages!==!1){const p=[];for(const[f,m]of e.messages){if(!this.mapping.channels.has(f))continue;const w=this.filterMessages(m,t);for(const k of w)p.push({channelId:f,message:k})}p.sort((f,m)=>parseFloat(f.message.ts)-parseFloat(m.message.ts));const g=new Map;let c=0;for(const{channelId:f,message:m}of p){if(this.abortController.signal.aborted)break;const w=this.mapMessage(m,f,this.mapping,g),k=await this.config.createMessage(w);k.success&&k.id?((!m.thread_ts||m.thread_ts===m.ts)&&g.set(m.ts,k.id),s.messagesImported++,w.isThreadReply&&s.threadsImported++,s.reactionsImported+=w.reactions.length):r.push({phase:"messages",itemId:m.ts,itemType:"message",message:k.error??"Failed to create message"}),c++,yield{phase:"messages",total:p.length,processed:c,failed:r.filter(T=>T.phase==="messages").length,current:`${c}/${p.length}`,percentage:Math.round(c/p.length*100),isComplete:!1,errors:r},await this.delay(d)}}if(t.importFiles&&t.downloadFiles&&this.config.uploadFile&&this.config.downloadFile){const p=[];for(const c of e.messages.values())for(const f of c)f.files&&p.push(...f.files);let g=0;for(const c of p){if(this.abortController.signal.aborted)break;try{const f=c.url_private_download??c.url_private;if(f&&this.config.slackToken){const m=await this.config.downloadFile(f,this.config.slackToken),w=await this.config.uploadFile(c,m);w.success&&w.url?(this.mapping.files.set(c.id,w.url),s.filesImported++):r.push({phase:"files",itemId:c.id,itemType:"file",message:w.error??"Failed to upload file"})}}catch(f){r.push({phase:"files",itemId:c.id,itemType:"file",message:f instanceof Error?f.message:"File download failed"})}g++,yield{phase:"files",total:p.length,processed:g,failed:r.filter(f=>f.phase==="files").length,current:c.name,percentage:Math.round(g/p.length*100),isComplete:!1,errors:r},await this.delay(d)}}const u=new Date;return yield{phase:"complete",total:0,processed:0,failed:r.length,percentage:100,isComplete:!0,errors:r},{status:(r.length>0,"completed"),stats:s,mapping:this.mapping,errors:r,startedAt:a,completedAt:u,duration:u.getTime()-a.getTime()}}finally{this.abortController=null}}cancel(){var e;(e=this.abortController)==null||e.abort()}mapUser(e){var t,r,s,a,o;return{slackId:e.id,email:e.email,displayName:((t=e.profile)==null?void 0:t.display_name)||e.name,realName:e.real_name,avatarUrl:((r=e.profile)==null?void 0:r.image_192)||((s=e.profile)==null?void 0:s.image_72),title:(a=e.profile)==null?void 0:a.title,phone:(o=e.profile)==null?void 0:o.phone,timezone:e.tz,isAdmin:e.is_admin??!1,isBot:e.is_bot??!1,isDeactivated:e.deleted??!1}}mapChannel(e,t){var s,a;let r="public";return e.is_private&&(r="private"),e.is_im&&(r="dm"),e.is_mpim&&(r="mpim"),{slackId:e.id,name:e.name,type:r,description:(s=e.purpose)==null?void 0:s.value,topic:(a=e.topic)==null?void 0:a.value,isArchived:e.is_archived??!1,creatorId:e.creator?t.get(e.creator):void 0,memberIds:(e.members??[]).map(o=>t.get(o)).filter(o=>!!o),createdAt:e.created?new Date(e.created*1e3):void 0}}mapMessage(e,t,r,s){const a=r.channels.get(t)??t,o=e.user?r.users.get(e.user):void 0,{text:d,html:u}=this.convertSlackMessage(e.text,r.users),p=e.thread_ts!==void 0&&e.thread_ts!==e.ts,g=e.thread_ts?s.get(e.thread_ts):void 0,c=[];if(e.files)for(const m of e.files)c.push({type:m.mimetype.startsWith("image/")?"image":"file",url:r.files.get(m.id)??m.url_private,name:m.name,size:m.size});if(e.attachments)for(const m of e.attachments)m.image_url?c.push({type:"image",url:m.image_url}):m.title_link&&c.push({type:"link",url:m.title_link,name:m.title});const f=(e.reactions??[]).map(m=>({emoji:m.name,userIds:m.users.map(w=>r.users.get(w)).filter(w=>!!w),count:m.count}));return{channelId:a,senderId:o,content:d,htmlContent:u,threadId:g,isThreadReply:p,attachments:c,reactions:f,createdAt:e.ts?new Date(parseFloat(e.ts)*1e3):void 0,editedAt:e.edited?new Date(parseFloat(e.edited.ts)*1e3):void 0}}convertSlackMessage(e,t){let r=e,s=this.escapeHtml(e);const a=/<@([A-Z0-9]+)(?:\|([^>]+))?>/g;return r=r.replace(a,(o,d,u)=>u?`@${u}`:"@user"),s=s.replace(/<@([A-Z0-9]+)(?:\|([^&]+))?>/g,(o,d,u)=>`<span class="mention" data-user-id="${t.get(d)??d}">@${u??"user"}</span>`),r=r.replace(/<#([A-Z0-9]+)\|([^>]+)>/g,"#$2"),s=s.replace(/<#([A-Z0-9]+)\|([^&]+)>/g,'<span class="channel-mention">#$2</span>'),r=r.replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)"),r=r.replace(/<(https?:\/\/[^>]+)>/g,"$1"),s=s.replace(/<(https?:\/\/[^|&]+)\|([^&]+)>/g,'<a href="$1">$2</a>'),s=s.replace(/<(https?:\/\/[^&]+)>/g,'<a href="$1">$1</a>'),r=this.convertEmoji(r),s=this.convertEmoji(s),s=s.replace(/\*([^*]+)\*/g,"<strong>$1</strong>"),s=s.replace(/\b_([^_]+)_\b/g,"<em>$1</em>"),s=s.replace(/~([^~]+)~/g,"<del>$1</del>"),s=s.replace(/`([^`]+)`/g,"<code>$1</code>"),s=s.replace(/```([^`]+)```/g,"<pre>$1</pre>"),s=s.replace(/\n/g,"<br>"),{text:r,html:s}}convertEmoji(e){const t={":smile:":"๐",":laughing:":"๐",":blush:":"๐",":heart_eyes:":"๐",":heart:":"โค๏ธ",":thumbsup:":"๐",":thumbsdown:":"๐",":wave:":"๐",":clap:":"๐",":fire:":"๐ฅ",":rocket:":"๐",":star:":"โญ",":sparkles:":"โจ",":tada:":"๐",":100:":"๐ฏ",":thinking_face:":"๐ค",":eyes:":"๐",":pray:":"๐",":muscle:":"๐ช",":ok_hand:":"๐",":white_check_mark:":"โ
",":x:":"โ",":warning:":"โ ๏ธ",":question:":"โ",":exclamation:":"โ",":point_right:":"๐",":point_left:":"๐",":point_up:":"๐",":point_down:":"๐"};return e.replace(/:([a-z0-9_+-]+):/g,(r,s)=>t[r]??r)}filterMessages(e,t){return e.filter(r=>r.subtype==="bot_message"?!0:!(t.messagesAfter&&new Date(parseFloat(r.ts)*1e3)<t.messagesAfter||t.messagesBefore&&new Date(parseFloat(r.ts)*1e3)>t.messagesBefore||!t.importThreads&&r.thread_ts&&r.thread_ts!==r.ts))}async extractZipContents(e){return console.warn("ZIP extraction requires JSZip library. Use parseSlackExportFromJson() for JSON input."),new Map}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}delay(e){return new Promise(t=>setTimeout(t,e))}}let Ee=null;function Ze(i){if(!Ee&&i&&(Ee=new Lt(i)),!Ee)throw new Error("SlackImportService not initialized. Call with config first.");return Ee}function gi(){Ee=null}function mi(i={}){const{config:e}=i,t=l.useMemo(()=>{if(e)return Ze(e);try{return Ze()}catch{return null}},[e]),[r,s]=l.useState(null),[a,o]=l.useState(!1),[d,u]=l.useState(null),p=l.useCallback(m=>{if(!t)throw new Error("Service not initialized");return t.parseSlackExportFromJson(m)},[t]),g=l.useCallback((m,w)=>{if(!t)throw new Error("Service not initialized");return t.previewImport(m,w)},[t]),c=l.useCallback(async function*(m,w){var k,T;if(!t)throw new Error("Service not initialized");o(!0),u(null);try{for await(const U of t.import(m,w))s(U),yield U;const h=t.import(m,w);let C;for await(const U of h)C=U;const A=(T=(k=h.next)==null?void 0:k.call(h))==null?void 0:T.value;return A&&u(A),A}finally{o(!1)}},[t]),f=l.useCallback(()=>{t==null||t.cancel(),o(!1)},[t]);return{parseJson:p,preview:g,import:c,cancel:f,progress:r,isImporting:a,result:d}}const Ft={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."},Qe={US:"+1",CA:"+1",UK:"+44",DE:"+49",FR:"+33",PL:"+48",ES:"+34",IT:"+39",AU:"+61",JP:"+81",IN:"+91",BR:"+55",MX:"+52"};class ot{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=Ft,this.ivrText={..._t,...e.ivrText}}on(e,t){this.eventHandlers[e]=t}off(e){delete this.eventHandlers[e]}emit(e,...t){const r=this.eventHandlers[e];r&&r(...t)}generateDialInInfo(e,t){const r=this.getAvailableNumbers(),s=this.generateAccessPin(),a=this.generateAccessPin(8),o={meetingId:e,dialInNumbers:r,accessPin:s,hostPin:a,meetingTitle:t,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 t=Qe[e],r=Math.floor(1e9+Math.random()*9e9).toString();return`${t}${r}`}formatPhoneNumber(e){const t=Qe[e],r=this.generatePhoneNumber(e).slice(t.length);return e==="US"||e==="CA"?`${t} (${r.slice(0,3)}) ${r.slice(3,6)}-${r.slice(6)}`:`${t} ${r}`}generateAccessPin(e=6){return Math.floor(Math.random()*Math.pow(10,e)).toString().padStart(e,"0")}async handleIncomingCall(e,t,r){const s={callId:e,callerNumber:t,callerName:r,state:"connecting",joinedAt:Date.now(),audioStats:{volume:0,isMuted:!1,packetLoss:0,quality:5},isHost:!1,isModerator:!1};return this.participants.set(e,s),this.updateParticipantState(e,"waiting-pin"),await this.playIvr(e,"welcome"),await this.playIvr(e,"enterPin"),s}async validatePinAndJoin(e,t,r){const s=this.participants.get(e);if(!s)return{success:!1,isHost:!1};const a=this.meetingDialIns.get(t);if(!a)return await this.playIvr(e,"invalidPin"),{success:!1,isHost:!1};const o=r===a.hostPin;return r===a.accessPin||o?(s.isHost=o,s.isModerator=o,this.updateParticipantState(e,"joined"),await this.playIvr(e,"joined"),this.emit("onParticipantJoined",{...s}),{success:!0,isHost:o}):(await this.playIvr(e,"invalidPin"),{success:!1,isHost:!1})}getParticipant(e){return this.participants.get(e)}getParticipants(){return Array.from(this.participants.values())}updateParticipantState(e,t){const r=this.participants.get(e);if(!r)return;const s=r.state;r.state=t,this.emit("onParticipantStateChanged",{...r},s)}async muteParticipant(e){const t=this.participants.get(e);t&&(t.audioStats.isMuted=!0,this.updateParticipantState(e,"muted"),await this.playIvr(e,"muted"))}async unmuteParticipant(e){const t=this.participants.get(e);t&&(t.audioStats.isMuted=!1,this.updateParticipantState(e,"joined"),await this.playIvr(e,"unmuted"))}async toggleMute(e){const t=this.participants.get(e);return t?t.audioStats.isMuted?(await this.unmuteParticipant(e),!1):(await this.muteParticipant(e),!0):!1}async putOnHold(e){this.participants.get(e)&&(this.updateParticipantState(e,"on-hold"),await this.playIvr(e,"onHold"))}async removeFromHold(e){this.participants.get(e)&&(this.updateParticipantState(e,"joined"),await this.playIvr(e,"joined"))}async muteAll(e=!0){for(const t of this.participants.values())e&&(t.isHost||t.isModerator)||await this.muteParticipant(t.callId)}async unmuteAll(){for(const e of this.participants.values())await this.unmuteParticipant(e.callId)}async handleDtmf(e,t){const r=this.participants.get(e);r&&(this.emit("onDtmfReceived",{...r},t),t===this.dtmfCommands.toggleMute?await this.toggleMute(e):t===this.dtmfCommands.raiseHand||(t===this.dtmfCommands.leave?await this.disconnectParticipant(e):t===this.dtmfCommands.help?await this.playHelp(e):(r.isHost||r.isModerator)&&(t===this.dtmfCommands.hostMuteAll?await this.muteAll():t===this.dtmfCommands.hostUnmuteAll?await this.unmuteAll():t===this.dtmfCommands.hostEndMeeting&&await this.endMeeting())))}setDtmfCommands(e){this.dtmfCommands={...this.dtmfCommands,...e}}async playIvr(e,t){const r=this.ivrText[t];await new Promise(s=>setTimeout(s,r.length*50))}async playCustomMessage(e,t){await new Promise(r=>setTimeout(r,t.length*50))}async playHelp(e){await this.playCustomMessage(e,`
|
|
6
|
+
`})]})}function Se({icon:i,label:e,onClick:t,active:r,style:s}){return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[n.jsx("button",{onClick:t,title:e,style:{width:44,height:44,borderRadius:"50%",border:"none",background:r?"var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))":"var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",color:"var(--nice-color-white, #fff)",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.2s",...s},children:n.jsx(y.NiceIcon,{name:i,size:18})}),n.jsx("span",{style:{fontSize:9,color:"var(--nice-overlay-light-50, rgba(255, 255, 255, 0.5))",textAlign:"center",maxWidth:50},children:e})]})}const Xt=[],Zt=[],Qt=["๐","โค๏ธ","๐","๐ฎ","๐ข","๐"];function Be({message:i,author:e,isMine:t,showAvatar:r,enableReactions:s,onReact:a,onReply:o,onEdit:d,onDelete:u,onPin:p,onOpenThread:g}){var C,A,U,M;const{t:c}=y.useNiceTranslation(),[f,m]=l.useState(!1),[w,k]=l.useState(!1),T=i.isDeleted,h=i.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.jsxs("div",{className:`nice-chat-message${t?" nice-chat-message--mine":""}${i.isPinned?" nice-chat-message--pinned":""}`,onMouseEnter:()=>m(!0),onMouseLeave:()=>{m(!1),k(!1)},children:[r&&!t&&n.jsxs("div",{style:{position:"relative",flexShrink:0},children:[n.jsx("div",{className:"nice-chat-avatar",style:{width:32,height:32,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontSize:13,fontWeight:600,flexShrink:0},children:!(e!=null&&e.avatarUrl)&&(((A=(C=e==null?void 0:e.name)==null?void 0:C[0])==null?void 0:A.toUpperCase())??"?")}),n.jsx(he,{status:((U=e==null?void 0:e.presence)==null?void 0:U.status)??"unknown",size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),n.jsxs("div",{style:{maxWidth:"70%",display:"flex",flexDirection:"column",alignItems:t?"flex-end":"flex-start"},children:[!t&&e&&n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginBottom:2,paddingLeft:2},children:e.displayName??e.name}),i.replyTo&&n.jsx("div",{className:"nice-chat-reply-preview",style:{borderLeft:"3px solid var(--nice-info, #6366f1)",paddingLeft:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)",marginBottom:4,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.replyTo.content}),n.jsx("div",{className:`nice-chat-bubble${t?" nice-chat-bubble--mine":""}`,style:{padding:"8px 12px",borderRadius:t?"18px 18px 4px 18px":"18px 18px 18px 4px",background:t?"var(--nice-info, #6366f1)":"var(--nice-bg-secondary, #f3f4f6)",color:t?"var(--nice-color-white, #fff)":"var(--nice-text, #111827)",fontSize:14,lineHeight:1.5,wordBreak:"break-word"},children:T?n.jsx("span",{style:{fontStyle:"italic",opacity:.6},children:c("chatWindow.thisMessageWasDeleted","This message was deleted")}):i.contentType==="image"&&((M=i.attachments)!=null&&M[0])?n.jsx("img",{src:i.attachments[0].url,alt:i.attachments[0].name,style:{maxWidth:280,maxHeight:280,borderRadius:8,display:"block"}}):n.jsx("span",{children:i.content})}),!T&&i.attachments&&i.attachments.length>0&&i.contentType!=="image"&&n.jsx("div",{className:"nice-chat-attachments",style:{marginTop:4},children:i.attachments.map(P=>n.jsxs("a",{href:P.url,target:"_blank",rel:"noreferrer",className:"nice-chat-attachment",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:12,color:t?"var(--nice-overlay-light-85, rgba(255, 255, 255, 0.85))":"var(--nice-info, #6366f1)",textDecoration:"none",background:t?"var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))":"var(--nice-primary-bg, #e0e7ff)",borderRadius:6,padding:"3px 8px",marginTop:2},children:[n.jsx(y.NiceIcon,{name:"paperclip",size:14})," ",P.name]},P.id))}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:2},children:[n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:h}),i.editedAt&&n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:c("chatWindow.edited","(edited)")}),t&&n.jsx("span",{style:{display:"inline-flex",alignItems:"center",color:i.status==="read"?"var(--nice-info, #6366f1)":"var(--nice-text-muted, #9ca3af)"},children:i.status==="sending"?n.jsx(y.NiceIcon,{name:"circle",size:12}):i.status==="sent"?n.jsx(y.NiceIcon,{name:"check",size:12}):n.jsxs("span",{style:{display:"inline-flex",marginRight:-6},children:[n.jsx(y.NiceIcon,{name:"check",size:12}),n.jsx(y.NiceIcon,{name:"check",size:12})]})})]}),i.reactions&&i.reactions.length>0&&n.jsx("div",{className:"nice-chat-reactions",style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:i.reactions.map(P=>n.jsxs("button",{onClick:()=>a(i.id,P.emoji),style:{background:P.mine?"var(--nice-primary-bg, #e0e7ff)":"var(--nice-bg-secondary, #f3f4f6)",border:P.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:[P.emoji," ",P.count]},P.emoji))}),(i.threadCount??0)>0&&n.jsxs("button",{className:"nice-chat-thread-btn",onClick:()=>g==null?void 0:g(i),style:{background:"none",border:"none",color:"var(--nice-info, #6366f1)",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:2,display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(y.NiceIcon,{name:"message",size:14})," ",i.threadCount===1?c("chatWindow.repliesOne","{threadCount} reply").replace("{threadCount}",String(i.threadCount??"")):c("chatWindow.repliesMany","{threadCount} replies").replace("{threadCount}",String(i.threadCount??""))]})]}),f&&!T&&n.jsxs("div",{className:"nice-chat-actions",style:{position:"absolute",top:-16,[t?"left":"right"]:16,display:"flex",gap:2,background:"var(--nice-bg, #fff)",borderRadius:8,boxShadow:"0 2px 8px var(--nice-overlay-12, rgba(0, 0, 0, 0.12))",padding:"3px 6px",zIndex:10},children:[s&&n.jsxs("div",{style:{position:"relative"},children:[n.jsx("button",{title:c("chatWindow.react","React"),"aria-label":c("chatWindow.react","React"),onClick:()=>k(P=>!P),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:n.jsx(y.NiceIcon,{name:"heart",size:16})}),w&&n.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:Qt.map(P=>n.jsx("button",{onClick:()=>{a(i.id,P),k(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:P},P))})]}),n.jsx("button",{title:c("chatWindow.reply","Reply"),"aria-label":c("chatWindow.reply","Reply"),onClick:()=>o(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:n.jsx(y.NiceIcon,{name:"reply",size:16})}),t&&d&&n.jsx("button",{title:c("chatWindow.edit","Edit"),"aria-label":c("chatWindow.edit","Edit"),onClick:()=>d(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:n.jsx(y.NiceIcon,{name:"edit",size:16})}),p&&n.jsx("button",{title:i.isPinned?c("chatWindow.unpin","Unpin"):c("chatWindow.pin","Pin"),"aria-label":i.isPinned?c("chatWindow.unpin","Unpin"):c("chatWindow.pin","Pin"),onClick:()=>p(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:n.jsx(y.NiceIcon,{name:"map-pin",size:16})}),t&&u&&n.jsx("button",{title:c("chatWindow.delete","Delete"),"aria-label":c("chatWindow.delete","Delete"),onClick:()=>u(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px",color:"var(--nice-danger, #ef4444)"},children:n.jsx(y.NiceIcon,{name:"trash",size:16})})]})]})}function dt({placeholder:i,maxLength:e,replyTo:t,onCancelReply:r,onSend:s,onAttach:a,disabled:o}){const{t:d}=y.useNiceTranslation(),u=i??d("chatWindow.typeAMessage","Type a messageโฆ"),[p,g]=l.useState(""),c=l.useRef(null);l.useEffect(()=>{t&&c.current&&c.current.focus()},[t]);const f=k=>{k.key==="Enter"&&!k.shiftKey&&(k.preventDefault(),m())},m=()=>{const k=p.trim();k&&(s(k),g(""),c.current&&(c.current.style.height="auto"))},w=k=>{g(k.target.value),k.target.style.height="auto",k.target.style.height=`${Math.min(k.target.scrollHeight,120)}px`};return n.jsxs("div",{className:"nice-chat-input-area",style:{padding:"8px 12px",borderTop:"1px solid var(--nice-border, #e5e7eb)",background:"var(--nice-bg, #fff)"},children:[t&&n.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:[n.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d("chatWindow.replying","Replying: {content}").replace("{content}",String(t.content))}),n.jsx("button",{onClick:r,title:d("chatWindow.cancelReply","Cancel reply"),"aria-label":d("chatWindow.cancelReply","Cancel reply"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",marginLeft:8,display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"close",size:16})})]}),n.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:8},children:[a&&n.jsx("button",{onClick:a,title:d("chatWindow.attachFile","Attach file"),"aria-label":d("chatWindow.attachFile","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:n.jsx(y.NiceIcon,{name:"paperclip",size:18})}),n.jsx("textarea",{ref:c,value:p,onChange:w,onKeyDown:f,placeholder:u,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,fontFamily:"inherit",lineHeight:1.5,overflow:"hidden"}}),n.jsx("button",{onClick:m,disabled:!p.trim()||o,title:d("chatWindow.send","Send"),"aria-label":d("chatWindow.send","Send"),style:{background:p.trim()?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)",border:"none",borderRadius:"50%",width:36,height:36,cursor:p.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--nice-color-white, #fff)",transition:"background 0.15s"},children:n.jsx(y.NiceIcon,{name:"send",size:16})})]}),e&&p.length>e*.8&&n.jsxs("div",{style:{textAlign:"right",fontSize:11,color:p.length>=e?"var(--nice-danger, #ef4444)":"var(--nice-text-muted, #9ca3af)",marginTop:2},children:[p.length,"/",e]})]})}function Re({conversation:i,messages:e=Xt,users:t=Zt,currentUser:r,isLoading:s=!1,hasMore:a=!1,showHeader:o=!0,showUserAvatars:d=!0,enableReactions:u=!0,enableThreads:p=!0,enableAttachments:g=!0,placeholder:c,maxMessageLength:f,onSendMessage:m,onEditMessage:w,onDeleteMessage:k,onReactToMessage:T,onPinMessage:h,onLoadMoreMessages:C,onStartCall:A,className:U,style:M,id:P,"data-testid":G}){var H,S;const{t:F}=y.useNiceTranslation(),L=l.useRef(null),N=l.useRef(null),[z,E]=l.useState(null),[V,J]=l.useState(null),j=l.useMemo(()=>{const b=new Map;return t.forEach(Y=>b.set(Y.id,Y)),b},[t]);l.useEffect(()=>{var b;(b=L.current)==null||b.scrollIntoView({behavior:"smooth"})},[e]);const O=l.useCallback(()=>{const b=N.current;!b||!a||s||b.scrollTop===0&&e.length>0&&(C==null||C(i.id,e[0].id))},[a,s,e,i.id,C]),Z=l.useCallback(b=>{m==null||m(i.id,b,"text"),E(null)},[i.id,m]),D=i.type==="dm"?j.get(i.participantIds.find(b=>b!==r.id)??""):void 0;return n.jsxs("div",{id:P,"data-testid":G,className:`nice-chat-window${U?` ${U}`:""}`,style:{display:"flex",flexDirection:"column",height:"100%",background:"var(--nice-bg, #fff)",...M},children:[o&&n.jsxs("div",{className:"nice-chat-header",style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:(D??i).avatarUrl?`url(${(D??i).avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:15,flexShrink:0},children:!(D??i).avatarUrl&&((H=((D==null?void 0:D.name)??i.name??"?")[0])==null?void 0:H.toUpperCase())}),n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600,fontSize:15},children:(D==null?void 0:D.displayName)??(D==null?void 0:D.name)??i.name??F("chatWindow.chat","Chat")}),D&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:1},children:[n.jsx(he,{status:D.presence.status,size:"xs"}),n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:D.presence.statusMessage??D.presence.status})]}),i.type!=="dm"&&n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:F("chatWindow.members","{participantIds} members").replace("{participantIds}",String(i.participantIds.length))})]})]}),i.type==="dm"&&A&&D&&n.jsxs("div",{style:{display:"flex",gap:4},children:[n.jsx("button",{onClick:()=>A([D.id],"audio"),title:F("chatWindow.audioCall","Audio call"),"aria-label":F("chatWindow.audioCall","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:n.jsx(y.NiceIcon,{name:"phone",size:16})}),n.jsx("button",{onClick:()=>A([D.id],"video"),title:F("chatWindow.videoCall","Video call"),"aria-label":F("chatWindow.videoCall","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:n.jsx(y.NiceIcon,{name:"video",size:16})})]})]}),n.jsxs("div",{ref:N,className:"nice-chat-messages",onScroll:O,style:{flex:1,overflowY:"auto",padding:"8px 0",display:"flex",flexDirection:"column"},children:[a&&n.jsx("button",{onClick:()=>e.length>0&&(C==null?void 0:C(i.id,e[0].id)),disabled:s,style:{display:"block",margin:"8px auto",background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,padding:"4px 16px",fontSize:12,color:"var(--nice-text-secondary, #6b7280)",cursor:"pointer"},children:s?F("chatWindow.loading","Loadingโฆ"):F("chatWindow.loadOlderMessages","Load older messages")}),e.map((b,Y)=>{const X=e[Y-1],Q=d&&(!X||X.authorId!==b.authorId);return n.jsx(Be,{message:b,author:j.get(b.authorId),isMine:b.authorId===r.id,showAvatar:Q,enableReactions:u,onReact:(K,ie)=>T==null?void 0:T(K,ie),onReply:K=>E(K),onEdit:w?K=>w(K.id,K.content):void 0,onDelete:k?K=>k(K.id):void 0,onPin:h?K=>h(K.id):void 0,onOpenThread:p?K=>J(K):void 0},b.id)}),n.jsx("div",{ref:L})]}),V&&n.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:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid var(--nice-border, #e5e7eb)"},children:[n.jsx("span",{style:{fontWeight:600,fontSize:14},children:F("chatWindow.thread","Thread")}),n.jsx("button",{onClick:()=>J(null),title:F("chatWindow.closeThread","Close thread"),"aria-label":F("chatWindow.closeThread","Close thread"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"close",size:18})})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[n.jsx(Be,{message:V,author:j.get(V.authorId),isMine:V.authorId===r.id,showAvatar:!0,enableReactions:u,onReact:(b,Y)=>T==null?void 0:T(b,Y),onReply:()=>{}}),(S=V.thread)==null?void 0:S.map(b=>n.jsx(Be,{message:b,author:j.get(b.authorId),isMine:b.authorId===r.id,showAvatar:!0,enableReactions:u,onReact:(Y,X)=>T==null?void 0:T(Y,X),onReply:()=>{}},b.id))]}),n.jsx(dt,{placeholder:F("chatWindow.replyInThread","Reply in threadโฆ"),onSend:b=>m==null?void 0:m(i.id,b,"text")})]}),n.jsx(dt,{placeholder:c,maxLength:f,replyTo:z,onCancelReply:()=>E(null),onSend:Z,onAttach:g?()=>{}:void 0})]})}const en=[],tn=[];function nn({conversation:i,partner:e,isActive:t,lastMessage:r,onClick:s}){var c;const{t:a}=y.useNiceTranslation(),o=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??i.name??"Group",d=((c=o[0])==null?void 0:c.toUpperCase())??"?",u=(e==null?void 0:e.avatarUrl)??i.avatarUrl,p=r?r.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"",g=r?r.isDeleted?"Message deleted":r.content.slice(0,50):"";return n.jsxs("button",{className:`nice-messenger-conv-item${t?" nice-messenger-conv-item--active":""}`,onClick:s,style:{display:"flex",alignItems:"center",gap:10,padding:"10px 14px",background:t?"var(--nice-accent-tint-10, #ede9fe)":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",position:"relative"},children:[n.jsxs("div",{style:{position:"relative",flexShrink:0},children:[n.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:u?`url(${u}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-color-white, #fff)",fontWeight:700,fontSize:16},children:!u&&d}),e&&n.jsx(he,{status:e.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}}),i.type!=="dm"&&n.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:n.jsx(y.NiceIcon,{name:"hash",size:10})})]}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline"},children:[n.jsx("span",{style:{fontWeight:i.unreadCount>0?700:500,fontSize:14,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o}),n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",flexShrink:0,marginLeft:4},children:p})]}),n.jsx("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:g})]}),(i.unreadCount>0||i.mentionCount>0)&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,alignItems:"flex-end",flexShrink:0},children:[i.mentionCount>0&&n.jsxs("span",{style:{background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:["@",i.mentionCount]}),i.unreadCount>0&&n.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:10,padding:"1px 5px",fontWeight:700},children:i.unreadCount>99?"99+":i.unreadCount})]}),i.isMuted&&n.jsx("span",{style:{position:"absolute",bottom:8,right:8,color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex"},children:n.jsx(y.NiceIcon,{name:"mic",size:12,title:a("messenger.muted","Muted")})})]})}function Ct({conversations:i=en,messages:e,users:t=tn,currentUser:r,activeConversationId:s,teams:a,enableGroupConversations:o=!0,showPresence:d=!0,enableSearch:u=!0,onSendMessage:p,onEditMessage:g,onDeleteMessage:c,onReactToMessage:f,onPinMessage:m,onLoadMoreMessages:w,onMarkAsRead:k,onStartCall:T,onCreateConversation:h,className:C,style:A,id:U,"data-testid":M}){var S;const{t:P}=y.useNiceTranslation(),[G,F]=l.useState(s??null),[L,N]=l.useState(""),[z,E]=l.useState("all");l.useMemo(()=>{const b=new Map;return t.forEach(Y=>b.set(Y.id,Y)),b},[t]);const V=l.useMemo(()=>{let b=i;if(z==="unread"&&(b=b.filter(Y=>Y.unreadCount>0)),z==="groups"&&(b=b.filter(Y=>Y.type!=="dm")),L.trim()){const Y=L.toLowerCase();b=b.filter(X=>{var K,ie;const Q=Ge(X,r.id,t);return(Q==null?void 0:Q.name.toLowerCase().includes(Y))||((K=X.name)==null?void 0:K.toLowerCase().includes(Y))||((ie=X.lastMessage)==null?void 0:ie.content.toLowerCase().includes(Y))})}return[...b].sort((Y,X)=>{var ie,de;if(Y.isPinned!==X.isPinned)return Y.isPinned?-1:1;const Q=((ie=Y.lastMessage)==null?void 0:ie.timestamp.getTime())??Y.updatedAt.getTime();return(((de=X.lastMessage)==null?void 0:de.timestamp.getTime())??X.updatedAt.getTime())-Q})},[i,z,L,r.id,t]),J=l.useMemo(()=>i.find(b=>b.id===G)??null,[i,G]),j=l.useMemo(()=>G?e[G]??[]:[],[e,G]),O=l.useCallback(b=>{F(b),k==null||k(b)},[k]),Z=l.useMemo(()=>et(i),[i]),D=a??[],H=t.filter(b=>b.id!==r.id&&b.presence.status==="online").slice(0,6);return n.jsxs("div",{id:U,"data-testid":M,className:`nice-messenger${C?` ${C}`:""}`,style:{display:"flex",height:"100%",background:"var(--nice-bg, #fff)",overflow:"hidden",...A},children:[n.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:[n.jsxs("div",{style:{padding:"14px 14px 8px",borderBottom:"1px solid var(--nice-border, #e5e7eb)"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("span",{style:{fontWeight:700,fontSize:16},children:[P("messenger.messages","Messages")," ",Z>0&&n.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:10,padding:"1px 6px",fontWeight:700,marginLeft:4},children:Z})]}),o&&h&&n.jsx("button",{onClick:()=>h([],"group"),title:P("messenger.newConversation","New conversation"),"aria-label":P("messenger.newConversation","New conversation"),style:{background:"var(--nice-info, #6366f1)",border:"none",borderRadius:6,padding:"5px 8px",cursor:"pointer",color:"var(--nice-text-on-primary, #fff)",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"plus",size:13})})]}),u&&n.jsx("input",{type:"search",value:L,onChange:b=>N(b.target.value),placeholder:P("messenger.searchConversations","Search conversationsโฆ"),style:{width:"100%",marginTop:8,padding:"6px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,fontSize:13,boxSizing:"border-box",background:"var(--nice-bg, #fff)"}}),n.jsx("div",{style:{display:"flex",gap:2,marginTop:8},children:["all","unread","groups"].map(b=>n.jsx("button",{onClick:()=>E(b),style:{flex:1,padding:"4px 0",border:"none",borderRadius:6,background:z===b?"var(--nice-info, #6366f1)":"transparent",color:z===b?"var(--nice-color-white, #fff)":"var(--nice-text-secondary, #6b7280)",cursor:"pointer",fontSize:12,textTransform:"capitalize",fontWeight:z===b?600:400},children:b},b))})]}),d&&H.length>0&&n.jsxs("div",{style:{padding:"8px 14px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",overflowX:"auto"},children:[n.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",marginBottom:6},children:P("messenger.onlineNow","ONLINE NOW")}),n.jsx("div",{style:{display:"flex",gap:10},children:H.map(b=>{var Y;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:3},children:[n.jsxs("div",{style:{position:"relative"},children:[n.jsx("div",{style:{width:34,height:34,borderRadius:"50%",background:b.avatarUrl?`url(${b.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:13,cursor:"pointer"},title:b.name,children:!b.avatarUrl&&((Y=b.name[0])==null?void 0:Y.toUpperCase())}),n.jsx(he,{status:b.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),n.jsx("span",{style:{fontSize:10,color:"var(--nice-text-secondary, #6b7280)",maxWidth:36,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.displayName??b.name.split(" ")[0]})]},b.id)})})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[D.length>0&&z==="all"&&n.jsx("div",{style:{padding:"8px 14px 4px",fontSize:11,color:"var(--nice-text-muted, #9ca3af)",fontWeight:600,letterSpacing:"0.05em"},children:P("messenger.directMessages","DIRECT MESSAGES")}),V.length===0?n.jsx("div",{style:{padding:24,textAlign:"center",color:"var(--nice-text-muted, #9ca3af)",fontSize:13},children:P("messenger.noConversations","No conversations")}):V.map(b=>n.jsx(nn,{conversation:b,partner:Ge(b,r.id,t),isActive:b.id===G,lastMessage:b.lastMessage,onClick:()=>O(b.id)},b.id))]}),n.jsxs("div",{style:{padding:"10px 14px",borderTop:"1px solid var(--nice-border, #e5e7eb)",display:"flex",alignItems:"center",gap:8},children:[n.jsxs("div",{style:{position:"relative"},children:[n.jsx("div",{style:{width:32,height:32,borderRadius:"50%",background:r.avatarUrl?`url(${r.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:13},children:!r.avatarUrl&&((S=r.name[0])==null?void 0:S.toUpperCase())}),n.jsx(he,{status:r.presence.status,size:"xs",style:{position:"absolute",bottom:0,right:0}})]}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontWeight:600,fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.displayName??r.name}),n.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.presence.statusMessage??r.presence.status})]})]})]}),n.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:J?n.jsx(Re,{conversation:J,messages:j,users:t,currentUser:r,onSendMessage:p,onEditMessage:g,onDeleteMessage:c,onReactToMessage:f,onPinMessage:m,onLoadMoreMessages:w,onStartCall:T,style:{height:"100%"}}):n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"var(--nice-text-muted, #9ca3af)",gap:12},children:[n.jsx(y.NiceIcon,{name:"message",size:48}),n.jsx("span",{style:{fontSize:15},children:P("messenger.selectAConversationToStart","Select a conversation to start messaging")})]})})]})}const rn=[],sn=[],an=["๐","โค๏ธ","๐","๐","๐ฎ","๐ข"];function Ue({message:i,author:e,isMine:t,enableReactions:r,enableThreads:s,onReact:a,onOpenThread:o,onReply:d}){var k,T,h;const{t:u}=y.useNiceTranslation(),[p,g]=l.useState(!1),[c,f]=l.useState(!1),m=i.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),w=i.timestamp.toLocaleDateString([],{month:"short",day:"numeric"});return n.jsxs("div",{className:`nice-channel-msg${p?" nice-channel-msg--hovered":""}${t?" nice-channel-msg--mine":""}`,onMouseEnter:()=>g(!0),onMouseLeave:()=>{g(!1),f(!1)},children:[n.jsx("div",{style:{width:36,flexShrink:0},children:n.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:14},children:!(e!=null&&e.avatarUrl)&&(((T=(k=e==null?void 0:e.name)==null?void 0:k[0])==null?void 0:T.toUpperCase())??"?")})}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:2},children:[n.jsx("span",{style:{fontWeight:600,fontSize:14,color:"var(--nice-text, #111827)"},children:(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??u("channelView.unknown","Unknown")}),e&&n.jsx(he,{status:e.presence.status,size:"xs"}),n.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:[w," ",m]}),i.editedAt&&n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)"},children:u("channelView.edited","(edited)")}),i.isPinned&&n.jsxs("span",{style:{fontSize:11,color:"var(--nice-info, #6366f1)",display:"inline-flex",alignItems:"center",gap:3},children:[n.jsx(y.NiceIcon,{name:"map-pin",size:12})," ",u("channelView.pinned","Pinned")]})]}),i.isDeleted?n.jsx("span",{style:{fontStyle:"italic",color:"var(--nice-text-muted, #9ca3af)",fontSize:14},children:u("channelView.thisMessageWasDeleted","This message was deleted")}):n.jsx("div",{style:{fontSize:14,lineHeight:1.6,color:"var(--nice-text, #1f2937)",wordBreak:"break-word"},children:i.contentType==="image"&&((h=i.attachments)!=null&&h[0])?n.jsx("img",{src:i.attachments[0].url,alt:i.attachments[0].name,style:{maxWidth:400,maxHeight:300,borderRadius:8,display:"block",marginTop:4}}):i.content}),!i.isDeleted&&i.attachments&&i.attachments.length>0&&i.contentType!=="image"&&n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:4},children:i.attachments.map(C=>n.jsxs("a",{href:C.url,target:"_blank",rel:"noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:12,color:"var(--nice-info, #6366f1)",background:"var(--nice-accent-tint-10, #ede9fe)",borderRadius:6,padding:"3px 8px",textDecoration:"none"},children:[n.jsx(y.NiceIcon,{name:"paperclip",size:14})," ",C.name]},C.id))}),i.reactions&&i.reactions.length>0&&n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:i.reactions.map(C=>n.jsxs("button",{onClick:()=>a(i.id,C.emoji),style:{background:C.mine?"var(--nice-accent-tint-10, #ede9fe)":"var(--nice-bg-secondary, #f3f4f6)",border:C.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:[C.emoji," ",C.count]},C.emoji))}),s&&(i.threadCount??0)>0&&n.jsxs("button",{onClick:()=>o(i),style:{background:"none",border:"none",color:"var(--nice-info, #6366f1)",fontSize:12,cursor:"pointer",padding:"2px 0",marginTop:3,display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(y.NiceIcon,{name:"message",size:14})," ",i.threadCount===1?u("channelView.repliesOne","{threadCount} reply").replace("{threadCount}",String(i.threadCount??"")):u("channelView.repliesMany","{threadCount} replies").replace("{threadCount}",String(i.threadCount??""))," ",n.jsx(y.NiceIcon,{name:"arrow-right",size:12})]})]}),p&&!i.isDeleted&&n.jsxs("div",{style:{position:"absolute",top:-16,right:16,display:"flex",gap:2,background:"var(--nice-bg, #fff)",borderRadius:8,boxShadow:"0 2px 8px var(--nice-overlay-12, rgba(0, 0, 0, 0.12))",padding:"3px 6px",zIndex:10},children:[r&&n.jsxs("div",{style:{position:"relative"},children:[n.jsx("button",{onClick:()=>f(C=>!C),title:u("channelView.react","React"),"aria-label":u("channelView.react","React"),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},children:n.jsx(y.NiceIcon,{name:"heart",size:16})}),c&&n.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:an.map(C=>n.jsx("button",{onClick:()=>{a(i.id,C),f(!1)},style:{background:"none",border:"none",cursor:"pointer",fontSize:18},children:C},C))})]}),n.jsx("button",{onClick:()=>d(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},title:u("channelView.reply","Reply"),"aria-label":u("channelView.reply","Reply"),children:n.jsx(y.NiceIcon,{name:"reply",size:16})}),s&&n.jsx("button",{onClick:()=>o(i),style:{background:"none",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",padding:"2px 4px"},title:u("channelView.openThread","Open thread"),"aria-label":u("channelView.openThread","Open thread"),children:n.jsx(y.NiceIcon,{name:"message",size:16})})]})]})}function It({channel:i,messages:e=rn,users:t=sn,currentUser:r,team:s,isLoading:a=!1,hasMore:o=!1,enableThreads:d=!0,enableReactions:u=!0,enableAttachments:p=!0,onSendMessage:g,onEditMessage:c,onDeleteMessage:f,onReactToMessage:m,onPinMessage:w,onLoadMoreMessages:k,onStartCall:T,className:h,style:C,id:A,"data-testid":U}){var H;const{t:M}=y.useNiceTranslation(),P=l.useRef(null),G=l.useRef(null),[F,L]=l.useState(""),[N,z]=l.useState(null),[E,V]=l.useState(null),J=l.useMemo(()=>{const S=new Map;return t.forEach(b=>S.set(b.id,b)),S},[t]);l.useEffect(()=>{var S;(S=P.current)==null||S.scrollIntoView({behavior:"smooth"})},[e]);const j=l.useCallback(()=>{const S=G.current;!S||!o||a||S.scrollTop===0&&e.length>0&&(k==null||k(i.id,e[0].id))},[o,a,e,i.id,k]),O=l.useCallback(()=>{const S=F.trim();S&&(g==null||g(i.id,S,"text"),L(""),z(null))},[F,i.id,g]),Z=S=>{S.key==="Enter"&&!S.shiftKey&&(S.preventDefault(),O())},D=t.filter(S=>S.presence.status==="online").length;return n.jsxs("div",{id:A,"data-testid":U,className:`nice-channel-view${h?` ${h}`:""}`,style:{display:"flex",height:"100%",background:"var(--nice-bg, #fff)",overflow:"hidden",...C},children:[n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsx(y.NiceIcon,{name:"hash",size:20,style:{color:"var(--nice-text-secondary, #6b7280)"}}),n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:700,fontSize:16},children:i.name}),(i.topic||i.description)&&n.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",marginTop:1},children:[i.topic&&n.jsx("span",{className:"nice-channel-view__topic",style:{fontWeight:600,color:"var(--nice-text-primary, #111827)"},children:i.topic}),i.topic&&i.description&&" ยท ",i.description]})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:[n.jsx("span",{style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:"var(--nice-success, #22c55e)",marginRight:4,verticalAlign:"middle"}}),M("channelView.online","{onlineCount} online").replace("{onlineCount}",String(D))]}),T&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>T(t.map(S=>S.id),"audio"),style:{background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"5px 8px",cursor:"pointer",display:"inline-flex",alignItems:"center"},title:M("channelView.audioCall","Audio call"),"aria-label":M("channelView.audioCall","Audio call"),children:n.jsx(y.NiceIcon,{name:"phone",size:15})}),n.jsx("button",{onClick:()=>T(t.map(S=>S.id),"video"),style:{background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"5px 8px",cursor:"pointer",display:"inline-flex",alignItems:"center"},title:M("channelView.videoMeet","Video meet"),"aria-label":M("channelView.videoMeet","Video meet"),children:n.jsx(y.NiceIcon,{name:"video",size:15})})]})]})]}),n.jsxs("div",{ref:G,onScroll:j,style:{flex:1,overflowY:"auto",padding:"8px 0"},children:[o&&n.jsx("button",{onClick:()=>e.length>0&&(k==null?void 0:k(i.id,e[0].id)),disabled:a,style:{display:"block",margin:"8px auto",background:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,padding:"4px 16px",fontSize:12,color:"var(--nice-text-secondary, #6b7280)",cursor:"pointer"},children:a?M("channelView.loading","Loadingโฆ"):M("channelView.loadOlderMessages","Load older messages")}),e.map(S=>n.jsx(Ue,{message:S,author:J.get(S.authorId),isMine:S.authorId===r.id,enableReactions:u,enableThreads:d,onReact:(b,Y)=>m==null?void 0:m(b,Y),onOpenThread:b=>V(b),onReply:b=>z(b)},S.id)),n.jsx("div",{ref:P})]}),n.jsxs("div",{style:{padding:"8px 16px",borderTop:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[N&&n.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:[n.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M("channelView.replyingTo","Replying to: {content}").replace("{content}",String(N.content))}),n.jsx("button",{onClick:()=>z(null),title:M("channelView.cancelReply","Cancel reply"),"aria-label":M("channelView.cancelReply","Cancel reply"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"close",size:16})})]}),n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-end"},children:[p&&n.jsx("button",{title:M("channelView.attach","Attach"),"aria-label":M("channelView.attach","Attach"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",padding:"6px 4px",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"paperclip",size:18})}),n.jsx("textarea",{value:F,onChange:S=>L(S.target.value),onKeyDown:Z,placeholder:M("channelView.message","Message #{name}").replace("{name}",String(i.name)),rows:1,style:{flex:1,resize:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:"8px 12px",fontSize:14,fontFamily:"inherit",lineHeight:1.5,overflow:"hidden",maxHeight:100}}),n.jsx("button",{onClick:O,disabled:!F.trim(),title:M("channelView.send","Send"),"aria-label":M("channelView.send","Send"),style:{background:F.trim()?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)",border:"none",borderRadius:"50%",width:36,height:36,cursor:F.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--nice-color-white, #fff)",transition:"background 0.15s"},children:n.jsx(y.NiceIcon,{name:"send",size:15})})]})]})]}),E&&n.jsxs("div",{style:{width:340,flexShrink:0,borderLeft:"1px solid var(--nice-border, #e5e7eb)",display:"flex",flexDirection:"column",overflow:"hidden"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",flexShrink:0},children:[n.jsx("span",{style:{fontWeight:600,fontSize:14},children:M("channelView.thread","Thread")}),n.jsx("button",{onClick:()=>V(null),title:M("channelView.closeThread","Close thread"),"aria-label":M("channelView.closeThread","Close thread"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"close",size:18})})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[n.jsx(Ue,{message:E,author:J.get(E.authorId),isMine:E.authorId===r.id,enableReactions:u,enableThreads:!1,onReact:(S,b)=>m==null?void 0:m(S,b),onOpenThread:()=>{},onReply:()=>{}}),n.jsx("div",{style:{padding:"6px 14px",color:"var(--nice-text-muted, #9ca3af)",fontSize:12,borderTop:"1px solid var(--nice-bg-secondary, #f3f4f6)"},children:E.threadCount===1?M("channelView.repliesOne","{threadCount} reply").replace("{threadCount}",String(E.threadCount??0)):M("channelView.repliesMany","{threadCount} replies").replace("{threadCount}",String(E.threadCount??0))}),(H=E.thread)==null?void 0:H.map(S=>n.jsx(Ue,{message:S,author:J.get(S.authorId),isMine:S.authorId===r.id,enableReactions:u,enableThreads:!1,onReact:(b,Y)=>m==null?void 0:m(b,Y),onOpenThread:()=>{},onReply:()=>{}},S.id))]}),n.jsx("div",{style:{padding:"8px 12px",borderTop:"1px solid var(--nice-border, #e5e7eb)"},children:n.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-end"},children:[n.jsx("textarea",{placeholder:M("channelView.replyInThread","Reply in threadโฆ"),rows:1,onKeyDown:S=>{if(S.key==="Enter"&&!S.shiftKey){S.preventDefault();const b=S.target.value.trim();b&&(g==null||g(i.id,b,"text"),S.target.value="")}},style:{flex:1,resize:"none",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:"7px 10px",fontSize:13,fontFamily:"inherit",overflow:"hidden"}}),n.jsx("button",{title:M("channelView.send","Send"),"aria-label":M("channelView.send","Send"),style:{background:"var(--nice-info, #6366f1)",border:"none",borderRadius:"50%",width:32,height:32,cursor:"pointer",color:"var(--nice-text-on-primary, #fff)",display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsx(y.NiceIcon,{name:"send",size:14})})]})})]})]})}function He({participant:i,isLocal:e,isPinned:t,onPin:r,size:s="medium",fill:a=!1}){var h;const{t:o}=y.useNiceTranslation(),d=l.useRef(null),{user:u,isMuted:p,isCameraOff:g,isScreenSharing:c,isSpeaking:f,isHandRaised:m,stream:w,screenStream:k}=i;l.useEffect(()=>{if(!d.current)return;const C=c?k:w;C&&(d.current.srcObject=C)},[w,k,c]);const T=!g&&!!w;return n.jsxs("div",{className:`nice-conference-tile${f?" nice-conference-tile--speaking":""}${t?" nice-conference-tile--pinned":""}`,style:a?{height:"100%",minHeight:0}:{aspectRatio:"16/9"},children:[T?n.jsx("video",{ref:d,autoPlay:!0,muted:e,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"cover",transform:e&&!c?"scaleX(-1)":"none"}}):n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:8},children:[n.jsx("div",{style:{width:s==="large"?64:s==="small"?28:44,height:s==="large"?64:s==="small"?28:44,borderRadius:"50%",background:u.avatarUrl?`url(${u.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:s==="large"?28:s==="small"?12:18},children:!u.avatarUrl&&((h=u.name[0])==null?void 0:h.toUpperCase())}),s!=="small"&&n.jsx("span",{style:{color:"var(--nice-text-primary, #fff)",fontSize:12},children:u.displayName??u.name})]}),n.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:[n.jsxs("span",{style:{color:"var(--nice-color-white, #fff)",fontSize:11,fontWeight:500},children:[u.displayName??u.name,e&&o("videoConference.you"," (You)")]}),n.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[m&&n.jsx(y.NiceIcon,{name:"cursor",size:13}),p&&n.jsx(y.NiceIcon,{name:"mic",size:12}),c&&n.jsx(y.NiceIcon,{name:"monitor",size:12}),s!=="small"&&n.jsx("div",{style:{width:6,height:6,borderRadius:"50%",background:f?"var(--nice-success, #22c55e)":"transparent",border:"1px solid var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))"}})]})]}),s!=="small"&&n.jsx("button",{onClick:r,style:{position:"absolute",top:6,right:6,background:"var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",border:"none",borderRadius:4,padding:"2px 5px",color:t?"var(--nice-info, #6366f1)":"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))",cursor:"pointer",fontSize:12},title:t?o("videoConference.unpin","Unpin"):o("videoConference.pin","Pin"),"aria-label":t?o("videoConference.unpin","Unpin"):o("videoConference.pin","Pin"),children:n.jsx(y.NiceIcon,{name:"map-pin",size:12})}),i.connectionQuality!=="none"&&s!=="small"&&n.jsx("div",{style:{position:"absolute",top:6,left:6,width:14,height:10,display:"flex",gap:2,alignItems:"flex-end"},children:[1,2,3].map(C=>n.jsx("div",{style:{flex:1,background:i.connectionQuality==="excellent"||i.connectionQuality==="good"&&C<=2||i.connectionQuality==="fair"&&C<=1?"var(--nice-success, #22c55e)":"var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))",height:`${C*30}%`,borderRadius:1}},C))})]})}function nt({session:i,currentUser:e,localStream:t,enableScreenSharing:r=!0,enableRecording:s=!1,enableTranscription:a=!1,enableRaiseHand:o=!0,maxGridCols:d=4,onEndCall:u,onMuteAudio:p,onMuteVideo:g,onStartScreenShare:c,onStopScreenShare:f,onRaiseHand:m,className:w,style:k,id:T,"data-testid":h}){const{t:C}=y.useNiceTranslation(),[A,U]=l.useState(!1),[M,P]=l.useState(!1),[G,F]=l.useState(!1),[L,N]=l.useState(!1),[z,E]=l.useState(i.pinnedParticipantId??null),[V,J]=l.useState(i.layout==="sidebar"?"grid":i.layout??"grid"),[j,O]=l.useState(0),[Z,D]=l.useState(!1);l.useEffect(()=>{J(i.layout==="spotlight"?"spotlight":"grid")},[i.layout]),l.useEffect(()=>{if(i.status!=="active")return;const _=setInterval(()=>O(ee=>ee+1),1e3);return()=>clearInterval(_)},[i.status]);const H=_=>{const ee=Math.floor(_/3600),ae=Math.floor(_%3600/60),oe=_%60;return ee>0?`${ee}:${String(ae).padStart(2,"0")}:${String(oe).padStart(2,"0")}`:`${String(ae).padStart(2,"0")}:${String(oe).padStart(2,"0")}`},S=()=>{const _=!A;U(_),p==null||p(_)},b=()=>{const _=!M;P(_),g==null||g(_)},Y=async()=>{G?(F(!1),f==null||f()):(F(!0),await(c==null?void 0:c()))},X=()=>{const _=!L;N(_),m==null||m(_)},Q=[{user:e,isMuted:A,isCameraOff:M,isScreenSharing:G,isSpeaking:!1,isHandRaised:L,stream:t,connectionQuality:"excellent"},...i.participants.filter(_=>_.user.id!==e.id)],K=z?Q.find(_=>_.user.id===z):null,ie=K??(V==="spotlight"?Q.find(_=>_.isSpeaking)??Q[1]??Q[0]:null),de=Q.filter(_=>_.user.id!==(ie==null?void 0:ie.user.id)),ce=Q.length,xe=Math.min(d,ce<=1?1:ce<=2||ce<=4?2:ce<=9?3:4);return n.jsxs("div",{id:T,"data-testid":h,className:`nice-video-conference${w?` ${w}`:""}`,style:{position:"relative",width:"100%",height:"100%",background:"var(--nice-bg-primary, #111827)",display:"flex",flexDirection:"column",overflow:"hidden",...k},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 16px",flexShrink:0,color:"var(--nice-text-primary, #fff)"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[n.jsxs("span",{style:{fontSize:15,fontWeight:600},children:[i.id.slice(0,8),"โฆ"]}),n.jsx("span",{style:{fontSize:12,color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"},children:H(j)}),i.isRecording&&n.jsxs("span",{style:{fontSize:11,color:"var(--nice-danger, #ef4444)",display:"flex",alignItems:"center",gap:4},children:[n.jsx(y.NiceIcon,{name:"circle",size:11})," ",C("videoConference.recording","Recording")]})]}),n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[n.jsx("button",{onClick:()=>J(V==="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-color-white, #fff)",cursor:"pointer",fontSize:12},children:V==="grid"?n.jsxs(n.Fragment,{children:[n.jsx(y.NiceIcon,{name:"grid",size:14})," ",C("videoConference.grid","Grid")]}):n.jsxs(n.Fragment,{children:[n.jsx(y.NiceIcon,{name:"square",size:14})," ",C("videoConference.spotlight","Spotlight")]})}),n.jsxs("button",{onClick:()=>D(_=>!_),style:{display:"flex",alignItems:"center",gap:4,background:Z?"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-color-white, #fff)",cursor:"pointer",fontSize:12},children:[n.jsx(y.NiceIcon,{name:"users",size:14})," ",Q.length]})]})]}),n.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden",gap:4,padding:"0 8px 8px"},children:[n.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:4,overflow:"hidden"},children:ie?n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{flex:1,minHeight:0},children:n.jsx(He,{participant:ie,isLocal:ie.user.id===e.id,isPinned:K!=null,onPin:()=>E(K?null:ie.user.id),size:"large",fill:!0})}),n.jsx("div",{style:{display:"flex",gap:4,height:90,flexShrink:0,overflowX:"auto"},children:de.map(_=>n.jsx("div",{style:{width:140,flexShrink:0},children:n.jsx(He,{participant:_,isLocal:_.user.id===e.id,isPinned:!1,onPin:()=>E(_.user.id),size:"small"})},_.user.id))})]}):n.jsx("div",{style:{flex:1,display:"grid",gridTemplateColumns:`repeat(${xe}, 1fr)`,gridAutoRows:"minmax(0, 1fr)",gap:6,overflow:"hidden"},children:Q.map(_=>n.jsx(He,{participant:_,isLocal:_.user.id===e.id,isPinned:_.user.id===z,onPin:()=>E(ee=>ee===_.user.id?null:_.user.id),size:ce<=4?"large":"medium",fill:!0},_.user.id))})}),Z&&n.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:[n.jsx("div",{style:{padding:"10px 12px",fontWeight:600,fontSize:13,color:"var(--nice-text-primary, #fff)",borderBottom:"1px solid var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))"},children:C("videoConference.participants","Participants ({allParticipants})").replace("{allParticipants}",String(Q.length))}),n.jsx("div",{style:{flex:1,overflowY:"auto",padding:8},children:Q.map(_=>{var ee;return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px"},children:[n.jsx("div",{style:{width:28,height:28,borderRadius:"50%",background:_.user.avatarUrl?`url(${_.user.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontSize:11,fontWeight:700},children:!_.user.avatarUrl&&((ee=_.user.name[0])==null?void 0:ee.toUpperCase())}),n.jsx("div",{style:{flex:1,minWidth:0},children:n.jsxs("div",{style:{color:"var(--nice-text-primary, #fff)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[_.user.displayName??_.user.name,_.user.id===e.id&&C("videoConference.you"," (You)")]})}),n.jsxs("div",{style:{display:"flex",gap:3,alignItems:"center"},children:[_.isHandRaised&&n.jsx(y.NiceIcon,{name:"cursor",size:11}),_.isMuted&&n.jsx(y.NiceIcon,{name:"mic",size:11}),n.jsx(he,{status:_.user.presence.status,size:"xs"})]})]},_.user.id)})})]})]}),n.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:[n.jsx(be,{icon:"mic",label:A?C("videoConference.unmute","Unmute"):C("videoConference.mute","Mute"),onClick:S,danger:A}),n.jsx(be,{icon:M?"camera":"video",label:M?C("videoConference.startVideo","Start video"):C("videoConference.stopVideo","Stop video"),onClick:b,danger:M}),r&&n.jsx(be,{icon:"monitor",label:G?C("videoConference.stopShare","Stop share"):C("videoConference.share","Share"),onClick:()=>{Y()},active:G}),o&&n.jsx(be,{icon:"cursor",label:C("videoConference.raiseHand","Raise hand"),onClick:X,active:L}),s&&n.jsx(be,{icon:"circle",label:i.isRecording?C("videoConference.stopRec","Stop rec"):C("videoConference.record","Record"),onClick:()=>{},active:i.isRecording,danger:i.isRecording}),a&&n.jsx(be,{icon:"type",label:i.isTranscribing?C("videoConference.stopCaptions","Stop captions"):C("videoConference.captions","Captions"),onClick:()=>{},active:i.isTranscribing}),n.jsx(be,{icon:"phone",label:C("videoConference.leave","Leave"),onClick:()=>u==null?void 0:u(i.id),end:!0})]})]})}function be({icon:i,label:e,onClick:t,active:r,danger:s,end:a}){return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[n.jsx("button",{title:e,onClick:t,style:{width:46,height:46,borderRadius:"50%",border:"none",background:a?"var(--nice-danger, #ef4444)":s?"var(--nice-danger-dark, #450a0a)":r?"var(--nice-info, #6366f1)":"var(--nice-overlay-light-12, rgba(255, 255, 255, 0.12))",color:"var(--nice-color-white, #fff)",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.15s"},children:n.jsx(y.NiceIcon,{name:i,size:18})}),n.jsx("span",{style:{fontSize:9,color:"var(--nice-overlay-light-50, rgba(255, 255, 255, 0.5))",textAlign:"center",maxWidth:52},children:e})]})}function qe(i){const e={days:864e5,weeks:6048e5,months:2592e6,years:31536e6,forever:Number.MAX_SAFE_INTEGER};return i.unit==="forever"?e.forever:e[i.unit]*i.value}function ze(i,e=new Date){if(i.unit!=="forever")return new Date(e.getTime()+qe(i))}class pt{constructor(e="nice2dev-communication"){this.storeName="nice_comm_store",this.db=null,this.dbName=e}async openDb(){return this.db?this.db:new Promise((e,t)=>{const r=indexedDB.open(this.dbName,1);r.onupgradeneeded=s=>{const a=s.target.result;a.objectStoreNames.contains(this.storeName)||a.createObjectStore(this.storeName,{keyPath:"key"})},r.onsuccess=s=>{this.db=s.target.result,e(this.db)},r.onerror=()=>t(r.error)})}async save(e,t,r){const s=await this.openDb();return new Promise((a,o)=>{const p=s.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:e,data:t,expiresAt:r==null?void 0:r.toISOString()});p.onsuccess=()=>a(),p.onerror=()=>o(p.error)})}async load(e){const t=await this.openDb();return new Promise((r,s)=>{const d=t.transaction(this.storeName,"readonly").objectStore(this.storeName).get(e);d.onsuccess=()=>{const u=d.result;if(!u){r(void 0);return}if(u.expiresAt&&new Date(u.expiresAt)<new Date){this.delete(e),r(void 0);return}r(u.data)},d.onerror=()=>s(d.error)})}async delete(e){const t=await this.openDb();return new Promise((r,s)=>{const d=t.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(e);d.onsuccess=()=>r(),d.onerror=()=>s(d.error)})}async list(e){const t=await this.openDb();return new Promise((r,s)=>{const d=t.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();d.onsuccess=()=>r((d.result??[]).filter(u=>u.startsWith(e))),d.onerror=()=>s(d.error)})}async clear(e){if(!e){const r=await this.openDb();return new Promise((s,a)=>{const u=r.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();u.onsuccess=()=>s(),u.onerror=()=>a(u.error)})}const t=await this.list(e);await Promise.all(t.map(r=>this.delete(r)))}}class on{constructor(e="nice_comm__"){this.prefix=e}async save(e,t,r){const s={data:t,expiresAt:r==null?void 0:r.toISOString()};localStorage.setItem(this.prefix+e,JSON.stringify(s))}async load(e){const t=localStorage.getItem(this.prefix+e);if(t)try{const r=JSON.parse(t);if(r.expiresAt&&new Date(r.expiresAt)<new Date){await this.delete(e);return}return r.data}catch{return}}async delete(e){localStorage.removeItem(this.prefix+e)}async list(e){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&s.startsWith(this.prefix+e)&&t.push(s.slice(this.prefix.length))}return t}async clear(e){(await this.list(e??"")).forEach(r=>localStorage.removeItem(this.prefix+r))}}class Tt{constructor(e,t){this.config=e,this.encryption=t,this.adapter=this.buildAdapter()}buildAdapter(){switch(this.config.provider){case"localstorage":return new on;case"custom":return this.config.customAdapter??new pt;default:return new pt}}getRuleFor(e){return this.config.retentionRules.find(t=>t.dataType===e)}async encode(e){var r;const t=JSON.stringify(e);return(r=this.encryption)!=null&&r.isEnabled()?this.encryption.encrypt(t,"messages"):t}async decode(e){var t;if(typeof e!="string")return e;if(!((t=this.encryption)!=null&&t.isEnabled()))try{return JSON.parse(e)}catch{return e}try{const r=await this.encryption.decrypt(e,"messages");return JSON.parse(r)}catch{return e}}async saveMessages(e,t){const r=this.getRuleFor("messages"),s=r?ze(r.activePeriod):void 0,a=await this.encode(t);await this.adapter.save(`msg:${e}`,a,s)}async loadMessages(e){const t=await this.adapter.load(`msg:${e}`);if(!t)return[];const r=await this.decode(t);return Array.isArray(r)?r:[]}async appendMessage(e,t){const r=await this.loadMessages(e);await this.saveMessages(e,[...r,t])}async saveWhiteboardSnapshot(e,t){const r=this.getRuleFor("whiteboard-snapshots"),s=r?ze(r.activePeriod):void 0,a=await this.encode(t);await this.adapter.save(`wb:${e}`,a,s)}async loadWhiteboardSnapshot(e){const t=await this.adapter.load(`wb:${e}`);return t?await this.decode(t):null}async saveRecordingMeta(e){const t=this.getRuleFor("recordings"),r=t?ze(t.activePeriod):void 0,s=await this.encode(e);await this.adapter.save(`rec:${e.id}`,s,r)}async loadRecordingMeta(e){const t=await this.adapter.load(`rec:${e}`);return t?await this.decode(t):null}async listRecordings(){const e=await this.adapter.list("rec:");return(await Promise.all(e.map(r=>this.loadRecordingMeta(r.slice(4))))).filter(Boolean)}async deleteRecording(e){await this.adapter.delete(`rec:${e}`)}async saveDocument(e,t){const r=this.getRuleFor("documents"),s=r?ze(r.activePeriod):void 0,a=await this.encode(t);await this.adapter.save(`doc:${e}`,a,s)}async loadDocument(e){const t=await this.adapter.load(`doc:${e}`);return t?this.decode(t):null}async enforceRetention(){let e=0,t=0;const r=new Date,s=[{prefix:"msg:",type:"messages"},{prefix:"wb:",type:"whiteboard-snapshots"},{prefix:"rec:",type:"recordings"},{prefix:"doc:",type:"documents"}];for(const{prefix:a,type:o}of s){const d=this.getRuleFor(o);if(!d)continue;const u=await this.adapter.list(a);for(const p of u){const g=await this.adapter.load(p);if(g){if(qe(d.activePeriod),d.archivePeriod){const c=`archive:${p}`,f=ze(d.archivePeriod,r);await this.adapter.save(c,g,f),e++}if(d.deleteAfterArchive&&d.archivePeriod){const c=qe(d.archivePeriod);new Date(r.getTime()+c)<r&&(await this.adapter.delete(`archive:${p}`),t++)}}}}return{archived:e,deleted:t}}async estimateUsageBytes(){return typeof window<"u"&&"storage"in navigator&&"estimate"in navigator.storage?(await navigator.storage.estimate()).usage??0:0}updateConfig(e){this.config=e,this.adapter=this.buildAdapter()}getConfig(){return this.config}}const it=[{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}],We=new Map;function zt(i,e,t){return We.has(i)||We.set(i,new Tt(e,t)),We.get(i)}function ln(i){We.delete(i)}const ut=["var(--nice-color-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-accent, #3f51b5)","var(--nice-primary, #2196f3)","var(--nice-info, #00bcd4)","var(--nice-success, #4caf50)","var(--nice-warning, #ff9800)","var(--nice-danger, #ff5722)","var(--nice-warning-dark, #795548)","var(--nice-text-secondary, #607d8b)"];function cn(i){let e=0;for(let t=0;t<i.length;t++)e=e*31+i.charCodeAt(t)>>>0;return ut[e%ut.length]}function ht(i,e,t){const r={...i},s=[...e];switch(t.type){case"object:add":case"object:update":{const a=t.payload;if(r[a.id]=a,s.length>0&&!s[0].objectIds.includes(a.id)){const o=a.layerId?s.find(d=>d.id===a.layerId)??s[0]:s[0];o.objectIds=[...o.objectIds,a.id]}break}case"object:delete":{const{id:a}=t.payload;delete r[a],s.forEach(o=>{o.objectIds=o.objectIds.filter(d=>d!==a)});break}case"object:move":{const{id:a,x:o,y:d}=t.payload;r[a]&&(r[a]={...r[a],x:o,y:d,updatedAt:t.timestamp});break}case"layer:add":{const a=t.payload;s.find(o=>o.id===a.id)||s.push(a);break}case"layer:update":{const a=t.payload,o=s.findIndex(d=>d.id===a.id);o!==-1&&(s[o]={...s[o],...a});break}case"layer:delete":{const{id:a}=t.payload,o=s.findIndex(d=>d.id===a);o!==-1&&s.splice(o,1);break}}return{objects:r,layers:s}}function dn(i,e){switch(e.type){case"LOAD_SESSION":return{...i,session:e.session,undoStack:[],redoStack:[],isDirty:!1};case"SET_TOOL":return{...i,activeTool:e.tool};case"APPLY_OP":{const{op:t,local:r}=e,{objects:s,layers:a}=ht(i.session.objects,i.session.layers,t),o={...i.session,objects:s,layers:a,updatedAt:t.timestamp},u=r&&["object:add","object:update","object:delete","object:move","layer:add","layer:update","layer:delete"].includes(t.type)?[...i.undoStack,[t]]:i.undoStack;return{...i,session:o,undoStack:u,redoStack:r?[]:i.redoStack,isDirty:!0}}case"UNDO":{if(i.undoStack.length===0)return i;const t=i.undoStack[i.undoStack.length-1],r=t.filter(o=>o.type==="object:add").map(o=>o.payload.id),s={...i.session.objects};r.forEach(o=>delete s[o]);const a=i.session.layers.map(o=>({...o,objectIds:o.objectIds.filter(d=>!r.includes(d))}));return{...i,session:{...i.session,objects:s,layers:a},undoStack:i.undoStack.slice(0,-1),redoStack:[t,...i.redoStack],isDirty:!0}}case"REDO":{if(i.redoStack.length===0)return i;const t=i.redoStack[0];let{objects:r,layers:s}={objects:i.session.objects,layers:i.session.layers};for(const a of t)({objects:r,layers:s}=ht(r,s,a));return{...i,session:{...i.session,objects:r,layers:s},undoStack:[...i.undoStack,t],redoStack:i.redoStack.slice(1),isDirty:!0}}case"SET_SELECTION":return{...i,selectedObjectIds:e.ids};case"SET_DRAWING":return{...i,isDrawing:e.value};case"SET_PANNING":return{...i,isPanning:e.value};case"UPDATE_CURSOR":{const{userId:t,x:r,y:s}=e,a=i.session.collaborators[t];return a?{...i,session:{...i.session,collaborators:{...i.session.collaborators,[t]:{...a,cursorX:r,cursorY:s,lastSeenAt:new Date}}}}:i}case"REMOVE_COLLABORATOR":{const t={...i.session.collaborators};return delete t[e.userId],{...i,session:{...i.session,collaborators:t}}}case"SET_VIEWPORT":return{...i,session:{...i.session,viewport:e.viewport}};case"MARK_SAVED":return{...i,isDirty:!1,lastSavedAt:new Date};default:return i}}function Nt(i){const{session:e,currentUser:t,onOperation:r,remoteOperations:s=[],readonly:a=!1,storageConfig:o,autoSaveMs:d=3e4}=i,[u,p]=l.useReducer(dn,{session:e,activeTool:a?"select":"pen",selectedObjectIds:[],undoStack:[],redoStack:[],isDrawing:!1,isPanning:!1,isDirty:!1}),g=l.useRef(0),c=l.useRef(null),f=l.useRef(null);l.useEffect(()=>{o&&(f.current=zt(`wb_${e.id}`,o),f.current.loadWhiteboardSnapshot(e.id).then(j=>{j&&p({type:"LOAD_SESSION",session:j})}))},[e.id,o]),l.useEffect(()=>{if(!d||!f.current||!u.isDirty)return;const j=setTimeout(()=>{var O;(O=f.current)==null||O.saveWhiteboardSnapshot(u.session.id,u.session).then(()=>{p({type:"MARK_SAVED"})})},d);return()=>clearTimeout(j)},[u.isDirty,u.session,d]);const m=l.useRef(new Set);l.useEffect(()=>{for(const j of s)if(!m.current.has(j.id)&&j.userId!==t.id)if(m.current.add(j.id),j.type==="cursor:move"){const{x:O,y:Z}=j.payload;p({type:"UPDATE_CURSOR",userId:j.userId,x:O,y:Z})}else j.type==="viewport:sync"||p({type:"APPLY_OP",op:j,local:!1})},[s,t.id]);const w=l.useCallback((j,O)=>({id:`${t.id}_${++g.current}_${Date.now()}`,sessionId:u.session.id,type:j,userId:t.id,timestamp:new Date,payload:O}),[t.id,u.session.id]),k=l.useCallback(j=>{a||p({type:"SET_TOOL",tool:j})},[a]),T=l.useCallback(j=>{if(a)return;const O=w("object:add",j);p({type:"APPLY_OP",op:O,local:!0}),r==null||r(O)},[a,r,w]),h=l.useCallback(j=>{if(a)return;const O=w("object:update",j);p({type:"APPLY_OP",op:O,local:!0}),r==null||r(O)},[a,r,w]),C=l.useCallback(j=>{if(!a){for(const O of j){const Z=w("object:delete",{id:O});p({type:"APPLY_OP",op:Z,local:!0}),r==null||r(Z)}p({type:"SET_SELECTION",ids:[]})}},[a,r,w]),A=l.useCallback(j=>{if(!a)for(const{id:O,x:Z,y:D}of j){const H=w("object:move",{id:O,x:Z,y:D});p({type:"APPLY_OP",op:H,local:!0}),r==null||r(H)}},[a,r,w]),U=l.useCallback(j=>{p({type:"SET_SELECTION",ids:j})},[]),M=l.useCallback(()=>{a||p({type:"UNDO"})},[a]),P=l.useCallback(()=>{a||p({type:"REDO"})},[a]),G=l.useCallback(j=>{p({type:"SET_VIEWPORT",viewport:j});const O=w("viewport:sync",j);r==null||r(O)},[r,w]),F=l.useCallback((j,O)=>{if(c.current)return;c.current=setTimeout(()=>{c.current=null},50);const Z=w("cursor:move",{x:j,y:O});r==null||r(Z)},[r,w]),L=l.useCallback(j=>{if(a)return;const O={id:`layer_${Date.now()}`,name:j,visible:!0,locked:!1,objectIds:[]},Z=w("layer:add",O);p({type:"APPLY_OP",op:Z,local:!0}),r==null||r(Z)},[a,r,w]),N=l.useCallback(j=>{if(a)return;const O=w("layer:update",j);p({type:"APPLY_OP",op:O,local:!0}),r==null||r(O)},[a,r,w]),z=l.useCallback(j=>{if(a)return;const O=w("layer:delete",{id:j});p({type:"APPLY_OP",op:O,local:!0}),r==null||r(O)},[a,r,w]),E=l.useCallback(j=>{const O={user:j,cursorX:0,cursorY:0,color:cn(j.id),selectedObjectIds:[],activeTool:"pen",lastSeenAt:new Date};p({type:"APPLY_OP",op:w("cursor:move",O),local:!1})},[]),V=l.useCallback(j=>{p({type:"REMOVE_COLLABORATOR",userId:j})},[]),J=l.useCallback(async()=>{f.current&&(await f.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:k,addObject:T,updateObject:h,deleteObjects:C,moveObjects:A,setSelection:U,undo:M,redo:P,setViewport:G,broadcastCursor:F,addLayer:L,updateLayer:N,deleteLayer:z,registerCollaborator:E,removeCollaborator:V,saveNow:J}}const pn=[{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 De(){return`${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Ve(i,e,t){return{sx:i*t.scale+t.x,sy:e*t.scale+t.y}}function un(i,e,t){return{wx:(i-t.x)/t.scale,wy:(e-t.y)/t.scale}}function hn(i,e){return Math.hypot(e.x-i.x,e.y-i.y)}function fn(i,e){if(!(e.points.length<2)){i.save(),i.globalAlpha=e.opacity,i.strokeStyle=y.resolveCssColor(e.color,i.canvas),i.lineWidth=e.strokeWidth,i.lineCap="round",i.lineJoin="round",e.tool==="highlighter"&&(i.globalCompositeOperation="multiply"),i.beginPath(),i.moveTo(e.points[0].x,e.points[0].y);for(let t=1;t<e.points.length;t++){const r={x:(e.points[t-1].x+e.points[t].x)/2,y:(e.points[t-1].y+e.points[t].y)/2};i.quadraticCurveTo(e.points[t-1].x,e.points[t-1].y,r.x,r.y)}i.stroke(),i.restore()}}function gn(i,e){switch(i.save(),i.globalAlpha=e.opacity,i.strokeStyle=y.resolveCssColor(e.strokeColor,i.canvas),i.lineWidth=e.strokeWidth,e.fillColor&&(i.fillStyle=y.resolveCssColor(e.fillColor,i.canvas)),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(e.rotation*Math.PI/180),i.beginPath(),e.shape){case"rect":i.rect(-e.width/2,-e.height/2,e.width,e.height);break;case"ellipse":i.ellipse(0,0,e.width/2,e.height/2,0,0,Math.PI*2);break;case"triangle":{const t=e.width/2,r=e.height/2;i.moveTo(0,-r),i.lineTo(t,r),i.lineTo(-t,r),i.closePath();break}case"diamond":{const t=e.width/2,r=e.height/2;i.moveTo(0,-r),i.lineTo(t,0),i.lineTo(0,r),i.lineTo(-t,0),i.closePath();break}}e.fillColor&&i.fill(),i.stroke(),i.restore()}function mn(i,e){if(i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(e.rotation*Math.PI/180),i.font=`${e.fontStyle} ${e.fontWeight} ${e.fontSize}px ${e.fontFamily}`,i.fillStyle=y.resolveCssColor(e.color,i.canvas),i.textAlign=e.textAlign,i.textBaseline="middle",e.backgroundColor){const t=i.measureText(e.text),r=4;i.fillStyle=y.resolveCssColor(e.backgroundColor,i.canvas),i.fillRect(-t.width/2-r,-e.fontSize/2-r,t.width+r*2,e.fontSize+r*2),i.fillStyle=y.resolveCssColor(e.color,i.canvas)}i.fillText(e.text,0,0),i.restore()}function yn(i,e){i.save(),i.translate(e.x,e.y),i.rotate(e.rotation*Math.PI/180),i.shadowColor=y.resolveCssColor("var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",i.canvas),i.shadowBlur=8,i.shadowOffsetY=3,i.fillStyle=y.resolveCssColor(e.backgroundColor,i.canvas),i.fillRect(0,0,e.width,e.height),i.shadowColor="transparent",i.fillStyle=y.resolveCssColor(e.textColor,i.canvas),i.font=`${e.fontSize}px sans-serif`,i.textAlign="left",i.textBaseline="top";const t=10,r=e.width-t*2,s=e.fontSize*1.4,a=e.text.split(" ");let o="",d=t;for(const u of a){const p=o?`${o} ${u}`:u;i.measureText(p).width>r&&o?(i.fillText(o,t,d),o=u,d+=s):o=p}o&&i.fillText(o,t,d),i.restore()}function xn(i,e){if(!(e.points.length<2)){if(i.save(),i.strokeStyle=y.resolveCssColor(e.strokeColor,i.canvas),i.lineWidth=e.strokeWidth,i.lineCap="round",i.beginPath(),i.moveTo(e.points[0].x,e.points[0].y),e.curved&&e.points.length>2){for(let t=1;t<e.points.length-1;t++){const r=e.points[t],s={x:(r.x+e.points[t+1].x)/2,y:(r.y+e.points[t+1].y)/2};i.quadraticCurveTo(r.x,r.y,s.x,s.y)}i.lineTo(e.points[e.points.length-1].x,e.points[e.points.length-1].y)}else for(let t=1;t<e.points.length;t++)i.lineTo(e.points[t].x,e.points[t].y);if(i.stroke(),e.arrowEnd==="arrow"){const t=e.points[e.points.length-1],r=e.points[e.points.length-2],s=Math.atan2(t.y-r.y,t.x-r.x),a=12;i.beginPath(),i.moveTo(t.x,t.y),i.lineTo(t.x-a*Math.cos(s-Math.PI/6),t.y-a*Math.sin(s-Math.PI/6)),i.moveTo(t.x,t.y),i.lineTo(t.x-a*Math.cos(s+Math.PI/6),t.y-a*Math.sin(s+Math.PI/6)),i.stroke()}i.restore()}}function bn(i,e){i.save(),i.strokeStyle=y.resolveCssColor(e.borderColor??"var(--nice-text-muted, #aaa)",i.canvas),i.lineWidth=2,i.setLineDash([8,4]),e.backgroundColor&&(i.fillStyle=y.resolveCssColor(e.backgroundColor,i.canvas),i.fillRect(e.x,e.y,e.width,e.height)),i.strokeRect(e.x,e.y,e.width,e.height),i.setLineDash([]),i.fillStyle=y.resolveCssColor("var(--nice-text-secondary, #555)",i.canvas),i.font="bold 13px sans-serif",i.fillText(e.name,e.x+8,e.y-6),i.restore()}function vn(i,e){if(e.visible)switch(e.type){case"stroke":return fn(i,e);case"shape":return gn(i,e);case"text":return mn(i,e);case"sticky":return yn(i,e);case"connector":return xn(i,e);case"frame":return bn(i,e);case"image":{const t=e,r=new Image;r.src=t.dataUrl??t.url,i.save(),i.translate(t.x+t.width/2,t.y+t.height/2),i.rotate(t.rotation*Math.PI/180),i.drawImage(r,-t.width/2,-t.height/2,t.width,t.height),i.restore();break}}}function rt(i){const{t:e}=y.useNiceTranslation();return i.session?n.jsx(wn,{...i,session:i.session}):n.jsx("div",{className:i.className,style:i.style,"data-testid":i["data-testid"],children:n.jsx(y.NiceEmpty,{title:e("whiteboard.noSession","No whiteboard session")})})}function wn({session:i,currentUser:e,onOperation:t,remoteOperations:r=[],readonly:s=!1,enableLayers:a=!0,enableExport:o=!0,enableLaserPointer:d=!0,enableVectorEditor:u=!1,enableDiagramEditor:p=!1,onExport:g,onSessionUpdate:c,storageConfig:f,className:m,style:w,"data-testid":k}){const{t:T}=y.useNiceTranslation(),h=Nt({session:i,currentUser:e,onOperation:t,remoteOperations:r,readonly:s,storageConfig:f,autoSaveMs:3e4}),C=l.useRef(null);l.useRef(null);const A=l.useRef(0),[U,M]=l.useState(!1),[P,G]=l.useState("#1a1a1a"),[F,L]=l.useState(3),[N,z]=l.useState(void 0),[E,V]=l.useState(18),[J,j]=l.useState("var(--nice-warning-bg, #fef08a)"),[O,Z]=l.useState(null),[D,H]=l.useState(null),S=l.useRef({active:!1,startX:0,startY:0,currentPoints:[],currentId:"",spaceDown:!1,panStart:null,laserPoints:[]}),b=l.useCallback((x,v,$,B)=>{if(!h.session.gridEnabled)return;const W=h.session.gridSize*v.scale,q=(v.x%W+W)%W,I=(v.y%W+W)%W;x.strokeStyle=y.resolveCssColor("var(--nice-border-color, rgba(180,180,200,0.35))",x.canvas),x.lineWidth=1,x.beginPath();for(let R=q;R<$;R+=W)x.moveTo(R,0),x.lineTo(R,B);for(let R=I;R<B;R+=W)x.moveTo(0,R),x.lineTo($,R);x.stroke()},[h.session.gridEnabled,h.session.gridSize]),Y=l.useCallback((x,v)=>{for(const $ of h.collaborators){if($.user.id===e.id)continue;const{sx:B,sy:W}=Ve($.cursorX,$.cursorY,v);x.save(),x.fillStyle=$.color,x.beginPath(),x.moveTo(B,W),x.lineTo(B+14,W+5),x.lineTo(B+5,W+14),x.closePath(),x.fill(),x.fillStyle=$.color,x.font="bold 11px sans-serif",x.fillText($.user.name,B+16,W+14),x.restore()}},[h.collaborators,e.id]),X=l.useCallback((x,v)=>{if(h.selectedObjectIds.length!==0)for(const $ of h.selectedObjectIds){const B=h.session.objects[$];if(!B)continue;const{sx:W,sy:q}=Ve(B.x,B.y,v),I=B.width*v.scale,R=B.height*v.scale;x.strokeStyle=y.resolveCssColor("var(--nice-primary, #4f8df9)",x.canvas),x.lineWidth=1.5,x.setLineDash([4,2]),x.strokeRect(W-2,q-2,I+4,R+4),x.setLineDash([]);const ne=[[W-2,q-2],[W+I+2,q-2],[W-2,q+R+2],[W+I+2,q+R+2]];x.fillStyle=y.resolveCssColor("var(--nice-bg, #fff)",x.canvas),x.strokeStyle=y.resolveCssColor("var(--nice-primary, #4f8df9)",x.canvas),x.lineWidth=1.5;for(const[te,se]of ne)x.fillRect(te-4,se-4,8,8),x.strokeRect(te-4,se-4,8,8)}},[h.selectedObjectIds,h.session.objects]),Q=l.useCallback(()=>{const x=C.current;if(!x)return;const v=x.getContext("2d");if(!v)return;const{width:$,height:B}=x,W=h.viewport;v.clearRect(0,0,$,B),v.fillStyle=y.resolveCssColor(h.session.backgroundColor,x),v.fillRect(0,0,$,B),b(v,W,$,B),v.save();const q=Object.values(h.session.objects).filter(I=>I.visible).sort((I,R)=>I.zIndex-R.zIndex);v.translate(W.x,W.y),v.scale(W.scale,W.scale);for(const I of q)vn(v,I);if(S.current.active&&S.current.currentPoints.length>1){const I=S.current.currentPoints;v.strokeStyle=y.resolveCssColor(P,x),v.lineWidth=F,v.lineCap="round",v.lineJoin="round",v.beginPath(),v.moveTo(I[0].x,I[0].y);for(let R=1;R<I.length;R++)v.lineTo(I[R].x,I[R].y);v.stroke()}if(S.current.laserPoints.length>1&&h.activeTool==="laser"){const I=S.current.laserPoints;v.strokeStyle="#ff2c2c",v.lineWidth=3,v.globalAlpha=.7,v.beginPath(),v.moveTo(I[0].x,I[0].y);for(let R=1;R<I.length;R++)v.lineTo(I[R].x,I[R].y);v.stroke(),v.globalAlpha=1}v.restore(),X(v,W),Y(v,W)},[h.session,h.viewport,h.activeTool,b,Y,X,P,F]);l.useLayoutEffect(()=>{function x(){Q(),A.current=requestAnimationFrame(x)}return A.current=requestAnimationFrame(x),()=>cancelAnimationFrame(A.current)},[Q]),l.useEffect(()=>{const x=C.current;if(!x)return;const v=new ResizeObserver(()=>{x.width=x.offsetWidth,x.height=x.offsetHeight});return v.observe(x),x.width=x.offsetWidth,x.height=x.offsetHeight,()=>v.disconnect()},[]),l.useEffect(()=>{function x(v){if(v.target.tagName==="INPUT"||v.target.tagName==="TEXTAREA"||(v.code==="Space"&&(S.current.spaceDown=v.type==="keydown",v.preventDefault()),v.type!=="keydown"))return;(v.ctrlKey||v.metaKey)&&(v.key==="z"&&(v.preventDefault(),h.undo()),v.key==="y"&&(v.preventDefault(),h.redo()),v.key==="s"&&(v.preventDefault(),h.saveNow()),v.key==="a"&&(v.preventDefault(),h.setSelection(Object.keys(h.session.objects)))),(v.key==="Delete"||v.key==="Backspace")&&h.selectedObjectIds.length>0&&h.deleteObjects(h.selectedObjectIds);const $={v:"select",p:"pen",h:"highlighter",e:"eraser",r:"rect",c:"ellipse",t:"text",s:"sticky",i:"image",a:"arrow",l:"laser"};!v.ctrlKey&&!v.metaKey&&$[v.key]&&h.setTool($[v.key])}return window.addEventListener("keydown",x),window.addEventListener("keyup",x),()=>{window.removeEventListener("keydown",x),window.removeEventListener("keyup",x)}},[h]);const K=l.useCallback(x=>{const v=C.current.getBoundingClientRect(),$=x.clientX-v.left,B=x.clientY-v.top,{wx:W,wy:q}=un($,B,h.viewport);return{x:W,y:q,pressure:x.pressure??.5}},[h.viewport]),ie=l.useCallback(x=>{if(s)return;x.target.setPointerCapture(x.pointerId);const v=K(x);if(x.button===1||S.current.spaceDown){S.current.panStart={x:x.clientX,y:x.clientY,vpX:h.viewport.x,vpY:h.viewport.y};return}const $=h.activeTool;if(S.current.active=!0,S.current.startX=v.x,S.current.startY=v.y,S.current.currentId=De(),$==="pen"||$==="highlighter")S.current.currentPoints=[v];else if($==="laser")S.current.laserPoints=[v];else if($==="select"){const B=Object.values(h.session.objects).filter(W=>W.visible&&W.x<=v.x&&W.y<=v.y&&W.x+W.width>=v.x&&W.y+W.height>=v.y).sort((W,q)=>q.zIndex-W.zIndex)[0];B?x.shiftKey?h.setSelection([...h.selectedObjectIds,B.id]):h.setSelection([B.id]):h.setSelection([])}},[s,K,h]),de=l.useCallback(x=>{const v=K(x);if(h.broadcastCursor(v.x,v.y),S.current.panStart){const{x:B,y:W,vpX:q,vpY:I}=S.current.panStart;h.setViewport({...h.viewport,x:q+(x.clientX-B),y:I+(x.clientY-W)});return}if(!S.current.active)return;const $=h.activeTool;if($==="pen"||$==="highlighter"){const B=S.current.currentPoints;(B.length===0||hn(B[B.length-1],v)>2)&&(S.current.currentPoints=[...B,v])}else if($==="laser"){const B=S.current.laserPoints;S.current.laserPoints=[...B.slice(-40),v]}else if($==="select"&&h.selectedObjectIds.length>0){const B=v.x-S.current.startX,W=v.y-S.current.startY;S.current.startX=v.x,S.current.startY=v.y,h.moveObjects(h.selectedObjectIds.map(q=>{const I=h.session.objects[q];return{id:q,x:I.x+B,y:I.y+W}}))}},[K,h]),ce=l.useCallback(x=>{if(S.current.panStart){S.current.panStart=null;return}if(!S.current.active)return;const v=K(x),$=h.activeTool,B=S.current.startX,W=S.current.startY,q=S.current.currentId,I=new Date;switch(S.current.active=!1,$){case"pen":case"highlighter":{const R=S.current.currentPoints;if(R.length<2)break;const ne={id:q,type:"stroke",x:Math.min(...R.map(te=>te.x)),y:Math.min(...R.map(te=>te.y)),width:Math.max(...R.map(te=>te.x))-Math.min(...R.map(te=>te.x)),height:Math.max(...R.map(te=>te.y))-Math.min(...R.map(te=>te.y)),rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:I,points:R,color:P,strokeWidth:F,opacity:$==="highlighter"?.4:1,tool:$};h.addObject(ne),S.current.currentPoints=[];break}case"rect":case"ellipse":case"triangle":{const R=Math.min(B,v.x),ne=Math.min(W,v.y),te=Math.abs(v.x-B),se=Math.abs(v.y-W);if(te<5||se<5)break;const pe={rect:"rect",ellipse:"ellipse",triangle:"triangle"},me={id:q,type:"shape",x:R,y:ne,width:te,height:se,rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:I,shape:pe[$],fillColor:N,strokeColor:P,strokeWidth:F,opacity:1};h.addObject(me);break}case"arrow":case"line":{const R={id:q,type:"connector",x:Math.min(B,v.x),y:Math.min(W,v.y),width:Math.abs(v.x-B),height:Math.abs(v.y-W),rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:I,points:[{x:B,y:W},{x:v.x,y:v.y}],strokeColor:P,strokeWidth:F,arrowStart:"none",arrowEnd:$==="arrow"?"arrow":"none",curved:!1};h.addObject(R);break}case"text":{const R={id:q,type:"text",x:v.x,y:v.y,width:200,height:E+10,rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:I,text:T("whiteboard.clickToEdit","Click to edit"),fontSize:E,fontFamily:"sans-serif",fontWeight:"normal",fontStyle:"normal",textAlign:"left",color:P};h.addObject(R),Z(q);break}case"sticky":{const R={id:q,type:"sticky",x:v.x,y:v.y,width:180,height:150,rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:I,text:T("whiteboard.note","Note..."),backgroundColor:J,textColor:"var(--nice-text, #333)",fontSize:14,authorId:e.id};h.addObject(R),Z(q);break}case"frame":{const R=Math.min(B,v.x),ne=Math.min(W,v.y),te=Math.abs(v.x-B),se=Math.abs(v.y-W);if(te<20||se<20)break;const pe={id:q,type:"frame",x:R,y:ne,width:te,height:se,rotation:0,zIndex:0,locked:!1,visible:!0,createdBy:e.id,createdAt:I,name:`Frame ${Object.keys(h.session.objects).length+1}`,childIds:[],borderColor:"#8888"};h.addObject(pe);break}case"image":{const R=document.createElement("input");R.type="file",R.accept="image/*",R.onchange=()=>{var se;const ne=(se=R.files)==null?void 0:se[0];if(!ne)return;const te=new FileReader;te.onload=pe=>{var Pe;const me=(Pe=pe.target)==null?void 0:Pe.result,fe=new Image;fe.onload=()=>{const Ae=400/fe.width,Fe={id:De(),type:"image",x:v.x,y:v.y,width:fe.width*Ae,height:fe.height*Ae,rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:me,dataUrl:me,originalWidth:fe.width,originalHeight:fe.height};h.addObject(Fe)},fe.src=me},te.readAsDataURL(ne)},R.click();break}}},[K,h,e.id,P,F,N,E,J,T]),xe=l.useCallback(x=>{if(x.preventDefault(),!x.ctrlKey&&!x.metaKey){h.setViewport({...h.viewport,x:h.viewport.x-x.deltaX,y:h.viewport.y-x.deltaY});return}const v=C.current.getBoundingClientRect(),$=x.clientX-v.left,B=x.clientY-v.top,q=-x.deltaY>0?1.1:.9,I=Math.min(8,Math.max(.1,h.viewport.scale*q));h.setViewport({scale:I,x:$-($-h.viewport.x)*(I/h.viewport.scale),y:B-(B-h.viewport.y)*(I/h.viewport.scale)})},[h]),_=l.useCallback(x=>{if(x==="json"){const W=JSON.stringify(h.session,null,2);g==null||g("json",W);const q=document.createElement("a");q.href=URL.createObjectURL(new Blob([W],{type:"application/json"})),q.download=`${h.session.title}.json`,q.click();return}const v=C.current;if(!v)return;const $=v.toDataURL("image/png");g==null||g("png",$);const B=document.createElement("a");B.href=$,B.download=`${h.session.title}.png`,B.click()},[h.session,g]);l.useEffect(()=>{c==null||c(h.session)},[h.session,c]),l.useEffect(()=>{function x(v){if(v.clipboardData){for(const $ of Array.from(v.clipboardData.items))if($.type.startsWith("image/")){const B=$.getAsFile();if(!B)continue;const W=new FileReader;W.onload=q=>{var ne;const I=(ne=q.target)==null?void 0:ne.result,R=new Image;R.onload=()=>{const se=400/R.width,pe={id:De(),type:"image",x:100,y:100,width:R.width*se,height:R.height*se,rotation:0,zIndex:Object.keys(h.session.objects).length,locked:!1,visible:!0,createdBy:e.id,createdAt:new Date,url:I,dataUrl:I,originalWidth:R.width,originalHeight:R.height};h.addObject(pe)},R.src=I},W.readAsDataURL(B);break}}}return window.addEventListener("paste",x),()=>window.removeEventListener("paste",x)},[h,e.id]);const ee=O?h.session.objects[O]:null,ae=l.useMemo(()=>ee?Ve(ee.x,ee.y,h.viewport):null,[ee,h.viewport]),oe=["var(--nice-warning-bg, #fef08a)","var(--nice-primary-bg, #bfdbfe)","var(--nice-success-bg, #bbf7d0)","var(--nice-danger-bg, #fecaca)","var(--nice-accent-tint-10, #e9d5ff)","var(--nice-warning-bg, #fed7aa)"],le=l.useMemo(()=>{var v;const x={};for(const $ of pn)(x[v=$.group]??(x[v]=[])).push($);return Object.values(x)},[]);return n.jsxs("div",{className:m,"data-testid":k,style:{position:"relative",display:"flex",flexDirection:"column",width:"100%",height:"100%",overflow:"hidden",background:"var(--nice-bg-secondary, #f5f5f5)",fontFamily:"system-ui, sans-serif",...w},children:[n.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:[le.map((x,v)=>n.jsxs(l.Fragment,{children:[v>0&&n.jsx("div",{style:{width:1,height:24,background:"var(--nice-border, #e5e7eb)",margin:"0 2px"}}),x.map($=>n.jsx("button",{onClick:()=>h.setTool($.id),title:`${$.label}`,style:{padding:"4px 7px",border:`1.5px solid ${h.activeTool===$.id?"var(--nice-info, #6366f1)":"transparent"}`,borderRadius:6,background:h.activeTool===$.id?"var(--nice-primary-bg, #eef2ff)":"transparent",cursor:"pointer",fontSize:15,minWidth:30,color:h.activeTool===$.id?"var(--nice-accent, #4f46e5)":"var(--nice-text, #374151)",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:n.jsx(y.NiceIcon,{name:$.icon,size:15})},$.id))]},v)),n.jsx("div",{style:{width:1,height:24,background:"var(--nice-border, #e5e7eb)",margin:"0 4px"}}),n.jsxs("label",{title:T("whiteboard.strokeColor","Stroke color"),style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:T("whiteboard.color","Color")}),n.jsx("input",{type:"color",value:P,onChange:x=>G(x.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}})]}),n.jsxs("label",{title:T("whiteboard.fillColor","Fill color"),style:{display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:T("whiteboard.fill","Fill")}),n.jsx("input",{type:"color",value:N??"#ffffff",onChange:x=>z(x.target.value),style:{width:28,height:28,border:"none",padding:0,borderRadius:4,cursor:"pointer"}}),n.jsx("button",{onClick:()=>z(void 0),style:{fontSize:11,padding:"1px 5px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:4,cursor:"pointer",background:N?"var(--nice-bg, #fff)":"var(--nice-bg-secondary, #f3f4f6)"},children:T("whiteboard.noFill","No fill")})]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:T("whiteboard.width","Width")}),n.jsx("input",{type:"range",min:1,max:24,step:1,value:F,onChange:x=>L(Number(x.target.value)),style:{width:70}}),n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",minWidth:20},children:F})]}),h.activeTool==="sticky"&&n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)"},children:T("whiteboard.note2","Note:")}),oe.map(x=>n.jsx("button",{onClick:()=>j(x),style:{width:20,height:20,background:x,border:`2px solid ${J===x?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)"}`,borderRadius:4,cursor:"pointer"}},x))]}),n.jsx("div",{style:{flex:1}}),n.jsx("button",{onClick:h.undo,disabled:!h.canUndo,title:T("whiteboard.undoCtrlZ","Undo (Ctrl+Z)"),"aria-label":T("whiteboard.undo","Undo"),style:ue(!h.canUndo),children:n.jsx(y.NiceIcon,{name:"reply",size:13})}),n.jsx("button",{onClick:h.redo,disabled:!h.canRedo,title:T("whiteboard.redoCtrlY","Redo (Ctrl+Y)"),"aria-label":T("whiteboard.redo","Redo"),style:ue(!h.canRedo),children:n.jsx(y.NiceIcon,{name:"forward",size:13})}),n.jsx("div",{style:{width:1,height:24,background:"var(--nice-border, #e5e7eb)"}}),n.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",minWidth:42,textAlign:"center"},children:[Math.round(h.viewport.scale*100),"%"]}),n.jsx("button",{onClick:()=>h.setViewport({x:0,y:0,scale:1}),style:ue(),title:T("whiteboard.resetZoom","Reset zoom"),"aria-label":T("whiteboard.resetZoom","Reset zoom"),children:n.jsx(y.NiceIcon,{name:"target",size:13})}),a&&n.jsx("button",{onClick:()=>M(x=>!x),style:ue(!1,U),title:T("whiteboard.layers","Layers"),"aria-label":T("whiteboard.layers","Layers"),children:n.jsx(y.NiceIcon,{name:"layers",size:13})}),n.jsx("button",{onClick:()=>{const x={id:De(),sessionId:h.session.id,type:"object:update",userId:e.id,timestamp:new Date,payload:{...h.session,gridEnabled:!h.session.gridEnabled}};t==null||t(x)},style:ue(!1,h.session.gridEnabled),title:T("whiteboard.toggleGrid","Toggle grid"),"aria-label":T("whiteboard.toggleGrid","Toggle grid"),children:n.jsx(y.NiceIcon,{name:"hash",size:13})}),u&&n.jsx("button",{onClick:()=>H(x=>x==="vector"?null:"vector"),style:ue(!1,D==="vector"),title:T("whiteboard.vectorEditorPanel","Vector Editor panel"),"aria-label":T("whiteboard.vectorEditorPanel","Vector Editor panel"),children:n.jsx(y.NiceIcon,{name:"pen",size:13})}),p&&n.jsx("button",{onClick:()=>H(x=>x==="diagram"?null:"diagram"),style:ue(!1,D==="diagram"),title:T("whiteboard.diagramEditorPanel","Diagram Editor panel"),"aria-label":T("whiteboard.diagramEditorPanel","Diagram Editor panel"),children:n.jsx(y.NiceIcon,{name:"hexagon",size:13})}),n.jsx("button",{onClick:()=>void h.saveNow(),style:ue(),title:T("whiteboard.saveCtrlS","Save (Ctrl+S)"),"aria-label":T("whiteboard.save","Save"),children:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center"},children:[n.jsx(y.NiceIcon,{name:"save",size:13}),h.isDirty&&"*"]})}),o&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>_("png"),style:ue(),title:T("whiteboard.exportPng","Export PNG"),"aria-label":T("whiteboard.exportPng","Export PNG"),children:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:2},children:["PNG",n.jsx(y.NiceIcon,{name:"download",size:12})]})}),n.jsx("button",{onClick:()=>_("json"),style:ue(),title:T("whiteboard.exportJson","Export JSON"),"aria-label":T("whiteboard.exportJson","Export JSON"),children:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:2},children:[T("whiteboard.json","JSON"),n.jsx(y.NiceIcon,{name:"download",size:12})]})})]})]}),n.jsxs("div",{style:{display:"flex",flex:1,overflow:"hidden",position:"relative"},children:[n.jsx("canvas",{ref:C,style:{flex:1,display:"block",cursor:kn(h.activeTool,S.current.spaceDown)},onPointerDown:ie,onPointerMove:de,onPointerUp:ce,onWheel:xe,onContextMenu:x=>x.preventDefault()}),a&&U&&n.jsx(Sn,{layers:h.layers,objects:h.session.objects,onAdd:()=>h.addLayer(`Layer ${h.layers.length+1}`),onUpdate:x=>h.updateLayer(x),onDelete:x=>h.deleteLayer(x)}),D&&n.jsxs("div",{style:{position:"absolute",right:U?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:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[n.jsx("strong",{style:{fontSize:13},children:D==="vector"?T("whiteboard.vectorEditor","Vector Editor"):T("whiteboard.diagramEditor","Diagram Editor")}),n.jsx("button",{onClick:()=>H(null),style:{border:"none",background:"none",cursor:"pointer",fontSize:16},"aria-label":T("whiteboard.close","Close"),children:n.jsx(y.NiceIcon,{name:"close",size:16})})]}),n.jsx("p",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:D==="vector"?T("whiteboard.renderTheFullNice2devUi","Render the full @nice2dev/ui-graphics VectorEditor here. Pass the whiteboard's StorageConfig to persist edits and onOperation to broadcast strokes in real time."):T("whiteboard.renderTheFullNice2devUi2","Render the full @nice2dev/ui-diagrams NiceDiagramEditor here. Pass the collaborativeDiagram YDoc to enable simultaneous multi-user editing.")}),n.jsx("div",{id:`wb-integration-${D}`,style:{width:"100%",height:400}})]})]}),h.collaborators.length>1&&n.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:[n.jsx("span",{children:T("whiteboard.collaborators","Collaborators:")}),h.collaborators.map(x=>n.jsxs("span",{style:{display:"flex",alignItems:"center",gap:3},children:[n.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:x.color,display:"inline-block"}}),x.user.name]},x.user.id)),h.isDirty&&n.jsxs("span",{style:{marginLeft:"auto",color:"var(--nice-warning, #f59e0b)",display:"inline-flex",alignItems:"center",gap:3},children:[n.jsx(y.NiceIcon,{name:"circle",size:10})," ",T("whiteboard.unsaved","unsaved")]}),h.lastSavedAt&&!h.isDirty&&n.jsxs("span",{style:{marginLeft:"auto",color:"var(--nice-success, #10b981)",display:"inline-flex",alignItems:"center",gap:3},children:[n.jsx(y.NiceIcon,{name:"check",size:10})," ",T("whiteboard.saved","Saved {lastSavedAt}").replace("{lastSavedAt}",String(h.lastSavedAt.toLocaleTimeString()))]})]}),ee&&ae&&n.jsx("textarea",{autoFocus:!0,defaultValue:ee.text,onBlur:x=>{const v={...ee,text:x.target.value,updatedAt:new Date,updatedBy:e.id};h.updateObject(v),Z(null)},style:{position:"absolute",left:ae.sx,top:ae.sy,minWidth:ee.width*h.viewport.scale,minHeight:ee.height*h.viewport.scale,fontSize:(ee.fontSize??14)*h.viewport.scale,fontFamily:"sans-serif",background:ee.type==="sticky"?ee.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:ee.type==="sticky"?ee.textColor:ee.color}})]})}function Sn({layers:i,objects:e,onAdd:t,onUpdate:r,onDelete:s}){const{t:a}=y.useNiceTranslation();return n.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:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[n.jsx("strong",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:a("whiteboard.layers","Layers")}),n.jsx("button",{onClick:t,style:{fontSize:16,border:"none",background:"none",cursor:"pointer",color:"var(--nice-info, #6366f1)",display:"inline-flex",alignItems:"center"},title:a("whiteboard.addLayer","Add layer"),"aria-label":a("whiteboard.addLayer","Add layer"),children:n.jsx(y.NiceIcon,{name:"plus",size:16})})]}),[...i].reverse().map(o=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",borderRadius:5,background:"var(--nice-bg-secondary, #f9fafb)",opacity:o.visible?1:.5},children:[n.jsx("button",{onClick:()=>r({id:o.id,visible:!o.visible}),title:a("whiteboard.toggleVisibility","Toggle visibility"),"aria-label":a("whiteboard.toggleVisibility","Toggle visibility"),style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,display:"inline-flex",alignItems:"center",color:o.visible?"var(--nice-text, #374151)":"var(--nice-text-muted, #9ca3af)"},children:n.jsx(y.NiceIcon,{name:o.visible?"eye":"eye-off",size:13})}),n.jsx("button",{onClick:()=>r({id:o.id,locked:!o.locked}),title:a("whiteboard.toggleLock","Toggle lock"),"aria-label":a("whiteboard.toggleLock","Toggle lock"),style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,display:"inline-flex",alignItems:"center",opacity:o.locked?1:.5},children:n.jsx(y.NiceIcon,{name:"lock",size:13})}),n.jsx("span",{style:{flex:1,fontSize:11,color:"var(--nice-text, #374151)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o.name}),n.jsx("span",{style:{fontSize:10,color:"var(--nice-text-muted, #9ca3af)"},children:o.objectIds.filter(d=>d in e).length}),i.length>1&&n.jsx("button",{onClick:()=>s(o.id),title:a("whiteboard.deleteLayer","Delete layer"),"aria-label":a("whiteboard.deleteLayer","Delete layer"),style:{border:"none",background:"none",cursor:"pointer",fontSize:13,padding:0,display:"inline-flex",alignItems:"center",color:"var(--nice-danger, #ef4444)"},children:n.jsx(y.NiceIcon,{name:"trash",size:13})})]},o.id))]})}function ue(i=!1,e=!1){return{padding:"4px 8px",border:`1.5px solid ${e?"var(--nice-info, #6366f1)":"var(--nice-border, #e5e7eb)"}`,borderRadius:6,background:e?"var(--nice-primary-bg, #eef2ff)":"var(--nice-bg, #fff)",cursor:i?"default":"pointer",opacity:i?.35:1,fontSize:13,color:e?"var(--nice-accent, #4f46e5)":"var(--nice-text, #374151)",fontWeight:e?600:400}}function kn(i,e){if(e)return"grab";switch(i){case"pen":case"highlighter":return"crosshair";case"eraser":return"cell";case"select":return"default";case"text":return"text";case"laser":return"none";default:return"crosshair"}}const jn=[],Cn=[],In=[];function ve({icon:i,label:e,active:t,badge:r,onClick:s}){return n.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",gap:2},children:[n.jsxs("button",{title:e,onClick:s,style:{width:44,height:44,borderRadius:10,border:"none",background:t?"var(--nice-overlay-light-20, rgba(255, 255, 255, 0.2))":"transparent",color:"var(--nice-color-white, #fff)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",position:"relative"},children:[n.jsx(y.NiceIcon,{name:i,size:20}),r!=null&&r>0&&n.jsx("span",{style:{position:"absolute",top:4,right:4,background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700,lineHeight:1.4},children:r>99?"99+":r})]}),n.jsx("span",{style:{fontSize:9,color:"var(--nice-overlay-light-70, rgba(255, 255, 255, 0.7))",letterSpacing:"0.03em"},children:e})]})}function Tn({team:i,activeChannelId:e,onSelectChannel:t}){var o;const[r,s]=l.useState(!1),a=i.channels.reduce((d,u)=>d+u.unreadCount,0);return n.jsxs("div",{className:"nice-workspace-team",children:[n.jsxs("button",{onClick:()=>s(d=>!d),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:[n.jsx("span",{style:{color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:r?"chevron-right":"chevron-down",size:12})}),n.jsx("div",{style:{width:20,height:20,borderRadius:4,background:i.avatarUrl?`url(${i.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:9,flexShrink:0},children:!i.avatarUrl&&((o=i.name[0])==null?void 0:o.toUpperCase())}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.name}),!r&&a>0&&n.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:a})]}),!r&&i.channels.map(d=>n.jsxs("button",{onClick:()=>t(i.id,d.id),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 10px 5px 34px",background:d.id===e?"var(--nice-accent-tint-10, #ede9fe)":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:d.unreadCount>0?"var(--nice-text, #111827)":"var(--nice-text-secondary, #4b5563)",fontSize:13,fontWeight:d.unreadCount>0?600:400},children:[n.jsx("span",{style:{color:"var(--nice-text-muted, #9ca3af)",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:d.isPrivate?"lock":"hash",size:12})}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d.name}),d.mentionCount>0&&n.jsxs("span",{style:{background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 5px",fontWeight:700},children:["@",d.mentionCount]}),d.unreadCount>0&&d.mentionCount===0&&n.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700},children:d.unreadCount})]},d.id))]})}function zn({conversation:i,partner:e,isActive:t,onClick:r}){var a;const s=(e==null?void 0:e.displayName)??(e==null?void 0:e.name)??i.name??"Group";return n.jsxs("button",{onClick:r,style:{display:"flex",alignItems:"center",gap:8,padding:"5px 10px",background:t?"var(--nice-accent-tint-10, #ede9fe)":"transparent",border:"none",width:"100%",textAlign:"left",cursor:"pointer",color:i.unreadCount>0?"var(--nice-text, #111827)":"var(--nice-text-secondary, #4b5563)",fontWeight:i.unreadCount>0?600:400,fontSize:13},children:[n.jsxs("div",{style:{position:"relative",flexShrink:0},children:[n.jsx("div",{style:{width:24,height:24,borderRadius:"50%",background:e!=null&&e.avatarUrl?`url(${e.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:10},children:!(e!=null&&e.avatarUrl)&&((a=s[0])==null?void 0:a.toUpperCase())}),e&&n.jsx(he,{status:e.presence.status,size:"xs",style:{position:"absolute",bottom:-1,right:-1}})]}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),i.unreadCount>0&&n.jsx("span",{style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",borderRadius:10,fontSize:9,padding:"1px 4px",fontWeight:700,flexShrink:0},children:i.unreadCount})]})}function Et({currentUser:i,users:e=jn,teams:t=Cn,conversations:r=In,messages:s,activeCall:a,incomingCall:o,meetings:d,transport:u,rtcConfig:p,enableCalls:g=!0,enableMeetings:c=!0,enableScreenSharing:f=!0,enableWhiteboard:m=!1,storageConfig:w,onSendMessage:k,onEditMessage:T,onDeleteMessage:h,onReactToMessage:C,onPinMessage:A,onLoadMoreMessages:U,onMarkAsRead:M,onStartCall:P,onAcceptCall:G,onDeclineCall:F,onEndCall:L,onMuteAudio:N,onMuteVideo:z,onStartScreenShare:E,onStopScreenShare:V,className:J,style:j,id:O,"data-testid":Z}){var W,q;const{t:D}=y.useNiceTranslation(),[H,S]=l.useState("teams"),[b,Y]=l.useState(null),[X,Q]=l.useState(""),[K,ie]=l.useState(null),de=()=>{K||ie({id:`wb-workspace-${Date.now()}`,title:D("teamsWorkspace.teamWhiteboard","Team Whiteboard"),objects:{},layers:[{id:"layer-0",name:"Layer 1",visible:!0,locked:!1,objectIds:[]}],collaborators:{},viewport:{x:0,y:0,scale:1},width:4e3,height:3e3,backgroundColor:"#ffffff",gridEnabled:!0,gridSize:20,snapEnabled:!0,createdAt:new Date,updatedAt:new Date,ownerId:i.id,permissions:"edit"})},ce=l.useMemo(()=>{const I=new Map;return e.forEach(R=>I.set(R.id,R)),I},[e]),xe=l.useMemo(()=>et(r),[r]),_=l.useMemo(()=>r.reduce((I,R)=>I+R.mentionCount,0),[r]),ee=l.useMemo(()=>{if(b!=null&&b.channelId)for(const I of t){const R=I.channels.find(ne=>ne.id===b.channelId);if(R)return R}},[t,b]),ae=l.useMemo(()=>{if(b!=null&&b.teamId)return t.find(I=>I.id===b.teamId)},[t,b]),oe=l.useMemo(()=>r.find(I=>I.id===(b==null?void 0:b.conversationId))??null,[r,b]),le=l.useMemo(()=>{const I=(b==null?void 0:b.channelId)??(b==null?void 0:b.conversationId);return I?s[I]??[]:[]},[s,b]),x=!!o&&!a,v=!!a,$=l.useMemo(()=>r.filter(I=>I.type==="dm"||I.type==="group"),[r]),B=l.useMemo(()=>{if(!X)return $;const I=X.toLowerCase();return $.filter(R=>{var te;const ne=ce.get(R.participantIds.find(se=>se!==i.id)??"");return(ne==null?void 0:ne.name.toLowerCase().includes(I))||((te=R.name)==null?void 0:te.toLowerCase().includes(I))})},[$,X,ce,i.id]);return n.jsxs("div",{id:O,"data-testid":Z,className:`nice-teams-workspace${J?` ${J}`:""}`,style:{position:"relative",height:"100%",...j},children:[n.jsx(y.NiceAppShell,{flush:!0,height:"100%",className:"nice-teams-workspace__shell",style:{background:"var(--nice-bg, #fff)",overflow:"hidden"},sidebar:n.jsxs("div",{style:{display:"flex",height:"100%",minHeight:0},children:[n.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:[n.jsx("div",{style:{width:36,height:36,borderRadius:"50%",background:i.avatarUrl?`url(${i.avatarUrl}) center/cover`:"var(--nice-accent, #818cf8)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:14,marginBottom:8,flexShrink:0},children:!i.avatarUrl&&((W=i.name[0])==null?void 0:W.toUpperCase())}),n.jsx(ve,{icon:"zap",label:D("teamsWorkspace.activity","Activity"),active:H==="activity",badge:_,onClick:()=>S("activity")}),n.jsx(ve,{icon:"message",label:D("teamsWorkspace.chat","Chat"),active:H==="chat",badge:xe,onClick:()=>S("chat")}),n.jsx(ve,{icon:"users",label:D("teamsWorkspace.teams","Teams"),active:H==="teams",onClick:()=>S("teams")}),g&&n.jsx(ve,{icon:"phone",label:D("teamsWorkspace.calls","Calls"),active:H==="calls",onClick:()=>S("calls")}),c&&n.jsx(ve,{icon:"calendar",label:D("teamsWorkspace.meetings","Meetings"),active:H==="meetings",onClick:()=>S("meetings")}),n.jsx(ve,{icon:"folder",label:D("teamsWorkspace.files","Files"),active:H==="files",onClick:()=>S("files")}),m&&n.jsx(ve,{icon:"edit",label:D("teamsWorkspace.board","Board"),active:H==="whiteboard",onClick:()=>{S("whiteboard"),de()}})]}),n.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:[n.jsxs("div",{style:{padding:"12px 10px 8px",flexShrink:0},children:[n.jsx("div",{style:{fontWeight:700,fontSize:15,color:"var(--nice-text, #374151)",marginBottom:8,textTransform:"capitalize"},children:H}),n.jsx("input",{type:"search",value:X,onChange:I=>Q(I.target.value),placeholder:D("teamsWorkspace.search","Search {navSection}โฆ").replace("{navSection}",String(H)),style:{width:"100%",padding:"5px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:16,fontSize:12,boxSizing:"border-box",background:"var(--nice-bg, #fff)"}})]}),n.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[H==="teams"&&n.jsx(n.Fragment,{children:t.map(I=>n.jsx(Tn,{team:I,activeChannelId:b==null?void 0:b.channelId,onSelectChannel:(R,ne)=>{Y({type:"channel",teamId:R,channelId:ne}),M==null||M(ne)}},I.id))}),H==="chat"&&n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:"var(--nice-text-muted, #9ca3af)",fontWeight:600,letterSpacing:"0.05em"},children:D("teamsWorkspace.directMessages","DIRECT MESSAGES")}),B.map(I=>{const R=ce.get(I.participantIds.find(ne=>ne!==i.id)??"");return n.jsx(zn,{conversation:I,partner:R,isActive:(b==null?void 0:b.conversationId)===I.id,onClick:()=>{Y({type:I.type==="dm"?"dm":"group",conversationId:I.id}),M==null||M(I.id)}},I.id)})]}),H==="activity"&&n.jsxs("div",{style:{padding:12},children:[r.filter(I=>I.unreadCount>0).map(I=>n.jsxs("button",{onClick:()=>{S(I.type==="channel"?"teams":"chat"),Y({type:I.type==="channel"?"channel":"dm",conversationId:I.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:[n.jsx("strong",{children:I.name??D("teamsWorkspace.conversation","Conversation")})," ",D("teamsWorkspace.unread","โ {unreadCount} unread").replace("{unreadCount}",String(I.unreadCount))]},I.id)),r.every(I=>I.unreadCount===0)&&n.jsxs("p",{style:{color:"var(--nice-text-muted, #9ca3af)",fontSize:13,textAlign:"center",marginTop:24,display:"flex",alignItems:"center",justifyContent:"center",gap:4},children:[D("teamsWorkspace.allCaughtUp","All caught up")," ",n.jsx(y.NiceIcon,{name:"check",size:13})]})]}),H==="calls"&&n.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8},children:[n.jsxs("button",{onClick:()=>P==null?void 0:P(e.map(I=>I.id).filter(I=>I!==i.id),"audio"),style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[n.jsx(y.NiceIcon,{name:"phone",size:14})," ",D("teamsWorkspace.newAudioCall","New audio call")]}),n.jsxs("button",{onClick:()=>P==null?void 0:P(e.map(I=>I.id).filter(I=>I!==i.id),"video"),style:{background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[n.jsx(y.NiceIcon,{name:"video",size:14})," ",D("teamsWorkspace.newVideoCall","New video call")]})]}),H==="meetings"&&n.jsxs("div",{style:{padding:12},children:[(d??[]).map(I=>n.jsxs("div",{style:{padding:"8px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,marginBottom:8},children:[n.jsx("div",{style:{fontWeight:600,fontSize:13},children:I.title}),n.jsx("div",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginTop:2},children:I.scheduledStart.toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}),n.jsx("button",{onClick:()=>{},style:{marginTop:6,background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:6,padding:"3px 10px",fontSize:12,cursor:"pointer"},children:D("teamsWorkspace.join","Join")})]},I.id)),(d??[]).length===0&&n.jsx("p",{style:{color:"var(--nice-text-muted, #9ca3af)",fontSize:13,textAlign:"center",marginTop:24},children:D("teamsWorkspace.noUpcomingMeetings","No upcoming meetings")})]}),H==="files"&&n.jsx("div",{style:{padding:12},children:n.jsx("p",{style:{color:"var(--nice-text-muted, #9ca3af)",fontSize:13,textAlign:"center",marginTop:24},children:D("teamsWorkspace.noFilesSharedYet","No files shared yet")})}),H==="whiteboard"&&n.jsxs("div",{style:{padding:12},children:[n.jsxs("button",{onClick:()=>de(),style:{width:"100%",background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px 12px",cursor:"pointer",fontSize:13,fontWeight:600,marginBottom:8,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[n.jsx(y.NiceIcon,{name:"edit",size:14})," ",K?D("teamsWorkspace.openWhiteboard","Open whiteboard"):D("teamsWorkspace.newWhiteboard","New whiteboard")]}),K&&n.jsxs("div",{style:{padding:"6px 10px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,fontSize:12,color:"var(--nice-text, #374151)"},children:[n.jsx("div",{style:{fontWeight:500},children:K.title}),n.jsx("div",{style:{color:"var(--nice-text-muted, #9ca3af)",marginTop:2},children:D("teamsWorkspace.objects","{objects} objects").replace("{objects}",String(Object.keys(K.objects).length))})]})]})]})]})]}),children:n.jsxs("div",{style:{flex:1,height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[(b==null?void 0:b.type)==="channel"&&ee?n.jsx(It,{channel:ee,messages:le,users:(ae==null?void 0:ae.members)??e,currentUser:i,team:ae,onSendMessage:k,onEditMessage:T,onDeleteMessage:h,onReactToMessage:C,onPinMessage:A,onLoadMoreMessages:U,onStartCall:g?P:void 0,style:{height:"100%"}}):((b==null?void 0:b.type)==="dm"||(b==null?void 0:b.type)==="group")&&oe?n.jsx(Re,{conversation:oe,messages:le,users:e,currentUser:i,onSendMessage:k,onEditMessage:T,onDeleteMessage:h,onReactToMessage:C,onPinMessage:A,onLoadMoreMessages:U,onStartCall:g?P:void 0,style:{height:"100%"}}):H==="whiteboard"&&K?n.jsx(rt,{session:K,currentUser:i,storageConfig:w,onSessionUpdate:I=>ie(I),style:{height:"100%"}}):n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",color:"var(--nice-text-muted, #9ca3af)",gap:12},children:[n.jsx(y.NiceIcon,{name:H==="teams"?"users":H==="chat"?"message":H==="calls"?"phone":H==="whiteboard"?"edit":"zap",size:56}),n.jsx("span",{style:{fontSize:17,fontWeight:500},children:H==="teams"?D("teamsWorkspace.selectAChannelToGet","Select a channel to get started"):H==="chat"?D("teamsWorkspace.selectAConversation","Select a conversation"):H==="calls"?D("teamsWorkspace.startOrJoinACall","Start or join a call"):H==="whiteboard"?D("teamsWorkspace.clickNewWhiteboardToStart",'Click "New whiteboard" to start'):D("teamsWorkspace.nothingSelected","Nothing selected")})]}),v&&a&&n.jsx("div",{style:{position:"absolute",inset:0,zIndex:50},children:a.participants.length>2?n.jsx(nt,{session:a,currentUser:i,enableScreenSharing:f,onEndCall:L,onMuteAudio:N,onMuteVideo:z,onStartScreenShare:E,onStopScreenShare:V}):n.jsx(tt,{session:a,currentUser:i,enableScreenSharing:f,onEndCall:L,onMuteAudio:N,onMuteVideo:z,onStartScreenShare:E,onStopScreenShare:V})})]})}),x&&o&&n.jsxs("div",{style:{position:"absolute",top:16,right:16,width:300,background:"var(--nice-text, #1f2937)",borderRadius:12,padding:16,boxShadow:"0 8px 32px var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",zIndex:100,color:"var(--nice-text-inverse, #fff)"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:12},children:[n.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:o.caller.avatarUrl?`url(${o.caller.avatarUrl}) center/cover`:"var(--nice-info, #6366f1)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-primary, #fff)",fontWeight:700,fontSize:16},children:!o.caller.avatarUrl&&((q=o.caller.name[0])==null?void 0:q.toUpperCase())}),n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:o.caller.displayName??o.caller.name}),n.jsx("div",{style:{fontSize:12,color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"},children:D("teamsWorkspace.incomingCall","Incoming {callType} call").replace("{callType}",String(o.callType))})]})]}),n.jsxs("div",{style:{display:"flex",gap:8},children:[n.jsxs("button",{onClick:()=>F==null?void 0:F(o.callId),style:{flex:1,background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[n.jsx(y.NiceIcon,{name:"phone",size:14})," ",D("teamsWorkspace.decline","Decline")]}),n.jsxs("button",{onClick:()=>G==null?void 0:G(o.callId),style:{flex:1,background:"var(--nice-success, #22c55e)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:8,padding:"8px",cursor:"pointer",fontWeight:600,fontSize:13,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6},children:[n.jsx(y.NiceIcon,{name:"phone",size:14})," ",D("teamsWorkspace.accept","Accept")]})]})]})]})}const Rt=[],Nn={"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 En({props:i,onExpand:e}){const{t}=y.useNiceTranslation(),[r,s]=l.useState(!1),{bubblePosition:a="bottom-right",bubbleLabel:o,currentUser:d,users:u=Rt,conversations:p=[],messages:g={},activeConversationId:c,onSendMessage:f,onReactToMessage:m,onPinMessage:w,onDeleteMessage:k,onEditMessage:T,onLoadMoreMessages:h,onStartCall:C}=i,A=Nn[a],U=p.find(P=>P.id===c)??p[0]??null,M=U?g[U.id]??[]:[];return n.jsxs("div",{style:{position:"fixed",zIndex:9999,...A},children:[r&&U&&n.jsxs("div",{style:{position:"absolute",bottom:a.startsWith("bottom")?64:void 0,top:a.startsWith("top")?64:void 0,right:a.endsWith("right")?0:void 0,left:a.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:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px",background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)",flexShrink:0},children:[n.jsx("span",{style:{fontWeight:700,fontSize:15},children:o??t("communication.chat","Chat")}),n.jsxs("div",{style:{display:"flex",gap:4},children:[n.jsx("button",{onClick:()=>e("messenger"),title:t("communication.openFullChat","Open full chat"),"aria-label":t("communication.openFullChat","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-color-white, #fff)",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"expand",size:13})}),n.jsx("button",{onClick:()=>s(!1),title:t("communication.close","Close"),"aria-label":t("communication.close","Close"),style:{background:"none",border:"none",color:"var(--nice-text-primary, #fff)",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:"close",size:18})})]})]}),n.jsx(Re,{conversation:U,messages:M,users:u,currentUser:d,showHeader:!1,onSendMessage:f,onEditMessage:T,onDeleteMessage:k,onReactToMessage:m,onPinMessage:w,onLoadMoreMessages:h,onStartCall:C,style:{flex:1}})]}),n.jsx("button",{onClick:()=>s(P=>!P),style:{width:56,height:56,borderRadius:"50%",background:"var(--nice-info, #6366f1)",border:"none",boxShadow:"0 4px 16px var(--nice-accent-tint-40, rgba(99, 102, 241, 0.4))",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--nice-text-on-primary, #fff)",transition:"transform 0.15s"},title:r?t("communication.closeChat","Close chat"):o??t("communication.openChat","Open chat"),"aria-label":r?t("communication.closeChat","Close chat"):o??t("communication.openChat","Open chat"),children:n.jsx(y.NiceIcon,{name:r?"close":"message",size:24})})]})}function Rn({call:i,onAccept:e,onDecline:t}){const{t:r}=y.useNiceTranslation();return n.jsxs("div",{style:{position:"fixed",top:16,left:"50%",transform:"translateX(-50%)",zIndex:9998,background:"var(--nice-text, #1f2937)",color:"var(--nice-text-inverse, #fff)",borderRadius:12,padding:"12px 20px",boxShadow:"0 8px 32px var(--nice-overlay-40, rgba(0, 0, 0, 0.4))",display:"flex",alignItems:"center",gap:16,minWidth:280},children:[n.jsx("div",{style:{display:"flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:i.callType==="video"?"video":"phone",size:28})}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:600,fontSize:14},children:i.caller.displayName??i.caller.name}),n.jsx("div",{style:{fontSize:12,color:"var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"},children:r("communication.incomingCall","Incoming {callType} callโฆ").replace("{callType}",String(i.callType))})]}),n.jsx("button",{onClick:t,style:{background:"var(--nice-danger, #ef4444)",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",color:"var(--nice-text-on-primary, #fff)",display:"inline-flex",alignItems:"center",justifyContent:"center"},title:r("communication.decline","Decline"),"aria-label":r("communication.decline","Decline"),children:n.jsx(y.NiceIcon,{name:"phone",size:18})}),n.jsx("button",{onClick:e,style:{background:"var(--nice-success, #22c55e)",border:"none",borderRadius:"50%",width:38,height:38,cursor:"pointer",color:"var(--nice-text-on-primary, #fff)",display:"inline-flex",alignItems:"center",justifyContent:"center"},title:r("communication.accept","Accept"),"aria-label":r("communication.accept","Accept"),children:n.jsx(y.NiceIcon,{name:"phone",size:18})})]})}function Pt(i){const{t:e}=y.useNiceTranslation(),{mode:t,currentUser:r,users:s=Rt,conversations:a=[],messages:o={},activeConversationId:d,teams:u=[],meetings:p,activeCall:g,incomingCall:c,transport:f="webrtc",rtcConfig:m,onSendMessage:w,onEditMessage:k,onDeleteMessage:T,onReactToMessage:h,onPinMessage:C,onLoadMoreMessages:A,onMarkAsRead:U,onStartCall:M,onAcceptCall:P,onDeclineCall:G,onEndCall:F,onMuteAudio:L,onMuteVideo:N,onStartScreenShare:z,onStopScreenShare:E,onRaiseHand:V,onModeChange:J,enableScreenSharing:j=!0,enableMeetings:O=!0,enableWhiteboard:Z=!1,storageConfig:D,encryptionConfig:H,className:S,style:b,id:Y,"data-testid":X}=i,[Q,K]=l.useState(t),[ie,de]=l.useState(null),ce=l.useMemo(()=>({id:`wb-${r.id}-${Date.now()}`,title:e("communication.whiteboard","Whiteboard"),objects:{},layers:[{id:"layer-0",name:"Layer 1",visible:!0,locked:!1,objectIds:[]}],collaborators:{},viewport:{x:0,y:0,scale:1},width:4e3,height:3e3,backgroundColor:"#ffffff",gridEnabled:!0,gridSize:20,snapEnabled:!0,createdAt:new Date,updatedAt:new Date,ownerId:r.id,permissions:"edit"}),[r.id,e]),[xe,_]=l.useState(g??null),[ee,ae]=l.useState(c??null),oe=g??xe,le=c??ee;l.useEffect(()=>{K(t)},[t]),l.useEffect(()=>{g!==void 0&&_(g)},[g]),l.useEffect(()=>{c!==void 0&&ae(c)},[c]);const{state:x,startCall:v,acceptCall:$,declineCall:B,endCall:W,toggleMic:q,toggleCamera:I,startScreenShare:R,stopScreenShare:ne}=jt({currentUser:r,transport:f,rtcConfig:m,onCallEnded:re=>{_(null),F==null||F(re)},onIncomingCall:re=>{ae(re)}}),te=l.useCallback(re=>{K(re),J==null||J(re)},[J]),se=l.useCallback(async(re,ct)=>{if(M){await M(re,ct);return}const Ht=await v(re,ct);_(Ht),K(re.length>2?"conference":"call")},[M,v]),pe=l.useCallback(async()=>{var re;P&&le?await P(le.callId):await $(),ae(null),K((re=x.activeCall)!=null&&re.participants&&x.activeCall.participants.length>2?"conference":"call")},[P,le,$,x.activeCall]),me=l.useCallback(()=>{G&&le?G(le.callId):B(),ae(null)},[G,le,B]),fe=l.useCallback(re=>{F?F(re):W(),_(null),K(t)},[F,W,t]),Pe=l.useCallback(re=>{q(),L==null||L(re)},[q,L]),lt=l.useCallback(re=>{I(),N==null||N(re)},[I,N]),Ae=l.useCallback(async()=>{await R(),await(z==null?void 0:z())},[R,z]),Fe=l.useCallback(()=>{ne(),E==null||E()},[ne,E]),Te={onSendMessage:w,onEditMessage:k,onDeleteMessage:T,onReactToMessage:h,onPinMessage:C,onLoadMoreMessages:A,onMarkAsRead:U,onStartCall:se,onEndCall:fe,onMuteAudio:Pe,onMuteVideo:lt,onStartScreenShare:Ae,onStopScreenShare:Fe,onRaiseHand:V},_e=a.find(re=>re.id===d)??a[0],ge=oe?oe.participants.length>2?"conference":"call":Q,Ut={width:"100%",height:"100%",position:"relative",...b};return n.jsxs("div",{id:Y,"data-testid":X,className:`nice-communication nice-communication--${ge}${S?` ${S}`:""}`,style:Ut,children:[le&&ge!=="workspace"&&n.jsx(Rn,{call:le,onAccept:pe,onDecline:me}),ge==="bubble"&&n.jsx(En,{props:i,onExpand:te}),ge==="chat"&&_e&&n.jsx(Re,{conversation:_e,messages:o[_e.id]??[],users:s,currentUser:r,...Te,style:{height:"100%"}}),ge==="messenger"&&n.jsx(Ct,{conversations:a,messages:o,activeConversationId:d,users:s,currentUser:r,teams:u,...Te,onAcceptCall:P,onDeclineCall:G,style:{height:"100%"}}),ge==="workspace"&&n.jsx(Et,{currentUser:r,users:s,teams:u,conversations:a,messages:o,meetings:p,activeCall:oe??void 0,incomingCall:le??void 0,transport:f,rtcConfig:m,enableCalls:!0,enableMeetings:O,enableScreenSharing:j,...Te,onAcceptCall:pe,onDeclineCall:me,style:{height:"100%"}}),ge==="call"&&oe&&n.jsx(tt,{session:oe,currentUser:r,localStream:x.localStream??void 0,enableScreenSharing:j,...Te,style:{height:"100%"}}),ge==="conference"&&oe&&n.jsx(nt,{session:oe,currentUser:r,localStream:x.localStream??void 0,enableScreenSharing:j,...Te,style:{height:"100%"}}),ge==="whiteboard"&&Z&&n.jsx(rt,{session:ie??ce,currentUser:r,storageConfig:D,onSessionUpdate:re=>de(re),style:{height:"100%"}})]})}const Pn={messages:"Messages",attachments:"Attachments","whiteboard-snapshots":"Whiteboard snapshots",recordings:"Recordings",transcripts:"Transcripts",documents:"Documents","call-logs":"Call logs","audit-logs":"Audit logs"},ft={none:"No encryption","AES-GCM-128":"AES-GCM 128-bit","AES-GCM-256":"AES-GCM 256-bit (recommended)","ChaCha20-Poly1305":"ChaCha20-Poly1305","E2E-ECDH-P384":"End-to-End ECDH P-384"},An={messages:"Messages",attachments:"Attachments",whiteboard:"Whiteboard",recordings:"Recordings",documents:"Documents",calls:"Calls (metadata)",presence:"Presence data",all:"Everything"},Dn=["days","weeks","months","years","forever"];function gt(i){if(i===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],r=Math.floor(Math.log(i)/Math.log(e));return`${(i/Math.pow(e,r)).toFixed(1)} ${t[r]}`}function mt({value:i,onChange:e,disabled:t=!1}){return n.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[n.jsx("input",{type:"number",min:1,max:9999,value:i.unit==="forever"?"":i.value,disabled:t||i.unit==="forever",onChange:r=>e({...i,value:Math.max(1,Number(r.target.value))}),style:{width:60,padding:"3px 6px",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:5,fontSize:12}}),n.jsx("select",{value:i.unit,disabled:t,onChange:r=>e({...i,unit:r.target.value}),style:{padding:"3px 6px",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:5,fontSize:12},children:Dn.map(r=>n.jsx("option",{value:r,children:r},r))})]})}function Mn({config:i,onChange:e}){const{t}=y.useNiceTranslation(),r=i.retentionRules.length>0?i.retentionRules:it;function s(a,o){const d=r.map(u=>u.dataType===a?{...u,...o}:u);e({...i,retentionRules:d})}return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[n.jsx("p",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",margin:0},children:t("storageSettings.configureHowLongEachData","Configure how long each data type is retained before archiving and eventual deletion. Legal-hold prevents deletion regardless of retention rules.")}),n.jsxs("div",{style:Ce,children:[n.jsx("label",{style:Ie,children:t("storageSettings.storageProvider","Storage provider")}),n.jsxs("select",{value:i.provider,onChange:a=>e({...i,provider:a.target.value}),style:we,children:[n.jsx("option",{value:"indexeddb",children:t("storageSettings.indexeddbBrowser","IndexedDB (browser)")}),n.jsx("option",{value:"localstorage",children:t("storageSettings.localstorageBrowser","LocalStorage (browser)")}),n.jsx("option",{value:"server",children:t("storageSettings.server","Server")}),n.jsx("option",{value:"custom",children:t("storageSettings.customAdapter","Custom adapter")})]})]}),i.provider==="server"&&n.jsxs("div",{style:Ce,children:[n.jsx("label",{style:Ie,children:t("storageSettings.serverUrl","Server URL")}),n.jsx("input",{type:"url",value:i.serverUrl??"",onChange:a=>e({...i,serverUrl:a.target.value}),placeholder:"https://your-api.example.com/storage",style:we})]}),n.jsx("hr",{style:{border:"none",borderTop:"1px solid var(--nice-border, #e5e7eb)",margin:"4px 0"}}),n.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12},children:[n.jsx("thead",{children:n.jsxs("tr",{style:{background:"var(--nice-bg-secondary, #f9fafb)"},children:[n.jsx("th",{style:ke,children:t("storageSettings.dataType","Data type")}),n.jsx("th",{style:ke,children:t("storageSettings.activePeriod","Active period")}),n.jsx("th",{style:ke,children:t("storageSettings.archiveAfter","Archive after")}),n.jsx("th",{style:ke,children:t("storageSettings.autoDelete","Auto-delete")}),n.jsx("th",{style:ke,children:t("storageSettings.userCanDelete","User can delete")}),n.jsx("th",{style:ke,children:t("storageSettings.legalHold","Legal hold")})]})}),n.jsx("tbody",{children:r.map(a=>n.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)"},children:[n.jsx("td",{style:{...je,fontWeight:500,color:"var(--nice-text, #374151)"},children:Pn[a.dataType]}),n.jsx("td",{style:je,children:n.jsx(mt,{value:a.activePeriod,onChange:o=>s(a.dataType,{activePeriod:o})})}),n.jsx("td",{style:je,children:a.archivePeriod?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx(mt,{value:a.archivePeriod,onChange:o=>s(a.dataType,{archivePeriod:o})}),n.jsx("button",{onClick:()=>s(a.dataType,{archivePeriod:void 0}),style:{border:"none",background:"none",cursor:"pointer",color:"var(--nice-danger, #ef4444)",display:"inline-flex",alignItems:"center"},title:t("storageSettings.removeArchivePeriod","Remove archive period"),"aria-label":t("storageSettings.removeArchivePeriod","Remove archive period"),children:n.jsx(y.NiceIcon,{name:"close",size:14})})]}):n.jsxs("button",{onClick:()=>s(a.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:[n.jsx(y.NiceIcon,{name:"plus",size:11})," ",t("storageSettings.add","Add")]})}),n.jsx("td",{style:{...je,textAlign:"center"},children:n.jsx("input",{type:"checkbox",checked:a.deleteAfterArchive,disabled:!a.archivePeriod,onChange:o=>s(a.dataType,{deleteAfterArchive:o.target.checked})})}),n.jsx("td",{style:{...je,textAlign:"center"},children:n.jsx("input",{type:"checkbox",checked:a.userCanDelete,onChange:o=>s(a.dataType,{userCanDelete:o.target.checked})})}),n.jsx("td",{style:{...je,textAlign:"center"},children:n.jsx("input",{type:"checkbox",checked:a.legalHoldEnabled??!1,onChange:o=>s(a.dataType,{legalHoldEnabled:o.target.checked})})})]},a.dataType))})]}),n.jsxs("div",{style:Ce,children:[n.jsx("label",{style:Ie,children:t("storageSettings.storageQuota","Storage quota")}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx("input",{type:"number",min:0,value:i.quota?Math.round(i.quota/1024/1024):0,onChange:a=>e({...i,quota:Number(a.target.value)*1024*1024}),style:{...we,width:90},placeholder:"0"}),n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:t("storageSettings.mb0Unlimited","MB (0 = unlimited)")})]})]})]})}function Wn({config:i,onChange:e}){const{t}=y.useNiceTranslation(),r=["messages","attachments","whiteboard","recordings","documents","calls","presence"];return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[n.jsx("p",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",margin:0},children:t("storageSettings.configureEncryptionAtRestAnd","Configure encryption at rest and in transit. E2E-ECDH ensures only participants can read conversations โ the server never sees plaintext.")}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsxs("label",{style:{position:"relative",display:"inline-block",width:42,height:22},children:[n.jsx("input",{type:"checkbox",checked:i.enabled,onChange:s=>e({...i,enabled:s.target.checked}),style:{opacity:0,width:0,height:0}}),n.jsx("span",{style:{position:"absolute",inset:0,borderRadius:22,background:i.enabled?"var(--nice-info, #6366f1)":"var(--nice-border, #d1d5db)",transition:"background 0.2s",cursor:"pointer"},children:n.jsx("span",{style:{position:"absolute",width:16,height:16,top:3,left:i.enabled?23:3,background:"var(--nice-bg, #fff)",borderRadius:"50%",transition:"left 0.2s"}})})]}),n.jsxs("span",{style:{fontSize:13,fontWeight:500,color:"var(--nice-text, #374151)",display:"inline-flex",alignItems:"center",gap:5},children:[n.jsx(y.NiceIcon,{name:"lock",size:14})," ",i.enabled?t("storageSettings.encryptionEnabled","Encryption enabled"):t("storageSettings.encryptionDisabled","Encryption disabled")]})]}),i.enabled&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:Ce,children:[n.jsx("label",{style:Ie,children:t("storageSettings.defaultAlgorithm","Default algorithm")}),n.jsx("select",{value:i.defaultAlgorithm,onChange:s=>e({...i,defaultAlgorithm:s.target.value}),style:we,children:Object.entries(ft).map(([s,a])=>n.jsx("option",{value:s,children:a},s))})]}),i.defaultAlgorithm==="E2E-ECDH-P384"&&n.jsxs("div",{style:Ce,children:[n.jsx("label",{style:Ie,children:t("storageSettings.keyExchangeUrl","Key exchange URL")}),n.jsx("input",{type:"url",value:i.keyExchangeUrl??"",onChange:s=>e({...i,keyExchangeUrl:s.target.value}),placeholder:t("storageSettings.wssYourServerE2eKey","wss://your-server/e2e-key-exchange"),style:we}),n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginTop:2},children:t("storageSettings.websocketEndpointForEcdhPublic","WebSocket endpoint for ECDH public key exchange between participants.")})]}),n.jsxs("div",{style:Ce,children:[n.jsx("label",{style:Ie,children:t("storageSettings.externalKeyBase64Optional","External key (base64, optional)")}),n.jsx("input",{type:"password",value:i.keyMaterial??"",onChange:s=>e({...i,keyMaterial:s.target.value||void 0}),placeholder:t("storageSettings.leaveEmptyToAutoGenerate","Leave empty to auto-generate"),style:we}),n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #6b7280)",marginTop:2},children:t("storageSettings.provideAPreSharedKey","Provide a pre-shared key for symmetric algorithms. Leave empty for automatic key generation.")})]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:i.showIndicator??!0,onChange:s=>e({...i,showIndicator:s.target.checked})}),n.jsx("span",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:t("storageSettings.showLockIndicatorInMessages","Show lock indicator in messages")})]}),n.jsx("hr",{style:{border:"none",borderTop:"1px solid var(--nice-border, #e5e7eb)",margin:"4px 0"}}),n.jsx("strong",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:t("storageSettings.perScopeOverrides","Per-scope overrides")}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:r.map(s=>{var u;const a=(u=i.scopeOverrides)==null?void 0:u.find(p=>p.scope===s),o=(a==null?void 0:a.enabled)??!1,d=(a==null?void 0:a.algorithm)??i.defaultAlgorithm;return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 8px",background:"var(--nice-bg-secondary, #f9fafb)",borderRadius:6},children:[n.jsx("input",{type:"checkbox",checked:o,onChange:p=>{const g=[...(i.scopeOverrides??[]).filter(c=>c.scope!==s),{scope:s,algorithm:d,enabled:p.target.checked}];e({...i,scopeOverrides:g})}}),n.jsx("span",{style:{minWidth:120,fontSize:12,color:"var(--nice-text, #374151)"},children:An[s]}),n.jsx("select",{value:d,disabled:!o,onChange:p=>{const g=[...(i.scopeOverrides??[]).filter(c=>c.scope!==s),{scope:s,algorithm:p.target.value,enabled:o}];e({...i,scopeOverrides:g})},style:{...we,flex:1,opacity:o?1:.4},children:Object.entries(ft).map(([p,g])=>n.jsx("option",{value:p,children:g},p))})]},s)})})]})]})}function On({storageConfig:i,defaultStorageConfig:e,encryptionConfig:t,onStorageConfigChange:r,onEncryptionConfigChange:s,currentUsageBytes:a=0,showEncryption:o=!0,showRetention:d=!0,showQuota:u=!0,className:p,style:g,"data-testid":c}){const{t:f}=y.useNiceTranslation(),[m,w]=l.useState("retention"),[k,T]=y.useControllableState({value:i,defaultValue:e,fallbackValue:{provider:"indexeddb",retentionRules:[]},onChange:r,componentName:"NiceStorageSettings"}),h=t??{enabled:!1,defaultAlgorithm:"AES-GCM-256",showIndicator:!0},C={...k,retentionRules:k.retentionRules.length>0?k.retentionRules:it};return n.jsxs("div",{className:p,"data-testid":c,style:{display:"flex",flexDirection:"column",gap:16,padding:20,background:"var(--nice-bg, #fff)",borderRadius:10,border:"1px solid var(--nice-border, #e5e7eb)",fontFamily:"system-ui, sans-serif",maxWidth:800,...g},children:[n.jsxs("div",{children:[n.jsx("h3",{style:{margin:0,fontSize:16,color:"var(--nice-text, #111827)"},children:f("storageSettings.storagePrivacy","Storage & Privacy")}),n.jsx("p",{style:{margin:"4px 0 0",fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:f("storageSettings.manageDataRetentionEncryptionAnd","Manage data retention, encryption, and storage settings.")})]}),u&&k.quota&&k.quota>0&&n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:12,color:"var(--nice-text-secondary, #6b7280)",marginBottom:4},children:[n.jsx("span",{children:f("storageSettings.storageUsed","Storage used")}),n.jsxs("span",{children:[gt(a)," / ",gt(k.quota)]})]}),n.jsx("div",{style:{height:6,background:"var(--nice-border, #e5e7eb)",borderRadius:3},children:n.jsx("div",{style:{width:`${Math.min(100,a/k.quota*100)}%`,height:"100%",background:a/k.quota>.9?"var(--nice-danger, #ef4444)":"var(--nice-info, #6366f1)",borderRadius:3,transition:"width 0.3s"}})})]}),d&&o&&n.jsx("div",{style:{display:"flex",gap:0,borderBottom:"1px solid var(--nice-border, #e5e7eb)"},children:["retention","encryption"].map(A=>n.jsx("button",{onClick:()=>w(A),style:{padding:"8px 18px",border:"none",borderBottom:`2px solid ${m===A?"var(--nice-info, #6366f1)":"transparent"}`,background:"none",cursor:"pointer",fontSize:13,fontWeight:m===A?600:400,color:m===A?"var(--nice-accent, #4f46e5)":"var(--nice-text-secondary, #6b7280)",marginBottom:-1,display:"inline-flex",alignItems:"center",gap:6},children:A==="retention"?n.jsxs(n.Fragment,{children:[n.jsx(y.NiceIcon,{name:"archive",size:13})," ",f("storageSettings.retention","Retention")]}):n.jsxs(n.Fragment,{children:[n.jsx(y.NiceIcon,{name:"lock",size:13})," ",f("storageSettings.encryption","Encryption")]})},A))}),n.jsxs("div",{children:[(m==="retention"||!o)&&d&&n.jsx(Mn,{config:C,onChange:T}),(m==="encryption"||!d)&&o&&n.jsx(Wn,{config:h,onChange:s??(()=>{})})]})]})}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)"},ke={padding:"6px 8px",textAlign:"left",fontSize:11,fontWeight:600,color:"var(--nice-text-secondary, #6b7280)",borderBottom:"1px solid var(--nice-border, #e5e7eb)"},je={padding:"8px 8px",verticalAlign:"middle"};function Le(i){const e=Math.floor(i/1e3),t=Math.floor(e/60),r=Math.floor(t/60);return r>0?`${r}:${String(t%60).padStart(2,"0")}:${String(e%60).padStart(2,"0")}`:`${String(t).padStart(2,"0")}:${String(e%60).padStart(2,"0")}`}function $n(i){if(i===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],r=Math.floor(Math.log(i)/Math.log(e));return`${(i/Math.pow(e,r)).toFixed(1)} ${t[r]}`}function Ln(i,e){return new Intl.DateTimeFormat(e,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(i))}const Fn=(i,e)=>i(`recording.state.${e}`,At[e].label),At={idle:{label:"Idle",icon:null,bg:"var(--nice-bg-secondary, #f3f4f6)",fg:"var(--nice-text-secondary, #6b7280)"},recording:{label:"Recording",icon:"circle",bg:"var(--nice-danger-bg, #fee2e2)",fg:"var(--nice-danger-dark, #dc2626)"},paused:{label:"Paused",icon:"pause",bg:"var(--nice-warning-bg, #fef3c7)",fg:"var(--nice-warning-dark, #d97706)"},processing:{label:"Processing",icon:"clock",bg:"var(--nice-accent-tint-10, #ede9fe)",fg:"var(--nice-accent, #7c3aed)"},ready:{label:"Ready",icon:"check",bg:"var(--nice-success-bg, #dcfce7)",fg:"var(--nice-success-dark, #16a34a)"},failed:{label:"Failed",icon:"close",bg:"var(--nice-danger-bg, #fee2e2)",fg:"var(--nice-danger-dark, #dc2626)"}};function _n({segments:i,onClose:e,currentTimeMs:t=0}){const{t:r}=y.useNiceTranslation();return n.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:n.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:[n.jsxs("div",{style:{padding:"14px 18px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("strong",{style:{fontSize:14,color:"var(--nice-text, #111827)"},children:r("recording.transcript","Transcript")}),n.jsx("button",{onClick:e,style:Hn,"aria-label":r("recording.close","Close"),children:n.jsx(y.NiceIcon,{name:"close",size:16})})]}),n.jsx("div",{style:{flex:1,overflowY:"auto",padding:"12px 18px"},children:i.length===0?n.jsx("p",{style:{fontSize:13,color:"var(--nice-text-muted, #9ca3af)",textAlign:"center",padding:"32px 0"},children:r("recording.noTranscript","No transcript available.")}):i.map(s=>{const a=t>=s.startMs&&t<s.endMs;return n.jsxs("div",{style:{marginBottom:12,padding:"8px 10px",borderRadius:6,background:a?"var(--nice-primary-bg, #eff6ff)":"transparent",borderLeft:`3px solid ${a?"var(--nice-primary, #3b82f6)":"transparent"}`,transition:"background 0.2s"},children:[n.jsxs("div",{style:{display:"flex",gap:10,alignItems:"baseline",marginBottom:3},children:[n.jsx("span",{style:{fontSize:11,fontWeight:600,color:"var(--nice-accent, #4f46e5)"},children:s.speakerName}),n.jsxs("span",{style:{fontSize:10,color:"var(--nice-text-muted, #9ca3af)"},children:[Le(s.startMs)," โ ",Le(s.endMs)]}),n.jsx("span",{style:{fontSize:10,color:"var(--nice-text-secondary, #d1d5db)"},children:r("recording.conf","{confidence}% conf.").replace("{confidence}",String(Math.round(s.confidence*100)))})]}),n.jsx("p",{style:{margin:0,fontSize:13,color:"var(--nice-text, #374151)",lineHeight:1.5},children:s.text})]},s.id)})})]})})}function Dt({startedAt:i}){const[e,t]=l.useState(0);return l.useEffect(()=>{const r=new Date(i).getTime(),s=setInterval(()=>t(Date.now()-r),500);return()=>clearInterval(s)},[i]),n.jsx(n.Fragment,{children:Le(e)})}function Bn({rec:i,onDelete:e,onDownload:t}){const{t:r,lang:s}=y.useNiceTranslation(),[a,o]=l.useState(!1),[d,u]=l.useState(0),p=l.useRef(null),g=At[i.state],c=Fn(r,i.state),f=i.state==="recording"||i.state==="paused";return n.jsxs(n.Fragment,{children:[a&&i.transcript&&n.jsx(_n,{segments:i.transcript,currentTimeMs:d,onClose:()=>o(!1)}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",flexWrap:"wrap"},children:[n.jsx("div",{style:{display:"flex",alignItems:"center"},children:n.jsx(y.NiceIcon,{name:i.sessionType==="call"?"phone":i.sessionType==="meeting"?"video":i.sessionType==="whiteboard"?"image":"monitor",size:20})}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontSize:13,fontWeight:500,color:"var(--nice-text, #111827)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.title??r("recording.recording","Recording {id}").replace("{id}",String(i.id.slice(0,8)))}),n.jsxs("div",{style:{fontSize:11,color:"var(--nice-text-muted, #9ca3af)",marginTop:2,display:"flex",gap:8},children:[n.jsx("span",{children:Ln(i.startedAt,s)}),n.jsx("span",{children:f?n.jsx(Dt,{startedAt:i.startedAt}):i.durationMs!=null?Le(i.durationMs):"โ"}),i.size!=null&&n.jsx("span",{children:$n(i.size)}),n.jsx("span",{children:r("recording.participants","{participants} participants").replace("{participants}",String(i.participants.length))})]})]}),n.jsxs("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:20,background:g.bg,color:g.fg,fontWeight:500,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[g.icon&&n.jsx(y.NiceIcon,{name:g.icon,size:11}),c]}),i.url&&i.state==="ready"&&n.jsx("audio",{ref:p,src:i.url,controls:!0,onTimeUpdate:()=>{p.current&&u(p.current.currentTime*1e3)},style:{height:32,maxWidth:180}}),n.jsxs("div",{style:{display:"flex",gap:4},children:[i.transcript&&i.transcript.length>0&&n.jsx("button",{onClick:()=>o(!0),style:Ye,title:r("recording.viewTranscript","View transcript"),"aria-label":r("recording.viewTranscript","View transcript"),children:n.jsx(y.NiceIcon,{name:"type",size:14})}),i.state==="ready"&&n.jsx("button",{onClick:()=>t(i),style:Ye,title:r("recording.download","Download"),"aria-label":r("recording.download","Download"),children:n.jsx(y.NiceIcon,{name:"download",size:14})}),n.jsx("button",{onClick:()=>e(i.id),style:{...Ye,color:"var(--nice-danger, #ef4444)"},title:r("recording.delete","Delete"),"aria-label":r("recording.delete","Delete"),children:n.jsx(y.NiceIcon,{name:"trash",size:14})})]})]})]})}function Un({recordings:i,onRecordingStart:e,onRecordingStop:t,onRecordingPause:r,onRecordingResume:s,onRecordingDelete:a,onRecordingDownload:o,activeRecordingId:d,sessionType:u="meeting",className:p,style:g,"data-testid":c}){const{t:f}=y.useNiceTranslation(),[m,w]=l.useState(i??[]),[k,T]=l.useState(""),[h,C]=l.useState("all");l.useEffect(()=>{i&&w(i)},[i]);const A=m.find(L=>L.id===d),U=(A==null?void 0:A.state)==="recording",M=(A==null?void 0:A.state)==="paused",P=m.filter(L=>{const N=h==="all"||L.sessionType===h,z=!k||(L.title??"").toLowerCase().includes(k.toLowerCase())||L.id.includes(k);return N&&z}),G=l.useCallback(L=>{w(N=>N.filter(z=>z.id!==L)),a==null||a(L)},[a]),F=l.useCallback(L=>{if(o){o(L.id);return}if(L.url){const N=document.createElement("a");N.href=L.url,N.download=`${L.title??L.id}.${L.mimeType.includes("mp4")?"mp4":"webm"}`,N.click()}else if(L.blob){const N=URL.createObjectURL(L.blob),z=document.createElement("a");z.href=N,z.download=`${L.title??L.id}.webm`,z.click(),setTimeout(()=>URL.revokeObjectURL(N),5e3)}},[o]);return n.jsxs("div",{className:p,"data-testid":c,style:{display:"flex",flexDirection:"column",background:"var(--nice-bg, #fff)",borderRadius:10,border:"1px solid var(--nice-border, #e5e7eb)",fontFamily:"system-ui, sans-serif",overflow:"hidden",...g},children:[n.jsxs("div",{style:{padding:"14px 16px",borderBottom:"1px solid var(--nice-border, #e5e7eb)",display:"flex",gap:8,alignItems:"center"},children:[n.jsx(y.NiceIcon,{name:"mic",size:16}),n.jsx("strong",{style:{fontSize:14,color:"var(--nice-text, #111827)",flex:1},children:f("recording.recordings","Recordings")}),n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-muted, #9ca3af)"},children:f("recording.total","{recordings} total").replace("{recordings}",String(m.length))})]}),n.jsxs("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[n.jsxs("select",{value:u,disabled:U||M,onChange:()=>{},style:{...yt,flex:0},children:[n.jsx("option",{value:"call",children:f("recording.type.call","Call")}),n.jsx("option",{value:"meeting",children:f("recording.type.meeting","Meeting")}),n.jsx("option",{value:"whiteboard",children:f("recording.type.whiteboard","Whiteboard")}),n.jsx("option",{value:"screen",children:f("recording.type.screen","Screen")})]}),!U&&!M?n.jsxs("button",{onClick:e,style:{...Me,background:"var(--nice-danger, #ef4444)",color:"var(--nice-text-on-primary, #fff)"},children:[n.jsx(y.NiceIcon,{name:"circle",size:12})," ",f("recording.start","Start recording")]}):n.jsxs(n.Fragment,{children:[M?n.jsxs("button",{onClick:s,style:{...Me,background:"var(--nice-info, #6366f1)",color:"var(--nice-text-on-primary, #fff)"},children:[n.jsx(y.NiceIcon,{name:"play",size:12})," ",f("recording.resume","Resume")]}):n.jsxs("button",{onClick:r,style:{...Me,background:"var(--nice-warning, #f59e0b)",color:"var(--nice-text-on-primary, #fff)"},children:[n.jsx(y.NiceIcon,{name:"pause",size:12})," ",f("recording.pause","Pause")]}),n.jsxs("button",{onClick:t,style:{...Me,background:"var(--nice-text, #374151)",color:"var(--nice-text-inverse, #fff)"},children:[n.jsx(y.NiceIcon,{name:"stop",size:12})," ",f("recording.stop","Stop")]}),A&&n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-muted, #9ca3af)",marginLeft:4},children:n.jsx(Dt,{startedAt:A.startedAt})})]})]}),n.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #f3f4f6)",display:"flex",gap:6,alignItems:"center"},children:[n.jsx("input",{type:"search",value:k,onChange:L=>T(L.target.value),placeholder:f("recording.searchPlaceholder","Search recordingsโฆ"),style:{flex:1,padding:"4px 8px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,fontSize:12}}),n.jsxs("select",{value:h,onChange:L=>C(L.target.value),style:yt,children:[n.jsx("option",{value:"all",children:f("recording.filter.all","All types")}),n.jsx("option",{value:"call",children:f("recording.filter.calls","Calls")}),n.jsx("option",{value:"meeting",children:f("recording.filter.meetings","Meetings")}),n.jsx("option",{value:"whiteboard",children:f("recording.type.whiteboard","Whiteboard")}),n.jsx("option",{value:"screen",children:f("recording.type.screen","Screen")})]})]}),n.jsx("div",{style:{flex:1,overflowY:"auto"},children:P.length===0?n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:32,gap:8,color:"var(--nice-text-muted, #9ca3af)"},children:[n.jsx(y.NiceIcon,{name:"mic",size:32}),n.jsx("span",{style:{fontSize:13},children:f("recording.empty","No recordings found")}),n.jsx("span",{style:{fontSize:11},children:f("recording.emptyHint","Start a recording above or adjust your search filters.")})]}):P.map(L=>n.jsx(Bn,{rec:L,onDelete:G,onDownload:F},L.id))})]})}const Ye={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,background:"var(--nice-bg, #fff)",cursor:"pointer",padding:"4px 8px",fontSize:14,lineHeight:1},Me={border:"none",borderRadius:6,cursor:"pointer",padding:"6px 14px",fontSize:12,fontWeight:500,display:"inline-flex",alignItems:"center",gap:4},yt={padding:"4px 6px",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,fontSize:12,color:"var(--nice-text, #374151)",background:"var(--nice-bg, #fff)"},Hn={border:"none",background:"none",cursor:"pointer",fontSize:16,color:"var(--nice-text-muted, #9ca3af)",lineHeight:1,padding:4};function xt({participant:i,isFollowing:e,onClick:t}){const r=i.user.displayName??i.user.name,s=r.split(" ").map(a=>a[0]).slice(0,2).join("").toUpperCase();return n.jsxs("button",{onClick:t,title:`${r}${e?" (following)":""} โ ${i.editingRegion??"viewing"}`,style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:"50%",background:i.color,color:"var(--nice-color-white, #fff)",fontSize:11,fontWeight:600,border:`2px solid ${e?"var(--nice-bg, #fff)":i.color}`,boxShadow:e?`0 0 0 2px ${i.color}`:"none",cursor:"pointer",flexShrink:0,transition:"transform 0.15s",position:"relative",overflow:"visible"},children:[i.user.avatarUrl?n.jsx("img",{src:i.user.avatarUrl,alt:s,style:{width:"100%",height:"100%",borderRadius:"50%",objectFit:"cover"}}):s,i.isActive&&n.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 Vn({participant:i,containerRect:e}){if(!i.cursorX||!i.cursorY||!e)return null;const t=i.cursorX,r=i.cursorY;return n.jsxs("div",{style:{position:"absolute",left:t,top:r,pointerEvents:"none",zIndex:9e3,transform:"translate(-2px, -2px)"},children:[n.jsx("svg",{width:16,height:20,style:{display:"block"},children:n.jsx("path",{d:"M2 2 L2 16 L6 12 L10 18 L12 17 L8 11 L14 11 Z",fill:i.color,stroke:"var(--nice-bg, #fff)",strokeWidth:1.5})}),n.jsx("div",{style:{background:i.color,color:"var(--nice-color-white, #fff)",fontSize:10,padding:"1px 5px",borderRadius:3,whiteSpace:"nowrap",marginTop:-2,marginLeft:10},children:i.user.displayName??i.user.name})]})}function Yn({count:i}){const{t:e}=y.useNiceTranslation();return i===0?null:n.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:[n.jsx(y.NiceIcon,{name:"warning",size:12})," ",i>1?e("collaborativeEditor.editConflictsAutoMergingMany","{count} edit conflicts โ auto-mergingโฆ").replace("{count}",String(i)):e("collaborativeEditor.editConflictsAutoMergingOne","{count} edit conflict โ auto-mergingโฆ").replace("{count}",String(i))]})}function Kn(){const{t:i}=y.useNiceTranslation();return n.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:n.jsxs("div",{style:{background:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",color:"var(--nice-color-white, #fff)",fontSize:12,padding:"4px 14px",borderRadius:20,display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(y.NiceIcon,{name:"eye",size:12})," ",i("collaborativeEditor.viewOnly","View only")]})})}function Gn({pending:i}){const{t:e}=y.useNiceTranslation();return i===0?n.jsxs("span",{style:{fontSize:11,color:"var(--nice-success, #22c55e)",display:"inline-flex",alignItems:"center",gap:3},children:[n.jsx(y.NiceIcon,{name:"check",size:11})," ",e("collaborativeEditor.synced","Synced")]}):n.jsxs("span",{style:{fontSize:11,color:"var(--nice-warning, #f59e0b)",display:"inline-flex",alignItems:"center",gap:3},children:[n.jsx(y.NiceIcon,{name:"upload",size:11})," ",e("collaborativeEditor.pending","{pending} pendingโฆ").replace("{pending}",String(i))]})}function qn({participant:i,isFollowing:e,onClick:t}){const{t:r}=y.useNiceTranslation();return n.jsxs("button",{onClick:t,style:{fontSize:11,padding:"2px 8px",border:`1px solid ${e?i.color:"var(--nice-border, #e5e7eb)"}`,borderRadius:20,background:e?i.color:"var(--nice-bg, #fff)",color:e?"var(--nice-color-white, #fff)":"var(--nice-text-secondary, #6b7280)",cursor:"pointer",display:"flex",alignItems:"center",gap:4},children:[n.jsx(y.NiceIcon,{name:"eye",size:11})," ",e?r("collaborativeEditor.unfollow","Unfollow"):r("collaborativeEditor.follow","Follow {name}").replace("{name}",String((i.user.displayName??i.user.name).split(" ")[0]))]})}function Jn({editorType:i,sessionId:e,currentUser:t,participants:r=[],onOperation:s,onParticipantJoin:a,onParticipantLeave:o,onCursorMove:d,isReadOnly:u=!1,showParticipants:p=!0,showCursors:g=!0,pendingOperations:c=0,conflictCount:f=0,className:m,style:w,children:k,"data-testid":T}){const{t:h}=y.useNiceTranslation(),C=l.useRef(null),[A,U]=l.useState(null),[M,P]=l.useState(null),[G,F]=l.useState(!1);l.useEffect(()=>{const j=C.current;if(!j)return;const O=new ResizeObserver(()=>U(j.getBoundingClientRect()));return O.observe(j),U(j.getBoundingClientRect()),()=>O.disconnect()},[]);const L=l.useCallback(j=>{if(!C.current||!d)return;const O=C.current.getBoundingClientRect();d(j.clientX-O.left,j.clientY-O.top)},[d]),N=l.useCallback(j=>{P(O=>O===j?null:j)},[]),z={vector:{icon:"pen",label:h("collaborativeEditor.vector","Vector")},pixel:{icon:"image",label:h("collaborativeEditor.pixel","Pixel")},diagram:{icon:"bar-chart",label:h("collaborativeEditor.diagram","Diagram")},document:{icon:"file",label:h("collaborativeEditor.document","Document")},whiteboard:{icon:"edit",label:h("collaborativeEditor.whiteboard","Whiteboard")}},E=n.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:[n.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)",fontWeight:500,display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(y.NiceIcon,{name:z[i].icon,size:12}),z[i].label]}),n.jsx("span",{style:{flex:1}}),n.jsx(Gn,{pending:c}),p&&r.length>0&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:-4},children:[r.slice(0,5).map((j,O)=>n.jsx("div",{style:{marginLeft:O>0?-8:0,zIndex:10-O},children:n.jsx(xt,{participant:j,isFollowing:M===j.user.id,onClick:()=>{F(!0),N(j.user.id)}})},j.user.id)),r.length>5&&n.jsxs("button",{onClick:()=>F(!G),style:{marginLeft:-4,zIndex:5,width:30,height:30,borderRadius:"50%",background:"var(--nice-border, #e5e7eb)",border:"2px solid var(--nice-bg, #FFF)",fontSize:10,fontWeight:600,color:"var(--nice-text, #374151)",cursor:"pointer"},children:["+",r.length-5]})]}),p&&r.length>0&&n.jsx("button",{onClick:()=>F(!G),style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:5,background:G?"var(--nice-primary-bg, #eff6ff)":"var(--nice-bg, #fff)",padding:"3px 8px",cursor:"pointer",fontSize:11,color:G?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #6b7280)"},children:h("collaborativeEditor.online","{propParticipants} online").replace("{propParticipants}",String(r.length))})]}),V=n.jsxs("div",{ref:C,onMouseMove:L,style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},children:[k??n.jsxs("div",{id:`collab-editor-${i}-${e}`,style:{width:"100%",height:"100%",minHeight:400,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-bg-secondary, #f9fafb)",color:"var(--nice-text-muted, #9ca3af)",fontSize:13},children:[h("collaborativeEditor.dropYourEditorHereOr","Drop your {editorType} editor here or use the").replace("{editorType}",String(i))," ",n.jsx("code",{style:{background:"var(--nice-border, #e5e7eb)",padding:"1px 5px",borderRadius:3,margin:"0 4px"},children:`#collab-editor-${i}-${e}`})," ",h("collaborativeEditor.mountPoint","mount point.")]}),g&&r.filter(j=>j.user.id!==t.id&&j.cursorX!=null&&j.cursorY!=null).map(j=>n.jsx(Vn,{participant:j,containerRect:A},j.user.id)),n.jsx(Yn,{count:f}),u&&n.jsx(Kn,{})]}),J=G&&r.length>0?n.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:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[n.jsx("strong",{style:{fontSize:12,color:"var(--nice-text, #374151)"},children:h("collaborativeEditor.participants","Participants")}),n.jsx("button",{onClick:()=>F(!1),style:{border:"none",background:"none",cursor:"pointer",color:"var(--nice-text-muted, #9ca3af)",fontSize:14},"aria-label":h("collaborativeEditor.close","Close"),children:n.jsx(y.NiceIcon,{name:"close",size:14})})]}),r.map(j=>n.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:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx(xt,{participant:j,isFollowing:M===j.user.id,onClick:()=>N(j.user.id)}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontSize:12,fontWeight:500,color:"var(--nice-text, #111827)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j.user.displayName??j.user.name}),n.jsx("div",{style:{fontSize:10,color:"var(--nice-text-muted, #9ca3af)"},children:j.editingRegion??h("collaborativeEditor.viewing","viewing")})]})]}),j.user.id!==t.id&&n.jsx(qn,{participant:j,isFollowing:M===j.user.id,onClick:()=>N(j.user.id)})]},j.user.id))]}):void 0;return n.jsx(y.NiceAppShell,{flush:!0,className:m,"data-testid":T,style:{background:"var(--nice-bg, #fff)",fontFamily:"system-ui, sans-serif",...w},menubar:E,rightSidebar:J,children:V})}function st(i){let e="";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return btoa(e)}function at(i){const e=atob(i),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Xn(i){return new TextEncoder().encode(i)}function Zn(i){return new TextDecoder().decode(i)}async function Qn(i){return crypto.subtle.generateKey({name:"AES-GCM",length:i},!0,["encrypt","decrypt"])}async function ei(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-384"},!0,["deriveKey"])}async function ti(i,e){return crypto.subtle.deriveKey({name:"ECDH",public:e},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function ni(i,e){const t=crypto.getRandomValues(new Uint8Array(12)),r=Xn(e),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},i,r),a=new Uint8Array(s),o=new Uint8Array(12+a.length);return o.set(t,0),o.set(a,12),st(o)}async function ii(i,e){const t=at(e),r=t.slice(0,12),s=t.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},i,s);return Zn(new Uint8Array(a))}async function bt(i,e){const t=at(i);return crypto.subtle.importKey("raw",t,{name:"AES-GCM",length:e},!1,["encrypt","decrypt"])}async function ri(i){const e=await crypto.subtle.exportKey("raw",i);return st(new Uint8Array(e))}async function si(i){const e=await crypto.subtle.exportKey("spki",i);return st(new Uint8Array(e))}async function ai(i){const e=at(i);return crypto.subtle.importKey("spki",e,{name:"ECDH",namedCurve:"P-384"},!0,[])}class Mt{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 bt(this.config.keyMaterial,128):this.keys.aes256=await bt(this.config.keyMaterial,256);else if(e==="AES-GCM-256"||e==="AES-GCM-128"){const t=e==="AES-GCM-256"?256:128,r=await Qn(t);t===128?this.keys.aes128=r:this.keys.aes256=r}else if(e==="E2E-ECDH-P384"){const t=await ei();this.keys.ecdhPrivate=t.privateKey,this.keys.ecdhPublic=t.publicKey,this.keys.ecdhSessionKeys=new Map}this.ready=!0}async getPublicKeyForPeer(){return this.keys.ecdhPublic?si(this.keys.ecdhPublic):null}async registerPeerPublicKey(e,t){var a;if(!this.keys.ecdhPrivate)return;const r=await ai(t),s=await ti(this.keys.ecdhPrivate,r);(a=this.keys.ecdhSessionKeys)==null||a.set(e,s)}resolveAlgorithm(e){if(e&&this.config.scopeOverrides){const t=this.config.scopeOverrides.find(r=>(r.scope===e||r.scope==="all")&&r.enabled);if(t)return t.algorithm}return this.config.defaultAlgorithm}getKey(e,t){var r;switch(e){case"AES-GCM-256":return this.keys.aes256??null;case"AES-GCM-128":return this.keys.aes128??null;case"E2E-ECDH-P384":return t?((r=this.keys.ecdhSessionKeys)==null?void 0:r.get(t))??null:null;default:return null}}async encrypt(e,t,r){if(!this.config.enabled)return e;if(!this.ready)throw new Error("EncryptionService not initialised โ call init() first");const s=this.resolveAlgorithm(t);if(s==="none")return e;const a=this.getKey(s,r);return a?ni(a,e):(console.warn(`EncryptionService: no key found for algorithm "${s}" โ returning plaintext`),e)}async decrypt(e,t,r){if(!this.config.enabled)return e;if(!this.ready)throw new Error("EncryptionService not initialised โ call init() first");const s=this.resolveAlgorithm(t);if(s==="none")return e;const a=this.getKey(s,r);return a?ii(a,e):(console.warn(`EncryptionService: no key found for algorithm "${s}" โ returning as-is`),e)}async exportSymmetricKey(e){const t=e??this.config.defaultAlgorithm,r=this.getKey(t);return r?ri(r):null}isEnabled(){return this.config.enabled}getConfig(){return this.config}updateConfig(e){this.config=e,this.ready=!1}}const Oe=new Map;function oi(i,e){return Oe.has(i)||Oe.set(i,new Mt(e)),Oe.get(i)}function li(i){Oe.delete(i)}class Wt{constructor(e={}){this.recorder=null,this.chunks=[],this.session=null,this.recognition=null,this.segmentCounter=0,this.callbacks=e}start(e,t){var d,u,p;if(((d=this.recorder)==null?void 0:d.state)==="recording")throw new Error("Recording already in progress");const r=t.mimeType??this.chooseMimeType(),s=new MediaRecorder(e,{mimeType:r});this.chunks=[];const a=new Date,o=`rec_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return this.session={id:o,sessionType:t.sessionType,startedAt:a,state:"recording",mimeType:r,participants:[t.speakerId??"unknown"],title:t.title??`Recording ${a.toLocaleString()}`},s.ondataavailable=g=>{g.data&&g.data.size>0&&this.chunks.push(g.data)},s.onstop=()=>{var c,f,m,w;const g=new Blob(this.chunks,{type:r});this.session&&(this.session.blob=g,this.session.endedAt=new Date,this.session.durationMs=this.session.endedAt.getTime()-this.session.startedAt.getTime(),this.session.size=g.size,this.session.state="ready"),(f=(c=this.callbacks).onDataAvailable)==null||f.call(c,g),(w=(m=this.callbacks).onStateChange)==null||w.call(m,"ready")},s.onerror=g=>{var c,f,m,w;(f=(c=this.callbacks).onError)==null||f.call(c,new Error(String(g))),this.session&&(this.session.state="failed"),(w=(m=this.callbacks).onStateChange)==null||w.call(m,"failed")},s.start(t.timesliceMs??1e3),this.recorder=s,t.transcribe&&this.startTranscription(t.speakerId??"unknown",t.speakerName??"Participant"),(p=(u=this.callbacks).onStateChange)==null||p.call(u,"recording"),this.session}pause(){var e,t,r;((e=this.recorder)==null?void 0:e.state)==="recording"&&(this.recorder.pause(),this.session&&(this.session.state="paused"),(r=(t=this.callbacks).onStateChange)==null||r.call(t,"paused"))}resume(){var e,t,r;((e=this.recorder)==null?void 0:e.state)==="paused"&&(this.recorder.resume(),this.session&&(this.session.state="recording"),(r=(t=this.callbacks).onStateChange)==null||r.call(t,"recording"))}stop(){var e,t;return this.stopTranscription(),this.recorder&&this.recorder.state!=="inactive"&&(this.recorder.stop(),this.session&&(this.session.state="processing"),(t=(e=this.callbacks).onStateChange)==null||t.call(e,"processing")),this.session}startTranscription(e,t){const r=window,s=r.SpeechRecognition??r.webkitSpeechRecognition;if(!s)return;const a=new s;a.continuous=!0,a.interimResults=!1,a.lang="en-US";const o=Date.now();a.onresult=d=>{var p,g;const u=d.results;for(let c=d.resultIndex;c<u.length;c++){const f=u[c];if(!f.isFinal)continue;const m=f[0],w=Date.now(),k={id:`seg_${++this.segmentCounter}`,speakerId:e,speakerName:t,text:m.transcript.trim(),startMs:w-o-1500,endMs:w-o,confidence:m.confidence??.9};this.session&&(this.session.transcript=[...this.session.transcript??[],k]),(g=(p=this.callbacks).onTranscriptSegment)==null||g.call(p,k)}},a.onerror=()=>{};try{a.start(),this.recognition=a}catch{}}stopTranscription(){var e;try{(e=this.recognition)==null||e.stop()}catch{}this.recognition=null}chooseMimeType(){const e=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm","audio/webm;codecs=opus","audio/ogg;codecs=opus"];for(const t of e)if(MediaRecorder.isTypeSupported(t))return t;return""}getState(){var e;return((e=this.session)==null?void 0:e.state)??"idle"}getSession(){return this.session}download(e){var a,o;const t=(a=this.session)==null?void 0:a.blob;if(!t)return;const r=URL.createObjectURL(t),s=document.createElement("a");s.href=r,s.download=e??`${((o=this.session)==null?void 0:o.title)??"recording"}.webm`,s.click(),setTimeout(()=>URL.revokeObjectURL(r),3e4)}}const $e=new Map;function ci(i,e){return $e.has(i)||$e.set(i,new Wt(e)),$e.get(i)}function di(i){$e.delete(i)}class Ot{constructor(e){this.events=[],this.eventListeners=new Map,this.config={serverUrl:e.serverUrl,apiKey:e.apiKey??"",anonymizeIp:e.anonymizeIp??!0,enableGeoLocation:e.enableGeoLocation??!1,pixelPath:e.pixelPath??"/pixel",redirectPath:e.redirectPath??"/redirect",hashAlgorithm:e.hashAlgorithm??"sha256"}}generateTrackingPixel(e){const t=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,metadata:e.metadata}),r=e.width??1,s=e.height??1,a=`${this.config.serverUrl}${this.config.pixelPath}?${t}`;return`<img src="${this.escapeHtml(a)}" width="${r}" height="${s}" alt="" style="display:block;width:${r}px;height:${s}px;border:0;" />`}generateTrackingPixelUrl(e){const t=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,metadata:e.metadata});return`${this.config.serverUrl}${this.config.pixelPath}?${t}`}wrapLink(e){const t=this.buildTrackingParams({messageId:e.messageId,recipientId:e.recipientId,campaignId:e.campaignId,url:e.url,linkName:e.linkName});return`${this.config.serverUrl}${this.config.redirectPath}?${t}`}wrapLinksForTracking(e,t){const r=t.excludePatterns??[/^mailto:/i,/^tel:/i,/^#/,/unsubscribe/i],s=/<a\s+([^>]*?)href=["']([^"']+)["']([^>]*?)>/gi;return e.replace(s,(a,o,d,u)=>{if(r.some(f=>f.test(d)))return a;const g=this.extractLinkName(o+u)??d,c=this.wrapLink({url:d,messageId:t.messageId,recipientId:t.recipientId,campaignId:t.campaignId,linkName:g});return`<a ${o}href="${this.escapeHtml(c)}"${u}>`})}recordEvent(e){const t={...e,id:this.generateEventId(),timestamp:new Date,ipAddress:this.config.anonymizeIp?this.anonymizeIpAddress(e.ipAddress):e.ipAddress};return this.events.push(t),this.notifyListeners(t),t}parseTrackingParams(e){const t=e.get("mid"),r=e.get("rid");if(!t||!r)return null;const s={};return e.forEach((a,o)=>{o.startsWith("m_")&&(s[o.substring(2)]=a)}),{messageId:t,recipientHash:r,campaignId:e.get("cid")??void 0,url:e.get("url")??void 0,linkName:e.get("ln")??void 0,metadata:Object.keys(s).length>0?s:void 0}}getStats(e){let t=this.events;e&&(t=this.events.filter(f=>!(e.campaignId&&f.campaignId!==e.campaignId||e.messageId&&f.messageId!==e.messageId||e.startDate&&f.timestamp<e.startDate||e.endDate&&f.timestamp>e.endDate)));const r=new Set(t.map(f=>f.recipientHash)),s=t.filter(f=>f.type==="open"),a=t.filter(f=>f.type==="click"),o=t.filter(f=>f.type==="bounce"),d=t.filter(f=>f.type==="unsubscribe"),u=t.filter(f=>f.type==="complaint"),p=new Set(s.map(f=>f.recipientHash)).size,g=new Set(a.map(f=>f.recipientHash)).size,c=r.size;return{sent:c+o.length,delivered:c,opens:s.length,uniqueOpens:p,clicks:a.length,uniqueClicks:g,bounces:o.length,unsubscribes:d.length,complaints:u.length,openRate:c>0?p/c:0,clickRate:c>0?g/c:0,clickToOpenRate:p>0?g/p:0,bounceRate:c>0?o.length/(c+o.length):0}}getLinkStats(e){let t=this.events.filter(o=>o.type==="click"&&o.url);e&&(t=t.filter(o=>!(e.campaignId&&o.campaignId!==e.campaignId||e.messageId&&o.messageId!==e.messageId)));const r=new Map;for(const o of t){const d=o.url;r.has(d)||r.set(d,{url:d,linkName:void 0,total:0,unique:new Set});const u=r.get(d);u.total++,u.unique.add(o.recipientHash)}const s=t.length,a=[];for(const[,o]of r)a.push({url:o.url,linkName:o.linkName,totalClicks:o.total,uniqueClicks:o.unique.size,clickShare:s>0?o.total/s:0});return a.sort((o,d)=>d.totalClicks-o.totalClicks)}getDeviceStats(e){let t=this.events.filter(s=>s.type==="open");e!=null&&e.campaignId&&(t=t.filter(s=>s.campaignId===e.campaignId));const r={desktop:0,mobile:0,tablet:0,unknown:0};for(const s of t){const a=s.device??"unknown";r[a]=(r[a]??0)+1}return r}on(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t),()=>{var r;(r=this.eventListeners.get(e))==null||r.delete(t)}}onAny(e){const t=["open","click","bounce","unsubscribe","complaint"].map(r=>this.on(r,e));return()=>{t.forEach(r=>r())}}generateUnsubscribeLink(e){const t=new URLSearchParams;return t.set("rid",this.hashRecipientId(e.recipientId)),e.listId&&t.set("lid",e.listId),t.set("action","unsubscribe"),`${this.config.serverUrl}/unsubscribe?${t.toString()}`}generateListUnsubscribeHeader(e){return`<${this.generateUnsubscribeLink(e)}>`}clearEvents(){this.events=[]}exportEvents(e){return e!=null&&e.anonymize?this.events.map(t=>({...t,recipientHash:"anonymized",ipAddress:void 0,userAgent:void 0})):[...this.events]}buildTrackingParams(e){const t=new URLSearchParams;if(t.set("mid",e.messageId),t.set("rid",this.hashRecipientId(e.recipientId)),e.campaignId&&t.set("cid",e.campaignId),e.url&&t.set("url",e.url),e.linkName&&t.set("ln",e.linkName),e.metadata)for(const[r,s]of Object.entries(e.metadata))t.set(`m_${r}`,s);return t.toString()}hashRecipientId(e){let t=0;for(let r=0;r<e.length;r++){const s=e.charCodeAt(r);t=(t<<5)-t+s,t=t&t}return Math.abs(t).toString(36)}anonymizeIpAddress(e){if(e){if(e.includes(".")){const t=e.split(".");return t[3]="0",t.join(".")}return e.includes(":")?e.split(":").slice(0,3).join(":")+"::":e}}extractLinkName(e){const t=e.match(/title=["']([^"']+)["']/i);if(t)return t[1];const r=e.match(/data-link-name=["']([^"']+)["']/i);if(r)return r[1]}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}generateEventId(){return`evt_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}notifyListeners(e){const t=this.eventListeners.get(e.type);if(t)for(const r of t)try{r(e)}catch(s){console.error("Tracking event listener error:",s)}}}let ye=null;function Je(i){if(!ye&&i&&(ye=new Ot(i)),!ye)throw new Error("EmailTrackingService not initialized. Call with config first.");return ye}function pi(){ye==null||ye.clearEvents(),ye=null}function ui(i){const{config:e,campaignId:t,autoRefreshInterval:r}=i,s=l.useMemo(()=>{if(e)return Je(e);try{return Je()}catch{return null}},[e]),[a,o]=l.useState(null),[d,u]=l.useState([]),p=l.useCallback(()=>{s&&(o(s.getStats({campaignId:t})),u(s.getLinkStats({campaignId:t})))},[s,t]);l.useEffect(()=>{if(p(),r&&s){const m=setInterval(p,r);return()=>clearInterval(m)}},[p,r,s]),l.useEffect(()=>{if(s)return s.onAny(()=>{p()})},[s,p]);const g=l.useCallback((m,w)=>s?s.generateTrackingPixel({messageId:m,recipientId:w,campaignId:t}):"",[s,t]),c=l.useCallback((m,w,k)=>s?s.wrapLinksForTracking(m,{messageId:w,recipientId:k,campaignId:t}):m,[s,t]),f=l.useCallback(m=>{s==null||s.recordEvent(m)},[s]);return{generatePixel:g,wrapLinks:c,stats:a,linkStats:d,recordEvent:f,refreshStats:p}}class $t{constructor(e){this.templates=new Map,this.campaigns=new Map,this.abortControllers=new Map,this.config={sendEmail:e.sendEmail,rateLimit:e.rateLimit??60,batchSize:e.batchSize??10,retryOnFail:e.retryOnFail??!0,maxRetries:e.maxRetries??3,dateFormatter:e.dateFormatter??this.defaultDateFormatter,numberFormatter:e.numberFormatter??this.defaultNumberFormatter,currencyFormatter:e.currencyFormatter??this.defaultCurrencyFormatter}}createTemplate(e){const t={...e,id:this.generateId("tpl"),createdAt:new Date,updatedAt:new Date};return this.templates.set(t.id,t),t}updateTemplate(e,t){const r=this.templates.get(e);if(!r)throw new Error(`Template not found: ${e}`);const s={...r,...t,updatedAt:new Date};return this.templates.set(e,s),s}getTemplate(e){return this.templates.get(e)}deleteTemplate(e){return this.templates.delete(e)}listTemplates(){return Array.from(this.templates.values())}extractFields(e){const t=/\{\{([^}]+)\}\}/g,r=new Set;let s;for(;(s=t.exec(e))!==null;){const a=s[1].trim();if(a.startsWith("#if "))r.add(a.substring(4).trim());else if(a.startsWith("#unless "))r.add(a.substring(8).trim());else if(a.startsWith("#each "))r.add(a.substring(6).trim());else if(!a.startsWith("/")&&!a.startsWith("else")){const[o]=a.split("|");r.add(o.trim())}}return Array.from(r)}createCampaign(e){if(!this.templates.has(e.templateId))throw new Error(`Template not found: ${e.templateId}`);const t={...e,id:this.generateId("cmp"),status:"draft",recipients:e.recipients.map(r=>({...r,status:"pending"})),createdAt:new Date};return this.campaigns.set(t.id,t),t}getCampaign(e){return this.campaigns.get(e)}updateCampaign(e,t){const r=this.campaigns.get(e);if(!r)throw new Error(`Campaign not found: ${e}`);if(r.status==="sending")throw new Error("Cannot update campaign while sending");const s={...r,...t};return this.campaigns.set(e,s),s}addRecipients(e,t){const r=this.campaigns.get(e);if(!r)throw new Error(`Campaign not found: ${e}`);if(r.status==="sending")throw new Error("Cannot add recipients while sending");const s=t.map(a=>({...a,status:"pending"}));r.recipients.push(...s),this.campaigns.set(e,r)}removeRecipient(e,t){const r=this.campaigns.get(e);if(!r)return!1;const s=r.recipients.findIndex(a=>a.id===t);return s===-1?!1:(r.recipients.splice(s,1),!0)}listCampaigns(){return Array.from(this.campaigns.values())}validateCampaign(e){const t=this.campaigns.get(e);if(!t)return{isValid:!1,errors:[{type:"syntax_error",message:"Campaign not found"}],warnings:[],missingFields:new Map};const r=this.templates.get(t.templateId);if(!r)return{isValid:!1,errors:[{type:"syntax_error",message:"Template not found"}],warnings:[],missingFields:new Map};const s=[],a=[],o=new Map;t.recipients.length===0&&s.push({type:"empty_recipient",message:"No recipients in campaign"});for(const p of t.recipients){if(!p.email){s.push({type:"empty_recipient",recipientId:p.id,message:`Recipient ${p.id} has no email address`});continue}const g=[];for(const c of r.fields)c.required&&!(c.name in p.data)&&(g.push(c.name),s.push({type:"missing_field",field:c.name,recipientId:p.id,message:`Required field "${c.name}" missing for ${p.email}`}));g.length>0&&o.set(p.id,g)}const d=this.extractFields(r.subject+r.htmlBody+(r.textBody??"")),u=r.fields.map(p=>p.name);for(const p of d)u.includes(p)||a.push({type:"unused_field",field:p,message:`Field "${p}" used in template but not defined`});return{isValid:s.length===0,errors:s,warnings:a,missingFields:o}}previewMerge(e,t){const r=this.templates.get(e);if(!r)throw new Error(`Template not found: ${e}`);return{subject:this.processTemplate(r.subject,t,r.fields),html:this.processTemplate(r.htmlBody,t,r.fields),text:r.textBody?this.processTemplate(r.textBody,t,r.fields):void 0}}async*sendCampaign(e){const t=this.campaigns.get(e);if(!t)throw new Error(`Campaign not found: ${e}`);const r=this.templates.get(t.templateId);if(!r)throw new Error(`Template not found: ${t.templateId}`);const s=this.validateCampaign(e);if(!s.isValid)throw new Error(`Campaign validation failed: ${s.errors.map(f=>f.message).join(", ")}`);t.status="sending",t.startedAt=new Date,this.campaigns.set(e,t);const a=new AbortController;this.abortControllers.set(e,a);const o=t.recipients.filter(f=>f.status==="pending"),d=o.length;let u=0,p=0;const g=Date.now(),c=60*1e3/(t.rateLimit??this.config.rateLimit);try{for(let f=0;f<o.length;f++){if(a.signal.aborted){t.status="paused";break}const m=o[f];try{const A=this.previewMerge(r.id,m.data),U=await this.config.sendEmail({to:m.email,cc:m.cc,bcc:m.bcc,from:t.fromEmail,fromName:t.fromName,replyTo:t.replyTo,subject:m.subjectOverride??A.subject,html:A.html,text:A.text});U.success?(m.status="sent",u++):(m.status="failed",m.error=U.error,p++)}catch(A){m.status="failed",m.error=A instanceof Error?A.message:"Unknown error",p++}const w=u+p,k=Date.now()-g,T=w>0?k/w:c,h=d-w,C=Math.round(h*T/1e3);yield{campaignId:e,total:d,sent:u,failed:p,pending:d-w,current:m.email,percentage:Math.round(w/d*100),estimatedTimeRemaining:C,isComplete:!1},f<o.length-1&&await this.delay(c)}t.status="completed",t.completedAt=new Date,this.campaigns.set(e,t),yield{campaignId:e,total:d,sent:u,failed:p,pending:0,percentage:100,isComplete:!0}}finally{this.abortControllers.delete(e)}}pauseCampaign(e){const t=this.abortControllers.get(e);t&&t.abort();const r=this.campaigns.get(e);r&&r.status==="sending"&&(r.status="paused",this.campaigns.set(e,r))}async*resumeCampaign(e){const t=this.campaigns.get(e);if(!t)throw new Error(`Campaign not found: ${e}`);if(t.status!=="paused")throw new Error("Campaign is not paused");t.status="draft",this.campaigns.set(e,t),yield*this.sendCampaign(e)}cancelCampaign(e){this.pauseCampaign(e);const t=this.campaigns.get(e);t&&(t.status="cancelled",this.campaigns.set(e,t))}async*retryFailed(e){const t=this.campaigns.get(e);if(!t)throw new Error(`Campaign not found: ${e}`);for(const r of t.recipients)r.status==="failed"&&(r.status="pending",r.error=void 0);t.status="draft",this.campaigns.set(e,t),yield*this.sendCampaign(e)}processTemplate(e,t,r){const s=new Map(r.map(a=>[a.name,a]));return e=this.processConditionals(e,t),e=this.processLoops(e,t),e=e.replace(/\{\{([^}#/]+)\}\}/g,(a,o)=>{const[d,...u]=o.trim().split("|").map(c=>c.trim());let p=this.getNestedValue(t,d);const g=s.get(d);p==null&&(p=(g==null?void 0:g.defaultValue)??""),g&&p!==""&&(p=this.formatValue(p,g));for(const c of u)p=this.applyFormatter(p,c);return String(p)}),e}processConditionals(e,t){const r=/\{\{#if\s+([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g;return e.replace(r,(s,a,o,d="")=>{const u=this.getNestedValue(t,a.trim());return this.isTruthy(u)?o:d})}processLoops(e,t){const r=/\{\{#each\s+([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g;return e.replace(r,(s,a,o)=>{const d=this.getNestedValue(t,a.trim());return Array.isArray(d)?d.map((u,p)=>{let g=o;return typeof u!="object"&&(g=g.replace(/\{\{this\}\}/g,String(u))),g=g.replace(/\{\{this\.([^}]+)\}\}/g,(c,f)=>String(this.getNestedValue(u,f)??"")),g=g.replace(/\{\{@index\}\}/g,String(p)),g=g.replace(/\{\{@first\}\}/g,String(p===0)),g=g.replace(/\{\{@last\}\}/g,String(p===d.length-1)),g}).join(""):""})}formatValue(e,t){switch(t.type){case"date":return e instanceof Date?this.config.dateFormatter(e,t.format??"short"):typeof e=="string"||typeof e=="number"?this.config.dateFormatter(new Date(e),t.format??"short"):String(e);case"number":return typeof e=="number"?this.config.numberFormatter(e,t.format??""):String(e);case"currency":if(typeof e=="number"){const[r="USD",s="en-US"]=(t.format??"USD|en-US").split("|");return this.config.currencyFormatter(e,r,s)}return String(e);case"boolean":return e?"Yes":"No";case"list":return Array.isArray(e)?e.join(t.format??", "):String(e);default:return String(e)}}applyFormatter(e,t){const r=String(e);switch(t.toLowerCase()){case"uppercase":return r.toUpperCase();case"lowercase":return r.toLowerCase();case"capitalize":return r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();case"titlecase":return r.replace(/\b\w/g,s=>s.toUpperCase());case"trim":return r.trim();case"escape":return this.escapeHtml(r);default:return r}}getNestedValue(e,t){const r=t.split(".");let s=e;for(const a of r){if(s==null)return;s=s[a]}return s}isTruthy(e){return e==null?!1:typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"||Array.isArray(e)?e.length>0:!0}defaultDateFormatter(e,t){const r={};switch(t){case"short":r.dateStyle="short";break;case"medium":r.dateStyle="medium";break;case"long":r.dateStyle="long";break;case"full":r.dateStyle="full";break;case"iso":return e.toISOString();default:r.dateStyle="medium"}return new Intl.DateTimeFormat("en-US",r).format(e)}defaultNumberFormatter(e,t){if(!t)return new Intl.NumberFormat().format(e);const r=parseInt(t,10);return isNaN(r)?String(e):new Intl.NumberFormat("en-US",{minimumFractionDigits:r,maximumFractionDigits:r}).format(e)}defaultCurrencyFormatter(e,t,r){return new Intl.NumberFormat(r,{style:"currency",currency:t}).format(e)}generateId(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}delay(e){return new Promise(t=>setTimeout(t,e))}}let Ne=null;function Xe(i){if(!Ne&&i&&(Ne=new $t(i)),!Ne)throw new Error("MailMergeService not initialized. Call with config first.");return Ne}function hi(){Ne=null}function fi(i={}){const{config:e}=i,t=l.useMemo(()=>{if(e)return Xe(e);try{return Xe()}catch{return null}},[e]),[r,s]=l.useState(null),[a,o]=l.useState(!1),[d,u]=l.useState([]),[p,g]=l.useState([]),c=l.useCallback(()=>{t&&(u(t.listTemplates()),g(t.listCampaigns()))},[t]),f=l.useCallback(C=>{if(!t)throw new Error("Service not initialized");const A=t.createTemplate(C);return c(),A},[t,c]),m=l.useCallback(C=>{if(!t)throw new Error("Service not initialized");const A=t.createCampaign(C);return c(),A},[t,c]),w=l.useCallback((C,A)=>{if(!t)throw new Error("Service not initialized");return t.previewMerge(C,A)},[t]),k=l.useCallback(C=>{if(!t)throw new Error("Service not initialized");return t.validateCampaign(C)},[t]),T=l.useCallback(async function*(C){if(!t)throw new Error("Service not initialized");o(!0);try{for await(const A of t.sendCampaign(C))s(A),yield A}finally{o(!1),c()}},[t,c]),h=l.useCallback(C=>{t==null||t.pauseCampaign(C),o(!1),c()},[t,c]);return{createTemplate:f,createCampaign:m,preview:w,validate:k,send:T,pause:h,progress:r,isSending:a,templates:d,campaigns:p}}class Lt{constructor(e){this.abortController=null,this.mapping={users:new Map,channels:new Map,files:new Map},this.config=e}async parseSlackExport(e){const t=await this.extractZipContents(e),r=t.get("users.json"),s=r?JSON.parse(r):[],a=t.get("channels.json"),o=a?JSON.parse(a):[],d=t.get("groups.json");if(d){const g=JSON.parse(d);o.push(...g.map(c=>({...c,is_private:!0})))}const u=t.get("dms.json");if(u){const g=JSON.parse(u);o.push(...g.map(c=>({...c,is_im:!0})))}const p=new Map;for(const g of o){const c=[],f=g.name;for(const[m,w]of t)if(m.startsWith(f+"/")&&m.endsWith(".json"))try{const k=JSON.parse(w);c.push(...k)}catch(k){console.warn(`Failed to parse messages from ${m}:`,k)}c.length>0&&p.set(g.id,c)}return{users:s,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,t={}){const r=e.users.filter(c=>t.importUsers!==!1&&!c.deleted),s=r.map(c=>this.mapUser(c)),a=e.channels.filter(c=>!(t.skipArchived&&c.is_archived||t.skipDirectMessages&&(c.is_im||c.is_mpim)||t.channelFilter&&!t.channelFilter.includes(c.id)&&!t.channelFilter.includes(c.name))),o=a.map(c=>this.mapChannel(c,new Map));let d=0;const u=new Map;for(const[c,f]of e.messages){const m=e.channels.find(T=>T.id===c);if(!m||!a.some(T=>T.id===c))continue;const k=this.filterMessages(f,t);u.set(m.name,k.length),d+=k.length}let p=0,g=0;for(const c of e.messages.values())for(const f of c)f.files&&(p+=f.files.length,g+=f.files.reduce((m,w)=>m+(w.size||0),0));return{users:{total:e.users.length,filtered:r.length,items:s},channels:{total:e.channels.length,filtered:a.length,items:o},messages:{total:d,perChannel:u},files:{total:p,totalSize:g}}}async*import(e,t={}){this.abortController=new AbortController,this.mapping={users:new Map,channels:new Map,files:new Map};const r=[],s={usersImported:0,channelsImported:0,messagesImported:0,filesImported:0,reactionsImported:0,threadsImported:0},a=new Date,d=1e3/(this.config.rateLimit??10);try{if(t.importUsers!==!1){const p=e.users.filter(c=>!c.deleted);let g=0;for(const c of p){if(this.abortController.signal.aborted)break;const f=this.mapUser(c),m=await this.config.createUser(f);m.success&&m.id?(this.mapping.users.set(c.id,m.id),s.usersImported++):r.push({phase:"users",itemId:c.id,itemType:"user",message:m.error??"Failed to create user"}),g++,yield{phase:"users",total:p.length,processed:g,failed:r.filter(w=>w.phase==="users").length,current:c.name,percentage:Math.round(g/p.length*100),isComplete:!1,errors:r},await this.delay(d)}}if(t.importChannels!==!1){const p=e.channels.filter(c=>{var f;return t.skipArchived&&c.is_archived||t.skipDirectMessages&&(c.is_im||c.is_mpim)?!1:(f=t.channelFilter)!=null&&f.length?t.channelFilter.includes(c.id)||t.channelFilter.includes(c.name):!0});let g=0;for(const c of p){if(this.abortController.signal.aborted)break;const f=this.mapChannel(c,this.mapping.users),m=await this.config.createChannel(f);m.success&&m.id?(this.mapping.channels.set(c.id,m.id),s.channelsImported++):r.push({phase:"channels",itemId:c.id,itemType:"channel",message:m.error??"Failed to create channel"}),g++,yield{phase:"channels",total:p.length,processed:g,failed:r.filter(w=>w.phase==="channels").length,current:c.name,percentage:Math.round(g/p.length*100),isComplete:!1,errors:r},await this.delay(d)}}if(t.importMessages!==!1){const p=[];for(const[f,m]of e.messages){if(!this.mapping.channels.has(f))continue;const w=this.filterMessages(m,t);for(const k of w)p.push({channelId:f,message:k})}p.sort((f,m)=>parseFloat(f.message.ts)-parseFloat(m.message.ts));const g=new Map;let c=0;for(const{channelId:f,message:m}of p){if(this.abortController.signal.aborted)break;const w=this.mapMessage(m,f,this.mapping,g),k=await this.config.createMessage(w);k.success&&k.id?((!m.thread_ts||m.thread_ts===m.ts)&&g.set(m.ts,k.id),s.messagesImported++,w.isThreadReply&&s.threadsImported++,s.reactionsImported+=w.reactions.length):r.push({phase:"messages",itemId:m.ts,itemType:"message",message:k.error??"Failed to create message"}),c++,yield{phase:"messages",total:p.length,processed:c,failed:r.filter(T=>T.phase==="messages").length,current:`${c}/${p.length}`,percentage:Math.round(c/p.length*100),isComplete:!1,errors:r},await this.delay(d)}}if(t.importFiles&&t.downloadFiles&&this.config.uploadFile&&this.config.downloadFile){const p=[];for(const c of e.messages.values())for(const f of c)f.files&&p.push(...f.files);let g=0;for(const c of p){if(this.abortController.signal.aborted)break;try{const f=c.url_private_download??c.url_private;if(f&&this.config.slackToken){const m=await this.config.downloadFile(f,this.config.slackToken),w=await this.config.uploadFile(c,m);w.success&&w.url?(this.mapping.files.set(c.id,w.url),s.filesImported++):r.push({phase:"files",itemId:c.id,itemType:"file",message:w.error??"Failed to upload file"})}}catch(f){r.push({phase:"files",itemId:c.id,itemType:"file",message:f instanceof Error?f.message:"File download failed"})}g++,yield{phase:"files",total:p.length,processed:g,failed:r.filter(f=>f.phase==="files").length,current:c.name,percentage:Math.round(g/p.length*100),isComplete:!1,errors:r},await this.delay(d)}}const u=new Date;return yield{phase:"complete",total:0,processed:0,failed:r.length,percentage:100,isComplete:!0,errors:r},{status:(r.length>0,"completed"),stats:s,mapping:this.mapping,errors:r,startedAt:a,completedAt:u,duration:u.getTime()-a.getTime()}}finally{this.abortController=null}}cancel(){var e;(e=this.abortController)==null||e.abort()}mapUser(e){var t,r,s,a,o;return{slackId:e.id,email:e.email,displayName:((t=e.profile)==null?void 0:t.display_name)||e.name,realName:e.real_name,avatarUrl:((r=e.profile)==null?void 0:r.image_192)||((s=e.profile)==null?void 0:s.image_72),title:(a=e.profile)==null?void 0:a.title,phone:(o=e.profile)==null?void 0:o.phone,timezone:e.tz,isAdmin:e.is_admin??!1,isBot:e.is_bot??!1,isDeactivated:e.deleted??!1}}mapChannel(e,t){var s,a;let r="public";return e.is_private&&(r="private"),e.is_im&&(r="dm"),e.is_mpim&&(r="mpim"),{slackId:e.id,name:e.name,type:r,description:(s=e.purpose)==null?void 0:s.value,topic:(a=e.topic)==null?void 0:a.value,isArchived:e.is_archived??!1,creatorId:e.creator?t.get(e.creator):void 0,memberIds:(e.members??[]).map(o=>t.get(o)).filter(o=>!!o),createdAt:e.created?new Date(e.created*1e3):void 0}}mapMessage(e,t,r,s){const a=r.channels.get(t)??t,o=e.user?r.users.get(e.user):void 0,{text:d,html:u}=this.convertSlackMessage(e.text,r.users),p=e.thread_ts!==void 0&&e.thread_ts!==e.ts,g=e.thread_ts?s.get(e.thread_ts):void 0,c=[];if(e.files)for(const m of e.files)c.push({type:m.mimetype.startsWith("image/")?"image":"file",url:r.files.get(m.id)??m.url_private,name:m.name,size:m.size});if(e.attachments)for(const m of e.attachments)m.image_url?c.push({type:"image",url:m.image_url}):m.title_link&&c.push({type:"link",url:m.title_link,name:m.title});const f=(e.reactions??[]).map(m=>({emoji:m.name,userIds:m.users.map(w=>r.users.get(w)).filter(w=>!!w),count:m.count}));return{channelId:a,senderId:o,content:d,htmlContent:u,threadId:g,isThreadReply:p,attachments:c,reactions:f,createdAt:e.ts?new Date(parseFloat(e.ts)*1e3):void 0,editedAt:e.edited?new Date(parseFloat(e.edited.ts)*1e3):void 0}}convertSlackMessage(e,t){let r=e,s=this.escapeHtml(e);const a=/<@([A-Z0-9]+)(?:\|([^>]+))?>/g;return r=r.replace(a,(o,d,u)=>u?`@${u}`:"@user"),s=s.replace(/<@([A-Z0-9]+)(?:\|([^&]+))?>/g,(o,d,u)=>`<span class="mention" data-user-id="${t.get(d)??d}">@${u??"user"}</span>`),r=r.replace(/<#([A-Z0-9]+)\|([^>]+)>/g,"#$2"),s=s.replace(/<#([A-Z0-9]+)\|([^&]+)>/g,'<span class="channel-mention">#$2</span>'),r=r.replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)"),r=r.replace(/<(https?:\/\/[^>]+)>/g,"$1"),s=s.replace(/<(https?:\/\/[^|&]+)\|([^&]+)>/g,'<a href="$1">$2</a>'),s=s.replace(/<(https?:\/\/[^&]+)>/g,'<a href="$1">$1</a>'),r=this.convertEmoji(r),s=this.convertEmoji(s),s=s.replace(/\*([^*]+)\*/g,"<strong>$1</strong>"),s=s.replace(/\b_([^_]+)_\b/g,"<em>$1</em>"),s=s.replace(/~([^~]+)~/g,"<del>$1</del>"),s=s.replace(/`([^`]+)`/g,"<code>$1</code>"),s=s.replace(/```([^`]+)```/g,"<pre>$1</pre>"),s=s.replace(/\n/g,"<br>"),{text:r,html:s}}convertEmoji(e){const t={":smile:":"๐",":laughing:":"๐",":blush:":"๐",":heart_eyes:":"๐",":heart:":"โค๏ธ",":thumbsup:":"๐",":thumbsdown:":"๐",":wave:":"๐",":clap:":"๐",":fire:":"๐ฅ",":rocket:":"๐",":star:":"โญ",":sparkles:":"โจ",":tada:":"๐",":100:":"๐ฏ",":thinking_face:":"๐ค",":eyes:":"๐",":pray:":"๐",":muscle:":"๐ช",":ok_hand:":"๐",":white_check_mark:":"โ
",":x:":"โ",":warning:":"โ ๏ธ",":question:":"โ",":exclamation:":"โ",":point_right:":"๐",":point_left:":"๐",":point_up:":"๐",":point_down:":"๐"};return e.replace(/:([a-z0-9_+-]+):/g,(r,s)=>t[r]??r)}filterMessages(e,t){return e.filter(r=>r.subtype==="bot_message"?!0:!(t.messagesAfter&&new Date(parseFloat(r.ts)*1e3)<t.messagesAfter||t.messagesBefore&&new Date(parseFloat(r.ts)*1e3)>t.messagesBefore||!t.importThreads&&r.thread_ts&&r.thread_ts!==r.ts))}async extractZipContents(e){return console.warn("ZIP extraction requires JSZip library. Use parseSlackExportFromJson() for JSON input."),new Map}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}delay(e){return new Promise(t=>setTimeout(t,e))}}let Ee=null;function Ze(i){if(!Ee&&i&&(Ee=new Lt(i)),!Ee)throw new Error("SlackImportService not initialized. Call with config first.");return Ee}function gi(){Ee=null}function mi(i={}){const{config:e}=i,t=l.useMemo(()=>{if(e)return Ze(e);try{return Ze()}catch{return null}},[e]),[r,s]=l.useState(null),[a,o]=l.useState(!1),[d,u]=l.useState(null),p=l.useCallback(m=>{if(!t)throw new Error("Service not initialized");return t.parseSlackExportFromJson(m)},[t]),g=l.useCallback((m,w)=>{if(!t)throw new Error("Service not initialized");return t.previewImport(m,w)},[t]),c=l.useCallback(async function*(m,w){var k,T;if(!t)throw new Error("Service not initialized");o(!0),u(null);try{for await(const U of t.import(m,w))s(U),yield U;const h=t.import(m,w);let C;for await(const U of h)C=U;const A=(T=(k=h.next)==null?void 0:k.call(h))==null?void 0:T.value;return A&&u(A),A}finally{o(!1)}},[t]),f=l.useCallback(()=>{t==null||t.cancel(),o(!1)},[t]);return{parseJson:p,preview:g,import:c,cancel:f,progress:r,isImporting:a,result:d}}const Ft={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."},Qe={US:"+1",CA:"+1",UK:"+44",DE:"+49",FR:"+33",PL:"+48",ES:"+34",IT:"+39",AU:"+61",JP:"+81",IN:"+91",BR:"+55",MX:"+52"};class ot{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=Ft,this.ivrText={..._t,...e.ivrText}}on(e,t){this.eventHandlers[e]=t}off(e){delete this.eventHandlers[e]}emit(e,...t){const r=this.eventHandlers[e];r&&r(...t)}generateDialInInfo(e,t){const r=this.getAvailableNumbers(),s=this.generateAccessPin(),a=this.generateAccessPin(8),o={meetingId:e,dialInNumbers:r,accessPin:s,hostPin:a,meetingTitle:t,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 t=Qe[e],r=Math.floor(1e9+Math.random()*9e9).toString();return`${t}${r}`}formatPhoneNumber(e){const t=Qe[e],r=this.generatePhoneNumber(e).slice(t.length);return e==="US"||e==="CA"?`${t} (${r.slice(0,3)}) ${r.slice(3,6)}-${r.slice(6)}`:`${t} ${r}`}generateAccessPin(e=6){return Math.floor(Math.random()*Math.pow(10,e)).toString().padStart(e,"0")}async handleIncomingCall(e,t,r){const s={callId:e,callerNumber:t,callerName:r,state:"connecting",joinedAt:Date.now(),audioStats:{volume:0,isMuted:!1,packetLoss:0,quality:5},isHost:!1,isModerator:!1};return this.participants.set(e,s),this.updateParticipantState(e,"waiting-pin"),await this.playIvr(e,"welcome"),await this.playIvr(e,"enterPin"),s}async validatePinAndJoin(e,t,r){const s=this.participants.get(e);if(!s)return{success:!1,isHost:!1};const a=this.meetingDialIns.get(t);if(!a)return await this.playIvr(e,"invalidPin"),{success:!1,isHost:!1};const o=r===a.hostPin;return r===a.accessPin||o?(s.isHost=o,s.isModerator=o,this.updateParticipantState(e,"joined"),await this.playIvr(e,"joined"),this.emit("onParticipantJoined",{...s}),{success:!0,isHost:o}):(await this.playIvr(e,"invalidPin"),{success:!1,isHost:!1})}getParticipant(e){return this.participants.get(e)}getParticipants(){return Array.from(this.participants.values())}updateParticipantState(e,t){const r=this.participants.get(e);if(!r)return;const s=r.state;r.state=t,this.emit("onParticipantStateChanged",{...r},s)}async muteParticipant(e){const t=this.participants.get(e);t&&(t.audioStats.isMuted=!0,this.updateParticipantState(e,"muted"),await this.playIvr(e,"muted"))}async unmuteParticipant(e){const t=this.participants.get(e);t&&(t.audioStats.isMuted=!1,this.updateParticipantState(e,"joined"),await this.playIvr(e,"unmuted"))}async toggleMute(e){const t=this.participants.get(e);return t?t.audioStats.isMuted?(await this.unmuteParticipant(e),!1):(await this.muteParticipant(e),!0):!1}async putOnHold(e){this.participants.get(e)&&(this.updateParticipantState(e,"on-hold"),await this.playIvr(e,"onHold"))}async removeFromHold(e){this.participants.get(e)&&(this.updateParticipantState(e,"joined"),await this.playIvr(e,"joined"))}async muteAll(e=!0){for(const t of this.participants.values())e&&(t.isHost||t.isModerator)||await this.muteParticipant(t.callId)}async unmuteAll(){for(const e of this.participants.values())await this.unmuteParticipant(e.callId)}async handleDtmf(e,t){const r=this.participants.get(e);r&&(this.emit("onDtmfReceived",{...r},t),t===this.dtmfCommands.toggleMute?await this.toggleMute(e):t===this.dtmfCommands.raiseHand||(t===this.dtmfCommands.leave?await this.disconnectParticipant(e):t===this.dtmfCommands.help?await this.playHelp(e):(r.isHost||r.isModerator)&&(t===this.dtmfCommands.hostMuteAll?await this.muteAll():t===this.dtmfCommands.hostUnmuteAll?await this.unmuteAll():t===this.dtmfCommands.hostEndMeeting&&await this.endMeeting())))}setDtmfCommands(e){this.dtmfCommands={...this.dtmfCommands,...e}}async playIvr(e,t){const r=this.ivrText[t];await new Promise(s=>setTimeout(s,r.length*50))}async playCustomMessage(e,t){await new Promise(r=>setTimeout(r,t.length*50))}async playHelp(e){await this.playCustomMessage(e,`
|
|
7
7
|
To mute or unmute yourself, press star 6.
|
|
8
8
|
To raise your hand, press star 9.
|
|
9
9
|
To leave the meeting, press pound.
|
package/dist/index.mjs
CHANGED
|
@@ -1415,7 +1415,6 @@ function dt({
|
|
|
1415
1415
|
borderRadius: 20,
|
|
1416
1416
|
padding: "8px 14px",
|
|
1417
1417
|
fontSize: 14,
|
|
1418
|
-
outline: "none",
|
|
1419
1418
|
fontFamily: "inherit",
|
|
1420
1419
|
lineHeight: 1.5,
|
|
1421
1420
|
overflow: "hidden"
|
|
@@ -2093,7 +2092,6 @@ function en({
|
|
|
2093
2092
|
border: "1px solid var(--nice-border, #e5e7eb)",
|
|
2094
2093
|
borderRadius: 16,
|
|
2095
2094
|
fontSize: 13,
|
|
2096
|
-
outline: "none",
|
|
2097
2095
|
boxSizing: "border-box",
|
|
2098
2096
|
background: "var(--nice-bg, #fff)"
|
|
2099
2097
|
}
|
|
@@ -2954,7 +2952,6 @@ function an({
|
|
|
2954
2952
|
borderRadius: 8,
|
|
2955
2953
|
padding: "8px 12px",
|
|
2956
2954
|
fontSize: 14,
|
|
2957
|
-
outline: "none",
|
|
2958
2955
|
fontFamily: "inherit",
|
|
2959
2956
|
lineHeight: 1.5,
|
|
2960
2957
|
overflow: "hidden",
|
|
@@ -3107,7 +3104,6 @@ function an({
|
|
|
3107
3104
|
borderRadius: 8,
|
|
3108
3105
|
padding: "7px 10px",
|
|
3109
3106
|
fontSize: 13,
|
|
3110
|
-
outline: "none",
|
|
3111
3107
|
fontFamily: "inherit",
|
|
3112
3108
|
overflow: "hidden"
|
|
3113
3109
|
}
|
|
@@ -6370,7 +6366,6 @@ function Rn({
|
|
|
6370
6366
|
border: "1px solid var(--nice-border, #e5e7eb)",
|
|
6371
6367
|
borderRadius: 16,
|
|
6372
6368
|
fontSize: 12,
|
|
6373
|
-
outline: "none",
|
|
6374
6369
|
boxSizing: "border-box",
|
|
6375
6370
|
background: "var(--nice-bg, #fff)"
|
|
6376
6371
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nice2dev/ui-communication",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.1",
|
|
4
4
|
"description": "NiceCommunication โ full-spectrum communication suite: chat bubble, messenger, voice/video calls, multi-party conference, and Teams-style workspace. Provider-agnostic RTC transport.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"react-dom": ">=17.0.0"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
|
-
"@nice2dev/ui": "^1.
|
|
38
|
+
"@nice2dev/ui": "^1.3.1",
|
|
39
39
|
"@testing-library/jest-dom": "^7.0.1",
|
|
40
40
|
"@testing-library/react": "^16.3.3",
|
|
41
41
|
"@types/react": "^19.2.18",
|