/* ===================== INKOOP =====================
   Inkoopprijzen snel checken & aanpassen per product.
   Wijzigingen werken direct door in alle winst- en margeberekeningen. */

function Inkoop({ db, onNav }) {
  const [, force] = React.useReducer(x => x + 1, 0);
  const [newSup, setNewSup] = React.useState("");
  const prods = db.products;
  const suppliers = window.STORE.get().suppliers || [];
  const filled = prods.filter(p => db.effCost(p) != null).length;

  const rows = prods.map(p => {
    const inkoop = db.effCost(p);
    const info = window.STORE.costInfo(p.sku) || {};
    const priceBol = db.bestPrice ? db.bestPrice(p, /bol/i) : null;
    const priceWeb = db.bestPrice ? db.bestPrice(p, /doosjehout|woo|webshop|eigen/i) : null;
    const margeBol = (inkoop != null && priceBol > 0 && db.winstPer) ? db.winstPer(p, priceBol, "Bol.com NL") : null;
    const margeWeb = (inkoop != null && priceWeb > 0 && db.winstPer) ? db.winstPer(p, priceWeb, "Doosjehout.nl") : null;
    const pctBol = (margeBol != null && priceBol > 0) ? margeBol / priceBol * 100 : null;
    return { p, inkoop, info, priceBol, priceWeb, margeBol, margeWeb, pctBol };
  });

  const voorraadWaarde = rows.reduce((s, r) => s + (r.inkoop != null ? r.inkoop * (r.p.stock || 0) : 0), 0);
  const dunne = rows.filter(r => r.pctBol != null && r.pctBol < 10).length;

  const margeCell = (marge, price) => {
    if (marge == null) return <span className="muted">—</span>;
    const pct = price > 0 ? marge / price * 100 : null;
    return (
      <span className="tnum" style={{ fontWeight: 600, color: marge < 0 ? "var(--danger)" : (pct != null && pct < 10 ? "var(--warn)" : "var(--ok)") }}>
        {fmtEur(marge)}{pct != null ? <span className="muted" style={{ fontWeight: 400, fontSize: 11 }}> ({Math.round(pct)}%)</span> : null}
      </span>
    );
  };

  const addSup = () => { if (newSup.trim()) { window.STORE.addSupplier(newSup.trim()); setNewSup(""); force(); } };

  return (
    <div className="view">
      <div className="page-head">
        <h1>Inkoop</h1>
        <div className="ph-sub">Inkoopprijzen per product — pas ze hier direct aan; alle winst- en margeberekeningen rekenen meteen mee.</div>
      </div>

      <div className="grid cols-4" style={{ marginBottom: "var(--space)" }}>
        <KPI icon="euro" iconBg="var(--accent-soft)" iconColor="var(--accent)" label="Ingevuld" value={filled + "/" + prods.length} foot={filled === prods.length ? "alles compleet ✓" : (prods.length - filled) + " ontbreekt nog"} />
        <KPI icon="boxes" iconBg="var(--surface-3)" iconColor="var(--text-2)" label="Voorraadwaarde (inkoop)" value={fmtEur(Math.round(voorraadWaarde))} foot="huidige voorraad × inkoopprijs" />
        <KPI icon="alert" iconBg={dunne ? "var(--warn-soft)" : "var(--ok-soft)"} iconColor={dunne ? "var(--warn)" : "var(--ok)"} label="Dunne marge (<10%)" value={dunne} foot="op bol NL — opletten bij adverteren" />
        <KPI icon="truck" iconBg="var(--brand-soft)" iconColor="var(--brand)" label="Leveranciers" value={suppliers.length} foot="koppel per product" />
      </div>

      <Card style={{ marginBottom: "var(--space)" }}>
        <CardHead title="Inkoopprijzen per product" icon="euro" sub="excl. btw, per stuk" right={<span className="pill accent">{filled}/{prods.length} ingevuld</span>} />
        <div style={{ overflowX: "auto" }}>
          <table className="tbl">
            <thead><tr><th>Product</th><th className="num">Voorraad</th><th style={{ width: 130 }}>Inkoopprijs</th><th style={{ width: 150 }}>Leverancier</th><th className="num">Prijs bol</th><th className="num" title="winst per stuk op bol NL, na btw/commissie/verzending">Marge bol NL</th><th className="num" title="winst per stuk via doosjehout.nl, na btw/verzending">Marge webshop</th></tr></thead>
            <tbody>
              {rows.map(({ p, inkoop, info, priceBol, priceWeb, margeBol, margeWeb }) => (
                <tr key={p.sku}>
                  <td>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <ProductThumb p={p} size={32} />
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 240 }}>{p.name}</div>
                        <div className="mono muted" style={{ fontSize: 11 }}>{p.sku}{p.perPackage > 1 ? " · " + p.perPackage + "/pakket" : ""}</div>
                      </div>
                    </div>
                  </td>
                  <td className="num tnum">{p.stock || 0}</td>
                  <td>
                    <div style={{ position: "relative" }}>
                      <span style={{ position: "absolute", left: 9, top: 8, color: "var(--text-3)", fontSize: 13 }}>€</span>
                      <input className="input tnum" style={{ paddingLeft: 22, textAlign: "right", borderColor: inkoop == null ? "var(--warn)" : undefined }} inputMode="decimal" placeholder="0,00"
                        defaultValue={info.cost != null ? String(info.cost).replace(".", ",") : ""}
                        onBlur={e => { window.STORE.setCost(p.sku, e.target.value === "" ? null : e.target.value, info.supplierId); force(); }} />
                    </div>
                  </td>
                  <td>
                    <select className="input" style={{ fontSize: 12.5 }} value={info.supplierId != null ? String(info.supplierId) : ""}
                      onChange={e => { window.STORE.setCost(p.sku, info.cost != null ? String(info.cost) : "", e.target.value === "" ? null : +e.target.value); force(); }}>
                      <option value="">—</option>
                      {suppliers.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                    </select>
                  </td>
                  <td className="num tnum muted">{priceBol != null ? fmtEur(priceBol) : "—"}</td>
                  <td className="num">{margeCell(margeBol, priceBol)}</td>
                  <td className="num">{margeCell(margeWeb, priceWeb)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="muted" style={{ fontSize: 12, padding: "10px 16px", borderTop: "1px solid var(--border)" }}>
          Marge = winst per stuk ná btw, commissie/platformkosten en verzending — vóór winstbelasting en advertentiekosten. Een oranje invoerveld betekent: inkoopprijs ontbreekt nog.
        </div>
      </Card>

      <Card>
        <CardHead title="Leveranciers" icon="truck" sub="voeg toe en koppel per product in de tabel hierboven" />
        <div className="card-pad" style={{ paddingTop: 6 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 4, marginBottom: 10 }}>
            {suppliers.length === 0 && <div className="muted" style={{ fontSize: 12.5 }}>Nog geen leveranciers.</div>}
            {suppliers.map(s => (
              <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, padding: "6px 2px" }}>
                <Icon name="truck" size={14} style={{ color: "var(--text-3)" }} />
                <span style={{ flex: 1, fontWeight: 600 }}>{s.name}</span>
                <span className="muted" style={{ fontSize: 12 }}>{rows.filter(r => r.info.supplierId === s.id).length} product(en)</span>
              </div>
            ))}
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <input className="input" placeholder="Naam leverancier…" value={newSup} onChange={e => setNewSup(e.target.value)} onKeyDown={e => { if (e.key === "Enter") addSup(); }} style={{ maxWidth: 280 }} />
            <button className="btn btn-primary" onClick={addSup}><Icon name="check" size={14} sw={2.4} />Toevoegen</button>
          </div>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { Inkoop });
