/* ---------- Transfer stock (multi-item) ---------- */
function TransferModal({ open, item, items, warehouses, onClose, onTransfer }) {
  const { useState, useEffect } = React;
  const blankLine = () => ({ key: Math.random().toString(36).slice(2), sku: "", qty: "" });
  const [from, setFrom] = useState("");
  const [dest, setDest] = useState("");
  const [lines, setLines] = useState([blankLine()]);
  const [errs, setErrs] = useState({});

  // stock available at the chosen source warehouse (products only)
  const srcItems = items.filter((i) => i.type !== "service" && i.wh === from && i.stock > 0);
  const itemBySku = (sku) => srcItems.find((i) => i.sku === sku);
  const labelFor = (i) => i.name + " · " + i.sku + " (" + i.stock + ")";
  const usedSkus = lines.map((l) => l.sku).filter(Boolean);

  useEffect(() => {
    if (open) {
      const startFrom = item ? item.wh : "";
      setFrom(startFrom);
      const others = warehouses.filter((w) => w !== startFrom);
      setDest(item && others.length === 1 ? others[0] : "");
      if (item) {
        // pre-fill the opened item, plus a trailing blank if more stock exists at its source
        const moreHere = items.some((i) => i.type !== "service" && i.wh === item.wh && i.stock > 0 && i.sku !== item.sku);
        setLines(moreHere ? [{ key: "init", sku: item.sku, qty: "" }, blankLine()] : [{ key: "init", sku: item.sku, qty: "" }]);
      } else {
        setLines([blankLine()]);
      }
      setErrs({});
    }
  }, [open, item]);

  if (!open) return null;
  const others = warehouses.filter((w) => w !== from);

  const setLine = (key, patch) => setLines((xs) => xs.map((l) => (l.key === key ? { ...l, ...patch } : l)));
  const removeLine = (key) => setLines((xs) => {
    const next = xs.filter((l) => l.key !== key);
    // never leave the list without a trailing blank row to type into
    if (next.length === 0 || next[next.length - 1].sku) next.push(blankLine());
    return next;
  });
  const pickLine = (key, label) => {
    const hit = srcItems.find((i) => labelFor(i) === label);
    setLines((xs) => {
      let next = xs.map((l) => (l.key === key ? { ...l, sku: hit ? hit.sku : "" } : l));
      // auto-grow: once the last row has an item (and stock remains), open a fresh blank row
      const last = next[next.length - 1];
      const usedAfter = next.map((l) => l.sku).filter(Boolean);
      if (last.sku && srcItems.length > usedAfter.length) next = [...next, blankLine()];
      return next;
    });
  };

  const filledLines = lines.filter((l) => l.sku && (parseInt(l.qty, 10) || 0) > 0);
  const totalUnits = filledLines.reduce((s, l) => s + (parseInt(l.qty, 10) || 0), 0);

  const save = () => {
    const e = {};
    if (!from) e.from = T("trf.errSource");
    if (!dest) e.dest = T("trf.errDestination");
    const valid = [];
    lines.forEach((l) => {
      if (!l.sku && !l.qty) return;                 // ignore untouched rows
      const it = itemBySku(l.sku);
      const q = parseInt(l.qty, 10);
      if (!it) { e.lines = T("trf.errPickItem"); return; }
      if (isNaN(q) || q <= 0) { e.lines = T("trf.errQtyAboveZero"); return; }
      if (q > it.stock) { e.lines = T("trf.errOnlyAvailable", { stock: it.stock, name: it.name, wh: TV(from) }); return; }
      valid.push({ item: it, qty: q });
    });
    if (!e.lines && valid.length === 0) e.lines = T("trf.errAddOneItem");
    setErrs(e);
    if (Object.keys(e).length) return;
    onTransfer(from, dest, valid);
  };

  return (
    <Modal open={true} onClose={onClose} title={T("trf.title")} width={640}
      sub={T("trf.sub")}
      footer={
        <div className="je-foot">
          <span className="inv-foot-total">{totalUnits > 0 ? T("trf.unitsItemsSummary", { units: totalUnits, items: filledLines.length }) : T("trf.nothingAddedYet")}</span>
          <div className="btnrow">
            <Btn onClick={onClose}>{T("common.cancel")}</Btn>
            <Btn variant="primary" icon="send" onClick={save}>{T("inv.transferStock")}</Btn>
          </div>
        </div>
      }>
      <div className="trf-route-pick">
        <Field label={T("trf.fromWarehouse")} error={errs.from}>
          <SearchSelect options={warehouses} placeholder={T("trf.sourcePlaceholder")} value={from}
            onChange={(v) => { setFrom(v); if (v === dest) setDest(""); setLines([blankLine()]); }} disabled={!!item} />
        </Field>
        <span className="trf-route-arrow"><Icon name="chevR" size={18} /></span>
        <Field label={T("trf.toWarehouse")} error={errs.dest}>
          <SearchSelect options={others} placeholder={T("trf.destinationPlaceholder")} value={dest} onChange={setDest} />
        </Field>
      </div>

      <div className="field">
        <div className="inv-items-head">
          <span className="field-label" style={{ margin: 0 }}>{T("trf.itemsToMove")}</span>
          {errs.lines ? <span className="field-err">{errs.lines}</span> : null}
        </div>
        {!from ? (
          <div className="trf-empty">{T("trf.chooseSourceFirst")}</div>
        ) : srcItems.length === 0 ? (
          <div className="trf-empty">{T("trf.noStockAt", { wh: TV(from) })}</div>
        ) : (
          <div className="inv-items">
            <div className="trf-line trf-line-head">
              <span>{T("inv.item")}</span>
              <span className="ta-c">{T("trf.available")}</span>
              <span className="ta-c">{T("common.qty")}</span>
              <span></span>
            </div>
            {lines.map((l) => {
              const it = itemBySku(l.sku);
              const opts = srcItems.filter((i) => i.sku === l.sku || !usedSkus.includes(i.sku)).map(labelFor);
              return (
                <div className={"trf-line" + (it ? "" : " trf-line-blank")} key={l.key}>
                  <SearchSelect options={opts} placeholder={T("trf.chooseAnItem")}
                    value={it ? labelFor(it) : ""} onChange={(v) => pickLine(l.key, v)} />
                  <span className="trf-avail mono">{it ? it.stock : "—"}</span>
                  <div className="trf-qty">
                    <input className="input inv-cell ta-c" type="number" min="1" max={it ? it.stock : undefined}
                      placeholder="0" value={l.qty} disabled={!it}
                      onChange={(e) => setLine(l.key, { qty: e.target.value })} />
                    {it ? <button type="button" className="trf-all" onClick={() => setLine(l.key, { qty: String(it.stock) })}>{T("trf.all")}</button> : null}
                  </div>
                  {it ? (
                    <button type="button" className="inv-del" onClick={() => removeLine(l.key)}
                      title={T("common.remove")} aria-label={T("acct.removeLine")}>
                      <Icon name="trash" size={15} />
                    </button>
                  ) : <span className="trf-del-spacer"></span>}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </Modal>
  );
}

window.TransferModal = TransferModal;
