// COMMUNICATIONS PLATFORM — Calls (voice/video with recording compliance)
const { useState: useCmCallsState } = React;

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

  const [filter, setFilter] = useCmCallsState('all');
  const [selected, setSelected] = useCmCallsState(data.calls[0].id);

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

  const filtered = data.calls.filter(c => {
    if (filter === 'video') return c.kind === 'video';
    if (filter === 'voice') return c.kind === 'voice';
    if (filter === 'recorded') return c.recorded;
    if (filter === 'external') return c.with.some(w => w.includes(':'));
    return true;
  });

  const current = data.calls.find(c => c.id === selected) || filtered[0];

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

  const participantLabel = (w) => {
    if (w.startsWith('client:')) return { name: w.split(':')[1], icon: '•', color: '#D97706', external: true };
    if (w.startsWith('external:')) return { name: w.split(':')[1], icon: '•', color: '#B91C1C', external: true };
    const p = personById[w];
    return { name: p?.name || w, icon: '•', initials: p?.initials || '?', color: p?.color || '#64748B', external: false };
  };

  const consentPill = (c) => {
    if (c === 'opt-in')  return { ...cm.statusPill('ok'), label: 'ok Consented' };
    if (c === 'opt-out') return { ...cm.statusPill('warn'), label: 'Opted-out' };
    return { ...cm.statusPill('fail'), label: 'No consent' };
  };

  const kpis = [
    { label: 'Calls today',         value: data.calls.filter(c => (Date.now() - new Date(c.ts)) < 24*3600*1000).length },
    { label: 'Avg duration',        value: fmtDuration(Math.round(data.calls.reduce((s,c) => s+c.duration, 0) / data.calls.length)) },
    { label: 'Recorded (consented)', value: data.calls.filter(c => c.recorded && c.consent === 'opt-in').length },
    { label: 'External parties',    value: data.calls.filter(c => c.with.some(w => w.includes(':'))).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>

      {/* Filter tabs */}
      <div style={{ display: 'flex', gap: '6px', marginBottom: '14px', flexWrap: 'wrap' }}>
        {['all','video','voice','recorded','external'].map(f => (
          <button key={f} onClick={() => setFilter(f)} style={{
            padding: '6px 12px', borderRadius: '6px', border: `1px solid ${filter === f ? '#0F766E' : Tc.color.border.light}`,
            background: filter === f ? cm.cipherBg : 'transparent',
            color: filter === f ? '#0F766E' : Tc.color.text.tertiary,
            fontSize: '11px', fontWeight: filter === f ? 700 : 500,
            cursor: 'pointer', textTransform: 'capitalize', fontFamily: Tc.font.family,
          }}>{f}</button>
        ))}
        <div style={{ flex: 1 }} />
        <button style={cm.btnSecondary}> Start voice call</button>
        <button style={cm.btnPrimary}> Start video call</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(320px, 420px)', gap: '16px' }}>
        {/* List */}
        <CmSectionCard title={`Call history · ${filtered.length}`}>
          <div style={cm.tableWrap}>
            <table style={cm.tableFixed}>
              <thead>
                <tr>
                  <th style={cm.th}>Kind</th>
                  <th style={cm.th}>Participants</th>
                  <th style={cm.th}>Matter</th>
                  <th style={cm.th}>Duration</th>
                  <th style={cm.th}>Consent</th>
                  <th style={cm.th}>When</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map(c => {
                  const active = current && current.id === c.id;
                  return (
                    <tr key={c.id} onClick={() => setSelected(c.id)} style={{ cursor: 'pointer', background: active ? 'rgba(13,148,136,0.06)' : 'transparent' }}>
                      <td style={cm.td}>
                        <span style={{ fontSize: '14px' }}>{c.kind === 'video' ? '' : ''}</span>
                        <span style={{ marginLeft: '6px', fontSize: '10px', color: Tc.color.text.tertiary }}>{c.direction === 'outbound' ? '↑' : '↓'}</span>
                      </td>
                      <td style={cm.td}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '4px', flexWrap: 'wrap' }}>
                          {c.with.slice(0, 3).map((w, i) => {
                            const p = participantLabel(w);
                            return (
                              <span key={i} style={{
                                display: 'inline-flex', alignItems: 'center', gap: '4px',
                                padding: '2px 8px', borderRadius: '10px',
                                background: p.external ? 'rgba(185,28,28,0.08)' : Tc.color.bg.secondary,
                                color: p.external ? '#B91C1C' : Tc.color.text.secondary,
                                fontSize: '10px', fontWeight: 600,
                              }}>
                                {p.icon || p.initials} {p.name}
                              </span>
                            );
                          })}
                          {c.with.length > 3 && <span style={{ fontSize: '10px', color: Tc.color.text.tertiary }}>+{c.with.length - 3}</span>}
                        </div>
                      </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, fontFamily: Tc.font.mono, fontSize: '11px' }}>{fmtDuration(c.duration)}</td>
                      <td style={cm.td}>
                        <span style={{ ...cm.tag, ...consentPill(c.consent) }}>{consentPill(c.consent).label}</span>
                        {c.recorded && <span style={{ ...cm.tag, ...cm.statusPill('e2ee'), marginLeft: '4px' }}>REC</span>}
                      </td>
                      <td style={cm.td}>
                        <span style={{ fontSize: '11px', color: Tc.color.text.tertiary }}>{cm.formatTime(c.ts)}</span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </CmSectionCard>

        {/* Detail */}
        {current && (
          <div>
            <CmSectionCard title="Call details">
              <div style={{ padding: '16px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '14px' }}>
                  <div style={{
                    width: '48px', height: '48px', borderRadius: '8px',
                    background: current.kind === 'video' ? '#0F766E' : '#2563EB',
                    color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: '22px',
                  }}>
                    {current.kind === 'video' ? '' : ''}
                  </div>
                  <div>
                    <div style={{ fontSize: '14px', fontWeight: 700, color: Tc.color.text.primary }}>
                      {current.kind === 'video' ? 'Video call' : 'Voice call'} · {current.direction}
                    </div>
                    <div style={{ fontSize: '11px', color: Tc.color.text.tertiary, marginTop: '2px' }}>
                      {new Date(current.ts).toLocaleString()} · {fmtDuration(current.duration)}
                    </div>
                  </div>
                </div>

                <div style={{ ...cm.sectionLabel, marginBottom: '8px' }}>Participants</div>
                <div style={{ marginBottom: '14px' }}>
                  {current.with.map((w, i) => {
                    const p = participantLabel(w);
                    return (
                      <div key={i} style={{
                        display: 'flex', alignItems: 'center', gap: '10px',
                        padding: '8px 0', borderBottom: `1px solid ${Tc.color.border.light}`,
                      }}>
                        <div style={{
                          width: '28px', height: '28px', borderRadius: '50%',
                          background: p.color, color: '#fff',
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          fontSize: '11px', fontWeight: 700,
                        }}>{p.icon || p.initials}</div>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontSize: '12px', fontWeight: 600, color: Tc.color.text.primary }}>{p.name}</div>
                          {p.external && <div style={{ fontSize: '10px', color: '#B91C1C' }}>External party</div>}
                        </div>
                      </div>
                    );
                  })}
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '14px' }}>
                  <div style={cm.stat}>
                    <div style={cm.statLabel}>Recording</div>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: current.recorded ? '#0F766E' : Tc.color.text.tertiary }}>
                      {current.recorded ? ' Encrypted recording' : 'Not recorded'}
                    </div>
                  </div>
                  <div style={cm.stat}>
                    <div style={cm.statLabel}>Transcript</div>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: current.transcribed ? '#0F766E' : Tc.color.text.tertiary }}>
                      {current.transcribed ? ' Available' : '—'}
                    </div>
                  </div>
                </div>

                {/* Consent banner */}
                <div style={{
                  padding: '10px 12px', borderRadius: '6px',
                  background: current.consent === 'opt-in' ? 'rgba(5,150,105,0.08)' : current.consent === 'opt-out' ? 'rgba(217,119,6,0.08)' : 'rgba(185,28,28,0.08)',
                  border: `1px solid ${current.consent === 'opt-in' ? 'rgba(5,150,105,0.22)' : current.consent === 'opt-out' ? 'rgba(217,119,6,0.22)' : 'rgba(185,28,28,0.22)'}`,
                  fontSize: '11px', color: Tc.color.text.secondary, lineHeight: 1.5, marginBottom: '14px',
                }}>
                  <strong style={{
                    color: current.consent === 'opt-in' ? '#059669' : current.consent === 'opt-out' ? '#D97706' : '#B91C1C',
                  }}>
                    {current.consent === 'opt-in'  && 'ok Consent captured'}
                    {current.consent === 'opt-out' && '! Opt-out on file'}
                    {current.consent === 'none'    && 'x No consent recorded'}
                  </strong>
                  <div style={{ marginTop: '2px' }}>
                    {current.consent === 'opt-in'  && 'All participants accepted recording and transcription notice.'}
                    {current.consent === 'opt-out' && 'One or more parties declined recording. Live session only.'}
                    {current.consent === 'none'    && 'No recording/consent notice captured. Check jurisdictional requirements.'}
                  </div>
                </div>

                {current.summary && (
                  <>
                    <div style={{ ...cm.sectionLabel, marginBottom: '6px' }}>AI Summary</div>
                    <div style={{
                      padding: '10px 12px', background: Tc.color.bg.secondary,
                      borderRadius: '6px', fontSize: '12px', color: Tc.color.text.primary,
                      lineHeight: 1.55, border: `1px solid ${Tc.color.border.light}`,
                    }}>
                      {current.summary}
                    </div>
                  </>
                )}

                <div style={{ display: 'flex', gap: '6px', marginTop: '14px' }}>
                  {current.transcribed && <button style={{ ...cm.btnSecondary, flex: 1 }}> Transcript</button>}
                  {current.recorded && <button style={{ ...cm.btnSecondary, flex: 1 }}>▶ Playback</button>}
                  <button style={{ ...cm.btnPrimary, flex: 1 }}> Call back</button>
                </div>
              </div>
            </CmSectionCard>
          </div>
        )}
      </div>
    </div>
  );
}

window.CommsCalls = CommsCalls;
