/* Relatórios — múltiplas visões */

function Relatorios({ ctx }) {
  const [report, setReport] = useState("geral");
  const [period, setPeriod] = useState({ kind: "month" });
  const [allInOne, setAllInOne] = useState(false);
  const refDate = DEFAULT_REF_DATE;
  const r = periodRange(period, refDate);

  const printReport = () => {
    // captura o conteúdo do bloco de relatórios e abre em janela de impressão
    const block = document.getElementById("reports-print-area");
    if (!block) return;
    const styles = Array.from(document.querySelectorAll("link[rel='stylesheet'], style")).map(el => el.outerHTML).join("\n");
    const logo = ctx.state.company.logo;
    const logoIsImage = logo && !/^data:application\/pdf/i.test(logo);
    const header = `
      <div style="display:flex;gap:16px;align-items:center;border-bottom:2px solid #1A1A1A;padding-bottom:14px;margin-bottom:18px;">
        ${logoIsImage ? `<img src="${logo}" style="width:60px;height:60px;object-fit:contain;" />` : `<div style="width:60px;height:60px;background:#D4310B;color:white;border-radius:10px;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:28px;font-family:'Bricolage Grotesque', sans-serif;">P</div>`}
        <div style="flex:1">
          <div style="font-family:'Bricolage Grotesque', sans-serif;font-size:24px;font-weight:700;letter-spacing:-.02em;">Relatórios — ${ctx.state.company.name}</div>
          <div style="font-size:12px;color:#666;">Período: <strong>${r.label}</strong> · Gerado em ${new Date().toLocaleString("pt-BR")}</div>
        </div>
      </div>
    `;
    const win = window.open("", "_blank", "width=1100,height=900");
    win.document.open();
    win.document.write(`<!DOCTYPE html><html lang="pt-BR"><head><meta charset="UTF-8"><title>Relatórios — ${r.label}</title>
      ${styles}
      <style>
        @page { size: A4; margin: 12mm 10mm; }
        * { box-sizing: border-box; }
        html, body { margin:0; padding:0; }
        body { background: #f0f0f0; }
        .print-doc { padding: 0; max-width: none; }
        .toolbar { position:sticky; top:0; background:#1A1A1A; color:white; padding:10px 14px; display:flex; gap:8px; align-items:center; z-index:50; }
        .toolbar h3 { margin:0; flex:1; font-size:13px; font-weight:600; font-family: Helvetica,Arial,sans-serif; }
        .toolbar button { background:white; color:#1A1A1A; border:none; padding:7px 12px; border-radius:6px; font-weight:600; font-size:12px; cursor:pointer; font-family: Helvetica,Arial,sans-serif; }
        .doc { background:white; max-width: 880px; margin: 14px auto; padding: 22px 26px; box-shadow: 0 4px 24px rgba(0,0,0,.12); }
        .card { break-inside: avoid; page-break-inside: avoid; box-shadow: none !important; }
        table { table-layout: auto; word-wrap: break-word; }
        .all-in-one > .report-block { page-break-after: always; }
        .all-in-one > .report-block:last-child { page-break-after: auto; }
        @media print { .toolbar { display:none !important; } .doc { box-shadow:none !important; margin:0 !important; padding:0 !important; max-width:none !important; width:auto !important; } body { background: white !important; padding:0 !important; } }
      </style>
      </head><body>
      <div class="toolbar"><h3>Relatórios — ${r.label}</h3><button onclick="window.print()">🖨 Imprimir / PDF</button><button onclick="window.close()" style="background:transparent;color:white;border:1px solid rgba(255,255,255,.4);">Fechar</button></div>
      <div class="doc">${header}${block.innerHTML}</div>
      </body></html>`);
    win.document.close();
  };

  return (
    <>
      <div className="page-head">
        <div>
          <h1>Relatórios</h1>
          <p>Análises detalhadas e exportáveis de toda a operação</p>
        </div>
        <div className="page-head__actions">
          <PeriodPicker value={period} onChange={setPeriod} refDate={refDate} />
          <button onClick={() => setAllInOne(a => !a)}
            style={{
              display:"inline-flex", alignItems:"center", gap:8, padding:"8px 12px", borderRadius:8,
              border:"1px solid " + (allInOne ? "var(--brand-600)" : "var(--line-strong)"),
              background: allInOne ? "var(--brand-50)" : "linear-gradient(180deg,#fff,#f8f8fa)",
              color: allInOne ? "var(--brand-700)" : "var(--ink-800)",
              fontWeight:600, fontSize:13, cursor:"pointer",
              boxShadow:"0 1px 0 rgba(255,255,255,.8) inset, 0 1px 2px rgba(15,15,20,.04)",
            }}>
            <Icons.Eye size={14}/> {allInOne ? "Ver por seção" : "Ver tudo em uma página"}
          </button>
          <Button variant="secondary" icon={<Icons.Print size={14}/>} onClick={printReport}>Imprimir</Button>
          <Button variant="primary" icon={<Icons.Download size={14}/>} onClick={printReport}>Exportar PDF</Button>
        </div>
      </div>

      {allInOne ? (
        <div id="reports-print-area">
          <div className="all-in-one">
            <div className="report-block"><SectionHead title="Visão geral" subtitle={r.label} /><RGeral ctx={ctx} period={period} refDate={refDate} /></div>
            <div className="report-block" style={{ marginTop:18 }}><SectionHead title="Por picolezeiro" /><RPicolezeiros ctx={ctx} /></div>
            <div className="report-block" style={{ marginTop:18 }}><SectionHead title="Por praia" /><RPraias ctx={ctx} /></div>
            <div className="report-block" style={{ marginTop:18 }}><SectionHead title="Por distribuidor" /><RDistribuidores ctx={ctx} /></div>
            <div className="report-block" style={{ marginTop:18 }}><SectionHead title="Por produto" /><RProdutos ctx={ctx} /></div>
            <div className="report-block" style={{ marginTop:18 }}><SectionHead title="Sobras e perdas" /><RSobras ctx={ctx} /></div>
            <div className="report-block" style={{ marginTop:18 }}><SectionHead title="Consumo de insumos" /><RInsumos ctx={ctx} /></div>
          </div>
        </div>
      ) : (
      <div style={{ display:"grid", gridTemplateColumns:"220px 1fr", gap:14 }}>
        <aside style={{ background:"white", border:"1px solid var(--line)", borderRadius:10, padding:8, height:"fit-content", position:"sticky", top: 80 }}>
          <div className="nav__label" style={{ padding:"8px 8px 4px" }}>Visão</div>
          {[
            { id:"geral", label:"Visão geral", icon:Icons.PieChart },
            { id:"picolezeiros", label:"Por picolezeiro", icon:Icons.User },
            { id:"praias", label:"Por praia", icon:Icons.Beach },
            { id:"distribuidores", label:"Por distribuidor", icon:Icons.Store },
            { id:"produtos", label:"Por produto", icon:Icons.Box },
            { id:"sobras", label:"Sobras e perdas", icon:Icons.AlertTriangle },
            { id:"insumos", label:"Consumo de insumos", icon:Icons.Factory },
          ].map(rep => {
            const Ic = rep.icon;
            const active = report === rep.id;
            return (
              <button key={rep.id} onClick={() => setReport(rep.id)}
                className={"nav__item" + (active ? " is-active" : "")}
                style={{ marginBottom: 2 }}
              ><Ic /> <span style={{ fontSize:12.5 }}>{rep.label}</span></button>
            );
          })}
        </aside>

        <div id="reports-print-area">
          {report === "geral" && <RGeral ctx={ctx} period={period} refDate={refDate} />}
          {report === "picolezeiros" && <RPicolezeiros ctx={ctx} />}
          {report === "praias" && <RPraias ctx={ctx} />}
          {report === "distribuidores" && <RDistribuidores ctx={ctx} />}
          {report === "produtos" && <RProdutos ctx={ctx} />}
          {report === "sobras" && <RSobras ctx={ctx} />}
          {report === "insumos" && <RInsumos ctx={ctx} />}
        </div>
      </div>
      )}
    </>
  );
}

function RGeral({ ctx, period, refDate }) {
  const inP = (dateStr) => period ? inPeriod(dateStr, period, refDate) : true;
  const fin = ctx.state.finance.filter(f => inP(f.date));
  const ins  = fin.filter(f => f.kind === "in").reduce((s, f) => s + f.value, 0);
  const outs = fin.filter(f => f.kind === "out").reduce((s, f) => s + f.value, 0);
  const inputCosts = fin.filter(f => f.cat === "Compra de Insumo" || f.cat === "Produção").reduce((s, f) => s + f.value, 0);
  const margin = ins > 0 ? ((ins - inputCosts) / ins) * 100 : 0;
  const commissions = fin.filter(f => f.cat === "Comissão Picolezeiro").reduce((s, f) => s + f.value, 0);

  return (
    <>
      <div className="grid-4" style={{ marginBottom:14 }}>
        <KPI tone="success" medal={<Icons.ArrowDown size={18} strokeWidth={2}/>} label="Faturamento" value={fmtBRL(ins)} sub="Entradas confirmadas" />
        <KPI tone="brand" medal={<Icons.PieChart size={18} strokeWidth={2}/>} label="Margem bruta" value={margin.toFixed(1) + "%"} sub="Faturamento − insumos" />
        <KPI tone="info" medal={<Icons.Users size={18} strokeWidth={2}/>} label="Comissões pagas" value={fmtBRL(commissions)} sub={`${ctx.state.picolezeiros.length} picolezeiros`} />
        <KPI tone="danger" medal={<Icons.ArrowUp size={18} strokeWidth={2}/>} label="Saídas totais" value={fmtBRL(outs)} sub="Custos + despesas" />
      </div>
      <Card title="Distribuição financeira" subtitle="Composição das entradas">
        {ins === 0 ? (
          <div className="empty"><p>Sem dados financeiros no período.</p></div>
        ) : (
        <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
          {["Venda Distribuidor", "Retorno Picolezeiro", "Outras Entradas"].map(cat => {
            const v = fin.filter(f => f.cat === cat && f.kind === "in").reduce((s, f) => s + f.value, 0);
            if (v === 0) return null;
            const pct = (v / ins) * 100;
            return (
              <div key={cat}>
                <div style={{ display:"flex", justifyContent:"space-between", marginBottom:6, fontSize:13 }}>
                  <span style={{ fontWeight:600 }}>{cat}</span>
                  <span className="numeric"><strong>{fmtBRL(v)}</strong> <span className="muted">· {pct.toFixed(0)}%</span></span>
                </div>
                <ProgressBar value={pct} max={100} />
              </div>
            );
          })}
        </div>
        )}
      </Card>
    </>
  );
}

function RPicolezeiros({ ctx }) {
  const data = ctx.state.picolezeiros.map(p => ({
    p,
    saidas: p.totals.saidas,
    vendido: p.totals.vendido,
    comissao: p.totals.comissao,
  })).sort((a,b)=>b.vendido-a.vendido);

  if (data.length === 0) {
    return <Card><div className="empty"><h4>Sem picolezeiros cadastrados</h4><p>Cadastre em Clientes para gerar este relatório.</p></div></Card>;
  }

  const max = Math.max(1, ...data.map(d => d.vendido));

  return (
    <Card title="Performance por picolezeiro" subtitle="Faturamento e comissão acumulados" flush>
      <table className="tbl">
        <thead>
          <tr>
            <th>Picolezeiro</th>
            <th className="num">Saídas</th>
            <th className="num">Faturado</th>
            <th className="num">Comissão</th>
            <th className="num">Comissão %</th>
            <th>Performance</th>
          </tr>
        </thead>
        <tbody>
          {data.map((d, i) => (
            <tr key={d.p.id}>
              <td>
                <div style={{ display:"flex", gap:10, alignItems:"center" }}>
                  <div className="avatar" style={{ width:28, height:28, fontSize:10, background:"linear-gradient(135deg, #333, #1a1a1a)" }}>{d.p.photo}</div>
                  <div>
                    <div style={{ fontWeight:600, color:"var(--ink-900)" }}>{d.p.name}</div>
                    <div className="subtle">{d.p.commission}% padrão</div>
                  </div>
                </div>
              </td>
              <td className="num numeric">{d.saidas}</td>
              <td className="num strong numeric">{fmtBRL(d.vendido)}</td>
              <td className="num numeric" style={{ color:"var(--brand-700)" }}>{fmtBRL(d.comissao)}</td>
              <td className="num numeric">{d.p.commission}%</td>
              <td style={{ width:160 }}>
                <ProgressBar value={d.vendido} max={max} tone={i === 0 ? "ok" : i < 3 ? "warn" : null} />
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

function RPraias({ ctx }) {
  // Aggregate from closed trips
  const byBeach = {};
  ctx.state.trips.filter(t => t.status === "fechado").forEach(t => {
    const beaches = t.beachesActual || [];
    if (beaches.length === 0) return;
    const perBeach = (t.faturado || 0) / beaches.length;
    const unitsSold = (t.sold || []).reduce((s, x) => s + x.qty, 0);
    const unitsTotal = t.items.reduce((s, x) => s + x.qty, 0);
    beaches.forEach(bid => {
      if (!byBeach[bid]) byBeach[bid] = { trips:0, units:0, sold:0, faturado:0 };
      byBeach[bid].trips++;
      byBeach[bid].units += unitsTotal / beaches.length;
      byBeach[bid].sold += unitsSold / beaches.length;
      byBeach[bid].faturado += perBeach;
    });
  });
  const rows = Object.entries(byBeach).map(([id, v]) => ({ id, ...v })).sort((a,b)=>b.faturado-a.faturado);

  if (rows.length === 0) {
    return <Card><div className="empty"><h4>Sem dados de praias</h4><p>Os dados aparecem após fechar retornos de picolezeiros.</p></div></Card>;
  }

  const max = rows[0].faturado;

  return (
    <>
      <div className="grid-2" style={{ gap: 14, marginBottom: 14 }}>
        <Card title="Top 3 praias" subtitle="Faturamento acumulado">
          <div style={{ display:"flex", flexDirection:"column", gap:14 }}>
            {rows.slice(0,3).map((p, i) => {
              const b = ctx.state.beaches.find(x => x.id === p.id);
              return (
                <div key={p.id}>
                  <div style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline", marginBottom:6 }}>
                    <div style={{ display:"flex", gap:8, alignItems:"center" }}>
                      <span style={{ fontFamily:"var(--font-display)", fontWeight:700, color:"var(--brand-600)", fontSize:20, width:22 }}>{i+1}</span>
                      <div>
                        <div style={{ fontWeight:600, color:"var(--ink-900)" }}>{b?.name}</div>
                        <div className="subtle">{b?.city} · {Math.round(p.trips)} idas</div>
                      </div>
                    </div>
                    <strong className="numeric">{fmtBRL(p.faturado)}</strong>
                  </div>
                  <ProgressBar value={p.faturado} max={max} />
                </div>
              );
            })}
          </div>
        </Card>
        <Card title="Métricas-chave">
          <div className="pill-row" style={{ flexDirection:"column", gap:14 }}>
            <Row label="Idas totais" value={<strong className="numeric">{Math.round(rows.reduce((s,x)=>s+x.trips,0))}</strong>} />
            <Row label="Unidades enviadas" value={<strong className="numeric">{fmtInt(Math.round(rows.reduce((s,x)=>s+x.units,0)))}</strong>} />
            <Row label="Unidades vendidas" value={<strong className="numeric">{fmtInt(Math.round(rows.reduce((s,x)=>s+x.sold,0)))}</strong>} />
            <Row label="Faturamento total" value={<strong className="numeric" style={{ color:"var(--brand-600)", fontSize:16 }}>{fmtBRL(rows.reduce((s,x)=>s+x.faturado,0))}</strong>} />
          </div>
        </Card>
      </div>

      <Card title="Detalhes por praia" flush>
        <table className="tbl">
          <thead>
            <tr>
              <th>Praia</th>
              <th>Município</th>
              <th className="num">Idas</th>
              <th className="num">Enviadas</th>
              <th className="num">Vendidas</th>
              <th className="num">Faturado</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(d => {
              const b = ctx.state.beaches.find(x => x.id === d.id);
              return (
                <tr key={d.id}>
                  <td className="strong">{b?.name}</td>
                  <td className="muted">{b?.city}</td>
                  <td className="num numeric">{Math.round(d.trips)}</td>
                  <td className="num numeric">{Math.round(d.units)}</td>
                  <td className="num strong numeric">{Math.round(d.sold)}</td>
                  <td className="num strong numeric">{fmtBRL(d.faturado)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    </>
  );
}

function Row({ label, value }) {
  return <div style={{ display:"flex", justifyContent:"space-between" }}><span className="muted">{label}</span><span>{value}</span></div>;
}

function RDistribuidores({ ctx }) {
  const list = ctx.state.distributors.slice().sort((a,b)=>b.totals.valor - a.totals.valor);
  if (list.length === 0) return <Card><div className="empty"><h4>Sem distribuidores</h4></div></Card>;
  const max = list[0]?.totals.valor || 1;
  return (
    <Card title="Distribuidores por volume" subtitle="Histórico de compras" flush>
      <table className="tbl">
        <thead>
          <tr>
            <th>Distribuidor</th>
            <th>Cidade</th>
            <th className="num">Compras</th>
            <th className="num">Volume</th>
            <th className="num">Ticket médio</th>
            <th>Participação</th>
          </tr>
        </thead>
        <tbody>
          {list.map(d => (
            <tr key={d.id}>
              <td className="strong">{d.name}</td>
              <td className="muted">{d.city}</td>
              <td className="num numeric">{d.totals.compras}</td>
              <td className="num strong numeric">{fmtBRL(d.totals.valor)}</td>
              <td className="num numeric muted">{fmtBRL(d.totals.compras > 0 ? d.totals.valor / d.totals.compras : 0)}</td>
              <td style={{ width:200 }}><ProgressBar value={d.totals.valor} max={max} /></td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

function RProdutos({ ctx }) {
  // Per-product sold units from closed trips
  const sold = {};
  ctx.state.trips.filter(t => t.status === "fechado").forEach(t => {
    (t.sold || []).forEach(s => { sold[s.productId] = (sold[s.productId] || 0) + s.qty; });
  });
  const data = ctx.state.products
    .map(p => ({ p, units: sold[p.id] || 0 }))
    .filter(x => x.units > 0)
    .sort((a,b)=>b.units-a.units);

  if (data.length === 0) {
    return <Card><div className="empty"><h4>Sem vendas registradas</h4><p>Os dados aparecem após fechar retornos.</p></div></Card>;
  }

  return (
    <Card title="Produtos mais vendidos" subtitle="Por unidades vendidas (picolezeiros)" flush>
      <table className="tbl">
        <thead>
          <tr>
            <th>Produto</th>
            <th>Linha</th>
            <th className="num">Unidades</th>
            <th className="num">Faturado</th>
            <th>Participação</th>
          </tr>
        </thead>
        <tbody>
          {data.map(d => (
            <tr key={d.p.id}>
              <td><span className="tag-flavor"><span className="sw" style={{ background: d.p.color }} />{d.p.flavor}</span></td>
              <td className="muted">{d.p.line}</td>
              <td className="num strong numeric">{d.units}</td>
              <td className="num strong numeric">{fmtBRL(d.units * d.p.price)}</td>
              <td style={{ width:160 }}><ProgressBar value={d.units} max={data[0].units} /></td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

function RSobras({ ctx }) {
  // From closed trips
  const sobrasByProduct = {};
  const saidasByProduct = {};
  ctx.state.trips.filter(t => t.status === "fechado").forEach(t => {
    t.items.forEach(it => { saidasByProduct[it.productId] = (saidasByProduct[it.productId] || 0) + it.qty; });
    (t.returned || []).forEach(r => { sobrasByProduct[r.productId] = (sobrasByProduct[r.productId] || 0) + r.qty; });
  });
  const totalSaidas = Object.values(saidasByProduct).reduce((s,x)=>s+x, 0);
  const totalSobras = Object.values(sobrasByProduct).reduce((s,x)=>s+x, 0);
  const taxaGeral = totalSaidas > 0 ? (totalSobras / totalSaidas * 100) : 0;

  const rows = Object.keys(saidasByProduct).map(pid => {
    const p = ctx.state.products.find(x => x.id === pid);
    const saidas = saidasByProduct[pid] || 0;
    const sobras = sobrasByProduct[pid] || 0;
    return { p, saidas, sobras, taxa: saidas > 0 ? (sobras/saidas*100) : 0 };
  }).filter(r => r.p).sort((a,b)=>b.sobras-a.sobras);

  return (
    <>
      <div className="grid-3" style={{ marginBottom:14 }}>
        <KPI tone="info" medal={<Icons.Box size={18} strokeWidth={2}/>} label="Total de sobras" value={Math.round(totalSobras) + " un"} sub="Voltadas ao estoque" />
        <KPI tone="brand" medal={<Icons.PieChart size={18} strokeWidth={2}/>} label="Taxa de sobra" value={taxaGeral.toFixed(1) + "%"} sub={`${Math.round(totalSaidas)} un total em saídas`} />
        <KPI tone="warning" medal={<Icons.AlertTriangle size={18} strokeWidth={2}/>} label="Sabores com sobra" value={rows.filter(r => r.sobras > 0).length + ""} sub={`de ${rows.length} sabores`} />
      </div>
      {rows.length === 0 ? (
        <Card><div className="empty"><h4>Sem dados de sobras</h4><p>Os dados aparecem após fechar retornos.</p></div></Card>
      ) : (
      <Card title="Sobras por sabor" flush>
        <table className="tbl">
          <thead>
            <tr>
              <th>Produto</th>
              <th className="num">Saídas</th>
              <th className="num">Sobras</th>
              <th className="num">Taxa</th>
              <th>Performance</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(r => (
              <tr key={r.p.id}>
                <td><span className="tag-flavor"><span className="sw" style={{ background: r.p.color }} />{r.p.flavor}</span></td>
                <td className="num numeric">{r.saidas}</td>
                <td className="num strong numeric">{r.sobras}</td>
                <td className="num numeric" style={{ color: r.taxa > 10 ? "var(--warning)" : r.taxa > 5 ? "var(--ink-700)" : "var(--success)" }}>{r.taxa.toFixed(1)}%</td>
                <td style={{ width:140 }}><ProgressBar value={Math.min(r.taxa, 30)} max={30} tone={r.taxa > 15 ? "danger" : r.taxa > 8 ? "warn" : "ok"} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
      )}
    </>
  );
}

function RInsumos({ ctx }) {
  // From recipes, sum required usage across all production
  const used = {};
  const prodLogs = ctx.state.finance.filter(f => f.cat === "Produção");
  // Match by recipe name in ref — heuristic
  ctx.state.recipes.forEach(r => {
    const matches = prodLogs.filter(p => p.ref.startsWith(r.name));
    // each ref ends with "(Nx)" — extract batches
    matches.forEach(m => {
      const m2 = m.ref.match(/\((\d+)x\)/);
      const batches = m2 ? parseInt(m2[1], 10) : 1;
      r.items.forEach(it => { used[it.inputId] = (used[it.inputId] || 0) + it.qty * batches; });
    });
  });

  const rows = ctx.state.inputs.map(inp => ({
    inp, used: used[inp.id] || 0, cost: (used[inp.id] || 0) * inp.unitCost,
  })).sort((a,b)=>b.cost-a.cost);

  return (
    <Card title="Consumo de insumos" subtitle="Baseado em produções registradas" flush>
      {rows.length === 0 || rows.every(r => r.used === 0) ? (
        <div className="empty">
          <h4>Sem consumo registrado</h4>
          <p>Registre produções em Fabricação para gerar este relatório.</p>
        </div>
      ) : (
      <table className="tbl">
        <thead>
          <tr>
            <th>Insumo</th>
            <th className="num">Consumido</th>
            <th className="num">Custo total</th>
            <th className="num">Estoque restante</th>
            <th>Cobertura estimada</th>
          </tr>
        </thead>
        <tbody>
          {rows.map(r => {
            const days = r.used > 0 ? Math.floor(r.inp.stock / Math.max(r.used / 30, 0.1)) : 999;
            return (
              <tr key={r.inp.id}>
                <td className="strong">{r.inp.name}</td>
                <td className="num numeric">{r.used} {r.inp.unit}</td>
                <td className="num strong numeric">{fmtBRL(r.cost)}</td>
                <td className="num numeric">{r.inp.stock} {r.inp.unit}</td>
                <td style={{ width: 160 }}>
                  <div style={{ display:"flex", gap:8, alignItems:"center" }}>
                    <ProgressBar value={Math.min(days, 60)} max={60} tone={days < 15 ? "danger" : days < 30 ? "warn" : "ok"} />
                    <span className="subtle numeric" style={{ minWidth: 50, textAlign:"right" }}>~{days > 99 ? "—" : days+"d"}</span>
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
      )}
    </Card>
  );
}

window.Relatorios = Relatorios;
