/* CONTROLLING · Vista 6 — CONFIGURAÇÃO
   5 abas: Thresholds · Workflows · Permissões · Integrações · Auditoria */

const CtrlConfigView = () => {
  const [aba, setAba] = React.useState('thresholds');
  const H = window.CtrlHelpers;

  const tabs = [
    { k: 'thresholds',  lbl: 'Thresholds & SLAs' },
    { k: 'workflows',   lbl: 'Workflows & escaladas' },
    { k: 'permissoes',  lbl: 'Permissões' },
    { k: 'integracoes', lbl: 'Integrações' },
    { k: 'auditoria',   lbl: 'Auditoria' },
  ];

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <div style={{ display: 'flex', gap: 4, padding: '0 0 14px', flexShrink: 0, borderBottom: '1px solid var(--border)', marginBottom: 14 }}>
        {tabs.map(t => (
          <button key={t.k} onClick={() => setAba(t.k)} style={{
            padding: '8px 14px', fontSize: 12, fontWeight: 600,
            cursor: 'pointer', background: 'transparent',
            color: aba === t.k ? 'var(--ai-500)' : 'var(--text-muted)',
            border: 'none',
            borderBottom: '2px solid ' + (aba === t.k ? 'var(--ai-500)' : 'transparent'),
            marginBottom: -1,
          }}>{t.lbl}</button>
        ))}
      </div>

      <div className="scrollbar" style={{ flex: 1, overflowY: 'auto' }}>
        {aba === 'thresholds'  && <Thresholds H={H} />}
        {aba === 'workflows'   && <Workflows />}
        {aba === 'permissoes'  && <Permissoes H={H} />}
        {aba === 'integracoes' && <Integracoes />}
        {aba === 'auditoria'   && <Auditoria />}
      </div>
    </div>
  );
};

// ─── Thresholds ──────────────────────────────────────────

const Thresholds = ({ H }) => (
  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14, paddingBottom: 40 }}>
    <ConfCard title="FSE · níveis de aprovação" sub={<>Quem aprova consoante o valor da fatura. <H.ValidarClara>Confirmar valores reais com a Clara — defaults aqui são suposição da equipa Digi.</H.ValidarClara></>}>
      <ConfRow label="Até 2.500 €"  control={<Pill>Clara aprova sozinha</Pill>} />
      <ConfRow label="2.500 – 10.000 €" control={<Pill warn>Escalar para Etelvina</Pill>} />
      <ConfRow label="Acima 10.000 €"  control={<Pill crit>Escalar para Direcção (FC + COO)</Pill>} />
      <ConfRow label="Threshold OCR baixa confiança" control={<Input value="< 70%" />} />
    </ConfCard>

    <ConfCard title="Compras · RFQ obrigatório">
      <ConfRow label="Encomenda directa até" control={<Input value="999 €" />} />
      <ConfRow label="RFQ obrigatório a partir de" control={<Input value="1.000 €" />} />
      <ConfRow label="Mínimo propostas RFQ" control={<Input value="3 propostas" />} />
      <ConfRow label="Decisão Direcção a partir de" control={<Input value="25.000 €" />} />
    </ConfCard>

    <ConfCard title="SLAs por estado">
      <ConfRow label="FSE · OCR + extracção" control={<Input value="< 30 min" />} />
      <ConfRow label="FSE · revisão Clara"   control={<Input value="2 dias úteis" />} />
      <ConfRow label="FSE · escalada"        control={<Input value="3 dias úteis" />} />
      <ConfRow label="Compras · pedido → encomenda" control={<Input value="5 dias úteis" />} />
      <ConfRow label="Compras · recepção → match"   control={<Input value="3 dias úteis" />} />
    </ConfCard>

    <ConfCard title="Tesouraria · alertas">
      <ConfRow label="Saldo mínimo · alerta amarelo" control={<Input value="350.000 €" />} />
      <ConfRow label="Saldo mínimo · alerta crítico" control={<Input value="250.000 €" />} />
      <ConfRow label="Antecipação cobrança · regra" control={<Pill>Sandra autoriza · até 1%</Pill>} />
      <ConfRow label="Notificação Sandra"  control={<Pill ok>Email + WhatsApp</Pill>} />
    </ConfCard>

    <ConfCard title="Activos · alertas de renovação">
      <ConfRow label="Frota · revisão"      control={<Input value="60 dias antes" />} />
      <ConfRow label="Frota · IPO"          control={<Input value="45 dias antes" />} />
      <ConfRow label="Frota · fim contrato" control={<Input value="120 dias antes" />} />
      <ConfRow label="Software · renovação" control={<Input value="90 dias antes" />} />
      <ConfRow label="Seguros · renovação"  control={<Input value="60 dias antes" />} />
    </ConfCard>

    <ConfCard title="Onboarding · prazos">
      <ConfRow label="Iniciar workflow"  control={<Input value="14 dias antes do start" />} />
      <ConfRow label="Bloqueio crítico"  control={<Input value="5 dias antes do start" />} />
      <ConfRow label="Recolha activos · demissão" control={<Input value="último dia" />} />
      <ConfRow label="Forward email"     control={<Input value="30 dias após saída" />} />
    </ConfCard>
  </div>
);

// ─── Workflows ─────────────────────────────────────────

const Workflows = () => (
  <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 14, paddingBottom: 40 }}>
    <ConfCard title="Workflow FSE · cadeia de aprovação"
      sub="Como uma fatura percorre os estados desde recepção até integração no Primavera. Visualização read-only — para alterar o circuito contactar IT.">
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0', overflowX: 'auto' }}>
        {['Recebida', 'OCR + extracção', 'Por rever', 'Por aprovar', 'Escalada', 'Aprovada', 'Integrada', 'Pagamento'].map((s, i, arr) => (
          <React.Fragment key={s}>
            <div style={{
              padding: '6px 10px', borderRadius: 4,
              background: 'var(--bg-sunken)', border: '1px solid var(--border)',
              fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap',
            }}>{s}</div>
            {i < arr.length - 1 && <span style={{ color: 'var(--text-dim)', fontSize: 14 }}>→</span>}
          </React.Fragment>
        ))}
      </div>
    </ConfCard>

    <ConfCard title="Templates · admissão / demissão"
      sub="3 templates default. Cada um tem checklist Clara · IT · RH. Click para editar tarefas.">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
        {[
          { t: 'Admissão · standard', n: '14 tasks · 3 mãos' },
          { t: 'Admissão · Comercial (com viatura)', n: '17 tasks · 3 mãos' },
          { t: 'Demissão · standard', n: '11 tasks · 3 mãos' },
        ].map(x => (
          <div key={x.t} style={{ padding: 10, borderRadius: 4, background: 'var(--bg-sunken)', border: '1px solid var(--border)' }}>
            <div style={{ fontSize: 12, fontWeight: 600 }}>{x.t}</div>
            <div className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)', marginTop: 2 }}>{x.n}</div>
            <button className="btn btn-xs" style={{ marginTop: 8 }}>Editar →</button>
          </div>
        ))}
      </div>
    </ConfCard>
  </div>
);

// ─── Permissões ─────────────────────────────────────────

const Permissoes = ({ H }) => {
  const rows = [
    { user: 'Clara Nobre',     role: 'Owner Controlling', scope: 'Todas excepto TAS · Farben Consulting', edit: true },
    { user: 'Etelvina Costa',  role: 'Aprovadora L2',     scope: 'FSE 2.500–10.000 €',                   edit: true },
    { user: 'Filipe Caldeira', role: 'Direcção',          scope: 'FSE > 10.000 € · RFQ > 25k',           edit: false },
    { user: 'Patrícia Mota',   role: 'Cobranças',         scope: 'Read · clientes a receber',            edit: false },
    { user: 'Sandra Monteiro', role: 'Tesouraria',        scope: 'Edit · entradas / pagamentos',         edit: true },
    { user: 'Paulino (IT)',    role: 'IT ops',            scope: 'Edit · activos software · onboarding IT', edit: true },
  ];
  return (
    <ConfCard title="Quem vê o quê · quem aprova o quê">
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11.5, marginTop: 6 }}>
        <thead>
          <tr style={{ borderBottom: '1px solid var(--border)' }}>
            <th style={{ padding: '8px 10px', textAlign: 'left', fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Pessoa</th>
            <th style={{ padding: '8px 10px', textAlign: 'left', fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Papel</th>
            <th style={{ padding: '8px 10px', textAlign: 'left', fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Scope</th>
            <th style={{ padding: '8px 10px', textAlign: 'right', fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Editar</th>
          </tr>
        </thead>
        <tbody>
          {rows.map(r => (
            <tr key={r.user} style={{ borderBottom: '1px solid var(--border)' }}>
              <td style={{ padding: '8px 10px', fontWeight: 600 }}>{r.user}</td>
              <td style={{ padding: '8px 10px', color: 'var(--text-muted)' }}>{r.role}</td>
              <td style={{ padding: '8px 10px', color: 'var(--text-muted)' }}>{r.scope}</td>
              <td style={{ padding: '8px 10px', textAlign: 'right' }}>
                {r.edit ? <Pill ok>edit</Pill> : <Pill>read</Pill>}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </ConfCard>
  );
};

// ─── Integrações ────────────────────────────────────────

const Integracoes = () => {
  const items = [
    { nome: 'Primavera ERP v10', estado: 'ok',   detalhe: 'Sync bidirecional · documentos FSE · centros custo · rubricas. Última sync 14:32.', endpoint: 'primavera://fb/v10' },
    { nome: 'Inbox email FSE',   estado: 'ok',   detalhe: 'IMAP · faturas@digidelta.pt · OCR automático.', endpoint: 'imap.digidelta.pt' },
    { nome: 'Pasta partilhada',  estado: 'ok',   detalhe: 'OneDrive · /Faturas/Inbox · drag & drop manual.', endpoint: 'onedrive://faturas/inbox' },
    { nome: 'EDI suppliers',     estado: 'warn', detalhe: '3/14 fornecedores ligados (EDP · Vodafone · Galp). Adicionar mais reduz lançamento manual.', endpoint: 'edi://gateway' },
    { nome: 'MDS broker portal', estado: 'ok',   detalhe: 'Apólices + alertas renovação · scrape diário 06:00.', endpoint: 'https://mds.pt/clientes' },
    { nome: 'LeasePlan / ALD',   estado: 'ok',   detalhe: 'Frota · contratos + alertas IPO/revisão.', endpoint: 'api.leaseplan.pt' },
    { nome: 'WhatsApp Business', estado: 'ok',   detalhe: 'Notificações Clara · briefing matinal + alertas críticos.', endpoint: '+351 91 311 22 33' },
  ];
  return (
    <ConfCard title="Sistemas conectados ao Controlling">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {items.map(i => (
          <div key={i.nome} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: 10, borderRadius: 4,
            background: 'var(--bg-sunken)', border: '1px solid var(--border)',
          }}>
            <span style={{
              width: 8, height: 8, borderRadius: '50%',
              background: i.estado === 'ok' ? 'var(--success)' : i.estado === 'warn' ? '#F59E0B' : 'var(--danger)',
              flexShrink: 0,
            }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 12, fontWeight: 600 }}>{i.nome}</span>
                <span className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)' }}>{i.endpoint}</span>
              </div>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{i.detalhe}</div>
            </div>
            <button className="btn btn-xs">Configurar</button>
          </div>
        ))}
      </div>
    </ConfCard>
  );
};

// ─── Auditoria ──────────────────────────────────────────

const Auditoria = () => {
  const log = [
    { ts: '2026-04-28 14:32', user: 'Sistema',         action: 'Sync Primavera concluído · 7 docs novos.' },
    { ts: '2026-04-28 11:42', user: 'Clara Nobre',      action: 'Aprovou fse-008 (Adobe · 516 €).' },
    { ts: '2026-04-28 09:14', user: 'Digi',              action: 'Notificação enviada a Sandra · saldo Sem 21 abaixo de 250k.' },
    { ts: '2026-04-28 08:00', user: 'Digi',              action: 'Briefing matinal enviado a Clara (WhatsApp).' },
    { ts: '2026-04-27 16:08', user: 'Clara Nobre',      action: 'Escalou fse-006 (MDS · 12.400 €) para Direcção.' },
    { ts: '2026-04-27 14:21', user: 'Clara Nobre',      action: 'Marcou Maria Silva · "contrato assinado" (admissão BIOND).' },
    { ts: '2026-04-27 10:15', user: 'Etelvina Costa',   action: 'Aprovou fse-002 escalada (Vodafone · 8.425 €).' },
    { ts: '2026-04-26 18:00', user: 'Sistema',         action: 'Integração diária Primavera · 14 docs.' },
    { ts: '2026-04-26 11:20', user: 'Paulino (IT)',    action: 'Marcou "email criado" · Maria Silva.' },
  ];
  return (
    <ConfCard title="Histórico de acções · últimas 48h"
      sub="Tudo é registado: sync ERP, aprovações, escaladas, comunicações automáticas. Filtrável por utilizador / módulo / período.">
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {log.map((l, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '160px 140px 1fr', gap: 12, padding: '8px 0', borderBottom: i < log.length-1 ? '1px solid var(--border)' : 'none', fontSize: 11.5 }}>
            <span className="font-mono" style={{ color: 'var(--text-dim)' }}>{l.ts}</span>
            <span style={{ color: 'var(--text-muted)' }}>{l.user}</span>
            <span>{l.action}</span>
          </div>
        ))}
      </div>
    </ConfCard>
  );
};

// ─── Atomos ──────────────────────────────────────────────

const ConfCard = ({ title, sub, children }) => (
  <div className="card" style={{ padding: 16 }}>
    <div className="font-display" style={{ fontSize: 14, fontWeight: 600 }}>{title}</div>
    {sub && <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2, marginBottom: 10 }}>{sub}</div>}
    <div style={{ marginTop: sub ? 0 : 10 }}>{children}</div>
  </div>
);

const ConfRow = ({ label, control }) => (
  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px dotted var(--border)' }}>
    <span style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>{label}</span>
    {control}
  </div>
);

const Pill = ({ children, ok, warn, crit }) => {
  const c = crit ? { bg: 'color-mix(in oklch, var(--danger) 14%, transparent)', fg: 'var(--danger)' }
          : warn ? { bg: 'color-mix(in oklch, #F59E0B 14%, transparent)', fg: '#F59E0B' }
          : ok   ? { bg: 'color-mix(in oklch, var(--success) 14%, transparent)', fg: 'var(--success)' }
          : { bg: 'var(--bg-sunken)', fg: 'var(--text)' };
  return (
    <span className="font-mono" style={{
      fontSize: 10, padding: '3px 8px', borderRadius: 3, fontWeight: 600,
      background: c.bg, color: c.fg, letterSpacing: '0.04em', whiteSpace: 'nowrap',
    }}>{children}</span>
  );
};

const Input = ({ value }) => (
  <span className="font-mono" style={{
    fontSize: 11, padding: '3px 8px', borderRadius: 3,
    background: 'var(--bg-sunken)', border: '1px solid var(--border)',
    fontWeight: 600, color: 'var(--text)',
  }}>{value}</span>
);

window.CtrlConfigView = CtrlConfigView;
