/* ============================================================
   Vista: Compras — Lista de reposición automática
   ============================================================ */
function Compras({ products, suppliers, toast }) {
  const [detail, setDetail] = useState(null);
  const toReorder = products
    .filter((p) => RB.stockState(p) !== "ok")
    .map((p) => ({ ...p, qty: RB.reorderQty(p), cost: RB.reorderQty(p) * p.buyPrice }));

  // agrupar por proveedor
  const bySupplier = {};
  toReorder.forEach((p) => { (bySupplier[p.supplier] = bySupplier[p.supplier] || []).push(p); });
  const supName = (id) => suppliers.find((s) => s.id === id) || { name: "Sin proveedor" };
  const grandTotal = toReorder.reduce((s, p) => s + p.cost, 0);

  const waText = (sid, items) =>
    encodeURIComponent(`Hola ${supName(sid).name}, quisiera reponer:\n` +
      items.map((p) => `• ${p.qty}× ${p.name} (${p.sku})`).join("\n") +
      `\nTotal estimado: ${RB.fmtARS(items.reduce((s, p) => s + p.cost, 0))}`);

  return (
    <div>
      <div className="stat-grid" style={{ gridTemplateColumns: "repeat(3,1fr)" }}>
        <div className="stat clickable" role="button" tabIndex={0}
          onClick={() => setDetail({
            title: "Productos a reponer · " + toReorder.length,
            intro: "Productos por debajo del ideal y cuánto conviene comprar de cada uno (cantidad sugerida × precio de compra).",
            rows: toReorder.slice().sort((a, b) => b.cost - a.cost).map((p) => ({ name: p.name, sub: supName(p.supplier).name + " · +" + p.qty + " u × " + RB.fmtARS(p.buyPrice), value: RB.fmtARS(p.cost) })),
            empty: "No hay nada para reponer, todo el stock está en orden. 🌿",
            foot: { label: "Costo total estimado", value: RB.fmtARS(grandTotal) },
          })}>
          <Icon name="chevron" className="stat-more" size={16} />
          <div className="stat-ico" style={{ background: "var(--crit-bg)", color: "var(--crit)" }}><Icon name="cart" /></div>
          <div className="stat-label">Productos a reponer</div><div className="stat-value">{toReorder.length}</div></div>
        <div className="stat clickable" role="button" tabIndex={0}
          onClick={() => setDetail({
            title: "Proveedores involucrados",
            intro: "A qué proveedores hay que pedirles para reponer todo, y cuánto suma cada uno.",
            rows: Object.entries(bySupplier).map(([sid, items]) => ({ name: supName(sid).name, sub: items.length + " producto(s)", value: RB.fmtARS(items.reduce((a, p) => a + p.cost, 0)) })),
            empty: "No hay reposiciones pendientes.",
            foot: { label: "Total", value: RB.fmtARS(grandTotal) },
          })}>
          <Icon name="chevron" className="stat-more" size={16} />
          <div className="stat-ico" style={{ background: "var(--info-bg)", color: "var(--info)" }}><Icon name="truck" /></div>
          <div className="stat-label">Proveedores involucrados</div><div className="stat-value">{Object.keys(bySupplier).length}</div></div>
        <div className="stat clickable" role="button" tabIndex={0}
          onClick={() => setDetail({
            title: "Costo estimado total",
            intro: "Lo que costaría reponer todo lo que falta, desglosado por proveedor.",
            rows: Object.entries(bySupplier).map(([sid, items]) => ({ name: supName(sid).name, sub: items.length + " producto(s)", value: RB.fmtARS(items.reduce((a, p) => a + p.cost, 0)) })).sort((a, b) => 0),
            empty: "No hay reposiciones pendientes.",
            foot: { label: "Costo total estimado", value: RB.fmtARS(grandTotal) },
          })}>
          <Icon name="chevron" className="stat-more" size={16} />
          <div className="stat-ico" style={{ background: "var(--ok-bg)", color: "var(--pine)" }}><Icon name="wallet" /></div>
          <div className="stat-label">Costo estimado total</div><div className="stat-value" style={{ fontSize: 26 }}>{RB.fmtARS(grandTotal)}</div></div>
      </div>
      {detail && <DetailModal {...detail} onClose={() => setDetail(null)} />}

      {toReorder.length === 0 && (
        <div className="card mt24"><div className="empty"><Icon name="check" size={46} /><div style={{ fontSize: 15 }}>No hay productos para reponer. Todo el stock está en orden 🌿</div></div></div>
      )}

      {Object.entries(bySupplier).map(([sid, items]) => {
        const s = supName(sid);
        const subtotal = items.reduce((a, p) => a + p.cost, 0);
        return (
          <div key={sid}>
            <div className="section-head">
              <div className="avatar" style={{ width: 34, height: 34, borderRadius: 10, background: "linear-gradient(135deg,var(--pine),var(--moss))" }}><Icon name="truck" size={17} /></div>
              <div><h2 style={{ fontSize: 18 }}>{s.name}</h2>
                <div className="muted" style={{ fontSize: 12.5 }}>{s.phone} · {s.email}</div></div>
              <span className="spacer"></span>
              <span className="badge badge-neutral">Subtotal {RB.fmtARS(subtotal)}</span>
              {s.whatsapp && <a className="btn btn-clay btn-sm" target="_blank" rel="noopener"
                href={"https://wa.me/" + (s.whatsapp || "").replace(/\D/g, "") + "?text=" + waText(sid, items)}>
                <Icon name="whatsapp" size={15} />Pedir por WhatsApp</a>}
            </div>
            <div className="table-wrap">
              <table className="tbl">
                <thead><tr><th>Producto</th><th>Estado</th><th className="center">Stock / Ideal</th>
                  <th className="center">Sugerido</th><th className="right">Costo unit.</th><th className="right">Costo estimado</th></tr></thead>
                <tbody>
                  {items.map((p) => (
                    <tr key={p.id}>
                      <td><div className="prod-cell"><ProdThumb product={p} /><div>
                        <div className="td-strong">{p.name}</div><div className="muted" style={{ fontSize: 12 }}>{p.sku}</div></div></div></td>
                      <td data-label="Estado"><StockBadge product={p} /></td>
                      <td className="center num muted" data-label="Stock / Ideal">{p.stock} / {RB.stockIdeal(p)}</td>
                      <td className="center num td-strong" style={{ fontSize: 15 }} data-label="Sugerido">+{p.qty}</td>
                      <td className="right num" data-label="Costo unit.">{RB.fmtARS(p.buyPrice)}</td>
                      <td className="right num td-strong" data-label="Costo estimado">{RB.fmtARS(p.cost)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { Compras });
