/* CONTROLLING · Vista 3 — COMPRAS
   Kanban 5 colunas: Pedidos · RFQ · Em encomenda · Recepção pendente · Conferida c/ fatura
   Drawer detalhe ao clicar num cartão (P-2841 tem detalhe completo). */

const CtrlComprasView = ({ ctx }) => {
  const H = window.CtrlHelpers;
  const [drawerId, setDrawerId] = React.useState(null);
  const [filtroEmp, setFiltroEmp] = React.useState(null);

  const cols = [
    { k: 'pedidos',   label: 'Pedidos',           sub: 'Aguarda triagem' },
    { k: 'rfq',       label: 'RFQ',               sub: '≥1.000 € · 2-3 propostas' },
    { k: 'encomenda', label: 'Em encomenda',      sub: 'Adjudicada · aguarda entrega' },
    { k: 'recepcao',  label: 'Recepção pendente', sub: 'Chegou · falta validar' },
    { k: 'conferida', label: 'Conferida c/ fatura', sub: 'Match com FSE · pronto pagamento' },
  ];

  const cardsByCol = {};
  cols.forEach(c => {
    cardsByCol[c.k] = window.CTRL_COMPRAS.filter(p => {
      if (p.col !== c.k) return false;
      if (ctx.empresa !== 'todas' && p.empresa !== ctx.empresa) return false;
      if (filtroEmp && p.empresa !== filtroEmp) return false;
      return true;
    });
  });

  const totalCol = (k) => cardsByCol[k].reduce((a, p) => a + (p.valor || 0), 0);
  const drawerData = drawerId ? window.CTRL_COMPRAS.find(p => p.id === drawerId) : null;

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>

      {/* Header com filtros + métricas */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 4px 12px', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span className="font-display" style={{ fontSize: 14, fontWeight: 600 }}>Pipeline compras</span>
          <span className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)', letterSpacing: '0.06em' }}>
            {window.CTRL_COMPRAS.length} cartões · {H.fmtEUR(window.CTRL_COMPRAS.reduce((a, p) => a + (p.valor || 0), 0))}
          </span>
        </div>
        <div style={{ display: 'flex', gap: 4 }}>
          <button onClick={() => setFiltroEmp(null)} className="font-mono" style={{
            fontSize: 9.5, padding: '3px 8px', borderRadius: 3, cursor: 'pointer',
            background: !filtroEmp ? 'var(--ai-500)' : 'transparent',
            color: !filtroEmp ? '#fff' : 'var(--text-muted)',
            border: '1px solid ' + (!filtroEmp ? 'var(--ai-500)' : 'var(--border)'),
            letterSpacing: '0.04em', fontWeight: 600, textTransform: 'uppercase',
          }}>Todas</button>
          {window.CTRL_EMPRESAS.filter(e => e.id !== 'todas').map(e => (
            <button key={e.id} onClick={() => setFiltroEmp(e.id)} className="font-mono" style={{
              fontSize: 9.5, padding: '3px 8px', borderRadius: 3, cursor: 'pointer',
              background: filtroEmp === e.id ? e.color : 'transparent',
              color: filtroEmp === e.id ? '#fff' : e.color,
              border: '1px solid ' + (filtroEmp === e.id ? e.color : `color-mix(in oklch, ${e.color} 30%, transparent)`),
              letterSpacing: '0.04em', fontWeight: 600,
            }}>{e.short}</button>
          ))}
          <span style={{ width: 1, background: 'var(--border)', margin: '0 4px' }} />
          <button className="btn btn-xs btn-ai">+ Novo pedido</button>
        </div>
      </div>

      {/* Kanban */}
      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 10, overflow: 'hidden' }}>
        {cols.map(col => (
          <div key={col.k} className="card" style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden', padding: 0 }}>
            {/* Col header */}
            <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--border)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <span className="font-display" style={{ fontSize: 12, fontWeight: 600 }}>{col.label}</span>
                <span className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)' }}>{cardsByCol[col.k].length}</span>
              </div>
              <div className="font-mono" style={{ fontSize: 9, color: 'var(--text-dim)', marginTop: 2, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{col.sub}</div>
              <div className="font-mono" style={{ fontSize: 10, color: 'var(--text-muted)', marginTop: 4, fontWeight: 600 }}>{H.fmtEUR(totalCol(col.k))}</div>
            </div>
            {/* Cards */}
            <div className="scrollbar" style={{ flex: 1, overflowY: 'auto', padding: '8px', display: 'flex', flexDirection: 'column', gap: 6 }}>
              {cardsByCol[col.k].map(p => (
                <CompraCard key={p.id} p={p} onClick={() => setDrawerId(p.id)} />
              ))}
              {cardsByCol[col.k].length === 0 && (
                <div style={{ textAlign: 'center', fontSize: 10.5, color: 'var(--text-dim)', padding: '20px 0' }}>—</div>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* Drawer */}
      {drawerData && (
        <DrawerCompra p={drawerData} onClose={() => setDrawerId(null)} />
      )}
    </div>
  );
};

// ─── Cartão ──────────────────────────────────────────────

const CompraCard = ({ p, onClick }) => {
  const H = window.CtrlHelpers;
  const slaCol = H.slaColor(p.sla);
  return (
    <button onClick={onClick} style={{
      padding: '8px 10px', textAlign: 'left',
      background: 'var(--bg-sunken)', border: '1px solid var(--border)',
      borderLeft: `2.5px solid ${slaCol}`,
      borderRadius: 4, cursor: 'pointer', display: 'block',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
        <span className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)', fontWeight: 600 }}>{p.id}</span>
        {H.empresaChip(p.empresa)}
      </div>
      <div style={{ fontSize: 11.5, lineHeight: 1.4, marginBottom: 6 }}>{p.titulo}</div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 10 }}>
        <span style={{ color: 'var(--text-dim)' }}>{p.solicitante}</span>
        <span className="font-mono" style={{ fontWeight: 600 }}>{p.valor ? H.fmtEUR(p.valor) : '—'}</span>
      </div>
      {p.rfq && (
        <div style={{ marginTop: 5, padding: '3px 6px', background: 'color-mix(in oklch, var(--ai-500) 8%, transparent)', borderRadius: 3, fontSize: 10, color: 'var(--ai-500)' }}>
          {p.rfq.propostas} propostas · melhor {H.fmtEUR(p.rfq.melhor)}
        </div>
      )}
      <div style={{ marginTop: 4, fontSize: 9.5, color: slaCol, fontFamily: 'var(--font-mono)' }}>
        {p.dias === 0 ? 'hoje' : `${p.dias}d`}{p.sla === 'late' ? ' · atrasado' : p.sla === 'warn' ? ' · atenção' : ''}
      </div>
    </button>
  );
};

// ─── Drawer ──────────────────────────────────────────────

const DrawerCompra = ({ p, onClose }) => {
  const H = window.CtrlHelpers;
  const detalhe = window.CTRL_COMPRA_DETALHE[p.id];

  return (
    <>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 40 }} />
      <div className="scrollbar" style={{
        position: 'absolute', top: 0, right: 0, bottom: 0, width: 480,
        background: 'var(--bg-elev)', borderLeft: '1px solid var(--border)',
        zIndex: 41, overflowY: 'auto', padding: 0,
      }}>
        {/* Header */}
        <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', position: 'sticky', top: 0, background: 'var(--bg-elev)', zIndex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span className="font-mono" style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 600 }}>{p.id}</span>
              {H.empresaChip(p.empresa, { large: true })}
            </div>
            <button onClick={onClose} className="btn btn-xs">✕</button>
          </div>
          <div className="font-display" style={{ fontSize: 15, fontWeight: 600, lineHeight: 1.3 }}>{p.titulo}</div>
          <div style={{ marginTop: 4, fontSize: 11, color: 'var(--text-muted)' }}>
            Solicitante <strong>{p.solicitante}</strong> · {p.dep} · {p.valor ? H.fmtEUR(p.valor) : 'sem orçamento'}
          </div>
        </div>

        {/* Conteúdo */}
        <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 16 }}>
          {detalhe ? (
            <>
              <DetSection num="1" title="Pedido" done>
                <Row label="Quem">{detalhe.pedido.quem}</Row>
                <Row label="Quando">{detalhe.pedido.quando}</Row>
                <Row label="Justificação">{detalhe.pedido.justificacao}</Row>
                <Row label="Urgência">{detalhe.pedido.urgencia}</Row>
                <Row label="Valor estimado">{H.fmtEUR(detalhe.pedido.valorEst)}</Row>
              </DetSection>

              <DetSection num="2" title="RFQ" done={!!detalhe.rfq} skipped={!detalhe.rfq}>
                {detalhe.rfq ? <div>—</div> : <div style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>Saltado · valor &lt; 1.000 € (encomenda directa)</div>}
              </DetSection>

              <DetSection num="3" title="Encomenda" done>
                <Row label="Nº">{detalhe.encomenda.num}</Row>
                <Row label="Fornecedor">{detalhe.encomenda.fornecedor}</Row>
                <Row label="Emissão">{detalhe.encomenda.emissao}</Row>
                <Row label="Prazo entrega">{detalhe.encomenda.prazo}</Row>
                <Row label="Total">{H.fmtEUR(detalhe.encomenda.total)}</Row>
              </DetSection>

              <DetSection num="4" title="Recepção" done>
                <Row label="Recebido por">{detalhe.recepcao.quem}</Row>
                <Row label="Data">{detalhe.recepcao.data}</Row>
                <Row label="Quantidade">{detalhe.recepcao.qtd}</Row>
                <Row label="Estado">{detalhe.recepcao.estado}</Row>
              </DetSection>

              <DetSection num="5" title="Match com fatura" pending>
                <div className="ai-surface" style={{ padding: 10, borderRadius: 4, borderLeft: '3px solid var(--ai-500)' }}>
                  <span className="ai-chip"><span className="ai-dot" />Digi · sugestão</span>
                  <div style={{ fontSize: 12, marginTop: 6, lineHeight: 1.5 }}>
                    Fatura <strong>{detalhe.matchFatura.sugerida}</strong> bate com esta encomenda:
                  </div>
                  <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 3, fontSize: 11.5 }}>
                    <div>{detalhe.matchFatura.qtdBate ? '✓' : '✗'} Quantidade bate</div>
                    <div>{detalhe.matchFatura.valorBate ? '✓' : '✗'} Valor bate · {H.fmtEUR(detalhe.matchFatura.valor)}</div>
                    <div>{detalhe.matchFatura.datasBatem ? '✓' : '✗'} Datas batem</div>
                  </div>
                  <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
                    <button className="btn btn-xs btn-ai">Confirmar match</button>
                    <button className="btn btn-xs">Rever fatura</button>
                  </div>
                </div>
              </DetSection>
            </>
          ) : (
            <>
              <div className="ai-surface" style={{ padding: 12, borderRadius: 4, borderLeft: '3px solid var(--ai-500)' }}>
                <span className="ai-chip"><span className="ai-dot" />Digi · contexto</span>
                <div style={{ fontSize: 12, marginTop: 6, lineHeight: 1.5 }}>
                  Detalhe completo deste cartão ainda não está mockado · ver <span className="font-mono" style={{ color: 'var(--ai-500)' }}>P-2841</span> para o exemplo de fluxo end-to-end (pedido → encomenda → recepção → match).
                </div>
              </div>
              <DetSection num="—" title={`Estado actual: ${p.col}`} done>
                <Row label="Cartão">{p.id}</Row>
                <Row label="Solicitante">{p.solicitante}</Row>
                <Row label="Departamento">{p.dep}</Row>
                <Row label="Valor">{p.valor ? H.fmtEUR(p.valor) : 'sem orçamento'}</Row>
                <Row label="Idade">{p.dias}d na coluna</Row>
              </DetSection>
            </>
          )}

          <div style={{ display: 'flex', gap: 6, paddingTop: 8, borderTop: '1px solid var(--border)' }}>
            <button className="btn btn-xs btn-ai">Avançar coluna</button>
            <button className="btn btn-xs">Comentar</button>
            <button className="btn btn-xs">Histórico</button>
          </div>
        </div>
      </div>
    </>
  );
};

const DetSection = ({ num, title, done, pending, skipped, children }) => {
  const dotColor = done ? 'var(--success)' : pending ? 'var(--ai-500)' : skipped ? 'var(--text-dim)' : 'var(--border)';
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
        <span style={{
          width: 18, height: 18, borderRadius: '50%',
          background: dotColor, color: '#fff',
          display: 'grid', placeItems: 'center',
          fontSize: 9, fontWeight: 700, fontFamily: 'var(--font-mono)',
        }}>{done ? '✓' : pending ? '●' : skipped ? '–' : num}</span>
        <span className="font-display" style={{ fontSize: 13, fontWeight: 600 }}>{title}</span>
      </div>
      <div style={{ paddingLeft: 26 }}>{children}</div>
    </div>
  );
};

const Row = ({ label, children }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '3px 0', fontSize: 11.5, borderBottom: '1px dotted var(--border)', gap: 12 }}>
    <span style={{ color: 'var(--text-muted)' }}>{label}</span>
    <span style={{ textAlign: 'right' }}>{children}</span>
  </div>
);

window.CtrlComprasView = CtrlComprasView;
