/* CONTROLLING · Vista 2 — FATURAS FSE
   Split: inbox esquerda (lista) · extracção centro · workflow direita
   Schema alinhado com CTRL_FSE: nDoc, emissao, vencimento, base, iva, total, rubrica, regimeIva, categoria, digiNote, estado, origem, confianca, ocrFlag, nextStep */

const CtrlFseView = ({ ctx }) => {
  const [selId, setSelId] = React.useState('fse-001');
  const [filtro, setFiltro] = React.useState('todas');

  const fses = window.CTRL_FSE.filter(f => {
    if (ctx.empresa !== 'todas' && f.empresa !== ctx.empresa) return false;
    if (filtro === 'rever')    return f.estado === 'rever';
    if (filtro === 'aprovar')  return f.estado === 'aprovar';
    if (filtro === 'escalada') return f.estado === 'escalada';
    if (filtro === 'flag')     return !!f.ocrFlag;
    return true;
  });
  const sel = window.CTRL_FSE.find(f => f.id === selId) || fses[0];

  return (
    <div style={{ height: '100%', display: 'grid', gridTemplateColumns: '320px 1fr 340px', gap: 12, overflow: 'hidden' }}>
      {/* INBOX */}
      <div className="card" style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden', padding: 0 }}>
        <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
            <span className="font-display" style={{ fontSize: 13, fontWeight: 600 }}>Inbox FSE</span>
            <span className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)' }}>{fses.length} faturas</span>
          </div>
          <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            {[
              { k: 'todas',    lbl: 'Todas' },
              { k: 'rever',    lbl: 'Por rever' },
              { k: 'aprovar',  lbl: 'Por aprovar' },
              { k: 'escalada', lbl: 'Escalada' },
              { k: 'flag',     lbl: '⚠ Flag' },
            ].map(f => (
              <button key={f.k} onClick={() => setFiltro(f.k)} className="font-mono"
                style={{
                  fontSize: 9.5, padding: '3px 7px', borderRadius: 3, cursor: 'pointer',
                  background: filtro === f.k ? 'var(--ai-500)' : 'transparent',
                  color: filtro === f.k ? '#fff' : 'var(--text-muted)',
                  border: '1px solid ' + (filtro === f.k ? 'var(--ai-500)' : 'var(--border)'),
                  letterSpacing: '0.04em', textTransform: 'uppercase', fontWeight: 600,
                }}>{f.lbl}</button>
            ))}
          </div>
          <input placeholder="Buscar fornecedor, NIF, documento…" style={{
            width: '100%', padding: '6px 10px', fontSize: 12, marginTop: 8,
            background: 'var(--bg-sunken)', border: '1px solid var(--border)', borderRadius: 4, color: 'var(--text)',
          }} />
        </div>
        <div className="scrollbar" style={{ flex: 1, overflowY: 'auto' }}>
          {fses.map(f => (
            <FseRow key={f.id} f={f} selected={f.id === selId} onClick={() => setSelId(f.id)} />
          ))}
        </div>
        <div style={{ padding: '8px 12px', borderTop: '1px solid var(--border)', fontSize: 10.5, color: 'var(--text-dim)', display: 'flex', justifyContent: 'space-between' }}>
          <span>Sync Primavera · 14:32</span>
          <button className="btn btn-xs">+ Manual</button>
        </div>
      </div>

      {/* EXTRACÇÃO + PDF */}
      <div className="card" style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden', padding: 0 }}>
        {sel ? <FseExtraction f={sel} /> : <EmptySplit />}
      </div>

      {/* WORKFLOW */}
      <div className="card" style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden', padding: 0 }}>
        {sel ? <FseWorkflow f={sel} /> : null}
      </div>
    </div>
  );
};

// ─── linha do inbox ──────────────────────────────────────────────

const FseRow = ({ f, selected, onClick }) => {
  const H = window.CtrlHelpers;
  const flagDot = f.ocrFlag === 'failed' ? 'var(--danger)' : f.ocrFlag === 'duplicate' ? '#F59E0B' : f.ocrFlag === 'low' ? '#F59E0B' : null;
  return (
    <button onClick={onClick} style={{
      width: '100%', padding: '10px 14px', textAlign: 'left',
      background: selected ? 'color-mix(in oklch, var(--ai-500) 8%, transparent)' : 'transparent',
      borderLeft: '3px solid ' + (selected ? 'var(--ai-500)' : 'transparent'),
      borderBottom: '1px solid var(--border)',
      cursor: 'pointer', display: 'block',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 3 }}>
        <span style={{ fontSize: 12, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}>
          {flagDot && <span style={{ width: 6, height: 6, borderRadius: '50%', background: flagDot }} />}
          {f.fornecedor}
        </span>
        <span className="font-mono" style={{ fontSize: 11, fontWeight: 600 }}>{H.fmtEURexact(f.total)}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
          <span title={f.origem} style={{ fontSize: 11, color: 'var(--text-dim)' }}>{H.origemIcon(f.origem)}</span>
          {H.empresaChip(f.empresa)}
          {H.fseEstadoBadge(f.estado)}
        </div>
        <span className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-muted)' }}>vence {f.diasVenc}d</span>
      </div>
      <div style={{ marginTop: 3, fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>
        {f.nDoc} · {f.emissao}
      </div>
    </button>
  );
};

// ─── extracção (centro) ──────────────────────────────────────────

const FseExtraction = ({ f }) => {
  const H = window.CtrlHelpers;
  return (
    <>
      <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span className="font-display" style={{ fontSize: 14, fontWeight: 600 }}>{f.fornecedor}</span>
            {H.fseEstadoBadge(f.estado)}
            {H.empresaChip(f.empresa, { large: true })}
          </div>
          <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2, fontFamily: 'var(--font-mono)' }}>
            {f.nDoc} · NIF {f.nif} · emissão {f.emissao} · vence {f.vencimento}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn btn-xs">PDF original</button>
          <button className="btn btn-xs">XML SAF-T</button>
        </div>
      </div>

      <div className="scrollbar" style={{ flex: 1, overflow: 'auto', padding: 16, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        {/* PDF preview */}
        <div>
          <div className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)', letterSpacing: '0.06em', marginBottom: 6, textTransform: 'uppercase' }}>PDF · página 1/1</div>
          <div style={{ aspectRatio: '0.71', background: '#fff', border: '1px solid var(--border)', borderRadius: 4, padding: 16, position: 'relative', fontSize: 9, color: '#1f2937', lineHeight: 1.5 }}>
            <div style={{ borderBottom: '1px solid #d1d5db', paddingBottom: 8, marginBottom: 10 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: '#111' }}>{f.fornecedor}</div>
              <div style={{ fontSize: 8, color: '#6b7280' }}>NIF {f.nif}</div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
              <div>
                <div style={{ fontSize: 8, color: '#6b7280' }}>FATURA</div>
                <div style={{ fontWeight: 600 }}>{f.nDoc}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 8, color: '#6b7280' }}>EMISSÃO</div>
                <div>{f.emissao}</div>
              </div>
            </div>
            <div style={{ background: '#f3f4f6', padding: 6, borderRadius: 2, marginBottom: 6, fontSize: 8.5 }}>
              {f.rubrica}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '3px 0', borderBottom: '1px dotted #e5e7eb' }}>
              <span>Subtotal</span><span>{f.base?.toFixed(2)} €</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '3px 0', borderBottom: '1px dotted #e5e7eb' }}>
              <span>IVA · {f.regimeIva}</span><span>{f.iva?.toFixed(2)} €</span>
            </div>
            <div style={{ marginTop: 12, paddingTop: 8, borderTop: '1px solid #d1d5db', textAlign: 'right' }}>
              <div style={{ fontWeight: 700 }}>TOTAL: {f.total.toFixed(2)} €</div>
              <div style={{ fontSize: 8, color: '#6b7280', marginTop: 2 }}>vencimento {f.vencimento}</div>
            </div>
            {f.confianca != null && (
              <div style={{ position: 'absolute', top: 56, right: 16, padding: '2px 4px', border: '1.5px solid var(--ai-500)', borderRadius: 2, fontSize: 8, color: '#312E81', background: 'rgba(165, 142, 251, 0.15)' }}>{f.nDoc}</div>
            )}
          </div>
        </div>

        {/* extracção */}
        <div>
          <div className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)', letterSpacing: '0.06em', marginBottom: 6, textTransform: 'uppercase', display: 'flex', justifyContent: 'space-between' }}>
            <span>Extracção · Digi</span>
            {f.confianca != null
              ? <span style={{ color: f.confianca >= 90 ? 'var(--success)' : f.confianca >= 70 ? '#F59E0B' : 'var(--danger)' }}>● {f.confianca}% confiança</span>
              : <span style={{ color: 'var(--ai-500)' }}>● a extrair…</span>}
          </div>
          <div style={{ background: 'var(--bg-sunken)', borderRadius: 4, padding: 12, border: '1px solid var(--border)' }}>
            <ExtField label="Fornecedor"     value={f.fornecedor} ok />
            <ExtField label="NIF"            value={f.nif} ok />
            <ExtField label="Nº documento"   value={f.nDoc} ok />
            <ExtField label="Emissão"        value={f.emissao} ok />
            <ExtField label="Vencimento"     value={f.vencimento} ok />
            <ExtField label="Empresa"        value={(window.CTRL_EMPRESAS.find(e=>e.id===f.empresa)||{}).label || '—'} ok />
            <ExtField label="Centro custo"   value={f.empresaCusto} ok />
            <ExtField label="Rubrica"        value={f.rubrica} ok />
            <ExtField label="Regime IVA"     value={f.regimeIva} ok />
            <ExtField label="Categoria"      value={f.categoria || 'a classificar'} ok={!!f.categoria} />
            <ExtField label="Base"           value={H.fmtEURexact(f.base)} ok />
            <ExtField label="IVA"            value={H.fmtEURexact(f.iva)} ok />
            <ExtField label="Total"          value={H.fmtEURexact(f.total)} ok bold />
          </div>

          {f.digiNote && (
            <div className="ai-surface" style={{ marginTop: 12, padding: 10, borderLeft: '3px solid var(--ai-500)', borderRadius: 4, fontSize: 11.5, lineHeight: 1.5 }}>
              <span className="ai-chip" style={{ marginBottom: 6 }}><span className="ai-dot" />Digi · análise</span>
              <div style={{ marginTop: 6, color: 'var(--text)' }}>{f.digiNote}</div>
            </div>
          )}

          {f.ocrFlag === 'duplicate' && (
            <div style={{ marginTop: 10, padding: 10, background: 'color-mix(in oklch, #F59E0B 8%, transparent)', border: '1px solid color-mix(in oklch, #F59E0B 26%, transparent)', borderRadius: 4, fontSize: 11.5 }}>
              <strong style={{ color: '#F59E0B' }}>⚠ Possível duplicado</strong>
              <div style={{ color: 'var(--text-muted)', marginTop: 4 }}>Mesmo Nº documento + total que <span style={{ fontFamily: 'var(--font-mono)' }}>fse-001</span>. Verifica se é entrada manual indevida.</div>
            </div>
          )}
          {f.ocrFlag === 'failed' && (
            <div style={{ marginTop: 10, padding: 10, background: 'color-mix(in oklch, var(--danger) 8%, transparent)', border: '1px solid color-mix(in oklch, var(--danger) 26%, transparent)', borderRadius: 4, fontSize: 11.5 }}>
              <strong style={{ color: 'var(--danger)' }}>⚠ Extracção falhou</strong>
              <div style={{ color: 'var(--text-muted)', marginTop: 4 }}>Scan baixa qualidade. Preencher manualmente recomendado.</div>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

const ExtField = ({ label, value, ok, bold }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', borderBottom: '1px dotted var(--border)', fontSize: 11.5, gap: 12 }}>
    <span style={{ color: 'var(--text-muted)', flexShrink: 0 }}>{label}</span>
    <span className="font-mono" style={{ fontWeight: bold ? 700 : 500, color: ok ? 'var(--text)' : 'var(--text-dim)', textAlign: 'right' }}>
      {value} {ok && <span style={{ color: 'var(--success)', marginLeft: 3, fontSize: 10 }}>✓</span>}
    </span>
  </div>
);

// ─── workflow (direita) ──────────────────────────────────────────

const FseWorkflow = ({ f }) => {
  const H = window.CtrlHelpers;
  const order = ['extraindo', 'rever', 'aprovar', 'escalada', 'aprovada', 'integrada'];
  const idx = order.indexOf(f.estado);

  const passos = [
    { l: 'Recebida',                key: 'rec',     done: true,                ts: f.emissao },
    { l: 'OCR + extracção',         key: 'ocr',    done: idx >= 1,            ts: f.confianca != null ? `${f.confianca}% confiança` : 'a processar' },
    { l: 'Por rever (Clara)',        key: 'rever',  done: idx >= 2,            active: f.estado === 'rever' },
    { l: f.total > 2500 ? 'Escalada Etelvina' : 'Aprovação Clara', key: 'apr', done: idx >= 4, active: f.estado === 'aprovar' || f.estado === 'escalada' },
    { l: 'Integrada Primavera',      key: 'int',   done: f.estado === 'integrada', active: f.estado === 'aprovada' },
    { l: 'Pagamento',                key: 'pag',   done: false,               muted: true },
  ];

  const accoesPorEstado = {
    rever:    { primary: 'Marcar revista', secondary: ['Devolver', 'Pedir info'] },
    aprovar:  { primary: 'Aprovar', secondary: ['Devolver', 'Pedir 2ª opinião'] },
    escalada: { primary: 'Aguardar Etelvina', secondary: ['Cancelar escalada'], disabled: true },
    aprovada: { primary: 'Integrar agora', secondary: [] },
    integrada:{ primary: 'Marcar pago', secondary: ['Ver lançamento'] },
    extraindo:{ primary: 'Aguardar…', secondary: [], disabled: true },
    devolvida:{ primary: 'Re-abrir', secondary: [] },
  }[f.estado] || { primary: 'Ver detalhe', secondary: [] };

  return (
    <>
      <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--border)' }}>
        <div className="font-display" style={{ fontSize: 13, fontWeight: 600 }}>Workflow</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>Estado actual · próxima acção</div>
      </div>

      <div className="scrollbar" style={{ flex: 1, overflowY: 'auto', padding: 14 }}>
        {passos.map((p, i) => (
          <div key={p.key} style={{ display: 'flex', gap: 10, paddingBottom: 12 }}>
            <div style={{ width: 18, display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
              <div style={{
                width: 16, height: 16, borderRadius: '50%',
                background: p.done ? 'var(--success)' : p.active ? 'var(--ai-500)' : 'var(--bg-sunken)',
                border: '2px solid ' + (p.done ? 'var(--success)' : p.active ? 'var(--ai-500)' : 'var(--border)'),
                display: 'grid', placeItems: 'center',
                color: '#fff', fontSize: 9, fontWeight: 700,
              }}>{p.done ? '✓' : p.active ? '●' : ''}</div>
              {i < passos.length - 1 && <div style={{ flex: 1, width: 1, background: 'var(--border)', minHeight: 14, marginTop: 2 }} />}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: p.done ? 'var(--text)' : p.active ? 'var(--ai-500)' : 'var(--text-muted)' }}>{p.l}</div>
              {p.ts && <div className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)', marginTop: 1 }}>{p.ts}</div>}
            </div>
          </div>
        ))}

        {/* Próxima acção */}
        <div className="ai-surface" style={{ marginTop: 8, padding: 12, borderRadius: 4, borderLeft: '3px solid var(--ai-500)' }}>
          <div className="font-mono" style={{ fontSize: 9.5, color: 'var(--ai-500)', letterSpacing: '0.06em', marginBottom: 6, textTransform: 'uppercase', fontWeight: 600 }}>Próxima acção</div>
          {f.escalada && <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 8 }}>{f.escalada}</div>}
          <button className="btn btn-xs btn-ai" style={{ width: '100%', marginBottom: 6, opacity: accoesPorEstado.disabled ? 0.6 : 1 }} disabled={accoesPorEstado.disabled}>
            {accoesPorEstado.primary}
          </button>
          {accoesPorEstado.secondary.map(s => (
            <button key={s} className="btn btn-xs" style={{ width: '100%', marginBottom: 4 }}>{s}</button>
          ))}
        </div>

        {/* Histórico fornecedor */}
        {window.CTRL_FORN_HISTORICO[f.fornecedor] && (
          <div style={{ marginTop: 14, padding: 12, background: 'var(--bg-sunken)', borderRadius: 4, border: '1px solid var(--border)' }}>
            <div className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)', letterSpacing: '0.06em', marginBottom: 8, textTransform: 'uppercase' }}>Histórico fornecedor</div>
            {window.CTRL_FORN_HISTORICO[f.fornecedor].map((h, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, padding: '3px 0', borderBottom: i < window.CTRL_FORN_HISTORICO[f.fornecedor].length-1 ? '1px dotted var(--border)' : 'none' }}>
                <span style={{ color: 'var(--text-muted)' }}>{h.mes}</span>
                <span style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <span className="font-mono" style={{ fontWeight: 600 }}>{H.fmtEURexact(h.valor)}</span>
                  <span className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)', minWidth: 32, textAlign: 'right' }}>{h.delta}</span>
                </span>
              </div>
            ))}
          </div>
        )}
      </div>
    </>
  );
};

const EmptySplit = () => (
  <div style={{ flex: 1, display: 'grid', placeItems: 'center', color: 'var(--text-dim)', fontSize: 12 }}>
    Selecciona uma fatura no inbox.
  </div>
);

window.CtrlFseView = CtrlFseView;
