/* Wood OS — Financeiro (caixa, recebíveis, despesas, margem) */
const { useState: useStateFin, useMemo: useMemoFin } = React;

/* ============================================================
   Helpers
   ============================================================ */
const PAY_CATEGORY_META = {
  "Madeira/MDF":    { color: "#34D399", icon: "package" },
  "Tampos":         { color: "#38BDF8", icon: "ruler" },
  "Ferragem":       { color: "#F59E0B", icon: "settings" },
  "Acabamento":     { color: "#A78BFA", icon: "spark" },
  "RH":             { color: "#F472B6", icon: "users" },
  "Operacional":    { color: "#FB923C", icon: "zap" },
  "Infraestrutura": { color: "#22D3EE", icon: "building" },
  "Frota":          { color: "#86EFAC", icon: "truck" },
  "Insumos":        { color: "#FCD34D", icon: "boxes" },
};

const FIN_STATUS_META = {
  recebido: { label: "Recebido", dot: "#22C55E", bg: "rgba(34,197,94,0.14)",  fg: "#22C55E", icon: "check" },
  pago:     { label: "Pago",     dot: "#22C55E", bg: "rgba(34,197,94,0.14)",  fg: "#22C55E", icon: "check" },
  pendente: { label: "Pendente", dot: "#38BDF8", bg: "rgba(56,189,248,0.12)", fg: "#38BDF8", icon: "clock" },
  atrasado: { label: "Atrasado", dot: "#EF4444", bg: "rgba(239,68,68,0.12)",  fg: "#EF4444", icon: "alert" },
};

const pct = (n) => `${n > 0 ? "+" : ""}${n.toFixed(1)}%`;

/* ============================================================
   FinancialPage
   ============================================================ */
const FinancialPage = ({ navigate }) => {
  const f = MOCK.financial;
  const [tab, setTab] = useStateFin("overview");
  const [creating, setCreating] = useStateFin(false);
  const [kind, setKind] = useStateFin("receivable");

  const deltaReceita = ((f.summary.receitaMes - f.summary.receitaAnt) / f.summary.receitaAnt) * 100;
  const deltaDespesa = ((f.summary.despesaMes - f.summary.despesaAnt) / f.summary.despesaAnt) * 100;
  const margem = ((f.summary.saldoMes / f.summary.receitaMes) * 100);

  return (
    <>
      <PageHeader
        kicker="Sistema"
        title="Financeiro"
        subtitle="Visão de caixa, contas a receber, despesas e margem real por obra. Acompanhe o lucro de cada projeto em tempo real."
        actions={
          <>
            <button className="wood-btn wood-btn-secondary"><Icon name="external" size={13} /> Exportar relatório</button>
            <button className="wood-btn wood-btn-secondary"><Icon name="calendar" size={13} /> Período: Maio/26</button>
            <button className="wood-btn wood-btn-primary" onClick={() => setCreating(true)}><Icon name="plus" size={13} /> Lançamento</button>
          </>
        }
      />

      <FormModal open={creating} onClose={() => setCreating(false)}
        kicker="NOVO LANÇAMENTO" title="Adicionar movimentação financeira" icon="dollar"
        submitLabel="Lançar" maxWidth={600}>
        <FormRow label="Tipo" required>
          <div className="flex gap-2">
            {[
              { v: "receivable", label: "A receber", icon: "arrow-up-right", color: "var(--success)" },
              { v: "payable",    label: "A pagar",   icon: "send",           color: "var(--warning)" },
            ].map(o => (
              <button key={o.v} type="button" onClick={() => setKind(o.v)}
                className="flex-1 py-3 rounded-lg flex items-center justify-center gap-2"
                style={{
                  background: kind === o.v ? (o.v === "receivable" ? "rgba(34,197,94,0.12)" : "rgba(245,158,11,0.12)") : "var(--wood-surface-2)",
                  border: `1px solid ${kind === o.v ? o.color + "88" : "var(--wood-border)"}`,
                  color: kind === o.v ? o.color : "var(--text-2)",
                  cursor: "pointer", fontWeight: kind === o.v ? 600 : 500
                }}>
                <Icon name={o.icon} size={14} /> {o.label}
              </button>
            ))}
          </div>
        </FormRow>
        <FormRow label={kind === "receivable" ? "Cliente" : "Fornecedor"} required>
          {kind === "receivable" ? (
            <select className="wood-select">
              <option value="">Selecione um cliente…</option>
              {MOCK.clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          ) : (
            <input className="wood-input" placeholder="Nome do fornecedor" />
          )}
        </FormRow>
        <FormRow label="Descrição" required>
          <input className="wood-input" placeholder={kind === "receivable" ? "Ex: Cobertura Vieira Souto — parc. 2 (30%)" : "Ex: Chapas MDF Freijó 18mm × 24"} />
        </FormRow>
        <FormGrid cols={3}>
          <FormRow label="Valor (R$)" required>
            <input type="number" className="wood-input" placeholder="0,00" />
          </FormRow>
          <FormRow label="Vencimento" required>
            <input type="date" className="wood-input" />
          </FormRow>
          <FormRow label="Forma">
            <select className="wood-select">
              <option>PIX</option><option>Boleto</option><option>Transferência</option>
              <option>Cartão</option><option>Dinheiro</option>
            </select>
          </FormRow>
        </FormGrid>
        {kind === "payable" && (
          <FormGrid>
            <FormRow label="Categoria">
              <select className="wood-select">
                <option>Madeira/MDF</option><option>Tampos</option><option>Ferragem</option>
                <option>Acabamento</option><option>RH</option><option>Operacional</option>
                <option>Infraestrutura</option><option>Frota</option><option>Insumos</option>
              </select>
            </FormRow>
            <FormRow label="Nota fiscal (opcional)">
              <input className="wood-input" placeholder="NF-00000" />
            </FormRow>
          </FormGrid>
        )}
      </FormModal>

      {/* Top KPIs */}
      <div className="grid grid-cols-4 gap-4 mb-6">
        <MetricCard icon="trend-up" label="Receita do mês" value={fmtBRL(f.summary.receitaMes)} sub={`${pct(deltaReceita)} vs. abril`} trend={deltaReceita} accent="success" delay={0} />
        <MetricCard icon="trend-down" label="Despesa do mês" value={fmtBRL(f.summary.despesaMes)} sub={`${pct(deltaDespesa)} vs. abril`} trend={-deltaDespesa} accent="warning" delay={60} />
        <MetricCard icon="dollar" label="Saldo (lucro)" value={fmtBRL(f.summary.saldoMes)} sub={`margem ${margem.toFixed(1)}%`} accent="amber" delay={120} />
        <MetricCard icon="wallet" label="A receber" value={fmtBRL(f.summary.aReceber)} sub={`${fmtBRL(f.summary.aReceberAtrasado)} em atraso`} accent="info" delay={180} />
      </div>

      {/* Tabs */}
      <div className="flex items-center gap-1 mb-5" style={{ borderBottom: "1px solid var(--wood-border)" }}>
        {[
          { id: "overview",    label: "Visão geral",    icon: "compass" },
          { id: "receivables", label: "A receber",      icon: "wallet", count: f.receivables.filter(r => r.status !== "recebido").length },
          { id: "payables",    label: "A pagar",        icon: "credit-card", count: f.payables.filter(p => p.status !== "pago").length },
          { id: "margins",     label: "Margem por obra",icon: "activity" },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            className="px-3 py-2.5 flex items-center gap-1.5 text-sm"
            style={{
              background: "transparent", border: "none", cursor: "pointer",
              color: tab === t.id ? "var(--amber-bright)" : "var(--text-3)",
              fontWeight: tab === t.id ? 600 : 500,
              borderBottom: tab === t.id ? "2px solid var(--amber-bright)" : "2px solid transparent",
              marginBottom: -1, transition: "all 0.18s"
            }}>
            <Icon name={t.icon} size={13} /> {t.label}
            {t.count != null && t.count > 0 && (
              <span className="text-xs" style={{ color: "var(--text-4)", fontVariantNumeric: "tabular-nums" }}>{t.count}</span>
            )}
          </button>
        ))}
      </div>

      {tab === "overview"    && <FinancialOverview f={f} />}
      {tab === "receivables" && <ReceivablesPanel  items={f.receivables} />}
      {tab === "payables"    && <PayablesPanel     items={f.payables} />}
      {tab === "margins"     && <MarginsPanel      items={f.margins} navigate={navigate} />}
    </>
  );
};

/* ============================================================
   FinancialOverview
   ============================================================ */
const FinancialOverview = ({ f }) => {
  const overduePay = f.payables.filter(p => p.status === "atrasado");
  const overdueRec = f.receivables.filter(r => r.status === "atrasado");
  const upcomingRec = f.receivables.filter(r => r.status === "pendente").sort((a, b) => a.dueDate.localeCompare(b.dueDate)).slice(0, 5);
  const upcomingPay = f.payables.filter(p => p.status === "pendente").sort((a, b) => a.dueDate.localeCompare(b.dueDate)).slice(0, 5);

  return (
    <>
      {/* Cashflow chart */}
      <div className="wood-card p-5 mb-5">
        <div className="flex items-center justify-between mb-5">
          <div>
            <div className="text-md font-semibold tracking-tight">Fluxo de caixa</div>
            <div className="text-xs text-3">últimos 6 meses · receita vs. despesa</div>
          </div>
          <div className="flex items-center gap-4 text-xs">
            <span className="flex items-center gap-1.5"><span className="wood-dot" style={{ background: "var(--amber-bright)" }} /> Receita</span>
            <span className="flex items-center gap-1.5"><span className="wood-dot" style={{ background: "var(--error)" }} /> Despesa</span>
            <span className="flex items-center gap-1.5"><span className="wood-dot" style={{ background: "var(--info)" }} /> Saldo</span>
          </div>
        </div>
        <CashflowChart data={f.cashflow} />
      </div>

      <div className="grid grid-cols-2 gap-5 mb-5">
        {/* Upcoming receivables */}
        <div className="wood-card p-5">
          <div className="flex items-center justify-between mb-4">
            <div>
              <div className="text-md font-semibold tracking-tight">Próximos recebimentos</div>
              <div className="text-xs text-3">vencendo nos próximos dias</div>
            </div>
            <button className="text-xs text-amber" style={{ fontWeight: 600, background: "none", border: "none", cursor: "pointer" }}>Ver todos</button>
          </div>
          {upcomingRec.length === 0 ? (
            <EmptyState icon="wallet" title="Nada a receber" description="Sem parcelas pendentes nos próximos dias." />
          ) : (
            <div className="flex flex-col gap-2.5">
              {upcomingRec.map(r => <FinancialRow key={r.id} item={r} kind="rec" />)}
            </div>
          )}
        </div>

        {/* Upcoming payables */}
        <div className="wood-card p-5">
          <div className="flex items-center justify-between mb-4">
            <div>
              <div className="text-md font-semibold tracking-tight">Próximos pagamentos</div>
              <div className="text-xs text-3">contas a pagar próximas</div>
            </div>
            <button className="text-xs text-amber" style={{ fontWeight: 600, background: "none", border: "none", cursor: "pointer" }}>Ver todos</button>
          </div>
          {upcomingPay.length === 0 ? (
            <EmptyState icon="credit-card" title="Nada a pagar" description="Sem contas pendentes nos próximos dias." />
          ) : (
            <div className="flex flex-col gap-2.5">
              {upcomingPay.map(p => <FinancialRow key={p.id} item={p} kind="pay" />)}
            </div>
          )}
        </div>
      </div>

      {/* Alerts row */}
      {(overdueRec.length > 0 || overduePay.length > 0) && (
        <div className="grid grid-cols-2 gap-5">
          {overdueRec.length > 0 && (
            <div className="wood-card p-5" style={{ background: "rgba(239,68,68,0.04)", borderColor: "rgba(239,68,68,0.2)" }}>
              <div className="flex items-center gap-3 mb-3">
                <div style={{ width: 36, height: 36, borderRadius: 9, background: "rgba(239,68,68,0.14)", color: "var(--error)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                  <Icon name="alert" size={17} />
                </div>
                <div>
                  <div className="text-md font-semibold tracking-tight">Recebimentos em atraso</div>
                  <div className="text-xs text-error">{overdueRec.length} {overdueRec.length === 1 ? "cobrança" : "cobranças"} pendentes</div>
                </div>
              </div>
              <div className="flex flex-col gap-2">
                {overdueRec.map(r => <FinancialRow key={r.id} item={r} kind="rec" compact />)}
              </div>
            </div>
          )}
          {overduePay.length > 0 && (
            <div className="wood-card p-5" style={{ background: "rgba(245,158,11,0.04)", borderColor: "rgba(245,158,11,0.2)" }}>
              <div className="flex items-center gap-3 mb-3">
                <div style={{ width: 36, height: 36, borderRadius: 9, background: "rgba(245,158,11,0.14)", color: "var(--warning)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                  <Icon name="alert" size={17} />
                </div>
                <div>
                  <div className="text-md font-semibold tracking-tight">Pagamentos em atraso</div>
                  <div className="text-xs text-warning">{overduePay.length} {overduePay.length === 1 ? "conta" : "contas"} pendente{overduePay.length === 1 ? "" : "s"}</div>
                </div>
              </div>
              <div className="flex flex-col gap-2">
                {overduePay.map(p => <FinancialRow key={p.id} item={p} kind="pay" compact />)}
              </div>
            </div>
          )}
        </div>
      )}
    </>
  );
};

/* ============================================================
   CashflowChart — paired bars
   ============================================================ */
const CashflowChart = ({ data }) => {
  const max = Math.max(...data.map(d => Math.max(d.receita, d.despesa))) * 1.1;
  return (
    <div className="flex items-end gap-3" style={{ height: 220 }}>
      {data.map((d, i) => {
        const saldo = d.receita - d.despesa;
        const rH = (d.receita / max) * 180;
        const dH = (d.despesa / max) * 180;
        return (
          <div key={d.month} className="flex-1 flex flex-col items-center gap-1.5">
            <div className="flex items-end justify-center gap-1" style={{ width: "100%", height: 180 }}>
              <div className="relative flex-1 group" style={{ height: rH, maxWidth: 32 }}>
                <div style={{
                  position: "absolute", inset: 0,
                  background: "linear-gradient(180deg, var(--amber-bright), var(--amber-deep))",
                  borderRadius: "4px 4px 0 0",
                  boxShadow: "0 0 12px rgba(16,185,129,0.3)",
                  animation: `growUp 0.6s ${i * 60}ms var(--ease-out) both`
                }} />
              </div>
              <div className="relative flex-1" style={{ height: dH, maxWidth: 32 }}>
                <div style={{
                  position: "absolute", inset: 0,
                  background: "linear-gradient(180deg, #EF4444, #991B1B)",
                  borderRadius: "4px 4px 0 0",
                  opacity: 0.85,
                  animation: `growUp 0.6s ${i * 60 + 30}ms var(--ease-out) both`
                }} />
              </div>
            </div>
            <div className="text-xs text-3" style={{ fontWeight: 500 }}>{d.month}</div>
            <div className="text-xs" style={{ color: saldo >= 0 ? "var(--success)" : "var(--error)", fontVariantNumeric: "tabular-nums", fontWeight: 600 }}>
              {saldo >= 0 ? "+" : ""}{(saldo / 1000).toFixed(0)}k
            </div>
          </div>
        );
      })}
      <style>{`@keyframes growUp { from { transform: scaleY(0); transform-origin: bottom; } to { transform: scaleY(1); transform-origin: bottom; } }`}</style>
    </div>
  );
};

/* ============================================================
   FinancialRow — single line item (receivable or payable)
   ============================================================ */
const FinancialRow = ({ item, kind, compact }) => {
  const st = FIN_STATUS_META[item.status] || FIN_STATUS_META.pendente;
  const dleft = daysUntil(item.dueDate);
  const overdue = item.status === "atrasado";

  return (
    <div className="flex items-center gap-3 px-3 py-2.5 rounded-lg" style={{ background: "rgba(0,0,0,0.18)", border: "1px solid var(--wood-border-soft)" }}>
      <div style={{
        width: 32, height: 32, borderRadius: 8, flexShrink: 0,
        background: kind === "rec" ? "rgba(34,197,94,0.12)" : "rgba(245,158,11,0.12)",
        color: kind === "rec" ? "var(--success)" : "var(--warning)",
        border: "1px solid var(--wood-border)",
        display: "inline-flex", alignItems: "center", justifyContent: "center"
      }}>
        <Icon name={kind === "rec" ? "arrow-up-right" : "send"} size={14} />
      </div>
      <div className="flex-1 min-w-0">
        <div className="text-sm truncate" style={{ fontWeight: 500 }}>{kind === "rec" ? item.clientName : item.supplier}</div>
        <div className="text-xs text-3 truncate">{item.description}</div>
      </div>
      {!compact && (
        <div className="text-right" style={{ minWidth: 90 }}>
          <div className={`text-xs ${overdue ? "text-error" : dleft <= 5 ? "text-warning" : "text-3"}`} style={{ fontWeight: 500 }}>{fmtDate(item.dueDate)}</div>
          <div className="text-xs text-4">{overdue ? `${Math.abs(dleft)}d atrasado` : dleft === 0 ? "vence hoje" : `${dleft}d`}</div>
        </div>
      )}
      <div className="text-right" style={{ minWidth: 100 }}>
        <div className="text-sm" style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums", color: kind === "rec" ? "var(--success)" : "var(--text)" }}>
          {kind === "rec" ? "+" : ""}{fmtBRL(item.value)}
        </div>
      </div>
    </div>
  );
};

/* ============================================================
   ReceivablesPanel
   ============================================================ */
const ReceivablesPanel = ({ items }) => {
  const [filter, setFilter] = useStateFin("todos");
  const list = filter === "todos" ? items : items.filter(i => i.status === filter);
  const totals = useMemoFin(() => ({
    recebido: items.filter(i => i.status === "recebido").reduce((s, i) => s + i.value, 0),
    pendente: items.filter(i => i.status === "pendente").reduce((s, i) => s + i.value, 0),
    atrasado: items.filter(i => i.status === "atrasado").reduce((s, i) => s + i.value, 0),
  }), [items]);

  return (
    <>
      <div className="grid grid-cols-3 gap-4 mb-5">
        <div className="px-4 py-4 rounded-lg" style={{ background: "rgba(34,197,94,0.06)", border: "1px solid rgba(34,197,94,0.18)" }}>
          <div className="text-xs text-3 uppercase tracking-widest mb-1" style={{ fontWeight: 500 }}>RECEBIDO</div>
          <div className="text-xl font-semibold tracking-tight" style={{ color: "#22C55E" }}>{fmtBRL(totals.recebido)}</div>
        </div>
        <div className="px-4 py-4 rounded-lg" style={{ background: "rgba(56,189,248,0.06)", border: "1px solid rgba(56,189,248,0.18)" }}>
          <div className="text-xs text-3 uppercase tracking-widest mb-1" style={{ fontWeight: 500 }}>PENDENTE</div>
          <div className="text-xl font-semibold tracking-tight" style={{ color: "#38BDF8" }}>{fmtBRL(totals.pendente)}</div>
        </div>
        <div className="px-4 py-4 rounded-lg" style={{ background: "rgba(239,68,68,0.06)", border: "1px solid rgba(239,68,68,0.18)" }}>
          <div className="text-xs text-3 uppercase tracking-widest mb-1" style={{ fontWeight: 500 }}>EM ATRASO</div>
          <div className="text-xl font-semibold tracking-tight" style={{ color: "#EF4444" }}>{fmtBRL(totals.atrasado)}</div>
        </div>
      </div>

      <div className="wood-card p-3 mb-4 flex items-center gap-2 flex-wrap">
        <FilterChip active={filter === "todos"} onClick={() => setFilter("todos")} count={items.length}>Todas</FilterChip>
        <FilterChip active={filter === "pendente"} onClick={() => setFilter("pendente")} count={items.filter(i => i.status === "pendente").length}>Pendentes</FilterChip>
        <FilterChip active={filter === "atrasado"} onClick={() => setFilter("atrasado")} count={items.filter(i => i.status === "atrasado").length}>Atrasadas</FilterChip>
        <FilterChip active={filter === "recebido"} onClick={() => setFilter("recebido")} count={items.filter(i => i.status === "recebido").length}>Recebidas</FilterChip>
      </div>

      <div className="wood-card" style={{ padding: 0, overflow: "hidden" }}>
        <table className="wood-table">
          <thead>
            <tr><th>ID</th><th>Cliente</th><th>Descrição</th><th>Forma</th><th>Vencimento</th><th>Valor</th><th>Status</th></tr>
          </thead>
          <tbody>
            {list.map(r => {
              const st = FIN_STATUS_META[r.status];
              const dleft = daysUntil(r.dueDate);
              return (
                <tr key={r.id} style={{ cursor: "pointer" }}>
                  <td className="font-mono text-xs text-3">{r.id}</td>
                  <td>
                    <div className="flex items-center gap-2">
                      <Avatar name={r.clientName} size={26} />
                      <span className="text-sm" style={{ fontWeight: 500 }}>{r.clientName}</span>
                    </div>
                  </td>
                  <td className="text-sm">{r.description}</td>
                  <td className="text-xs text-3">{r.method}</td>
                  <td>
                    <div className={`text-sm ${r.status === "atrasado" ? "text-error" : dleft <= 5 && r.status === "pendente" ? "text-warning" : ""}`} style={{ fontWeight: 500 }}>{fmtDate(r.dueDate)}</div>
                    {r.status === "recebido" && r.receivedAt && <div className="text-xs text-success">recebido em {fmtDate(r.receivedAt)}</div>}
                  </td>
                  <td className="text-sm" style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{fmtBRL(r.value)}</td>
                  <td>
                    <span className="wood-badge" style={{ background: st.bg, color: st.fg, padding: "2px 8px" }}>
                      <Icon name={st.icon} size={10} /> {st.label}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

/* ============================================================
   PayablesPanel
   ============================================================ */
const PayablesPanel = ({ items }) => {
  const [filter, setFilter] = useStateFin("todos");
  const list = filter === "todos" ? items : items.filter(i => i.status === filter);
  const byCat = useMemoFin(() => {
    const m = {};
    items.forEach(p => { m[p.category] = (m[p.category] || 0) + p.value; });
    return Object.entries(m).sort((a, b) => b[1] - a[1]);
  }, [items]);

  return (
    <>
      {/* By category breakdown */}
      <div className="wood-card p-5 mb-5">
        <div className="text-md font-semibold tracking-tight mb-4">Despesas por categoria</div>
        <div className="grid grid-cols-3 gap-3">
          {byCat.map(([cat, value]) => {
            const meta = PAY_CATEGORY_META[cat] || { color: "#737373", icon: "package" };
            const total = items.reduce((s, i) => s + i.value, 0);
            const share = (value / total) * 100;
            return (
              <div key={cat} className="px-4 py-3 rounded-lg" style={{ background: "rgba(0,0,0,0.18)", border: "1px solid var(--wood-border-soft)" }}>
                <div className="flex items-center gap-2 mb-1.5" style={{ color: meta.color, fontSize: 11, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.06em" }}>
                  <Icon name={meta.icon} size={12} /> {cat}
                </div>
                <div className="text-lg font-semibold" style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(value)}</div>
                <div className="text-xs text-4">{share.toFixed(1)}% do total</div>
              </div>
            );
          })}
        </div>
      </div>

      <div className="wood-card p-3 mb-4 flex items-center gap-2 flex-wrap">
        <FilterChip active={filter === "todos"} onClick={() => setFilter("todos")} count={items.length}>Todas</FilterChip>
        <FilterChip active={filter === "pendente"} onClick={() => setFilter("pendente")} count={items.filter(i => i.status === "pendente").length}>Pendentes</FilterChip>
        <FilterChip active={filter === "atrasado"} onClick={() => setFilter("atrasado")} count={items.filter(i => i.status === "atrasado").length}>Atrasadas</FilterChip>
        <FilterChip active={filter === "pago"} onClick={() => setFilter("pago")} count={items.filter(i => i.status === "pago").length}>Pagas</FilterChip>
      </div>

      <div className="wood-card" style={{ padding: 0, overflow: "hidden" }}>
        <table className="wood-table">
          <thead>
            <tr><th>ID</th><th>Fornecedor</th><th>Descrição</th><th>Categoria</th><th>NF</th><th>Vencimento</th><th>Valor</th><th>Status</th></tr>
          </thead>
          <tbody>
            {list.map(p => {
              const st = FIN_STATUS_META[p.status];
              const meta = PAY_CATEGORY_META[p.category] || { color: "#737373", icon: "package" };
              const dleft = daysUntil(p.dueDate);
              return (
                <tr key={p.id} style={{ cursor: "pointer" }}>
                  <td className="font-mono text-xs text-3">{p.id}</td>
                  <td className="text-sm" style={{ fontWeight: 500 }}>{p.supplier}</td>
                  <td className="text-sm">{p.description}</td>
                  <td>
                    <span className="wood-badge" style={{ background: `${meta.color}14`, color: meta.color, padding: "2px 8px" }}>
                      <Icon name={meta.icon} size={10} /> {p.category}
                    </span>
                  </td>
                  <td className="font-mono text-xs text-3">{p.invoice}</td>
                  <td>
                    <div className={`text-sm ${p.status === "atrasado" ? "text-error" : dleft <= 5 && p.status === "pendente" ? "text-warning" : ""}`} style={{ fontWeight: 500 }}>{fmtDate(p.dueDate)}</div>
                    {p.status === "pago" && p.paidAt && <div className="text-xs text-success">pago em {fmtDate(p.paidAt)}</div>}
                  </td>
                  <td className="text-sm" style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{fmtBRL(p.value)}</td>
                  <td>
                    <span className="wood-badge" style={{ background: st.bg, color: st.fg, padding: "2px 8px" }}>
                      <Icon name={st.icon} size={10} /> {st.label}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

/* ============================================================
   MarginsPanel — per-project profitability
   ============================================================ */
const MarginsPanel = ({ items, navigate }) => {
  const totals = useMemoFin(() => ({
    budget: items.reduce((s, i) => s + i.budget, 0),
    materials: items.reduce((s, i) => s + i.materials, 0),
    labor: items.reduce((s, i) => s + i.labor, 0),
    overhead: items.reduce((s, i) => s + i.overhead, 0),
    profit: items.reduce((s, i) => s + i.profit, 0),
  }), [items]);

  return (
    <>
      <div className="wood-card p-5 mb-5" style={{ background: "linear-gradient(135deg, rgba(16,185,129,0.06), rgba(11,10,7,0.6))", borderColor: "rgba(16,185,129,0.25)" }}>
        <div className="grid grid-cols-5 gap-4 items-center">
          <div>
            <div className="text-xs text-3 uppercase tracking-widest mb-1" style={{ fontWeight: 500 }}>RECEITA TOTAL</div>
            <div className="text-xl font-semibold tracking-tight" style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(totals.budget)}</div>
          </div>
          <div>
            <div className="text-xs text-3 uppercase tracking-widest mb-1" style={{ fontWeight: 500 }}>MATERIAL</div>
            <div className="text-xl font-semibold tracking-tight" style={{ color: "var(--text-2)", fontVariantNumeric: "tabular-nums" }}>{fmtBRL(totals.materials)}</div>
          </div>
          <div>
            <div className="text-xs text-3 uppercase tracking-widest mb-1" style={{ fontWeight: 500 }}>MÃO DE OBRA</div>
            <div className="text-xl font-semibold tracking-tight" style={{ color: "var(--text-2)", fontVariantNumeric: "tabular-nums" }}>{fmtBRL(totals.labor)}</div>
          </div>
          <div>
            <div className="text-xs text-3 uppercase tracking-widest mb-1" style={{ fontWeight: 500 }}>OVERHEAD</div>
            <div className="text-xl font-semibold tracking-tight" style={{ color: "var(--text-2)", fontVariantNumeric: "tabular-nums" }}>{fmtBRL(totals.overhead)}</div>
          </div>
          <div style={{ borderLeft: "1px solid var(--wood-border)", paddingLeft: 16 }}>
            <div className="text-xs text-amber uppercase tracking-widest mb-1" style={{ fontWeight: 600 }}>LUCRO</div>
            <div className="text-2xl font-semibold tracking-tight wood-gradient-text" style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(totals.profit)}</div>
            <div className="text-xs text-3">margem {((totals.profit / totals.budget) * 100).toFixed(1)}%</div>
          </div>
        </div>
      </div>

      <div className="wood-card" style={{ padding: 0, overflow: "hidden" }}>
        <table className="wood-table">
          <thead>
            <tr>
              <th>Obra</th>
              <th>Receita</th>
              <th>Material</th>
              <th>Mão de obra</th>
              <th>Overhead</th>
              <th>Lucro</th>
              <th>Margem</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {items.map(m => {
              const margin = (m.profit / m.budget) * 100;
              const marginColor = margin >= 35 ? "var(--success)" : margin >= 25 ? "var(--amber-bright)" : margin >= 15 ? "var(--warning)" : "var(--error)";
              return (
                <tr key={m.projectId} style={{ cursor: "pointer" }} onClick={() => navigate("projects")}>
                  <td>
                    <div className="text-sm" style={{ fontWeight: 600 }}>{m.name}</div>
                    <div className="text-xs text-4 font-mono">{m.projectId}</div>
                  </td>
                  <td className="text-sm" style={{ fontVariantNumeric: "tabular-nums", fontWeight: 600 }}>{fmtBRL(m.budget)}</td>
                  <td className="text-sm text-3" style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(m.materials)}</td>
                  <td className="text-sm text-3" style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(m.labor)}</td>
                  <td className="text-sm text-3" style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(m.overhead)}</td>
                  <td className="text-sm" style={{ fontVariantNumeric: "tabular-nums", fontWeight: 600, color: "var(--amber-bright)" }}>{fmtBRL(m.profit)}</td>
                  <td>
                    <div className="flex items-center gap-2">
                      <div style={{ flex: 1, width: 60 }}>
                        <AnimatedProgress value={margin} max={50} height={4} color={`linear-gradient(90deg, ${marginColor}, ${marginColor}88)`} />
                      </div>
                      <span className="text-sm" style={{ color: marginColor, fontVariantNumeric: "tabular-nums", fontWeight: 600, minWidth: 50, textAlign: "right" }}>{margin.toFixed(1)}%</span>
                    </div>
                  </td>
                  <td><StatusPill status={m.status} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

/* expose */
Object.assign(window, { FinancialPage });
