// =============================================================
// Stock — boosters par série (NP/NH/H) + scellés
// =============================================================

const StockScreen = ({ state, actions }) => {
  const { stockSeries, sealed, categories } = state;
  const [tab, setTab] = useState("boosters");
  const [weighFor, setWeighFor] = useState(null); // catId
  const [adjustFor, setAdjustFor] = useState(null); // catId
  const [editSealed, setEditSealed] = useState(null); // sealed item
  const [addOpen, setAddOpen] = useState(false);
  const [search, setSearch] = useState("");

  const totalBoosters = stockSeries.reduce((a, s) => a + s.np + s.nh + s.h, 0);
  const totalSealed = sealed.reduce((a, x) => a + x.qty, 0);
  const valueBoosters = stockSeries.reduce((a, s) => a + (s.np + s.nh + s.h) * s.unit_cost, 0);
  const valueSealed = sealed.reduce((a, x) => a + x.qty * x.cost, 0);

  const filteredSeries = useMemo(() => {
    if (!search) return stockSeries;
    const q = search.toLowerCase();
    return stockSeries.filter(s => s.name.toLowerCase().includes(q) || s.short.toLowerCase().includes(q));
  }, [stockSeries, search]);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Stock</h1>
          <div className="page-sub">{totalBoosters} boosters · {totalSealed} scellés · valeur {fmtEUR(valueBoosters + valueSealed, { decimals: 0 })} €</div>
        </div>
        <div className="page-actions">
          <button className="btn" onClick={() => window.location.href = "/api/stock/export.csv"}><Icon name="download" /> Inventaire</button>
          <button className="btn btn-primary" onClick={() => setAddOpen(true)}>
            <Icon name="plus" /> Ajouter au stock
          </button>
        </div>
      </div>

      <div className="kpi-grid">
        <Kpi label="Boosters total" value={totalBoosters} unit="" meta={`${stockSeries.length} séries actives`} />
        <Kpi label="Valeur boosters" value={valueBoosters} unit="€" meta={totalBoosters ? `coût moyen ${(valueBoosters / totalBoosters).toFixed(2)} €/u` : "—"} />
        <Kpi label="Scellés total" value={totalSealed} unit="" meta={`${sealed.length} types d'items`} />
        <Kpi label="Valeur scellés" value={valueSealed} unit="€" meta={totalSealed ? `${fmtEUR(valueSealed / totalSealed, { decimals: 0 })} € moyen` : "—"} />
      </div>

      <div className="toolbar" style={{ marginTop: 16 }}>
        <Tabs value={tab} onChange={setTab} options={[
          { value: "boosters", label: `Boosters par série (${totalBoosters})` },
          { value: "sealed", label: `Scellés / Displays / Decks (${totalSealed})` },
        ]} />
        <div className="toolbar-spacer"></div>
        <div className="search">
          <Icon name="search" />
          <input placeholder="Rechercher une série..." value={search} onChange={e => setSearch(e.target.value)} />
        </div>
      </div>

      {tab === "boosters" && (
        <div className="stock-grid">
          {filteredSeries.map(s => (
            <SeriesCard key={s.cat + s.short}
                        series={s}
                        onWeigh={() => setWeighFor(s.cat)}
                        onAdjust={() => setAdjustFor(s.cat)}
                        onDelete={() => {
                          if (confirm(`Retirer la série « ${s.name} » du stock ? Le stock actuel (${s.np + s.nh + s.h} boosters) sera perdu.`)) {
                            actions.deleteStockSeries(s.cat);
                          }
                        }}
                        onRename={(newName, newShort) => actions.renameCategory(s.cat, newName, newShort)}
                        canWeigh={s.np > 0} />
          ))}
          {filteredSeries.length === 0 && (
            <div className="empty" style={{ gridColumn: "1 / -1" }}>Aucune série ne correspond.</div>
          )}
        </div>
      )}

      {tab === "sealed" && (
        <div className="card">
          <table className="tbl">
            <thead>
              <tr>
                <th style={{ width: 40 }}>#</th>
                <th>Item</th>
                <th>État</th>
                <th className="right">Qté</th>
                <th className="right">Coût unitaire</th>
                <th className="right">Valeur stock</th>
                <th style={{ width: 60 }}></th>
              </tr>
            </thead>
            <tbody>
              {sealed.filter(x => x.qty > 0).map(x => (
                <tr key={x.id} className="clickable">
                  <td className="mono muted">{x.displayNum}</td>
                  <td><b>{x.name}</b></td>
                  <td>
                    <span className={`tag ${x.state === "scellé" ? "tag-pos" : "tag-ghost"}`}>
                      {x.state}
                    </span>
                  </td>
                  <td className="right num">{x.qty}</td>
                  <td className="right num"><Money eur={x.cost} /></td>
                  <td className="right num"><Money eur={x.qty * x.cost} /></td>
                  <td>
                    <KebabMenu items={[
                      { label: "Modifier", icon: "edit", onClick: () => setEditSealed(x) },
                      { label: "Supprimer", icon: "trash", danger: true, onClick: () => {
                        if (confirm(`Supprimer « ${x.name} » du stock ?`)) actions.deleteSealedItem(x.id);
                      } },
                    ]} />
                  </td>
                </tr>
              ))}
              {sealed.length === 0 && (
                <tr><td colSpan="7" className="empty">Aucun scellé en stock.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      )}

      {weighFor !== null && (
        <WeighDrawer
          series={stockSeries.find(s => s.cat === weighFor)}
          onClose={() => setWeighFor(null)}
          onWeigh={(np, nh, h) => { actions.weighBoosters(weighFor, np, nh, h); setWeighFor(null); }}
        />
      )}

      {adjustFor !== null && (
        <AdjustStockDrawer
          series={stockSeries.find(s => s.cat === adjustFor)}
          onClose={() => setAdjustFor(null)}
          onSave={(target, reason, note) => {
            actions.adjustSeriesStock(adjustFor, target, reason, note);
            setAdjustFor(null);
          }}
        />
      )}

      {editSealed && (
        <EditSealedDrawer
          item={editSealed}
          onClose={() => setEditSealed(null)}
          onSave={(patch) => { actions.updateSealedItem(editSealed.id, patch); setEditSealed(null); }}
          onDelete={() => {
            if (confirm(`Supprimer « ${editSealed.name} » du stock ?`)) {
              actions.deleteSealedItem(editSealed.id);
              setEditSealed(null);
            }
          }}
        />
      )}

      <AddStockDrawer
        open={addOpen}
        onClose={() => setAddOpen(false)}
        categories={categories}
        actions={actions}
      />
    </div>
  );
};

const SeriesCard = ({ series: s, onWeigh, onAdjust, onDelete, onRename, canWeigh }) => {
  const tot = s.np + s.nh + s.h;
  const val = tot * s.unit_cost;
  const [editing, setEditing] = useState(false);
  const [draftName, setDraftName] = useState(s.name);
  const [draftShort, setDraftShort] = useState(s.short);
  const inputRef = useRef(null);

  // focus automatique quand on entre en mode edition
  useEffect(() => {
    if (editing && inputRef.current) inputRef.current.focus();
  }, [editing]);

  const startEdit = () => { setDraftName(s.name); setDraftShort(s.short); setEditing(true); };

  const confirmEdit = () => {
    const trimmedName  = draftName.trim();
    const trimmedShort = draftShort.trim();
    const nameChanged  = trimmedName  && trimmedName  !== s.name;
    const shortChanged = trimmedShort && trimmedShort !== s.short;
    if (nameChanged || shortChanged) {
      onRename(trimmedName || s.name, trimmedShort || s.short);
    }
    setEditing(false);
  };

  const cancelEdit = () => { setDraftName(s.name); setDraftShort(s.short); setEditing(false); };

  const onKeyDown = (e) => {
    if (e.key === "Enter")  { e.preventDefault(); confirmEdit(); }
    if (e.key === "Escape") { e.preventDefault(); cancelEdit();  }
  };

  return (
    <div className="series-card">
      <div className="series-card-head">
        <div style={{ flex: 1, minWidth: 0 }}>
          {editing ? (
            <div style={{ display: "flex", alignItems: "center", gap: 4, flexWrap: "wrap" }}>
              <input
                ref={inputRef}
                className="input"
                value={draftName}
                onChange={e => setDraftName(e.target.value)}
                onKeyDown={onKeyDown}
                placeholder="Nom"
                style={{ flex: "1 1 120px", minWidth: 0, fontSize: 13, padding: "3px 7px", height: 28 }}
              />
              <input
                className="input mono"
                value={draftShort}
                onChange={e => setDraftShort(e.target.value)}
                onKeyDown={onKeyDown}
                placeholder="Abrev"
                style={{ width: 60, flexShrink: 0, fontSize: 12, padding: "3px 6px", height: 28 }}
              />
              <button
                className="btn btn-sm btn-primary"
                onClick={confirmEdit}
                disabled={!draftName.trim()}
                title="Valider (Entree)"
                style={{ padding: "2px 6px", height: 28 }}
              >
                <Icon name="check" />
              </button>
              <button
                className="btn btn-sm"
                onClick={cancelEdit}
                title="Annuler (Echap)"
                style={{ padding: "2px 6px", height: 28 }}
              >
                <Icon name="close" />
              </button>
            </div>
          ) : (
            <>
              <div className="series-name">{s.name}</div>
              <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2, fontFamily: "var(--font-mono)", textTransform: "uppercase", letterSpacing: "0.05em" }}>
                {s.short}
              </div>
            </>
          )}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
          <div className="series-total">{tot}</div>
          <KebabMenu items={[
            { label: "Renommer", icon: "edit", onClick: startEdit },
            { label: "Ajuster le stock", icon: "edit", onClick: onAdjust },
            { label: "Peser des boosters", icon: "gauge", onClick: onWeigh, disabled: !canWeigh },
            { label: "Retirer la série", icon: "trash", danger: true, onClick: onDelete },
          ]} />
        </div>
      </div>

      <div className="series-bar">
        {s.np > 0 && <div className="series-bar-seg np" style={{ width: `${(s.np / tot) * 100}%` }}></div>}
        {s.nh > 0 && <div className="series-bar-seg nh" style={{ width: `${(s.nh / tot) * 100}%` }}></div>}
        {s.h > 0  && <div className="series-bar-seg h"  style={{ width: `${(s.h  / tot) * 100}%` }}></div>}
      </div>

      <div className="series-legend">
        <div className="lg np">
          <span className="lg-dot">Non pesé</span>
          <span className="lg-val">{s.np}</span>
        </div>
        <div className="lg nh">
          <span className="lg-dot">Pesé NH</span>
          <span className="lg-val">{s.nh}</span>
        </div>
        <div className="lg h">
          <span className="lg-dot">Hit</span>
          <span className="lg-val">{s.h}</span>
        </div>
      </div>

      <div className="series-meta-row">
        <span>coût unitaire <span className="mono">{s.unit_cost.toFixed(2)} €</span></span>
        <span>valeur <span className="mono">{fmtEUR(val, { decimals: 0 })} €</span></span>
      </div>

      <button
        className="btn btn-sm"
        onClick={onWeigh}
        disabled={!canWeigh}
        style={{ marginTop: 12, width: "100%", justifyContent: "center", opacity: canWeigh ? 1 : 0.5 }}
      >
        <Icon name="gauge" /> Peser des boosters
        {!canWeigh && <span style={{ color: "var(--ink-3)", fontSize: 11, marginLeft: 4 }}>· rien à peser</span>}
      </button>
    </div>
  );
};

// ---------- Weigh drawer — move from NP to NH/Hit ----------
const WeighDrawer = ({ series, onClose, onWeigh }) => {
  const [hit, setHit] = useState(0);
  const [pull, setPull] = useState(1); // how many to weigh

  const nhOut = Math.max(0, pull - hit);
  const valid = pull > 0 && pull <= series.np && hit >= 0 && hit <= pull;

  return (
    <Drawer open onClose={onClose}
      title={`Peser des boosters · ${series.name}`}
      sub={`${series.np} non pesés disponibles · coût unitaire ${series.unit_cost.toFixed(2)} €`}
      footer={
        <React.Fragment>
          <button className="btn" onClick={onClose}>Annuler</button>
          <button className="btn btn-primary" disabled={!valid} onClick={() => onWeigh(pull, nhOut, hit)}>
            <Icon name="check" /> Enregistrer la pesée
          </button>
        </React.Fragment>
      }
    >
      <div style={{ background: "var(--accent-tint)", color: "var(--accent)", padding: 12, borderRadius: 8, fontSize: 13, marginBottom: 22 }}>
        Tu prélèves des boosters dans le stock <b>non pesé</b>, tu les passes à la balance, et tu indiques combien sont des <b>hits</b>. Le reste passe en <b>pesé NH</b>.
      </div>

      <div className="field" style={{ marginBottom: 16 }}>
        <label>Combien tu en pèses ?</label>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <div className="input-suffix-wrap" style={{ flex: 1 }}>
            <input className="input mono" type="number" min={1} max={series.np}
                   value={pull}
                   onChange={e => setPull(Math.min(series.np, Math.max(0, Number(e.target.value))))} />
            <span className="input-suffix">/ {series.np}</span>
          </div>
          <button className="btn btn-sm" onClick={() => setPull(series.np)}>Tous ({series.np})</button>
        </div>
      </div>

      <div className="field" style={{ marginBottom: 22 }}>
        <label>Combien de hits trouvés ?</label>
        <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
          <button className="btn btn-sm" onClick={() => setHit(Math.max(0, hit - 1))} disabled={hit <= 0}>−</button>
          <input className="input mono" type="number" min={0} max={pull}
                 value={hit}
                 style={{ width: 80, textAlign: "center" }}
                 onChange={e => setHit(Math.min(pull, Math.max(0, Number(e.target.value))))} />
          <button className="btn btn-sm" onClick={() => setHit(Math.min(pull, hit + 1))} disabled={hit >= pull}>+</button>
          <span style={{ color: "var(--ink-3)", fontSize: 12, marginLeft: 8 }}>sur {pull} pesés</span>
        </div>
      </div>

      {/* Preview */}
      <div className="card card-pad" style={{ background: "var(--bg-sunk)", borderStyle: "dashed" }}>
        <div className="kpi-label" style={{ marginBottom: 12 }}>Résultat de la pesée</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
          <FlowStat label="Non pesé" before={series.np} after={series.np - pull} color="var(--ink-4)" />
          <FlowStat label="Pesé NH"  before={series.nh} after={series.nh + nhOut} color="var(--accent-2)" />
          <FlowStat label="Hit"      before={series.h}  after={series.h + hit}    color="var(--pos)" />
        </div>
      </div>
    </Drawer>
  );
};

const FlowStat = ({ label, before, after, color }) => {
  const delta = after - before;
  return (
    <div>
      <div style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 10.5, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 500 }}>
        <span style={{ width: 6, height: 6, borderRadius: "50%", background: color, display: "inline-block" }}></span>
        {label}
      </div>
      <div className="mono" style={{ fontSize: 16, marginTop: 6, display: "flex", alignItems: "baseline", gap: 6 }}>
        <span style={{ color: "var(--ink-3)" }}>{before}</span>
        <span style={{ color: "var(--ink-4)" }}>→</span>
        <span style={{ fontWeight: 600 }}>{after}</span>
        {delta !== 0 && (
          <span style={{ fontSize: 11, color: delta > 0 ? "var(--pos)" : "var(--neg)" }}>
            {delta > 0 ? "+" : ""}{delta}
          </span>
        )}
      </div>
    </div>
  );
};

// ---------- Add to stock drawer ----------
const AddStockDrawer = ({ open, onClose, categories, actions }) => {
  const [kind, setKind] = useState("series"); // "series" | "sealed"
  // series form
  const [cat, setCat] = useState(categories[0]?.id || 1);
  const [np, setNp] = useState(0);
  const [nh, setNh] = useState(0);
  const [h, setH]   = useState(0);
  const [unitCost, setUnitCost] = useState("");
  const [costModeSeries, setCostModeSeries] = useState("unit"); // "unit" | "global"
  // sealed form
  const [name, setName] = useState("");
  const [stateSealed, setStateSealed] = useState("scellé");
  const [qty, setQty] = useState(1);
  const [cost, setCost] = useState("");
  const [costModeSealed, setCostModeSealed] = useState("unit");
  const reset = () => { setKind("series"); setNp(0); setNh(0); setH(0); setUnitCost(""); setName(""); setQty(1); setCost(""); };

  const submit = () => {
    if (kind === "series") {
      const c = categories.find(x => x.id === Number(cat));
      const totalQtySeries = Number(np) + Number(nh) + Number(h);
      const finalUnitCost = costModeSeries === "global" && totalQtySeries > 0
        ? Number(unitCost) / totalQtySeries
        : Number(unitCost) || 0;
      actions.addStockSeries({
        cat: Number(cat),
        name: c?.name || "Série",
        short: c?.short || "—",
        np: Number(np) || 0,
        nh: Number(nh) || 0,
        h:  Number(h)  || 0,
        unit_cost: finalUnitCost,
      });
    } else {
      const qtyNum = Number(qty) || 1;
      const finalSealedCost = costModeSealed === "global" && qtyNum > 0
        ? Number(cost) / qtyNum
        : Number(cost) || 0;
      actions.addSealedItem({
        name: name || "Item scellé",
        state: stateSealed,
        qty: qtyNum,
        cost: finalSealedCost,
        cat: Number(cat) || null,
      });
    }
    reset();
    onClose();
  };

  const seriesValid = (Number(np) + Number(nh) + Number(h)) > 0 && Number(unitCost) > 0;
  const sealedValid = name && Number(qty) > 0 && Number(cost) > 0;

  return (
    <Drawer open={open} onClose={onClose}
      title="Ajouter au stock"
      sub="Crée une nouvelle entrée (sans passer par une commande)"
      footer={
        <React.Fragment>
          <button className="btn" onClick={onClose}>Annuler</button>
          <button className="btn btn-primary"
                  disabled={kind === "series" ? !seriesValid : !sealedValid}
                  onClick={submit}>
            <Icon name="check" /> Ajouter
          </button>
        </React.Fragment>
      }
    >
      <div style={{ marginBottom: 18 }}>
        <Tabs value={kind} onChange={setKind} options={[
          { value: "series", label: "Boosters par série" },
          { value: "sealed", label: "Scellé / Display / Deck" },
        ]} />
      </div>

      {kind === "series" && (
        <div className="flex-col" style={{ gap: 14 }}>
          <div className="field">
            <label>Série Pokémon</label>
            <NewCatInline
              categories={categories}
              value={cat}
              onChange={id => setCat(Number(id))}
              actions={actions}
            />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
            <div className="field">
              <label>Non pesé (NP)</label>
              <input className="input mono" type="number" min={0} value={np} onChange={e => setNp(e.target.value)} />
            </div>
            <div className="field">
              <label>Pesé NH</label>
              <input className="input mono" type="number" min={0} value={nh} onChange={e => setNh(e.target.value)} />
            </div>
            <div className="field">
              <label>Hit (H)</label>
              <input className="input mono" type="number" min={0} value={h} onChange={e => setH(e.target.value)} />
            </div>
          </div>
          <div className="field">
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 }}>
              <label style={{ margin: 0 }}>Cout {costModeSeries === "unit" ? "unitaire" : "global"} (€)</label>
              <div style={{ display: "inline-flex", border: "1px solid var(--line)", borderRadius: 6, overflow: "hidden", fontSize: 11 }}>
                <button type="button" onClick={() => setCostModeSeries("unit")}
                  style={{ padding: "2px 8px", background: costModeSeries === "unit" ? "var(--accent-tint)" : "transparent", color: costModeSeries === "unit" ? "var(--accent)" : "var(--ink-3)", border: "none", cursor: "pointer", fontWeight: 600 }}>
                  Unitaire
                </button>
                <button type="button" onClick={() => setCostModeSeries("global")}
                  style={{ padding: "2px 8px", background: costModeSeries === "global" ? "var(--accent-tint)" : "transparent", color: costModeSeries === "global" ? "var(--accent)" : "var(--ink-3)", border: "none", borderLeft: "1px solid var(--line)", cursor: "pointer", fontWeight: 600 }}>
                  Global
                </button>
              </div>
            </div>
            <div className="input-suffix-wrap">
              <input className="input mono" type="number" step="0.01"
                placeholder={costModeSeries === "unit" ? "1.85" : "55.50"}
                value={unitCost} onChange={e => setUnitCost(e.target.value)} />
              <span className="input-suffix">{costModeSeries === "unit" ? "€/u" : "€ total"}</span>
            </div>
            <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4 }}>
              {costModeSeries === "unit"
                ? "Coût moyen pondéré tous frais inclus (prix JPY + port + ZM ÷ taux)."
                : `Coût total du lot : divisé par ${Number(np) + Number(nh) + Number(h) || "?"} boosters au save.`}
            </div>
          </div>

          <div style={{ marginTop: 6, padding: 12, background: "var(--bg-sunk)", borderRadius: 8, fontSize: 12.5 }}>
            {(() => {
              const totQty = Number(np) + Number(nh) + Number(h);
              const totalEur = costModeSeries === "unit"
                ? totQty * Number(unitCost || 0)
                : Number(unitCost || 0);
              const perUnit = costModeSeries === "global" && totQty > 0
                ? Number(unitCost || 0) / totQty
                : Number(unitCost || 0);
              return (
                <React.Fragment>
                  <b>Total :</b> {totQty} boosters · valeur ≈ <span className="mono">{totalEur.toFixed(2)} €</span>
                  {totQty > 0 && <span style={{ color: "var(--ink-3)", marginLeft: 8 }}>({perUnit.toFixed(3)} €/u)</span>}
                </React.Fragment>
              );
            })()}
          </div>
        </div>
      )}

      {kind === "sealed" && (
        <div className="flex-col" style={{ gap: 14 }}>
          <div className="field">
            <label>Nom de l'item</label>
            <input className="input" placeholder="Display M1S shrink" value={name} onChange={e => setName(e.target.value)} />
          </div>
          <div className="field">
            <label>Collection (optionnel)</label>
            <NewCatInline
              categories={categories}
              value={cat}
              onChange={id => setCat(Number(id))}
              actions={actions}
            />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div className="field">
              <label>État</label>
              <select className="select" value={stateSealed} onChange={e => setStateSealed(e.target.value)}>
                <option value="scellé">scellé</option>
                <option value="non scellé">non scellé</option>
              </select>
            </div>
            <div className="field">
              <label>Quantité</label>
              <input className="input mono" type="number" min={1} value={qty} onChange={e => setQty(e.target.value)} />
            </div>
          </div>
          <div className="field">
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 }}>
              <label style={{ margin: 0 }}>Cout {costModeSealed === "unit" ? "unitaire" : "global"} (€)</label>
              <div style={{ display: "inline-flex", border: "1px solid var(--line)", borderRadius: 6, overflow: "hidden", fontSize: 11 }}>
                <button type="button" onClick={() => setCostModeSealed("unit")}
                  style={{ padding: "2px 8px", background: costModeSealed === "unit" ? "var(--accent-tint)" : "transparent", color: costModeSealed === "unit" ? "var(--accent)" : "var(--ink-3)", border: "none", cursor: "pointer", fontWeight: 600 }}>
                  Unitaire
                </button>
                <button type="button" onClick={() => setCostModeSealed("global")}
                  style={{ padding: "2px 8px", background: costModeSealed === "global" ? "var(--accent-tint)" : "transparent", color: costModeSealed === "global" ? "var(--accent)" : "var(--ink-3)", border: "none", borderLeft: "1px solid var(--line)", cursor: "pointer", fontWeight: 600 }}>
                  Global
                </button>
              </div>
            </div>
            <div className="input-suffix-wrap">
              <input className="input mono" type="number" step="0.01" value={cost} onChange={e => setCost(e.target.value)} />
              <span className="input-suffix">{costModeSealed === "unit" ? "€/u" : "€ total"}</span>
            </div>
          </div>
          <div style={{ padding: 12, background: "var(--bg-sunk)", borderRadius: 8, fontSize: 12.5 }}>
            {(() => {
              const qtyN = Number(qty) || 0;
              const costN = Number(cost || 0);
              const total = costModeSealed === "unit" ? qtyN * costN : costN;
              const perU = costModeSealed === "global" && qtyN > 0 ? costN / qtyN : costN;
              return (
                <React.Fragment>
                  <b>Total :</b> {qtyN} × <span className="mono">{perU.toFixed(2)} €/u</span> = <span className="mono">{total.toFixed(2)} €</span>
                </React.Fragment>
              );
            })()}
          </div>
        </div>
      )}
    </Drawer>
  );
};

// ---------- Kebab menu (popover) ----------
const KebabMenu = ({ items }) => {
  const [open, setOpen] = useState(false);
  const [up, setUp] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onKey);
    // flip up si proche du bas de fenetre
    if (ref.current) {
      const r = ref.current.getBoundingClientRect();
      setUp(window.innerHeight - r.bottom < 200);
    }
    return () => {
      document.removeEventListener("mousedown", onDoc);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);
  return (
    <div ref={ref} className="kebab-wrap">
      <button
        className={`btn btn-ghost btn-sm btn-icon ${open ? "is-active" : ""}`}
        aria-label="Actions"
        onClick={(e) => { e.stopPropagation(); setOpen(o => !o); }}
      >
        <Icon name="dots" />
      </button>
      {open && (
        <div className={`menu-pop ${up ? "up" : ""}`} role="menu">
          {items.map((it, i) => (
            <button
              key={i}
              role="menuitem"
              disabled={it.disabled}
              className={`menu-item ${it.danger ? "danger" : ""}`}
              onClick={(e) => {
                e.stopPropagation();
                if (it.disabled) return;
                setOpen(false);
                it.onClick && it.onClick();
              }}
            >
              {it.icon && <span className="menu-icon"><Icon name={it.icon} /></span>}
              <span>{it.label}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

// ---------- Adjust series stock drawer ----------
const ADJUST_REASONS = [
  { value: "ouvert",   label: "Ouvert perso",      help: "Boosters ouverts pour soi, hors vente" },
  { value: "perdu",    label: "Perte / vol / casse", help: "Boosters manquants a l'inventaire" },
  { value: "recompte", label: "Recomptage",          help: "Correction apres inventaire physique" },
  { value: "cadeau",   label: "Cadeau / promo",      help: "Donne gratuitement (sans vente)" },
  { value: "autre",    label: "Autre",               help: "Preciser dans la note" },
];

const AdjustStockDrawer = ({ series, onClose, onSave }) => {
  const [np, setNp] = useState(series.np);
  const [nh, setNh] = useState(series.nh);
  const [h, setH] = useState(series.h);
  const [reason, setReason] = useState("recompte");
  const [note, setNote] = useState("");

  const before = series.np + series.nh + series.h;
  const after = Number(np) + Number(nh) + Number(h);
  const delta = after - before;
  const changed = Number(np) !== series.np || Number(nh) !== series.nh || Number(h) !== series.h;
  const valid = changed && Number(np) >= 0 && Number(nh) >= 0 && Number(h) >= 0;

  const reasonObj = ADJUST_REASONS.find(r => r.value === reason);

  return (
    <Drawer open onClose={onClose}
      title={`Ajuster le stock · ${series.name}`}
      sub={`Modifier les quantités sans passer par une vente ou une pesée`}
      footer={
        <React.Fragment>
          <button className="btn" onClick={onClose}>Annuler</button>
          <button className="btn btn-primary" disabled={!valid}
                  onClick={() => onSave({ np: Number(np), nh: Number(nh), h: Number(h) }, reasonObj.label, note)}>
            <Icon name="check" /> Enregistrer l'ajustement
          </button>
        </React.Fragment>
      }
    >
      <div style={{ background: "var(--warn-tint)", color: "var(--warn)", padding: 12, borderRadius: 8, fontSize: 13, marginBottom: 22 }}>
        Modifie directement les compteurs si tu as <b>ouvert</b>, <b>perdu</b>, <b>donné</b> ou <b>mal compté</b> des boosters — autrement, utilise plutôt « Peser » ou « Ventes ».
      </div>

      <div className="flex-col" style={{ gap: 14 }}>
        <AdjustRow label="Non pesé" hint="Stock vierge, jamais passé à la balance"
                   value={np} onChange={setNp} before={series.np} color="var(--ink-4)" />
        <AdjustRow label="Pesé NH" hint="Pesé, pas un hit (no-hit)"
                   value={nh} onChange={setNh} before={series.nh} color="var(--accent-2)" />
        <AdjustRow label="Hit" hint="Pesé, contient une carte premium"
                   value={h} onChange={setH} before={series.h} color="var(--pos)" />
      </div>

      <div className="field" style={{ marginTop: 22 }}>
        <label>Motif de l'ajustement</label>
        <div className="reason-grid">
          {ADJUST_REASONS.map(r => (
            <button key={r.value}
                    type="button"
                    className={`reason-chip ${reason === r.value ? "is-active" : ""}`}
                    onClick={() => setReason(r.value)}>
              <span className="reason-label">{r.label}</span>
              <span className="reason-help">{r.help}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="field" style={{ marginTop: 14 }}>
        <label>Note (optionnel)</label>
        <input className="input" placeholder="ex. ouvert pour stream du 03/05"
               value={note} onChange={e => setNote(e.target.value)} />
      </div>

      <div className="card card-pad" style={{ background: "var(--bg-sunk)", borderStyle: "dashed", marginTop: 18 }}>
        <div className="kpi-label" style={{ marginBottom: 12 }}>Récapitulatif</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
          <FlowStat label="Non pesé" before={series.np} after={Number(np)} color="var(--ink-4)" />
          <FlowStat label="Pesé NH"  before={series.nh} after={Number(nh)} color="var(--accent-2)" />
          <FlowStat label="Hit"      before={series.h}  after={Number(h)}  color="var(--pos)" />
        </div>
        <div style={{ marginTop: 14, paddingTop: 12, borderTop: "1px dashed var(--line)", display: "flex", justifyContent: "space-between", fontSize: 12.5 }}>
          <span style={{ color: "var(--ink-3)" }}>Total boosters</span>
          <span className="mono">
            <span style={{ color: "var(--ink-3)" }}>{before}</span>
            <span style={{ color: "var(--ink-4)", margin: "0 6px" }}>→</span>
            <b>{after}</b>
            {delta !== 0 && (
              <span style={{ color: delta > 0 ? "var(--pos)" : "var(--neg)", marginLeft: 8 }}>
                {delta > 0 ? "+" : ""}{delta}
              </span>
            )}
          </span>
        </div>
        <div style={{ marginTop: 6, display: "flex", justifyContent: "space-between", fontSize: 12.5 }}>
          <span style={{ color: "var(--ink-3)" }}>Valeur stock</span>
          <span className="mono">
            <span style={{ color: "var(--ink-3)" }}>{fmtEUR(before * series.unit_cost, { decimals: 0 })} €</span>
            <span style={{ color: "var(--ink-4)", margin: "0 6px" }}>→</span>
            <b>{fmtEUR(after * series.unit_cost, { decimals: 0 })} €</b>
          </span>
        </div>
      </div>
    </Drawer>
  );
};

const AdjustRow = ({ label, hint, value, onChange, before, color }) => {
  const v = Number(value);
  const delta = v - before;
  return (
    <div className="adjust-row">
      <div className="adjust-row-meta">
        <div style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: color }}></span>
          <b style={{ fontSize: 13 }}>{label}</b>
        </div>
        <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2 }}>{hint}</div>
        <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4, fontFamily: "var(--font-mono)" }}>
          actuel : {before}
        </div>
      </div>
      <div className="adjust-row-input">
        <button className="btn btn-sm btn-icon" onClick={() => onChange(Math.max(0, v - 1))} disabled={v <= 0}>−</button>
        <input className="input mono" type="number" min={0} value={value}
               style={{ width: 80, textAlign: "center" }}
               onChange={e => onChange(Math.max(0, Number(e.target.value)))} />
        <button className="btn btn-sm btn-icon" onClick={() => onChange(v + 1)}>+</button>
        <span className="adjust-delta" style={{ color: delta === 0 ? "var(--ink-3)" : delta > 0 ? "var(--pos)" : "var(--neg)" }}>
          {delta === 0 ? "—" : (delta > 0 ? `+${delta}` : `${delta}`)}
        </span>
      </div>
    </div>
  );
};

// ---------- Edit sealed item drawer ----------
const EditSealedDrawer = ({ item, onClose, onSave, onDelete }) => {
  const [name, setName] = useState(item.name);
  const [stateSealed, setStateSealed] = useState(item.state);
  const [qty, setQty] = useState(item.qty);
  const [cost, setCost] = useState(item.cost);

  const valid = name.trim().length > 0 && Number(qty) >= 0 && Number(cost) >= 0;
  const changed = name !== item.name || stateSealed !== item.state || Number(qty) !== item.qty || Number(cost) !== item.cost;

  return (
    <Drawer open onClose={onClose}
      title="Modifier l'item scellé"
      sub={`#${item.displayNum} · création initiale : ${item.name}`}
      footer={
        <React.Fragment>
          <button className="btn btn-danger" onClick={onDelete}>
            <Icon name="trash" /> Supprimer
          </button>
          <div style={{ flex: 1 }}></div>
          <button className="btn" onClick={onClose}>Annuler</button>
          <button className="btn btn-primary" disabled={!valid || !changed}
                  onClick={() => onSave({ name: name.trim(), state: stateSealed, qty: Number(qty), cost: Number(cost) })}>
            <Icon name="check" /> Enregistrer
          </button>
        </React.Fragment>
      }
    >
      <div className="flex-col" style={{ gap: 14 }}>
        <div className="field">
          <label>Nom de l'item</label>
          <input className="input" value={name} onChange={e => setName(e.target.value)} autoFocus />
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div className="field">
            <label>État</label>
            <select className="select" value={stateSealed} onChange={e => setStateSealed(e.target.value)}>
              <option value="scelle">scellé</option>
              <option value="non_scelle">non scellé</option>
            </select>
          </div>
          <div className="field">
            <label>Quantité</label>
            <input className="input mono" type="number" min={0} value={qty}
                   onChange={e => setQty(e.target.value)} />
          </div>
        </div>
        <div className="field">
          <label>Coût unitaire (€)</label>
          <div className="input-suffix-wrap">
            <input className="input mono" type="number" step="0.01" value={cost}
                   onChange={e => setCost(e.target.value)} />
            <span className="input-suffix">€</span>
          </div>
        </div>
        <div style={{ padding: 12, background: "var(--bg-sunk)", borderRadius: 8, fontSize: 12.5 }}>
          <b>Valeur stock :</b> {qty} × {Number(cost || 0).toFixed(2)} € = <span className="mono">{(Number(qty) * Number(cost || 0)).toFixed(2)} €</span>
        </div>
      </div>
    </Drawer>
  );
};

window.StockScreen = StockScreen;
