// COMMUNICATIONS PLATFORM — Dashboard (overview KPIs + activity feed)
function CommsDashboard() {
  const cm = window.__cm;
  const Tc = window.ArbiterTokens;
  const data = window.COMMS_DATA;
  const k = data.kpis;

  const kpis = [
    { label: 'Active channels',   value: k.channelsActive,   hint: `${data.channels.filter(c => c.pinned).length} pinned` },
    { label: 'Direct messages',   value: k.dmsActive,        hint: `${data.dms.filter(d => d.unread > 0).length} unread` },
    { label: 'Messages today',    value: cm.num(k.messagesToday), hint: `${k.messagesTodayDays}d avg` },
    { label: 'Calls today',       value: k.callsToday,       hint: `${data.calls.filter(c => c.recorded).length} recorded (consented)` },
    { label: 'Unread email',      value: k.emailsUnread,     hint: `${k.mentionsUnread} @-mentions` },
    { label: 'Client portal rooms', value: k.clientPortalRooms, hint: `${data.portalRooms.reduce((s,p) => s + p.docs, 0)} shared docs` },
    { label: 'E2EE coverage',     value: `${k.e2eeCoverage}%`, hint: 'all channels, DMs, calls' },
    { label: 'Devices',           value: `${k.verifiedDevices}/${k.verifiedDevices + k.unverifiedDevices}`, hint: `${k.unverifiedDevices} unverified` },
  ];

  const recentChannels = data.channels
    .filter(c => !c.archived)
    .sort((a, b) => new Date(b.lastActivity) - new Date(a.lastActivity))
    .slice(0, 6);

  const recentCalls = data.calls.slice(0, 5);
  const topEmails = data.emailThreads.filter(e => e.unread).slice(0, 5);

  const personById = Object.fromEntries(data.people.map(p => [p.id, p]));

  const fmtDuration = (s) => {
    const m = Math.floor(s / 60);
    const ss = s % 60;
    return `${m}m ${ss.toString().padStart(2,'0')}s`;
  };

  return (
    <div>
      {/* KPI strip */}
      <div style={cm.stripKpi}>
        {kpis.map(kpi => (
          <div key={kpi.label} style={cm.stat}>
            <div style={cm.statLabel}>{kpi.label}</div>
            <div style={cm.statValue}>{kpi.value}</div>
            <div style={{ ...cm.statDelta, color: Tc.color.text.tertiary }}>{kpi.hint}</div>
          </div>
        ))}
      </div>

      {/* Security posture band */}
      <div style={{
        ...cm.card,
        background: cm.cipherBg,
        border: `1px solid ${cm.cipherBorder}`,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '12px', padding: '14px 16px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
            <div style={{ width: '36px', height: '36px', borderRadius: '8px', background: '#0F766E', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '18px' }}></div>
            <div>
              <div style={{ fontSize: '13px', fontWeight: 700, color: '#0F766E' }}>End-to-end encrypted · Signal-class protocol</div>
              <div style={{ fontSize: '11px', color: Tc.color.text.secondary, marginTop: '2px' }}>
                X3DH + Double-Ratchet · Forward-secret · Sealed-sender metadata · {k.verifiedDevices} devices verified
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: '8px' }}>
            <button style={cm.btnSecondary}>Key transparency log</button>
            <button style={cm.btnPrimary}>Verify device</button>
          </div>
        </div>
      </div>

      <div style={cm.split(360)}>
        {/* Recent channel activity */}
        <CmSectionCard title="Recent channel activity" action={<button style={cm.btnGhost}>Open messenger →</button>}>
          <div>
            {recentChannels.map(c => (
              <div key={c.id} style={{
                display: 'grid', gridTemplateColumns: '28px 1fr auto', gap: '12px', alignItems: 'center',
                padding: '10px 16px', borderBottom: `1px solid ${Tc.color.border.light}`,
              }}>
                <div style={{ width: '28px', height: '28px', borderRadius: '6px', background: c.color, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '13px', fontWeight: 700 }}>
                  #
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                    <span style={{ fontSize: '12px', fontWeight: 600, color: Tc.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</span>
                    {c.ethicalWall && <span style={{ ...cm.tag, ...cm.statusPill('warn') }}>ethical wall</span>}
                    {c.restricted && <span style={{ ...cm.tag, ...cm.statusPill('e2ee') }}>restricted</span>}
                  </div>
                  <div style={{ fontSize: '10px', color: Tc.color.text.tertiary, marginTop: '2px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.topic}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: '10px', color: Tc.color.text.tertiary }}>{cm.formatTime(c.lastActivity)}</div>
                  {c.unread > 0 && (
                    <div style={{ display: 'inline-block', marginTop: '3px', padding: '1px 7px', borderRadius: '10px', background: c.mention ? cm.crimson : '#0F766E', color: '#fff', fontSize: '10px', fontWeight: 700 }}>
                      {c.unread}{c.mention ? '@' : ''}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </CmSectionCard>

        {/* Recent calls */}
        <CmSectionCard title="Recent calls" action={<button style={cm.btnGhost}>Open calls →</button>}>
          <div>
            {recentCalls.map(v => {
              const participants = v.with.map(w => w.startsWith('client:') || w.startsWith('external:') ? w.split(':')[1] : personById[w]?.name || w).join(', ');
              return (
                <div key={v.id} style={{
                  display: 'grid', gridTemplateColumns: '24px 1fr auto', gap: '10px', alignItems: 'center',
                  padding: '10px 16px', borderBottom: `1px solid ${Tc.color.border.light}`,
                }}>
                  <div style={{ fontSize: '14px' }}>{v.kind === 'video' ? '' : ''}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: Tc.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{participants}</div>
                    <div style={{ fontSize: '10px', color: Tc.color.text.tertiary, marginTop: '2px' }}>
                      {v.direction === 'outbound' ? '↑ outbound' : '↓ inbound'} · {fmtDuration(v.duration)}
                      {v.matter && ` · matter ${v.matter}`}
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: '10px', color: Tc.color.text.tertiary }}>{cm.formatTime(v.ts)}</div>
                    {v.recorded && <div style={{ ...cm.tag, ...cm.statusPill('e2ee'), marginTop: '3px' }}>REC</div>}
                  </div>
                </div>
              );
            })}
          </div>
        </CmSectionCard>
      </div>

      <div style={cm.split(360)}>
        {/* Unread high-priority email */}
        <CmSectionCard title="Priority inbox" action={<button style={cm.btnGhost}>Open inbox →</button>}>
          <div>
            {topEmails.map(e => (
              <div key={e.id} style={{
                padding: '10px 16px', borderBottom: `1px solid ${Tc.color.border.light}`,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '3px' }}>
                  <span style={{ fontSize: '12px', fontWeight: 700, color: Tc.color.text.primary, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.subject}</span>
                  {e.encrypted && <CmLockChip text="E2EE" size="sm" />}
                  {e.starred && <span style={{ color: '#D97706' }}><Icons.Star size={11}/></span>}
                </div>
                <div style={{ fontSize: '11px', color: Tc.color.text.secondary, marginBottom: '4px' }}>
                  <span style={{ fontWeight: 600 }}>{e.from.split('@')[0]}</span>
                  <span style={{ color: Tc.color.text.tertiary }}> · {cm.formatTime(e.ts)}</span>
                  {e.count > 1 && <span style={{ color: Tc.color.text.tertiary }}> · {e.count} messages</span>}
                </div>
                <div style={{ fontSize: '11px', color: Tc.color.text.tertiary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.snippet}</div>
                <div style={{ display: 'flex', gap: '4px', marginTop: '6px', flexWrap: 'wrap' }}>
                  {e.labels.map(l => (
                    <span key={l} style={{ ...cm.tag, background: Tc.color.bg.secondary, color: Tc.color.text.tertiary }}>{l}</span>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </CmSectionCard>

        {/* Key transparency log */}
        <CmSectionCard title="Key transparency log" action={<button style={cm.btnGhost}>Full log →</button>}>
          <div>
            {data.keyEvents.map(ev => {
              const person = personById[ev.userId];
              const actionLabel = {
                device_registered: { text: 'Device registered', color: '#2563EB', icon: '▪' },
                key_rotated: { text: 'Key rotated', color: '#D97706', icon: '•' },
                fingerprint_verified: { text: 'Fingerprint verified', color: '#059669', icon: 'ok' },
                session_pinned: { text: 'Session pinned', color: '#0F766E', icon: '•' },
              }[ev.action] || { text: ev.action, color: '#64748B', icon: '•' };
              return (
                <div key={ev.id} style={{
                  display: 'grid', gridTemplateColumns: '28px 1fr auto', gap: '10px', alignItems: 'center',
                  padding: '10px 16px', borderBottom: `1px solid ${Tc.color.border.light}`,
                }}>
                  <div style={{ ...cm.avatar(person?.initials || '?', 28, person?.color || '#64748B'), display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                    {person?.initials || '?'}
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: Tc.color.text.primary }}>{person?.name || '—'}</div>
                    <div style={{ fontSize: '10px', color: Tc.color.text.tertiary, fontFamily: Tc.font.mono, marginTop: '2px' }}>{ev.deviceId} · {ev.fingerprint}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: '11px', fontWeight: 600, color: actionLabel.color }}>
                      <span style={{ marginRight: '4px' }}>{actionLabel.icon}</span>
                      {actionLabel.text}
                    </div>
                    <div style={{ fontSize: '10px', color: Tc.color.text.tertiary, marginTop: '2px' }}>{cm.formatTime(ev.ts)}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </CmSectionCard>
      </div>
    </div>
  );
}

window.CommsDashboard = CommsDashboard;
