// COMMUNICATIONS PLATFORM — Secure Messenger (E2EE channels/DMs · the crown jewel)
const { useState: useCmMsgState, useMemo: useCmMsgMemo, useRef: useCmMsgRef } = React;

function CommsSecureMessenger() {
  const cm = window.__cm;
  const Tc = window.ArbiterTokens;
  const data = window.COMMS_DATA;

  const [selected, setSelected] = useCmMsgState({ kind: 'channel', id: 'c1' });
  const [query, setQuery] = useCmMsgState('');
  const [composer, setComposer] = useCmMsgState('');
  const [showVerifyDrawer, setShowVerifyDrawer] = useCmMsgState(false);
  const [disappearing, setDisappearing] = useCmMsgState(false);

  const personById = useCmMsgMemo(() => Object.fromEntries(data.people.map(p => [p.id, p])), []);
  const me = data.people[0]; // u1 Marcus Kirkland

  const channels = data.channels.filter(c => !c.archived);
  const pinnedChannels = channels.filter(c => c.pinned);
  const matterChannels = channels.filter(c => c.matter && !c.pinned);
  const groupChannels = channels.filter(c => !c.matter && !c.pinned);

  const currentConv = selected.kind === 'channel'
    ? channels.find(c => c.id === selected.id)
    : data.dms.find(d => d.id === selected.id);

  const msgs = data.messages[selected.id] || [];

  const members = selected.kind === 'channel'
    ? data.people.slice(0, Math.min(currentConv?.members || 0, 8))
    : (currentConv?.userIds || []).map(id => personById[id]).filter(Boolean);

  const dmPartner = selected.kind === 'dm' && currentConv?.userIds?.length === 1 ? personById[currentConv.userIds[0]] : null;

  const convTitle = selected.kind === 'channel'
    ? `#${currentConv?.name || ''}`
    : dmPartner
      ? dmPartner.name
      : (currentConv?.userIds || []).map(id => personById[id]?.name).join(', ');

  const convTopic = selected.kind === 'channel'
    ? currentConv?.topic
    : dmPartner
      ? `${dmPartner.role} · ${dmPartner.dept}`
      : 'Group DM';

  const filteredChannels = (list) => query
    ? list.filter(c => c.name.toLowerCase().includes(query.toLowerCase()) || (c.topic || '').toLowerCase().includes(query.toLowerCase()))
    : list;

  const filteredDms = query
    ? data.dms.filter(d => d.userIds.some(uid => (personById[uid]?.name || '').toLowerCase().includes(query.toLowerCase())))
    : data.dms;

  // Layout: [sidebar 280] [main flex] [optional info/verify drawer 320]
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: showVerifyDrawer ? '280px 1fr 320px' : '280px 1fr',
      gap: '0',
      height: 'calc(100vh - 280px)', minHeight: '560px',
      border: `1px solid ${Tc.color.border.light}`,
      borderRadius: Tc.radius.lg,
      overflow: 'hidden',
      background: Tc.color.bg.card,
    }}>

      {/* SIDEBAR — channels + DMs */}
      <div style={{ borderRight: `1px solid ${Tc.color.border.light}`, background: Tc.color.bg.secondary, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        <div style={{ padding: '12px', borderBottom: `1px solid ${Tc.color.border.light}`, background: Tc.color.bg.card }}>
          <input
            style={{ ...cm.input, fontSize: '11px' }}
            placeholder="Search channels, people…"
            value={query}
            onChange={e => setQuery(e.target.value)}
          />
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '8px 0' }}>
          {pinnedChannels.length > 0 && (
            <SidebarGroup label="⭐ Pinned">
              {filteredChannels(pinnedChannels).map(c => (
                <SidebarChannelRow key={c.id} ch={c} active={selected.kind === 'channel' && selected.id === c.id} onClick={() => setSelected({ kind: 'channel', id: c.id })} />
              ))}
            </SidebarGroup>
          )}
          {matterChannels.length > 0 && (
            <SidebarGroup label="Matter channels">
              {filteredChannels(matterChannels).map(c => (
                <SidebarChannelRow key={c.id} ch={c} active={selected.kind === 'channel' && selected.id === c.id} onClick={() => setSelected({ kind: 'channel', id: c.id })} />
              ))}
            </SidebarGroup>
          )}
          {groupChannels.length > 0 && (
            <SidebarGroup label="Groups">
              {filteredChannels(groupChannels).map(c => (
                <SidebarChannelRow key={c.id} ch={c} active={selected.kind === 'channel' && selected.id === c.id} onClick={() => setSelected({ kind: 'channel', id: c.id })} />
              ))}
            </SidebarGroup>
          )}
          <SidebarGroup label="Direct messages">
            {filteredDms.map(d => {
              const partner = personById[d.userIds[0]];
              const isGroup = d.userIds.length > 1;
              return (
                <button key={d.id} onClick={() => setSelected({ kind: 'dm', id: d.id })}
                  style={sidebarRowStyle(selected.kind === 'dm' && selected.id === d.id)}>
                  <div style={{ position: 'relative' }}>
                    <div style={{ ...cm.avatar(partner?.initials || '?', 24, partner?.color || '#64748B'), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      {isGroup ? `+${d.userIds.length}` : partner?.initials}
                    </div>
                    {partner && (
                      <span style={{ position: 'absolute', bottom: 0, right: 0, ...cm.presenceDot(partner.status) }} />
                    )}
                  </div>
                  <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                      <span style={{ fontSize: '12px', fontWeight: d.unread > 0 ? 700 : 500, color: Tc.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {isGroup ? d.userIds.map(id => personById[id]?.initials).join(', ') : partner?.name}
                      </span>
                      {d.verified && <span style={{ fontSize: '9px', color: '#0F766E' }}><Icons.Check size={11}/></span>}
                    </div>
                    <div style={{ fontSize: '10px', color: Tc.color.text.tertiary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.lastSnippet}</div>
                  </div>
                  {d.unread > 0 && (
                    <span style={{ padding: '1px 6px', borderRadius: '10px', background: d.mention ? cm.crimson : '#0F766E', color: '#fff', fontSize: '10px', fontWeight: 700 }}>
                      {d.unread}{d.mention ? '@' : ''}
                    </span>
                  )}
                </button>
              );
            })}
          </SidebarGroup>
        </div>
        <div style={{ padding: '10px', borderTop: `1px solid ${Tc.color.border.light}`, background: Tc.color.bg.card, display: 'flex', gap: '6px' }}>
          <button style={{ ...cm.btnSecondary, flex: 1, fontSize: '10px' }}>+ Channel</button>
          <button style={{ ...cm.btnSecondary, flex: 1, fontSize: '10px' }}>+ DM</button>
        </div>
      </div>

      {/* MAIN PANE */}
      <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0, background: Tc.color.bg.card }}>
        {/* Conversation header */}
        <div style={{
          padding: '12px 20px', borderBottom: `1px solid ${Tc.color.border.light}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '12px', flexShrink: 0,
          background: Tc.color.bg.card,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px', minWidth: 0 }}>
            <div style={{
              width: '32px', height: '32px', borderRadius: '6px',
              background: currentConv?.color || '#0F766E', color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: '14px', fontWeight: 700,
            }}>
              {selected.kind === 'channel' ? '#' : (dmPartner?.initials || '+')}
            </div>
            <div style={{ minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <span style={{ fontSize: '14px', fontWeight: 700, color: Tc.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{convTitle}</span>
                <CmLockChip size="sm" />
                {selected.kind === 'channel' && currentConv?.ethicalWall && (
                  <span style={{ ...cm.tag, ...cm.statusPill('warn') }}> ethical wall</span>
                )}
                {selected.kind === 'channel' && currentConv?.restricted && (
                  <span style={{ ...cm.tag, ...cm.statusPill('info') }}>restricted</span>
                )}
              </div>
              <div style={{ fontSize: '11px', color: Tc.color.text.tertiary, marginTop: '2px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {convTopic}
                {selected.kind === 'channel' && ` · ${currentConv?.members} members`}
                {currentConv?.matter && ` · matter ${currentConv.matter}`}
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
            <button style={cm.btnGhost} title="Voice call"></button>
            <button style={cm.btnGhost} title="Video call"></button>
            <button style={cm.btnGhost} title="Pinned"></button>
            <button style={cm.btnGhost} title="Files"></button>
            <button
              style={{ ...cm.btnSecondary, color: showVerifyDrawer ? '#0F766E' : Tc.color.text.secondary }}
              onClick={() => setShowVerifyDrawer(!showVerifyDrawer)}
            >
               Keys
            </button>
          </div>
        </div>

        {/* Ethical wall warning */}
        {selected.kind === 'channel' && currentConv?.ethicalWall && (
          <div style={{
            padding: '8px 20px', background: 'rgba(217,119,6,0.08)', borderBottom: `1px solid rgba(217,119,6,0.22)`,
            fontSize: '11px', color: '#92400E', display: 'flex', alignItems: 'center', gap: '8px',
          }}>
            <span style={{ fontSize: '13px' }}></span>
            <span>
              <strong>Ethical wall enforced.</strong> This channel is isolated from matter {currentConv.matter} conflicts group.
              Membership changes require compliance review.
            </span>
          </div>
        )}

        {/* Message thread */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '16px 20px', background: Tc.color.bg.primary }}>
          {/* System message: E2EE confirmation */}
          <SystemMessage>
            <span style={{ fontSize: '14px', marginRight: '6px' }}></span>
            Messages in this conversation are end-to-end encrypted. Only participants with verified devices can read them.
            {selected.kind === 'dm' && dmPartner && !data.dms.find(d => d.id === selected.id)?.verified && (
              <span> <button onClick={() => setShowVerifyDrawer(true)} style={{ ...cm.btnGhost, padding: '2px 6px', textDecoration: 'underline' }}>Verify fingerprint →</button></span>
            )}
          </SystemMessage>

          {msgs.length === 0 ? (
            <div style={{ padding: '40px 20px', textAlign: 'center', color: Tc.color.text.tertiary, fontSize: '12px' }}>
              No messages yet — start the conversation.
            </div>
          ) : msgs.map((m, idx) => {
            const author = personById[m.userId];
            const prev = msgs[idx - 1];
            const grouped = prev && prev.userId === m.userId && (new Date(m.ts) - new Date(prev.ts) < 5 * 60 * 1000);
            return (
              <MessageBubble
                key={m.id}
                msg={m}
                author={author}
                grouped={grouped}
                cm={cm}
                Tc={Tc}
                isMe={m.userId === me.id}
              />
            );
          })}
        </div>

        {/* Composer */}
        <div style={{
          padding: '10px 20px 14px', borderTop: `1px solid ${Tc.color.border.light}`,
          background: Tc.color.bg.card, flexShrink: 0,
        }}>
          <div style={{
            border: `1px solid ${Tc.color.border.medium}`, borderRadius: Tc.radius.md,
            background: Tc.color.bg.card, padding: '4px',
          }}>
            <textarea
              value={composer}
              onChange={e => setComposer(e.target.value)}
              placeholder={`Message ${selected.kind === 'channel' ? '#' + (currentConv?.name || '') : (dmPartner?.name || 'group')}… (encrypted)`}
              style={{
                width: '100%', minHeight: '48px', resize: 'vertical',
                border: 'none', outline: 'none', padding: '8px 10px',
                fontSize: '12px', fontFamily: Tc.font.family, color: Tc.color.text.primary,
                background: 'transparent', boxSizing: 'border-box',
              }}
            />
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 6px' }}>
              <div style={{ display: 'flex', gap: '2px' }}>
                <button style={cm.btnGhost} title="Attach (encrypted)"></button>
                <button style={cm.btnGhost} title="Emoji"></button>
                <button style={cm.btnGhost} title="Mention">@</button>
                <button style={cm.btnGhost} title="Code">{'</>'}</button>
                <button
                  onClick={() => setDisappearing(!disappearing)}
                  style={{ ...cm.btnGhost, color: disappearing ? '#0F766E' : Tc.color.text.tertiary }}
                  title="Disappearing messages"
                >
                   {disappearing ? '24h' : 'off'}
                </button>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <span style={{ fontSize: '10px', color: Tc.color.text.tertiary }}> E2EE · sealed-sender</span>
                <button style={cm.btnPrimary} disabled={!composer.trim()}>Send</button>
              </div>
            </div>
          </div>
          <div style={{ fontSize: '10px', color: Tc.color.text.tertiary, marginTop: '6px', textAlign: 'center' }}>
            Your device fingerprint: <span style={{ fontFamily: Tc.font.mono }}>{me.fingerprint.split(' · ')[0]}…</span>
          </div>
        </div>
      </div>

      {/* VERIFY / KEYS DRAWER */}
      {showVerifyDrawer && (
        <div style={{ borderLeft: `1px solid ${Tc.color.border.light}`, background: Tc.color.bg.secondary, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          <div style={{ padding: '12px 16px', borderBottom: `1px solid ${Tc.color.border.light}`, background: Tc.color.bg.card, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontSize: '12px', fontWeight: 700, color: Tc.color.text.primary }}>Key verification</div>
              <div style={{ fontSize: '10px', color: Tc.color.text.tertiary, marginTop: '1px' }}>Compare fingerprints out-of-band</div>
            </div>
            <button style={cm.btnGhost} onClick={() => setShowVerifyDrawer(false)}><Icons.X size={11}/></button>
          </div>
          <div style={{ flex: 1, overflowY: 'auto', padding: '12px' }}>
            {members.map(p => (
              <div key={p.id} style={{
                padding: '12px', marginBottom: '10px',
                background: Tc.color.bg.card, borderRadius: Tc.radius.md,
                border: `1px solid ${Tc.color.border.light}`,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '8px' }}>
                  <div style={{ ...cm.avatar(p.initials, 32, p.color), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{p.initials}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: '12px', fontWeight: 700, color: Tc.color.text.primary }}>{p.name}</div>
                    <div style={{ fontSize: '10px', color: Tc.color.text.tertiary }}>{p.role} · {p.dept}</div>
                  </div>
                  <span style={{ ...cm.tag, ...cm.statusPill(p.id === me.id || ['u2','u3','u6'].includes(p.id) ? 'ok' : 'warn') }}>
                    {p.id === me.id ? 'you' : ['u2','u3','u6'].includes(p.id) ? 'ok verified' : 'unverified'}
                  </span>
                </div>
                <div style={{
                  padding: '8px 10px', borderRadius: '4px', background: Tc.color.bg.secondary,
                  fontFamily: Tc.font.mono, fontSize: '10px', color: Tc.color.text.secondary,
                  lineHeight: 1.5, wordBreak: 'break-all',
                }}>
                  {p.fingerprint}
                </div>
                {p.id !== me.id && (
                  <div style={{ display: 'flex', gap: '6px', marginTop: '8px' }}>
                    <button style={{ ...cm.btnSecondary, flex: 1, fontSize: '10px' }}> Scan QR</button>
                    <button style={{ ...cm.btnPrimary, flex: 1, fontSize: '10px' }}>ok Mark verified</button>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ——— helpers —————————————————————————————

function SidebarGroup({ label, children }) {
  const Tc = window.ArbiterTokens;
  return (
    <div style={{ marginBottom: '10px' }}>
      <div style={{
        fontSize: '10px', fontWeight: 700, color: Tc.color.text.tertiary,
        textTransform: 'uppercase', letterSpacing: '0.08em',
        padding: '4px 14px', marginTop: '4px', marginBottom: '2px',
      }}>{label}</div>
      {children}
    </div>
  );
}

function sidebarRowStyle(active) {
  const Tc = window.ArbiterTokens;
  return {
    display: 'flex', alignItems: 'center', gap: '8px',
    padding: '6px 12px', width: '100%', border: 'none',
    background: active ? 'rgba(13,148,136,0.12)' : 'transparent',
    cursor: 'pointer', fontFamily: Tc.font.family,
    borderLeft: active ? `3px solid #0F766E` : '3px solid transparent',
  };
}

function SidebarChannelRow({ ch, active, onClick }) {
  const Tc = window.ArbiterTokens;
  const cm = window.__cm;
  return (
    <button onClick={onClick} style={sidebarRowStyle(active)}>
      <span style={{ width: '16px', textAlign: 'center', color: ch.unread > 0 ? Tc.color.text.primary : Tc.color.text.tertiary, fontWeight: 700, fontSize: '12px' }}>#</span>
      <span style={{ flex: 1, textAlign: 'left', fontSize: '12px', fontWeight: ch.unread > 0 ? 700 : 500, color: Tc.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        {ch.name}
      </span>
      {ch.ethicalWall && <span style={{ fontSize: '10px' }} title="Ethical wall"></span>}
      {ch.unread > 0 && (
        <span style={{ padding: '1px 6px', borderRadius: '10px', background: ch.mention ? cm.crimson : '#0F766E', color: '#fff', fontSize: '10px', fontWeight: 700 }}>
          {ch.unread}{ch.mention ? '@' : ''}
        </span>
      )}
    </button>
  );
}

function SystemMessage({ children }) {
  const Tc = window.ArbiterTokens;
  return (
    <div style={{
      padding: '8px 12px', margin: '0 0 12px',
      background: 'rgba(20,184,166,0.06)', border: `1px solid rgba(20,184,166,0.22)`,
      borderRadius: '6px', fontSize: '11px', color: Tc.color.text.secondary,
      textAlign: 'center', lineHeight: 1.5,
    }}>
      {children}
    </div>
  );
}

function MessageBubble({ msg, author, grouped, cm, Tc, isMe }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '36px 1fr',
      gap: '10px', marginBottom: grouped ? '2px' : '10px',
      padding: grouped ? '1px 0' : '4px 0',
    }}>
      <div>
        {!grouped && (
          <div style={{ ...cm.avatar(author?.initials || '?', 32, author?.color || '#64748B'), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {author?.initials || '?'}
          </div>
        )}
      </div>
      <div style={{ minWidth: 0 }}>
        {!grouped && (
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '2px' }}>
            <span style={{ fontSize: '12px', fontWeight: 700, color: Tc.color.text.primary }}>{author?.name || 'Unknown'}</span>
            <span style={{ fontSize: '10px', color: Tc.color.text.tertiary }}>{cm.formatTime(msg.ts)}</span>
            {msg.pinned && <span style={{ fontSize: '10px', color: '#D97706' }} title="Pinned"></span>}
            {msg.edited && <span style={{ fontSize: '10px', color: Tc.color.text.tertiary, fontStyle: 'italic' }}>(edited)</span>}
          </div>
        )}
        <div style={{ fontSize: '12px', color: Tc.color.text.primary, lineHeight: 1.55, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
          {msg.body}
        </div>
        {msg.attachment && (
          <div style={{
            marginTop: '6px', display: 'inline-flex', alignItems: 'center', gap: '8px',
            padding: '8px 10px', border: `1px solid ${Tc.color.border.light}`,
            borderRadius: '6px', background: Tc.color.bg.card, maxWidth: '320px',
          }}>
            <div style={{ fontSize: '18px' }}></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: '11px', fontWeight: 600, color: Tc.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{msg.attachment.name}</div>
              <div style={{ fontSize: '10px', color: Tc.color.text.tertiary }}>{msg.attachment.size}{msg.attachment.encrypted && ' ·  encrypted'}</div>
            </div>
            <button style={cm.btnGhost}>↓</button>
          </div>
        )}
        {msg.reactions && msg.reactions.length > 0 && (
          <div style={{ display: 'flex', gap: '4px', marginTop: '6px', flexWrap: 'wrap' }}>
            {msg.reactions.map((r, i) => (
              <span key={i} style={{
                display: 'inline-flex', alignItems: 'center', gap: '3px',
                padding: '2px 8px', borderRadius: '10px',
                background: Tc.color.bg.secondary, border: `1px solid ${Tc.color.border.light}`,
                fontSize: '11px', cursor: 'pointer',
              }}>
                <span>{r.emoji}</span>
                <span style={{ color: Tc.color.text.secondary, fontWeight: 600 }}>{r.count}</span>
              </span>
            ))}
            <button style={{
              padding: '2px 8px', borderRadius: '10px', background: 'transparent',
              border: `1px dashed ${Tc.color.border.medium}`, fontSize: '11px',
              color: Tc.color.text.tertiary, cursor: 'pointer',
            }}>+</button>
          </div>
        )}
        {msg.thread > 0 && (
          <button style={{
            marginTop: '4px', padding: '3px 8px', borderRadius: '4px',
            background: 'transparent', border: 'none', cursor: 'pointer',
            fontSize: '11px', fontWeight: 600, color: '#0F766E',
          }}>
             {msg.thread} {msg.thread === 1 ? 'reply' : 'replies'}
          </button>
        )}
      </div>
    </div>
  );
}

window.CommsSecureMessenger = CommsSecureMessenger;
