// COMMUNICATIONS PLATFORM — Client Portal (external secure rooms)
const { useState: useCmPortalState } = React;

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

  const [selected, setSelected] = useCmPortalState(data.portalRooms[0].id);
  const current = data.portalRooms.find(r => r.id === selected);

  const kpis = [
    { label: 'Active rooms',          value: data.portalRooms.length },
    { label: 'Shared docs',           value: data.portalRooms.reduce((s,p) => s + p.docs, 0) },
    { label: 'Client messages',       value: data.portalRooms.reduce((s,p) => s + p.messages, 0) },
    { label: 'External contacts',     value: data.externalContacts.length },
  ];

  return (
    <div>
      <div style={cm.stripKpi}>
        {kpis.map(k => (
          <div key={k.label} style={cm.stat}>
            <div style={cm.statLabel}>{k.label}</div>
            <div style={cm.statValue}>{k.value}</div>
          </div>
        ))}
      </div>

      <div style={{
        display: 'grid', gridTemplateColumns: 'minmax(280px, 340px) 1fr',
        gap: '16px',
      }}>
        {/* Rooms list */}
        <CmSectionCard title="Secure rooms" action={<button style={cm.btnGhost}>+ New</button>}>
          <div>
            {data.portalRooms.map(r => {
              const active = selected === r.id;
              return (
                <button key={r.id} onClick={() => setSelected(r.id)} style={{
                  display: 'block', width: '100%', textAlign: 'left', cursor: 'pointer',
                  padding: '12px 14px', border: 'none',
                  background: active ? 'rgba(13,148,136,0.08)' : 'transparent',
                  borderLeft: active ? '3px solid #0F766E' : '3px solid transparent',
                  borderBottom: `1px solid ${Tc.color.border.light}`,
                  fontFamily: Tc.font.family,
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '4px' }}>
                    <span style={{ fontSize: '12px', fontWeight: 700, color: Tc.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>
                      {r.name}
                    </span>
                    {r.e2ee && <span style={{ ...cm.tag, ...cm.statusPill('e2ee'), flexShrink: 0 }}></span>}
                  </div>
                  <div style={{ fontSize: '10px', color: Tc.color.text.tertiary, marginBottom: '4px' }}>
                    Matter {r.matter} · {r.clients.length} external · {r.docs} docs · {r.messages} msgs
                  </div>
                  <div style={{ fontSize: '10px', color: Tc.color.text.tertiary }}>
                    Last activity {cm.formatTime(r.lastActivity)}
                  </div>
                </button>
              );
            })}
          </div>
        </CmSectionCard>

        {/* Room detail */}
        {current && (
          <div>
            <CmSectionCard
              title={current.name}
              action={<div style={{ display: 'flex', gap: '6px' }}>
                <button style={cm.btnSecondary}>Invite client</button>
                <button style={cm.btnPrimary}>+ Share doc</button>
              </div>}
            >
              <div style={{ padding: '16px' }}>
                {/* Status band */}
                <div style={{
                  padding: '12px 14px', borderRadius: '6px',
                  background: cm.cipherBg, border: `1px solid ${cm.cipherBorder}`,
                  marginBottom: '16px',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
                    <span style={{ fontSize: '16px' }}></span>
                    <span style={{ fontSize: '12px', fontWeight: 700, color: '#0F766E' }}>
                      End-to-end encrypted · {current.watermark === 'DYNAMIC' ? 'Dynamic watermarking' : 'Static watermarking'} · Access logged
                    </span>
                  </div>
                  <div style={{ fontSize: '11px', color: Tc.color.text.secondary, marginLeft: '24px' }}>
                    Clients authenticate via passwordless magic-link + device binding. All downloads watermarked with recipient + timestamp.
                  </div>
                </div>

                {/* Meta grid */}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: '10px', marginBottom: '16px' }}>
                  <div style={cm.stat}>
                    <div style={cm.statLabel}>Matter</div>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: Tc.color.text.primary, fontFamily: Tc.font.mono }}>{current.matter}</div>
                  </div>
                  <div style={cm.stat}>
                    <div style={cm.statLabel}>Documents</div>
                    <div style={cm.statValue}>{current.docs}</div>
                  </div>
                  <div style={cm.stat}>
                    <div style={cm.statLabel}>Messages</div>
                    <div style={cm.statValue}>{current.messages}</div>
                  </div>
                  <div style={cm.stat}>
                    <div style={cm.statLabel}>Expires</div>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: Tc.color.text.primary }}>{current.expiresAt}</div>
                  </div>
                </div>

                {/* External clients */}
                <div style={{ ...cm.sectionLabel, marginBottom: '8px' }}>External clients ({current.clients.length})</div>
                <div style={{ marginBottom: '16px' }}>
                  {current.clients.map((email, i) => (
                    <div key={i} style={{
                      display: 'flex', alignItems: 'center', gap: '10px',
                      padding: '10px 12px', marginBottom: '6px',
                      background: Tc.color.bg.secondary, borderRadius: '6px',
                      border: `1px solid ${Tc.color.border.light}`,
                    }}>
                      <div style={{
                        width: '28px', height: '28px', borderRadius: '50%',
                        background: '#D97706', color: '#fff',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontSize: '11px', fontWeight: 700,
                      }}></div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: '12px', fontWeight: 600, color: Tc.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{email}</div>
                        <div style={{ fontSize: '10px', color: Tc.color.text.tertiary }}>External · device bound · last seen {cm.formatTime(current.lastActivity)}</div>
                      </div>
                      <button style={cm.btnGhost}>⋯</button>
                    </div>
                  ))}
                </div>

                {/* Recent activity */}
                <div style={{ ...cm.sectionLabel, marginBottom: '8px' }}>Recent room activity</div>
                <div style={{ border: `1px solid ${Tc.color.border.light}`, borderRadius: '6px', overflow: 'hidden' }}>
                  {[
                    { icon: '◆', text: 'Revised term sheet v4 uploaded', who: 'You', ts: cm.formatTime(current.lastActivity) },
                    { icon: '▸', text: 'Client replied to latest message', who: current.clients[0].split('@')[0], ts: cm.formatTime(new Date(Date.now() - 3 * 3600 * 1000).toISOString()) },
                    { icon: '◇', text: 'Document downloaded (watermarked)', who: current.clients[0].split('@')[0], ts: cm.formatTime(new Date(Date.now() - 8 * 3600 * 1000).toISOString()) },
                    { icon: '•', text: 'New client invited and verified', who: 'You', ts: cm.formatTime(new Date(Date.now() - 24 * 3600 * 1000).toISOString()) },
                  ].map((ev, i) => (
                    <div key={i} style={{
                      display: 'grid', gridTemplateColumns: '24px 1fr auto',
                      gap: '10px', alignItems: 'center',
                      padding: '10px 12px',
                      borderBottom: i < 3 ? `1px solid ${Tc.color.border.light}` : 'none',
                      background: Tc.color.bg.card,
                    }}>
                      <span style={{ fontSize: '14px' }}>{ev.icon}</span>
                      <div>
                        <div style={{ fontSize: '12px', color: Tc.color.text.primary }}>{ev.text}</div>
                        <div style={{ fontSize: '10px', color: Tc.color.text.tertiary, marginTop: '2px' }}>{ev.who}</div>
                      </div>
                      <span style={{ fontSize: '10px', color: Tc.color.text.tertiary }}>{ev.ts}</span>
                    </div>
                  ))}
                </div>
              </div>
            </CmSectionCard>

            {/* External contacts directory */}
            <CmSectionCard title="External contacts directory">
              <div style={cm.tableWrap}>
                <table style={cm.tableFixed}>
                  <thead>
                    <tr>
                      <th style={cm.th}>Contact</th>
                      <th style={cm.th}>Organization</th>
                      <th style={cm.th}>Role</th>
                      <th style={cm.th}>Matter</th>
                      <th style={cm.th}>Verified</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.externalContacts.map(c => (
                      <tr key={c.id}>
                        <td style={cm.td}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <div style={{
                              width: '24px', height: '24px', borderRadius: '50%',
                              background: c.verified ? '#0F766E' : '#94A3B8',
                              color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
                              fontSize: '10px', fontWeight: 700,
                            }}>{c.name.split(' ').map(n => n[0]).slice(0,2).join('')}</div>
                            <div>
                              <div style={{ fontSize: '12px', fontWeight: 600 }}>{c.name}</div>
                              <div style={{ fontSize: '10px', color: Tc.color.text.tertiary }}>{c.email}</div>
                            </div>
                          </div>
                        </td>
                        <td style={cm.td}>{c.org}</td>
                        <td style={cm.td}>{c.role}</td>
                        <td style={cm.td}>{c.matter ? <span style={{ fontFamily: Tc.font.mono, fontSize: '11px' }}>{c.matter}</span> : <span style={{ color: Tc.color.text.tertiary }}>—</span>}</td>
                        <td style={cm.td}>
                          <span style={{ ...cm.tag, ...cm.statusPill(c.verified ? 'ok' : 'warn') }}>
                            {c.verified ? 'ok Verified' : 'Unverified'}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </CmSectionCard>
          </div>
        )}
      </div>
    </div>
  );
}

window.CommsClientPortal = CommsClientPortal;
