/* ============================================================
   Vista: Costos — Inflación + sugerencia de precios y márgenes
   ============================================================ */
function Costos({ products, onChange, toast }) {
  const [detail, setDetail] = useState(null);
  const rows = products.map((p) => ({
    ...p,
    inf: RB.inflationPct(p),
    mg: RB.margin(p),
    suggested: RB.suggestedSell(p),
  }));

  const avgInf = rows.reduce((s, r) => s + r.inf, 0) / (rows.length || 1);
  const avgMargin = rows.reduce((s, r) => s + r.mg, 0) / (rows.length || 1);
  const needReprice = rows.filter((r) => r.mg < RB.TARGET_MARGIN * 100 - 5);

  const applySuggested = (p) => {
    onChange((st) => ({ ...st, products: st.products.map((x) => x.id === p.id ? { ...x, sellPrice: Math.round(RB.suggestedSell(x) / 100) * 100 } : x) }));
    toast("Precio actualizado al sugerido");
  };
  const applyAll = () => {
    onChange((st) => ({ ...st, products: st.products.map((x) => RB.margin(x) < RB.TARGET_MARGIN * 100 - 5 ? { ...x, sellPrice: Math.round(RB.suggestedSell(x) / 100) * 100 } : x) }));
    toast("Precios actualizados");
  };

  return (
    <div>
      <div className="stat-grid" style={{ gridTemplateColumns: "repeat(3,1fr)" }}>
        <div className="stat clickable" role="button" tabIndex={0}
          onClick={() => setDetail({
            title: "Inflación en costos",
            intro: "Cuánto aumentó el precio de compra de cada producto (comparando la compra anterior con la actual). Promedio: " + RB.pct(avgInf) + ".",
            rows: rows.filter((r) => r.inf !== 0).sort((a, b) => b.inf - a.inf).map((r) => ({ name: r.name, sub: RB.fmtARS(r.buyPrevPrice) + " → " + RB.fmtARS(r.buyPrice), value: RB.pct(r.inf), color: r.inf > 0 ? "var(--crit)" : "var(--ok)" })),
            empty: "Todavía no hay historial de precios. Cuando cargues una nueva compra a un precio distinto, vas a ver acá cuánto subió cada producto.",
          })}>
          <Icon name="chevron" className="stat-more" size={16} />
          <div className="stat-ico" style={{ background: "var(--crit-bg)", color: "var(--crit)" }}><Icon name="trending" /></div>
          <div className="stat-label">Inflación promedio en costos</div>
          <div className="stat-value" style={{ color: "var(--crit)" }}>{RB.pct(avgInf)}</div>
          <div className="muted" style={{ fontSize: 12, marginTop: 6 }}>compra anterior → actual · ver detalle</div></div>
        <div className="stat clickable" role="button" tabIndex={0}
          onClick={() => setDetail({
            title: "Margen por producto",
            intro: "La ganancia sobre el precio de venta de cada producto. Margen = (venta − costo) ÷ venta. Objetivo recomendado: " + Math.round(RB.TARGET_MARGIN * 100) + "%.",
            rows: rows.slice().sort((a, b) => a.mg - b.mg).map((r) => ({ name: r.name, sub: "compra " + RB.fmtARS(r.buyPrice) + " · venta " + RB.fmtARS(r.sellPrice), value: Math.round(r.mg) + "%", color: r.mg < RB.TARGET_MARGIN * 100 - 5 ? "var(--warn)" : "var(--pine)" })),
            empty: "No hay productos cargados.",
            foot: { label: "Margen promedio", value: Math.round(avgMargin) + "%" },
          })}>
          <Icon name="chevron" className="stat-more" size={16} />
          <div className="stat-ico" style={{ background: "var(--ok-bg)", color: "var(--pine)" }}><Icon name="coins" /></div>
          <div className="stat-label">Margen promedio actual</div>
          <div className="stat-value">{Math.round(avgMargin)}%</div>
          <div className="muted" style={{ fontSize: 12, marginTop: 6 }}>recomendado {Math.round(RB.TARGET_MARGIN * 100)}% · ver detalle</div></div>
        <div className="stat clickable" role="button" tabIndex={0}
          onClick={() => setDetail({
            title: "Productos a re-precificar",
            intro: "Productos cuyo margen quedó por debajo del objetivo (" + Math.round(RB.TARGET_MARGIN * 100) + "%). Conviene subirles el precio de venta.",
            rows: needReprice.slice().sort((a, b) => a.mg - b.mg).map((r) => ({ name: r.name, sub: "margen actual " + Math.round(r.mg) + "% · sugerido " + RB.fmtARS(r.suggested), value: Math.round(r.mg) + "%", color: "var(--warn)" })),
            empty: "¡Todos los productos están en el margen objetivo o por encima! No hay nada para re-precificar. 🌿",
          })}>
          <Icon name="chevron" className="stat-more" size={16} />
          <div className="stat-ico" style={{ background: "var(--warn-bg)", color: "#A9801C" }}><Icon name="alert" /></div>
          <div className="stat-label">Productos a re-precificar</div>
          <div className="stat-value">{needReprice.length}</div>
          {needReprice.length > 0 && <button className="btn btn-clay btn-sm" style={{ marginTop: 8 }} onClick={(e) => { e.stopPropagation(); applyAll(); }}><Icon name="refresh" size={15} />Aplicar todos los sugeridos</button>}</div>
      </div>
      {detail && <DetailModal {...detail} onClose={() => setDetail(null)} />}

      <div className="section-head">
        <h2>Costos, inflación y precios</h2>
        <span className="sh-sub">· margen objetivo {Math.round(RB.TARGET_MARGIN * 100)}%</span>
      </div>
      <div className="table-wrap">
        <table className="tbl">
          <thead>
            <tr>
              <th>Producto</th>
              <th className="right">Compra ant.</th>
              <th className="right">Compra actual</th>
              <th className="center">Inflación</th>
              <th className="right">Venta actual</th>
              <th className="center">Margen</th>
              <th className="right">Venta sugerida</th>
              <th className="right">Acción</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r) => {
              const low = r.mg < RB.TARGET_MARGIN * 100 - 5;
              return (
                <tr key={r.id}>
                  <td><div className="prod-cell"><ProdThumb product={r} /><div>
                    <div className="td-strong">{r.name}</div><div className="muted" style={{ fontSize: 12 }}>{r.cat}</div></div></div></td>
                  <td className="right num muted" data-label="Compra ant.">{RB.fmtARS(r.buyPrevPrice)}</td>
                  <td className="right num td-strong" data-label="Compra actual">{RB.fmtARS(r.buyPrice)}</td>
                  <td className="center" data-label="Inflación">
                    <span className={"badge " + (r.inf > 15 ? "badge-crit" : r.inf > 0 ? "badge-warn" : "badge-ok")}>
                      {r.inf > 0 ? <Icon name="arrowUp" size={12} /> : <Icon name="arrowDown" size={12} />}{RB.pct(r.inf)}
                    </span>
                  </td>
                  <td className="right num" data-label="Venta actual">{RB.fmtARS(r.sellPrice)}</td>
                  <td className="center" data-label="Margen">
                    <span className={"badge " + (low ? "badge-warn" : "badge-ok")}><span className="dot"></span>{Math.round(r.mg)}%</span>
                  </td>
                  <td className="right num td-strong" style={{ color: "var(--clay)" }} data-label="Venta sugerida">{RB.fmtARS(r.suggested)}</td>
                  <td className="right" data-label="Acción">
                    <button className="btn btn-ghost btn-sm" disabled={!low} style={{ opacity: low ? 1 : .4 }} onClick={() => applySuggested(r)}>
                      <Icon name="check" size={14} />Aplicar
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      <p className="muted" style={{ fontSize: 12.5, marginTop: 14, maxWidth: 760 }}>
        El precio sugerido mantiene un margen del {Math.round(RB.TARGET_MARGIN * 100)}% sobre el costo de compra actual:
        <strong> precio = costo ÷ (1 − margen)</strong>. Podés ajustarlo manualmente desde cada producto.
      </p>
    </div>
  );
}

Object.assign(window, { Costos });
