// Inventory module — tabs: Inventories · Products & services · Transfers
const itemKey = (i) => i.sku + "·" + i.wh;

function Inventory() {
  const { useState, useEffect } = React;
  const apiMode = window.API && API.active();
  const [tab, setTab] = useState("inv");
  const [items, setItems] = useState(D.items);
  const [whs, setWhs] = useState(D.warehouses);
  const [branches, setBranches] = useState([]); // [{id, name}] when live
  const [transfers, setTransfers] = useState(D.transfers);
  const [writeoffs, setWriteoffs] = useState(D.writeoffs);

  // keep the shared dataset in sync so other modules (Manufacturing) see changes
  useEffect(() => { D.items = items; D.warehouses = whs; D.transfers = transfers; D.writeoffs = writeoffs; }, [items, whs, transfers, writeoffs]);

  // live data — stock is tracked globally on the server, so all products sit in the first branch
  useEffect(() => {
    if (!apiMode) return;
    Promise.all([
      API.inventory.branches.list().catch(() => []),
      API.inventory.products.list()
    ]).then(([brs, prods]) => {
      const names = brs.length ? brs.map((b) => b.name) : ["Main"];
      setBranches(brs);
      setWhs(names);
      setItems(prods.map((p) => ({ ...p, wh: names[0] })));
    }).catch(() => notify(T("inv.errLoadProducts")));
    API.inventory.writeoffs.list()
      .then((ws) => setWriteoffs(ws))
      .catch(() => notify(T("inv.errLoadWriteoffs")));
  }, []);
  const [wh, setWh] = useState("All");
  const [q, setQ] = useState("");
  const [sel, setSel] = useState(null);
  const [adj, setAdj] = useState("");
  const [showNew, setShowNew] = useState(false);
  const [showWh, setShowWh] = useState(false);
  const [transferItem, setTransferItem] = useState(null); // preselected item
  const [showTransfer, setShowTransfer] = useState(false); // from transfers tab
  const [showWriteoff, setShowWriteoff] = useState(false);

  const addWarehouse = (name) => {
    const v = name.trim();
    if (!v) return false;
    if (whs.some((w) => w.toLowerCase() === v.toLowerCase())) { notify(T("inv.warehouseExists", { name: v })); return false; }
    setWhs((ws) => [...ws, v]);
    notify(T("inv.warehouseCreated", { name: v }));
    return true;
  };

  const isSvc = (i) => i.type === "service";
  const status = (i) => (isSvc(i) ? (i.active === false ? "Inactive" : "Service") : i.stock === 0 ? "Out of stock" : i.stock < i.reorder ? "Low" : "In stock");
  const visible = items.filter((i) =>
    (wh === "All" || i.wh === wh) &&
    (q === "" || (i.name + " " + i.sku + " " + i.cat).toLowerCase().includes(q.toLowerCase()))
  );
  const stockValue = items.reduce((s, i) => s + (i.stock || 0) * (i.cost || 0), 0);
  const low = items.filter((i) => !isSvc(i) && i.stock > 0 && i.stock < i.reorder).length;
  const out = items.filter((i) => !isSvc(i) && i.stock === 0).length;

  const selItem = sel ? items.find((i) => itemKey(i) === sel) : null;

  const applyAdj = () => {
    const n = parseInt(adj, 10);
    if (isNaN(n) || n === 0) { notify(T("inv.errNonZeroAdjustment")); return; }
    setItems((list) => list.map((i) => (itemKey(i) === sel ? { ...i, stock: Math.max(0, i.stock + n) } : i)));
    setAdj("");
    notify(T("inv.stockAdjustedBy", { n: (n > 0 ? "+" : "") + n }));
  };

  const doTransferBatch = (from, dest, lines) => {
    // lines: [{ item, qty }]
    setItems((list) => {
      let next = list.slice();
      lines.forEach(({ item, qty }) => {
        next = next.map((i) => (itemKey(i) === itemKey(item) ? { ...i, stock: i.stock - qty } : i));
        const target = next.find((i) => i.sku === item.sku && i.wh === dest);
        if (target) {
          next = next.map((i) => (i === target ? { ...i, stock: i.stock + qty } : i));
        } else {
          const idx = next.findIndex((i) => i.sku === item.sku && i.wh === from);
          const insertAt = idx >= 0 ? idx + 1 : next.length;
          next = [...next.slice(0, insertAt), { ...item, wh: dest, stock: qty }, ...next.slice(insertAt)];
        }
      });
      return next;
    });
    const baseRef = 140 + transfers.length;
    const newTransfers = lines.map((ln, k) => ({
      id: "TRF-" + (baseRef + k), date: "Jun 13", item: ln.item.name, sku: ln.item.sku, from, to: dest, qty: ln.qty
    }));
    setTransfers((ts) => [...newTransfers, ...ts]);
    lines.forEach((ln, k) => {
      D.movements.unshift({ date: "Jun 13", type: "Transfer", qty: -ln.qty, ref: "TRF-" + (baseRef + k) + " · " + from + " → " + dest });
    });
    const totalUnits = lines.reduce((s, ln) => s + ln.qty, 0);
    notify(lines.length === 1
      ? T("inv.transferredOne", { qty: lines[0].qty, name: lines[0].item.name, from: TV(from), to: TV(dest) })
      : T("inv.transferredMany", { units: totalUnits, items: lines.length, from: TV(from), to: TV(dest) }));
    setTransferItem(null);
    setShowTransfer(false);
    setSel(null);
  };

  const doWriteoffBatch = (from, reason, note, lines) => {
    // lines: [{ item, qty }]
    if (apiMode) {
      const br = branches.find((b) => b.name === from);
      API.inventory.writeoffs.create({
        branchId: br ? br.id : null,
        reason: reason,
        note: note,
        lines: lines.map((ln) => ({ productId: ln.item.id, qty: ln.qty }))
      }).then((rows) => {
        setItems((list) => list.map((i) => {
          const hit = lines.find((ln) => itemKey(ln.item) === itemKey(i));
          return hit ? { ...i, stock: Math.max(0, i.stock - hit.qty) } : i;
        }));
        setWriteoffs((ws) => [...rows, ...ws]);
        const totalUnits = rows.reduce((s, r) => s + r.qty, 0);
        const totalCost = rows.reduce((s, r) => s + r.qty * (r.cost || 0), 0);
        notify(T("inv.writtenOffSummary", { units: totalUnits, reason: TV(reason), loss: money(totalCost) }));
        setShowWriteoff(false);
      }).catch((ex) => notify(T("inv.errSaveWriteoff", { message: ex.message })));
      return;
    }
    setItems((list) => {
      let next = list.slice();
      lines.forEach(({ item, qty }) => {
        next = next.map((i) => (itemKey(i) === itemKey(item) ? { ...i, stock: Math.max(0, i.stock - qty) } : i));
      });
      return next;
    });
    const baseRef = 62 + writeoffs.length;
    const newWos = lines.map((ln, k) => ({
      id: "WO-" + String(baseRef + k).padStart(3, "0"), date: "Jun 13", item: ln.item.name, sku: ln.item.sku,
      wh: from, qty: ln.qty, reason, cost: ln.item.cost || 0, note
    }));
    setWriteoffs((ws) => [...newWos, ...ws]);
    lines.forEach((ln, k) => {
      D.movements.unshift({ date: "Jun 13", type: "Write-off", qty: -ln.qty, ref: "WO-" + String(baseRef + k).padStart(3, "0") + " · " + reason });
    });
    const totalUnits = lines.reduce((s, ln) => s + ln.qty, 0);
    const totalCost = lines.reduce((s, ln) => s + ln.qty * (ln.item.cost || 0), 0);
    notify(T("inv.writtenOffSummary", { units: totalUnits, reason: TV(reason), loss: money(totalCost) }));
    setShowWriteoff(false);
  };
  const totalValue = stockValue || 1;
  const whStats = whs.map((w) => {
    const rows = items.filter((i) => i.wh === w && !isSvc(i));
    return {
      name: w,
      skus: rows.length,
      units: rows.reduce((s, i) => s + (i.stock || 0), 0),
      value: rows.reduce((s, i) => s + (i.stock || 0) * (i.cost || 0), 0),
      low: rows.filter((i) => i.stock === 0 || i.stock < i.reorder).length
    };
  });

  return (
    <div className="page" data-screen-label="Inventory">
      <KpiBar>
        <Stat label={T("inv.stockValue")} value={money(stockValue)} sub={T("inv.activeSkusN", { n: items.length })} />
        <Stat label={T("inv.unitsOnHand")} value={fmt(items.reduce((s, i) => s + (i.stock || 0), 0))} sub={T("inv.warehousesN", { n: whs.length })} />
        <Stat label={T("inv.belowReorderPoint")} value={String(low)} sub={T("inv.replenishmentSuggested")} />
        <Stat label={TV("Out of stock")} value={String(out)} sub={T("inv.backordersPossible")} />
      </KpiBar>

      <Tabs active={tab} onChange={setTab} tabs={[
        { id: "inv", label: T("inv.inventories"), count: whs.length },
        { id: "items", label: T("inv.productsAndServices"), count: items.length },
        { id: "trf", label: T("inv.transfers"), count: transfers.length },
        { id: "wo", label: T("inv.writeOff"), count: writeoffs.length }
      ]} />

      {tab === "inv" ? (
        <><div className="toolbar page-toolbar">
            <span className="dim" style={{ fontSize: 13 }}>{T("inv.stockLocationsHint")}</span>
            <Btn variant="primary" icon="plus" onClick={() => setShowWh(true)}>{T("inv.newWarehouse")}</Btn>
          </div>
        <section className="card">
          <DataTable rowKey={(r) => r.name} onRow={(r) => { setWh(r.name); setTab("items"); }} rows={whStats} cols={[
            { k: "name", label: T("inv.warehouse"), render: (r) => (
                <span className="cellwho">
                  <span className="attn-ico blue"><Icon name="building" size={16} /></span>
                  <span className="who2"><b>{TV(r.name)}</b><small>{T("inv.skusStockedN", { n: r.skus })}</small></span>
                </span>
              ) },
            { k: "units", label: T("inv.unitsOnHand"), align: "right", w: "130px", render: (r) => <span className="mono strong">{fmt(r.units)}</span> },
            { k: "value", label: T("inv.stockValue"), align: "right", w: "130px", render: (r) => <span className="mono strong">{money(r.value)}</span> },
            { k: "share", label: T("inv.shareOfValue"), w: "180px", render: (r) => (
                <span className="stockcell"><Progress value={(r.value / totalValue) * 100} /><span className="mono dim">{Math.round((r.value / totalValue) * 100)}%</span></span>
              ) },
            { k: "low", label: T("inv.needsReorder"), w: "130px", render: (r) => r.low > 0 ? <Badge tone="amber">{T("inv.itemsN", { n: r.low })}</Badge> : <Badge tone="green">{T("inv.allGood")}</Badge> },
            { k: "go", label: "", align: "right", w: "40px", render: () => <Icon name="chevR" size={15} style={{ color: "var(--ink3)" }} /> }
          ]} />
        </section></>
      ) : null}

      {tab === "items" ? (
        <><div className="toolbar page-toolbar">
            <div className="toolbar-left">
              <Chips active={wh} onChange={setWh} options={[{ id: "All", label: T("inv.allWarehouses") }]
                .concat(whs.map((w) => ({ id: w, label: TV(w) })))} />
            </div>
            <div className="toolbar-right">
              <div className="searchbox">
                <Icon name="search" size={15} />
                <input placeholder={T("inv.searchItems")} value={q} onChange={(e) => setQ(e.target.value)} />
              </div>
              <Btn variant="primary" icon="plus" onClick={() => setShowNew(true)}>{T("inv.newItem")}</Btn>
            </div>
          </div>
        <section className="card">
          <DataTable rowKey={itemKey} onRow={(r) => { setSel(itemKey(r)); setAdj(""); }} empty={T("inv.noItemsMatch")} rows={visible} cols={[
            { k: "sku", label: T("inv.sku"), w: "100px", render: (r) => <span className="mono strong">{r.sku}</span> },
            { k: "name", label: T("inv.item"), render: (r) => (
                <span className="cellwho">
                  {r.mainImage ? <img className="thumb" src={r.mainImage} alt="" /> : null}
                  <span className="who2"><b>{r.name}</b>{r.brand ? <small>{r.brand}{r.sub ? " · " + r.sub : ""}</small> : null}</span>
                </span>
              ) },
            { k: "cat", label: T("common.category"), w: "110px", render: (r) => <span className="dim">{TV(r.cat)}</span> },
            { k: "wh", label: T("inv.warehouse"), w: "110px", render: (r) => <span className="dim">{TV(r.wh)}</span> },
            { k: "stock", label: T("inv.onHand"), w: "150px", render: (r) => isSvc(r) ? <span className="dim">—</span> : (
                <span className="stockcell">
                  <span className="mono strong">{r.stock}</span>
                  <Progress value={(r.stock / ((r.reorder || 1) * 2)) * 100}
                    color={r.stock === 0 ? "var(--red)" : r.stock < r.reorder ? "var(--amber)" : "var(--accent)"} />
                </span>
              ) },
            { k: "cost", label: T("inv.unitCost"), align: "right", w: "90px", render: (r) => r.cost ? <span className="mono">{money(r.cost)}</span> : <span className="dim">—</span> },
            { k: "value", label: T("inv.value"), align: "right", w: "100px", render: (r) => isSvc(r) ? <span className="dim">—</span> : <span className="mono strong">{money(r.stock * r.cost)}</span> },
            { k: "status", label: T("common.status"), w: "120px", render: (r) => <Badge>{status(r)}</Badge> }
          ]} />
        </section></>
      ) : null}

      {tab === "trf" ? (
        <><div className="toolbar page-toolbar">
            <span className="dim" style={{ fontSize: 13 }}>{T("inv.transfersHint")}</span>
            <Btn variant="primary" icon="send" onClick={() => setShowTransfer(true)}>{T("inv.newTransfer")}</Btn>
          </div>
        <section className="card">
          <DataTable rowKey={(r) => r.id} rows={transfers} empty={T("inv.noTransfers")} cols={[
            { k: "id", label: T("common.ref"), w: "90px", render: (r) => <span className="mono strong">{r.id}</span> },
            { k: "date", label: T("common.date"), w: "90px", render: (r) => <span className="dim">{r.date}</span> },
            { k: "item", label: T("inv.item"), render: (r) => <span className="who2"><b>{r.item}</b><small className="mono">{r.sku}</small></span> },
            { k: "route", label: T("inv.route"), w: "220px", render: (r) => (
                <span className="trf-route"><span>{TV(r.from)}</span><Icon name="chevR" size={13} style={{ color: "var(--ink3)" }} /><span>{TV(r.to)}</span></span>
              ) },
            { k: "qty", label: T("common.qty"), align: "right", w: "80px", render: (r) => <span className="mono strong">{r.qty}</span> }
          ]} />
        </section></>
      ) : null}

      {tab === "wo" ? (
        <><div className="toolbar page-toolbar">
            <span className="dim" style={{ fontSize: 13 }}>{T("inv.writeOffHint")}</span>
            <Btn variant="primary" icon="trash" onClick={() => setShowWriteoff(true)}>{T("inv.newWriteOff")}</Btn>
          </div>
        <section className="card">
          <DataTable rowKey={(r) => r.id} rows={writeoffs} empty={T("inv.noWriteOffs")} cols={[
            { k: "id", label: T("common.ref"), w: "140px", render: (r) => <span className="mono strong">{r.ref || refNo(r.id)}</span> },
            { k: "date", label: T("common.date"), w: "84px", render: (r) => <span className="dim">{r.date}</span> },
            { k: "item", label: T("inv.item"), render: (r) => <span className="who2"><b>{r.item}</b><small className="mono">{r.sku} · {TV(r.wh)}</small></span> },
            { k: "reason", label: T("common.reason"), w: "170px", render: (r) => <Badge tone="amber">{r.reason}</Badge> },
            { k: "qty", label: T("common.qty"), align: "right", w: "70px", render: (r) => <span className="mono strong">{r.qty}</span> },
            { k: "loss", label: T("inv.costLoss"), align: "right", w: "110px", render: (r) => <span className="mono" style={{ color: "var(--red)" }}>−{money(r.qty * (r.cost || 0))}</span> }
          ]} />
        </section></>
      ) : null}

      <Drawer open={!!selItem} onClose={() => setSel(null)}
        title={selItem ? selItem.name : ""} sub={selItem ? selItem.sku + " · " + TV(selItem.cat) + " · " + TV(selItem.wh) : ""}
        footer={selItem && !isSvc(selItem) && selItem.stock > 0 && whs.length > 1 ? (
          <div className="btnrow">
            <Btn variant="primary" icon="send" onClick={() => setTransferItem(selItem)}>{T("inv.transferStock")}</Btn>
          </div>
        ) : null}>
        {selItem ? (
          <div>
            {selItem.mainImage ? <img className="drawer-img" src={selItem.mainImage} alt={selItem.name} /> : null}
            <div className="amount-hero">
              {isSvc(selItem)
                ? <span className="display">{money(selItem.price)} <small>/ {TV(selItem.unit || "hour")}</small></span>
                : <span className="display">{selItem.stock} <small>{T("common.units")}</small></span>}
              <Badge>{status(selItem)}</Badge>
            </div>
            {!isSvc(selItem) ? <KV k={T("inv.reorderPoint")} v={T("inv.unitsN", { n: selItem.reorder || 0 })} /> : null}
            {selItem.cost ? <KV k={T("inv.unitCost")} v={money(selItem.cost)} mono /> : null}
            <KV k={T("inv.sellPrice")} v={money(selItem.price)} mono />
            {selItem.tax != null ? <KV k={T("acct.tax")} v={T("inv.taxAfterTax", { pct: selItem.tax, amount: money(selItem.priceAfterTax) })} /> : null}
            {selItem.minPrice ? <KV k={T("inv.minimumPrice")} v={money(selItem.minPrice)} mono /> : null}
            {!isSvc(selItem) ? <KV k={T("inv.stockValue")} v={money(selItem.stock * selItem.cost)} mono /> : null}
            {selItem.cost && selItem.price ? <KV k={T("inv.margin")} v={Math.round(((selItem.price - selItem.cost) / selItem.price) * 100) + "%"} /> : null}
            {selItem.barcodes && selItem.barcodes.length ? (
              <div className="lineitems">
                <div className="li-head">{T("inv.barcodes")}</div>
                {selItem.barcodes.map((b, i) => (
                  <div key={i} className="li-row">
                    <span>{b.name || T("inv.barcodeN", { n: i + 1 })}</span>
                    <span className="mono strong">{b.code}</span>
                  </div>
                ))}
              </div>
            ) : null}
            {selItem.byWeight ? <KV k={T("inv.soldByWeight")} v={T("inv.yesPerKg")} /> : null}
            {selItem.points ? <KV k={T("inv.earnPoints")} v={T("inv.pointsPerSale", { n: selItem.points })} /> : null}
            {selItem.desc ? <p className="drawer-desc">{selItem.desc}</p> : null}

            {!isSvc(selItem) ? (
            <div className="adjust">
              <div className="li-head">{T("inv.quickAdjustment")}</div>
              <div className="adjust-row">
                <Btn small onClick={() => setAdj(String((parseInt(adj, 10) || 0) - 1))}>−</Btn>
                <Input value={adj} placeholder="±0" onChange={(e) => setAdj(e.target.value)}
                  style={{ textAlign: "center", width: 80 }} />
                <Btn small onClick={() => setAdj(String((parseInt(adj, 10) || 0) + 1))}>+</Btn>
                <Btn small variant="primary" onClick={applyAdj}>{T("common.apply")}</Btn>
              </div>
            </div>
            ) : null}

            {!isSvc(selItem) ? (
            <div className="lineitems">
              <div className="li-head">{T("inv.recentMovements")}</div>
              {D.movements.map((m, i) => (
                <div key={i} className="li-row">
                  <span><Badge>{m.type}</Badge></span>
                  <span className="dim" style={{ flex: 1, marginInlineStart: 10 }}>{TV(m.ref)}</span>
                  <span className="mono strong">{m.qty > 0 ? "+" + m.qty : m.qty}</span>
                </div>
              ))}
            </div>
            ) : null}
          </div>
        ) : null}
      </Drawer>

      <NewItemModal open={showNew} onClose={() => setShowNew(false)}
        warehouses={whs} onCreateWarehouse={addWarehouse}
        onCreate={(item) => {
        setItems((list) => [item, ...list]);
        setShowNew(false);
        setTab("items");
        notify(item.type === "service"
          ? T("inv.serviceCreated", { name: item.name, sku: item.sku })
          : T("inv.productCreated", { name: item.name, sku: item.sku }));
      }} />

      <NewWarehouseModal open={showWh} onClose={() => setShowWh(false)}
        onCreate={(name) => { if (addWarehouse(name)) setShowWh(false); }} />

      <TransferModal open={!!transferItem || showTransfer} item={transferItem} items={items}
        warehouses={whs} onClose={() => { setTransferItem(null); setShowTransfer(false); }} onTransfer={doTransferBatch} />

      <WriteoffModal open={showWriteoff} items={items} warehouses={whs}
        onClose={() => setShowWriteoff(false)} onWriteoff={doWriteoffBatch} />
    </div>
  );
}

/* ---------- New warehouse ---------- */
function NewWarehouseModal({ open, onClose, onCreate }) {
  const { useState, useEffect } = React;
  const [name, setName] = useState("");
  const [loc, setLoc] = useState("");
  const [err, setErr] = useState("");
  useEffect(() => { if (open) { setName(""); setLoc(""); setErr(""); } }, [open]);

  const save = () => {
    if (!name.trim()) { setErr(T("inv.errWarehouseName")); return; }
    onCreate(name);
  };
  return (
    <Modal open={open} onClose={onClose} title={T("inv.newWarehouse")} sub={T("inv.newWarehouseSub")}
      footer={<div className="btnrow"><Btn variant="primary" icon="check" onClick={save}>{T("inv.createWarehouse")}</Btn><Btn onClick={onClose}>{T("common.cancel")}</Btn></div>}>
      <Field label={T("common.name")} error={err}>
        <Input placeholder={T("inv.warehouseNamePlaceholder")} value={name} onChange={(e) => setName(e.target.value)}
          onKeyDown={(e) => { if (e.key === "Enter") save(); }} />
      </Field>
      <Field label={T("inv.locationOptional")}>
        <Input placeholder={T("inv.locationPlaceholder")} value={loc} onChange={(e) => setLoc(e.target.value)} />
      </Field>
    </Modal>
  );
}


window.Inventory = Inventory;
window.itemKey = itemKey;
