/* CONTROLLING · Vista 4 — ACTIVOS & SERVIÇOS
   4 abas: Frota · Telecom · Software · Seguros */

const CtrlActivosView = ({ ctx }) => {
  const [aba, setAba] = React.useState('frota');
  const H = window.CtrlHelpers;

  const filtra = (rows) => rows.filter(r => ctx.empresa === 'todas' || r.empresa === ctx.empresa || r.empresa === 'sgps' || r.empresa === 'sa+dc');
  const frota    = filtra(window.CTRL_FROTA);
  const telecom  = filtra(window.CTRL_TELECOM);
  const software = filtra(window.CTRL_SOFTWARE);
  const seguros  = filtra(window.CTRL_SEGUROS);

  const tabs = [
    { k: 'frota',    lbl: 'Frota',    n: frota.length,    icon: '🚐' },
    { k: 'telecom',  lbl: 'Telecom',  n: telecom.length,  icon: '📱' },
    { k: 'software', lbl: 'Software', n: software.length, icon: '💻' },
    { k: 'seguros',  lbl: 'Seguros',  n: seguros.length,  icon: '🛡' },
  ];

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* Tabs */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 0 12px', flexShrink: 0 }}>
        <div style={{ display: 'flex', gap: 6 }}>
          {tabs.map(t => (
            <button key={t.k} onClick={() => setAba(t.k)} style={{
              padding: '7px 14px', borderRadius: 5, fontSize: 12, fontWeight: 600,
              cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6,
              background: aba === t.k ? 'var(--ai-500)' : 'transparent',
              color: aba === t.k ? '#fff' : 'var(--text-muted)',
              border: '1px solid ' + (aba === t.k ? 'var(--ai-500)' : 'var(--border)'),
            }}>
              <span style={{ fontSize: 13 }}>{t.icon}</span>
              {t.lbl}
              <span className="font-mono" style={{ fontSize: 9.5, padding: '1px 5px', borderRadius: 3, background: aba === t.k ? 'rgba(255,255,255,0.2)' : 'var(--bg-sunken)', fontWeight: 700 }}>{t.n}</span>
            </button>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn btn-xs">Exportar</button>
          <button className="btn btn-xs btn-ai">+ Novo</button>
        </div>
      </div>

      {/* Tabela */}
      <div className="card scrollbar" style={{ flex: 1, overflowY: 'auto', padding: 0 }}>
        {aba === 'frota'    && <FrotaTable    rows={frota} H={H} />}
        {aba === 'telecom'  && <TelecomTable  rows={telecom} H={H} />}
        {aba === 'software' && <SoftwareTable rows={software} H={H} />}
        {aba === 'seguros'  && <SegurosTable  rows={seguros} H={H} />}
      </div>
    </div>
  );
};

// ─── Tabelas ──────────────────────────────────────────

const Th = ({ children, w, right }) => (
  <th className="font-mono" style={{
    padding: '10px 12px', textAlign: right ? 'right' : 'left',
    fontSize: 9.5, color: 'var(--text-dim)', letterSpacing: '0.06em',
    textTransform: 'uppercase', fontWeight: 600,
    width: w, position: 'sticky', top: 0, background: 'var(--bg-elev)',
    borderBottom: '1px solid var(--border)', zIndex: 1,
  }}>{children}</th>
);
const Td = ({ children, mono, right, color, weight }) => (
  <td style={{
    padding: '9px 12px', fontSize: 11.5,
    textAlign: right ? 'right' : 'left',
    fontFamily: mono ? 'var(--font-mono)' : 'inherit',
    color: color || 'var(--text)',
    fontWeight: weight || (mono ? 500 : 400),
  }}>{children}</td>
);
const Tr = ({ children }) => <tr style={{ borderBottom: '1px solid var(--border)' }}>{children}</tr>;

const AlertChip = ({ children, level = 'warn' }) => {
  const colors = {
    warn: { bg: 'color-mix(in oklch, #F59E0B 14%, transparent)', fg: '#F59E0B' },
    crit: { bg: 'color-mix(in oklch, var(--danger) 14%, transparent)', fg: 'var(--danger)' },
    ok:   { bg: 'color-mix(in oklch, var(--success) 14%, transparent)', fg: 'var(--success)' },
  }[level];
  return (
    <span className="font-mono" style={{
      fontSize: 9.5, padding: '2px 6px', borderRadius: 3, fontWeight: 600,
      background: colors.bg, color: colors.fg, letterSpacing: '0.04em',
    }}>{children}</span>
  );
};

const FrotaTable = ({ rows, H }) => (
  <table style={{ width: '100%', borderCollapse: 'collapse' }}>
    <thead><tr>
      <Th w={110}>Matrícula</Th>
      <Th>Marca / modelo</Th>
      <Th w={80}>Empresa</Th>
      <Th>Utilizador</Th>
      <Th>Tipo</Th>
      <Th w={110}>Fim contrato</Th>
      <Th w={90}>IPO</Th>
      <Th w={90}>Revisão</Th>
      <Th>Alertas</Th>
    </tr></thead>
    <tbody>
      {rows.map(r => (
        <Tr key={r.matricula}>
          <Td mono weight={700}>{r.matricula}</Td>
          <Td>{r.marca}</Td>
          <Td>{H.empresaChip(r.empresa)}</Td>
          <Td color="var(--text-muted)">{r.utilizador}</Td>
          <Td color="var(--text-muted)">{r.tipo}</Td>
          <Td mono>{r.fimContrato}</Td>
          <Td mono color={r.ipo === 'OK' ? 'var(--success)' : '#F59E0B'}>{r.ipo}</Td>
          <Td mono color="var(--text-muted)">{r.revisao}</Td>
          <Td><div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            {r.alertas.length === 0 ? <span style={{ color: 'var(--text-dim)', fontSize: 11 }}>—</span>
              : r.alertas.map(a => <AlertChip key={a}>{a}</AlertChip>)}
          </div></Td>
        </Tr>
      ))}
    </tbody>
  </table>
);

const TelecomTable = ({ rows, H }) => (
  <table style={{ width: '100%', borderCollapse: 'collapse' }}>
    <thead><tr>
      <Th>Número</Th>
      <Th>Utilizador</Th>
      <Th w={80}>Empresa</Th>
      <Th>Operador</Th>
      <Th>Plano</Th>
      <Th right w={90}>Custo / mês</Th>
      <Th w={100}>Actualizado</Th>
    </tr></thead>
    <tbody>
      {rows.map(r => (
        <Tr key={r.numero}>
          <Td mono weight={700}>{r.numero}</Td>
          <Td>{r.utilizador}</Td>
          <Td>{H.empresaChip(r.empresa)}</Td>
          <Td color="var(--text-muted)">{r.operador}</Td>
          <Td color="var(--text-muted)">{r.plano}</Td>
          <Td right mono weight={600}>{H.fmtEUR(r.custo)}</Td>
          <Td mono color="var(--text-dim)">{r.atualizado}</Td>
        </Tr>
      ))}
      <tr style={{ background: 'var(--bg-sunken)', fontWeight: 700 }}>
        <td colSpan={5} style={{ padding: '10px 12px', fontSize: 11.5, color: 'var(--text-muted)' }}>Total mensal · {rows.length} cartões</td>
        <td style={{ padding: '10px 12px', textAlign: 'right', fontFamily: 'var(--font-mono)' }}>{H.fmtEUR(rows.reduce((a, r) => a + r.custo, 0))}</td>
        <td></td>
      </tr>
    </tbody>
  </table>
);

const SoftwareTable = ({ rows, H }) => (
  <table style={{ width: '100%', borderCollapse: 'collapse' }}>
    <thead><tr>
      <Th>Software</Th>
      <Th>Fornecedor</Th>
      <Th w={80}>Empresa</Th>
      <Th>Tipo</Th>
      <Th w={100}>Renovação</Th>
      <Th right w={100}>Custo anual</Th>
      <Th>Owner</Th>
      <Th right w={70}>Users</Th>
      <Th>Estado</Th>
    </tr></thead>
    <tbody>
      {rows.map(r => (
        <Tr key={r.nome}>
          <Td weight={600}>{r.nome}</Td>
          <Td color="var(--text-muted)">{r.fornecedor}</Td>
          <Td><span className="font-mono" style={{ fontSize: 9.5, padding: '1px 5px', borderRadius: 3, background: 'var(--bg-sunken)', color: 'var(--text-muted)', fontWeight: 600, letterSpacing: '0.04em' }}>{(r.empresa || '').toUpperCase()}</span></Td>
          <Td color="var(--text-muted)">{r.tipo}</Td>
          <Td mono>{r.renovacao}</Td>
          <Td right mono weight={600}>{H.fmtEUR(r.custo)}</Td>
          <Td color="var(--text-muted)">{r.owner}</Td>
          <Td right mono color="var(--text-muted)">{r.users}</Td>
          <Td>{r.alerta ? <AlertChip>{r.alerta}</AlertChip> : <span style={{ color: 'var(--text-dim)', fontSize: 11 }}>—</span>}</Td>
        </Tr>
      ))}
    </tbody>
  </table>
);

const SegurosTable = ({ rows, H }) => (
  <table style={{ width: '100%', borderCollapse: 'collapse' }}>
    <thead><tr>
      <Th w={100}>Apólice</Th>
      <Th>Categoria</Th>
      <Th w={80}>Empresa</Th>
      <Th>Seguradora</Th>
      <Th w={70}>Broker</Th>
      <Th w={100}>Renovação</Th>
      <Th right w={100}>Prémio</Th>
      <Th>Alerta</Th>
    </tr></thead>
    <tbody>
      {rows.map(r => (
        <Tr key={r.apolice}>
          <Td mono weight={700}>{r.apolice}</Td>
          <Td>{r.cat}</Td>
          <Td><span className="font-mono" style={{ fontSize: 9.5, padding: '1px 5px', borderRadius: 3, background: 'var(--bg-sunken)', color: 'var(--text-muted)', fontWeight: 600, letterSpacing: '0.04em' }}>{(r.empresa || '').toUpperCase()}</span></Td>
          <Td color="var(--text-muted)">{r.seguradora}</Td>
          <Td color="var(--text-muted)">{r.broker}</Td>
          <Td mono>{r.renovacao}</Td>
          <Td right mono weight={600}>{H.fmtEUR(r.premio)}</Td>
          <Td>{r.alerta ? <AlertChip level={r.alerta.includes('38') ? 'crit' : 'warn'}>{r.alerta}</AlertChip> : <span style={{ color: 'var(--text-dim)', fontSize: 11 }}>—</span>}</Td>
        </Tr>
      ))}
    </tbody>
  </table>
);

window.CtrlActivosView = CtrlActivosView;
