/* ============================================================
   PCP — Product detail: BOM + production projection
   (shares global scope with ui.jsx / forms.jsx — loaded after forms2)
   ============================================================ */

function ProdutoDetailModal({ app, onClose, produto }) {
  const p = produto || app.produtos[0];
  if (!p) return null;
  const estoque = app.estoque;

  // resolve BOM against live stock
  const bom = (p.bom || []).map((b) => {
    const it = estoque.find((x) => x.sku === b.sku) || {};
    const custoUnit = it.preco || 0;
    const possiveis = b.qtd > 0 ? Math.floor((it.saldo || 0) / b.qtd) : Infinity;
    return { ...b, it, nome: it.nome || b.sku, un: it.un || "", saldo: it.saldo || 0,
      custoUnit, custoTot: custoUnit * b.qtd, possiveis, status: it.status || "ok" };
  });
  const custoTotal = Math.round(bom.reduce((s, b) => s + b.custoTot, 0));
  const margem = p.preco > 0 ? (p.preco - custoTotal) / p.preco : 0;

  // production projection
  const produzivel = bom.length ? Math.max(0, Math.min(...bom.map((b) => (b.possiveis === Infinity ? 9999 : b.possiveis)))) : 0;
  const limitante = bom.length ? bom.reduce((m, b) => (b.possiveis < m.possiveis ? b : m), bom[0]) : null;
  const key = (p.nome || "").toLowerCase().split(" ")[0];
  const demanda = app.pedidos.filter((pe) => ["aberto", "andamento"].includes(pe.status) && (pe.produto || "").toLowerCase().startsWith(key)).reduce((s, pe) => s + pe.qtd, 0);
  const faltam = Math.max(0, demanda - produzivel);
  const cobertura = demanda > 0 ? Math.min(100, Math.round((produzivel / demanda) * 100)) : 100;

  const printBOM = () => {
    PCPExport.printTable("BOM — " + p.nome, [
      { key: "sku", label: "Insumo SKU" }, { label: "Descrição", map: (b) => b.nome },
      { label: "Qtd / un", num: true, map: (b) => b.qtd + " " + b.un },
      { label: "Custo un.", num: true, map: (b) => PCPExport.BRL(b.custoUnit) },
      { label: "Custo total", num: true, map: (b) => PCPExport.BRL(b.custoTot) },
      { label: "Em estoque", num: true, map: (b) => b.saldo + " " + b.un },
    ], bom, [["Produto", p.sku + " · " + p.nome], ["Custo total", PCPExport.BRL(custoTotal)], ["Preço", PCPExport.BRL(p.preco)], ["Produzível agora", produzivel + " un"]]);
  };

  return (
    <Modal size="lg" icon="package" title={p.nome} sub={p.sku + " · " + p.modo} onClose={onClose}
      footer={<>
        <Btn icon="printer" onClick={printBOM}>Imprimir BOM</Btn>
        <Btn icon="edit" onClick={() => { onClose(); app.openModal("novoProduto", { edit: p }); }}>Editar</Btn>
        <span className="spacer" />
        <Btn variant="primary" icon="factory" onClick={() => { onClose(); app.openModal("novaOP", { fromPedido: { produto: p.nome, qtd: faltam || 1, prio: faltam > 0 ? 7 : 5 } }); }}>Criar OP{faltam > 0 ? " · " + faltam + " un" : ""}</Btn>
      </>}>

      {p.imgUrl && (
        <div style={{ width: "100%", height: 360, borderRadius: "var(--radius)", overflow: "hidden", background: "var(--bg)", border: "1px solid var(--line)", marginBottom: 16 }}>
          <img src={p.imgUrl} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
        </div>
      )}

      {/* headline numbers */}
      <div className="kv-big" style={{ marginBottom: 18 }}>
        <div className="b"><div className="l">Preço de venda</div><div className="v">{DB.BRL(p.preco)}</div></div>
        <div className="b"><div className="l">Custo (BOM)</div><div className="v">{DB.BRL(custoTotal)}</div></div>
        <div className="b"><div className="l">Margem</div><div className="v" style={{ color: margem > 0.4 ? "var(--ok)" : margem > 0 ? "var(--warn)" : "var(--crit)" }}>{(margem * 100).toFixed(0)}%</div></div>
      </div>

      {/* production projection */}
      <div className="form-sec">Projeção de produção</div>
      <div className="field-grid c3" style={{ marginBottom: 12 }}>
        <div className="sumbox"><div className="l small muted">Produzível com estoque</div><div style={{ fontSize: 24, fontWeight: 680, marginTop: 2 }}>{produzivel} <span className="muted" style={{ fontSize: 13, fontWeight: 400 }}>un</span></div></div>
        <div className="sumbox"><div className="l small muted">Demanda em pedidos</div><div style={{ fontSize: 24, fontWeight: 680, marginTop: 2 }}>{demanda} <span className="muted" style={{ fontSize: 13, fontWeight: 400 }}>un</span></div></div>
        <div className="sumbox"><div className="l small muted">A produzir</div><div style={{ fontSize: 24, fontWeight: 680, marginTop: 2, color: faltam > 0 ? "var(--crit)" : "var(--ok)" }}>{faltam} <span className="muted" style={{ fontSize: 13, fontWeight: 400 }}>un</span></div></div>
      </div>
      <div className="sumbox" style={{ marginBottom: 6 }}>
        <div className="row" style={{ justifyContent: "space-between", marginBottom: 7 }}>
          <span className="small muted">Cobertura da demanda com estoque atual</span>
          <span className="small strong">{cobertura}%</span>
        </div>
        <Bar value={cobertura} tone={cobertura >= 100 ? "ok" : cobertura >= 50 ? "warn" : "crit"} />
        {limitante && produzivel < 9999 && (
          <div className="help" style={{ marginTop: 10 }}>
            <Icon name={limitante.status !== "ok" ? "alert" : "box"} size={12} style={{ color: limitante.status !== "ok" ? "var(--crit)" : "var(--muted)" }} />
            {" "}Insumo limitante: <b style={{ color: "var(--ink)" }}>{limitante.nome}</b> — saldo de {limitante.saldo} {limitante.un} rende {limitante.possiveis} {limitante.possiveis === 1 ? "unidade" : "unidades"}.
          </div>
        )}
      </div>

      {/* BOM */}
      <div className="form-sec">Lista de materiais (BOM)</div>
      <div className="tbl-wrap">
        <table className="tbl">
          <thead><tr><th>Insumo</th><th className="num">Qtd/un</th><th className="num">Custo un.</th><th className="num">Custo total</th><th className="num">Em estoque</th><th>Rende</th></tr></thead>
          <tbody>
            {bom.length === 0 && <tr><td colSpan="6"><span className="muted">Sem BOM cadastrada. Edite o produto para adicionar insumos.</span></td></tr>}
            {bom.map((b, i) => (
              <tr key={i}>
                <td><span className="sku">{b.sku}</span> <span className="strong">{b.nome}</span></td>
                <td className="num">{b.qtd} <span className="muted small">{b.un}</span></td>
                <td className="num muted">{DB.BRL(b.custoUnit)}</td>
                <td className="num strong">{DB.BRL(b.custoTot)}</td>
                <td className="num"><span style={{ color: b.status === "ok" ? "var(--ink)" : `var(--${b.status})`, fontWeight: 600 }}>{b.saldo}</span> <span className="muted small">{b.un}</span></td>
                <td>{b.possiveis >= 9999 ? <span className="muted">—</span> : <Badge tone={b.possiveis === produzivel ? (b.possiveis < demanda ? "crit" : "warn") : undefined} dotted>{b.possiveis} un</Badge>}</td>
              </tr>
            ))}
          </tbody>
          {bom.length > 0 && (
            <tfoot>
              <tr>
                <td className="strong">Custo total por unidade</td>
                <td></td><td></td>
                <td className="num strong" style={{ color: "var(--ink)" }}>{DB.BRL(custoTotal)}</td>
                <td colSpan="2"></td>
              </tr>
            </tfoot>
          )}
        </table>
      </div>
    </Modal>
  );
}

Object.assign(window, { ProdutoDetailModal });
MODALS.produtoDetail = ProdutoDetailModal;
