/* =============================================================
   CoreIQ Office — Receiving: worklist, Receive Order, product history
   Uses shared bare globals: OD, oMoney, findP, findS, OIcon, Screen,
   KpiCard, StatusPill, useOffice. Registers 3 screens.
   ============================================================= */
const { useState: rcvUseState, useMemo: rcvUseMemo, useEffect: rcvUseEffect } = React;

function rcvSync() { const [, s] = rcvUseState(0); rcvUseEffect(() => window.RCV.subscribe(() => s(n => n + 1)), []); }
function rcvCtn(l) { return l.ord; }

// cost movement cell: recCost vs current cost
function RcvMove({ l }) {
  const up = l.recCost > l.cost + 0.001;
  const down = l.recCost < l.cost - 0.001;
  const cls = up ? "rcv-move--up" : down ? "rcv-move--down" : "rcv-move--flat";
  return (
    <span className={"rcv-move " + cls}>
      {up && <OIcon name="arrow-up"/>}{down && <OIcon name="arrow-down"/>}
      {oMoney(l.recCost)}
    </span>
  );
}

// =================================================================
// RECEIVING WORKLIST
// =================================================================
function ReceivingWorklist() {
  const { setScreen, setScreenState } = window.useOffice();
  rcvSync();
  const R = window.RCV;
  const [filter, setFilter] = rcvUseState("active");
  const list = R.deliveries();

  const FILTERS = [
    { k: "active", l: "To receive", pred: d => ["awaiting", "invoice-attached", "part-received"].includes(d.status) },
    { k: "awaiting", l: "Awaiting", pred: d => d.status === "awaiting" },
    { k: "part-received", l: "Part received", pred: d => d.status === "part-received" },
    { k: "received", l: "Received", pred: d => d.status === "received" },
    { k: "all", l: "All", pred: () => true },
  ];
  const shown = list.filter(FILTERS.find(f => f.k === filter).pred);

  const toReceive = list.filter(d => ["awaiting", "invoice-attached", "part-received"].includes(d.status));
  const totalUnits = toReceive.reduce((s, d) => s + d.lines.reduce((a, l) => a + l.ord * l.ctn, 0), 0);
  const totalValue = toReceive.reduce((s, d) => s + (R.totals(d.id)?.inc || 0), 0);

  function open(id) { setScreenState(s => ({ ...s, rcvDeliveryId: id })); setScreen("receiveOrder"); }

  return (
    <Screen eyebrow="Stock · goods-in" title="Receiving"
      actions={<>
        <button className="btn btn--ghost btn--sm" onClick={() => R.resetSeed()}><OIcon name="refresh"/> Reset demo</button>
        <button className="btn btn--primary btn--sm"><OIcon name="plus"/> Manual receipt</button>
      </>}>
      <div className="rcv-wl-stat-row">
        <KpiCard label="Deliveries to receive" value={toReceive.length} delta={{ text: list.filter(d => d.status === "awaiting").length + " not yet arrived" }}/>
        <KpiCard label="Lines waiting" value={toReceive.reduce((s, d) => s + d.lines.length, 0)} delta={{ text: "across " + toReceive.length + " orders" }}/>
        <KpiCard label="Units inbound" value={totalUnits.toLocaleString()} delta={{ text: "cartons + units" }}/>
        <KpiCard label="Invoice value inbound" value={oMoney(totalValue)} delta={{ dir: "up", text: "inc GST" }}/>
      </div>

      <div className="off-table">
        <div className="off-table-toolbar">
          <div className="off-filters">
            {FILTERS.map(f => (
              <button key={f.k} className={"off-filter" + (filter === f.k ? " off-filter--active" : "")} onClick={() => setFilter(f.k)}>
                {f.l}<span className="off-filter-count">{list.filter(f.pred).length}</span>
              </button>
            ))}
          </div>
        </div>
        <div className="off-grid" style={{ gridTemplateColumns: "108px 1.5fr 150px 120px 70px 70px 120px 150px" }}>
          <div className="off-grid-headcell">Order</div>
          <div className="off-grid-headcell">Supplier · invoice</div>
          <div className="off-grid-headcell">Notes</div>
          <div className="off-grid-headcell">Store · totes</div>
          <div className="off-grid-headcell" style={{ justifyContent: "flex-end" }}>Lines</div>
          <div className="off-grid-headcell" style={{ justifyContent: "flex-end" }}>Units</div>
          <div className="off-grid-headcell" style={{ justifyContent: "flex-end" }}>Inc GST</div>
          <div className="off-grid-headcell">Status</div>
          {shown.map(d => {
            const t = R.totals(d.id);
            const sm = R.statusMeta(d.status);
            const units = d.lines.reduce((a, l) => a + l.rec * l.ctn, 0);
            return (
              <div key={d.id} className="off-grid-row" style={{ cursor: "pointer" }} onClick={() => open(d.id)}>
                <div className="off-grid-cell off-cell-mono off-cell-strong">{d.id}<div className="off-muted off-cell-mono" style={{ fontSize: 11, marginTop: 2 }}>{d.po}</div></div>
                <div className="off-grid-cell off-cell-strong">{R.WS[d.ws]}<div className="off-cell-mono off-muted" style={{ fontSize: 11, marginTop: 2 }}>Inv {d.invoice}</div></div>
                <div className="off-grid-cell off-muted" style={{ fontSize: 12 }}>{d.notes}</div>
                <div className="off-grid-cell off-mono">{findS(d.store)?.code}<span className="off-muted"> · {d.totes}T</span></div>
                <div className="off-grid-cell off-cell-num">{d.lines.length}</div>
                <div className="off-grid-cell off-cell-num">{units}</div>
                <div className="off-grid-cell off-cell-num off-cell-strong">{oMoney(t?.inc || 0)}</div>
                <div className="off-grid-cell"><StatusPill kind={sm.kind} label={sm.label}/></div>
              </div>
            );
          })}
        </div>
      </div>
    </Screen>
  );
}

// =================================================================
// RECEIVE ORDER (interactive goods-in)
// =================================================================
function ReceiveOrder() {
  const { screen, screenState, setScreen, setScreenState, pushToast } = window.useOffice();
  rcvSync();
  const R = window.RCV;
  const id = screenState.rcvDeliveryId || R.deliveries()[0].id;
  const d = R.delivery(id);
  const [adv, setAdv] = rcvUseState(window.RCV_TWEAKS?.advancedCols ?? false);
  const [sel, setSel] = rcvUseState(0);
  rcvUseEffect(() => { setAdv(window.RCV_TWEAKS?.advancedCols ?? false); }, [window.RCV_TWEAKS?.advancedCols]);

  if (!d) return <Screen eyebrow="Stock · goods-in" title="Receive order"><div className="off-empty"><div className="empty-title">Delivery not found</div></div></Screen>;

  const t = R.totals(id);
  const declared = R.invoiceDeclared(id);
  const variance = Math.round((t.inc - declared) * 100) / 100;
  const sm = R.statusMeta(d.status);
  const done = d.status === "received";

  // grid template: with/without advanced cost columns
  const cols = adv
    ? "30px 130px minmax(160px,1.4fr) 56px 70px 56px 96px 90px 80px 80px 64px 48px 90px 90px"
    : "30px 130px minmax(180px,1.6fr) 56px 78px 60px 100px 70px 56px 96px 96px";

  function recOf(i) { return d.lines[i].rec; }

  function doReceive(selectedOnly) {
    R.receive(id);
    pushToast({ kind: "paid", icon: "check-circle", title: "Order received · " + id, meta: d.lines.length + " lines · " + oMoney(t.inc) + " inc GST" });
  }

  const HeadCells = adv
    ? ["", "PDE # / barcode", "Name", "Ord", "Rec", "SOH", "Rec Ex", "Exp Cost", "WS1", "Last", "Cost", "M/Up", "GST · Sell", "Total"]
    : ["", "PDE # / barcode", "Name", "Ord", "Rec", "SOH", "Rec cost", "M/Up", "GST", "Sell", "Total"];

  return (
    <Screen eyebrow={"Stock · goods-in · " + d.po} title={"Receive order " + id}
      actions={<>
        <button className="btn btn--ghost btn--sm" onClick={() => setScreen("receiving")}><OIcon name="chevron-left"/> Worklist</button>
        <button className="btn btn--secondary btn--sm" onClick={() => R.autoSet(id)}><OIcon name="check"/> Auto-set received</button>
        <button className="btn btn--secondary btn--sm" onClick={() => R.clearRec(id)}>Clear rec qtys</button>
        <button className="btn btn--primary btn--sm" disabled={done} onClick={() => doReceive(false)}><OIcon name="download"/> {done ? "Received" : "Receive"}</button>
      </>}>

      {/* header strip */}
      <div className="rcv-head">
        <div>
          <div className="rcv-field-grid">
            <div className="rcv-field"><span className="rcv-field-l">Order no.</span><span className="rcv-field-v is-mono">{d.id}</span></div>
            <div className="rcv-field"><span className="rcv-field-l">Status</span><span className="rcv-field-v"><StatusPill kind={sm.kind} label={sm.label}/></span></div>
            <div className="rcv-field"><span className="rcv-field-l">Supplier</span><span className="rcv-field-v">{R.WS[d.ws]}</span></div>
            <div className="rcv-field"><span className="rcv-field-l">Invoice no.</span><span className="rcv-field-v is-mono">{d.invoice}</span></div>
            <div className="rcv-field"><span className="rcv-field-l">Store</span><span className="rcv-field-v">{findS(d.store)?.name}</span></div>
            <div className="rcv-field"><span className="rcv-field-l">Totes</span><span className="rcv-field-v">{d.totes}</span></div>
          </div>
        </div>
        <div>
          <span className="rcv-field-l" style={{ display: "block", marginBottom: 6 }}>Notes</span>
          <div className="rcv-notes">{d.notes}</div>
          <div className="rcv-field" style={{ marginTop: 11 }}><span className="rcv-field-l">Created</span><span className="rcv-field-v is-mono">{d.created}</span></div>
        </div>
        <div className="rcv-head-scan">
          <div className="rcv-scan">
            <div className="rcv-scan-l"><OIcon name="search"/> Scan products</div>
            <input className="input" placeholder="Scan barcode to set received…"/>
          </div>
          <div className="rcv-field" style={{ marginTop: 11 }}>
            <span className="rcv-field-l">Show advanced cost columns</span>
            <label className="toggle" style={{ marginTop: 4 }}>
              <input type="checkbox" checked={adv} onChange={e => setAdv(e.target.checked)}/>
              <span className="toggle-track"><span className="toggle-thumb"></span></span>
              <span style={{ fontSize: 13 }}>{adv ? "Showing Exp / WS1 / Last / Cost" : "Essentials only"}</span>
            </label>
          </div>
        </div>
      </div>

      {/* grid */}
      <div className="rcv-table">
        <div className="rcv-table-toolbar">
          <span className="off-cell-strong" style={{ fontSize: 13 }}>Stock lines</span>
          <span className="rcv-tb-spacer"></span>
          <span className="rcv-tb-count">{d.lines.length} lines · {d.lines.reduce((a, l) => a + l.rec * l.ctn, 0)} units received</span>
        </div>
        <div className="rcv-grid">
          <div className="rcv-row rcv-row--head" style={{ gridTemplateColumns: cols }}>
            {HeadCells.map((h, i) => (
              <div key={i} className={"rcv-cell rcv-cell--head" + (i >= 3 && h !== "Name" && h !== "PDE # / barcode" ? " rcv-cell--num" : "")} style={ h === "GST" || h === "GST · Sell" ? { textAlign: "center" } : undefined}>{h}</div>
            ))}
          </div>
          {d.lines.map((l, i) => {
            const p = findP(l.productId);
            const short = l.rec < l.ord;
            const over = l.rec > l.ord;
            const total = R.lineTotal(l);
            return (
              <div key={i} className={"rcv-row rcv-row--body" + (sel === i ? " rcv-row--active" : "")} style={{ gridTemplateColumns: cols }} onClick={() => setSel(i)}>
                <div className="rcv-cell" style={{ textAlign: "center" }}>{l.bonus ? <OIcon name="star" width={13} height={13} className="rcv-bonus-star"/> : <OIcon name="star" width={13} height={13} style={{ color: "var(--text-subtle)", opacity: 0.4 }}/>}</div>
                <div className="rcv-cell rcv-cell--mono">{p.sku}</div>
                <div className="rcv-cell rcv-cell--name">{p.name} {p.strength !== "—" ? p.strength : ""}<small>{p.pack}</small></div>
                <div className="rcv-cell rcv-cell--num">{l.ord}</div>
                <div className="rcv-cell" style={{ display: "flex", justifyContent: "flex-end" }} onClick={e => e.stopPropagation()}>
                  <div className={"rcv-recq" + (short ? " rcv-recq--short" : over ? " rcv-recq--over" : "")}>
                    <button onClick={() => R.setReceived(id, i, l.rec - 1)}>−</button>
                    <input value={l.rec} onChange={e => R.setReceived(id, i, parseInt(e.target.value || "0", 10))}/>
                    <button onClick={() => R.setReceived(id, i, l.rec + 1)}>+</button>
                  </div>
                </div>
                <div className="rcv-cell rcv-cell--num rcv-soh">{l.soh.toFixed(2)} <OIcon name="arrow-up" width={10} height={10} className="rcv-soh-arrow"/></div>
                <div className="rcv-cell rcv-cell--num"><RcvMove l={l}/></div>
                {adv && <div className="rcv-cell rcv-cell--num off-muted">{oMoney(l.expCost)}</div>}
                {adv && <div className="rcv-cell rcv-cell--num off-muted">{oMoney(l.ws1)}</div>}
                {adv && <div className="rcv-cell rcv-cell--num off-muted">{oMoney(l.last)}</div>}
                {adv && <div className="rcv-cell rcv-cell--num">{oMoney(l.cost)}</div>}
                <div className="rcv-cell rcv-cell--num">{l.markup.toFixed(1)}%</div>
                <div className="rcv-cell" style={{ textAlign: "center" }} onClick={e => e.stopPropagation()}>
                  <span className={"rcv-gst " + (l.gst ? "rcv-gst--y" : "rcv-gst--n")}>{l.gst ? "Y" : "N"}</span>
                </div>
                <div className="rcv-cell rcv-cell--num rcv-cell--sell">{oMoney(l.sell)}</div>
                <div className="rcv-cell rcv-cell--num rcv-cell--strong">{oMoney(total)}</div>
              </div>
            );
          })}
        </div>
      </div>

      {/* selected line detail */}
      {d.lines[sel] && (() => {
        const l = d.lines[sel]; const p = findP(l.productId);
        return (
          <div className="rcv-linedetail">
            <div><div className="rcv-ld-k">Stock name</div><div className="rcv-ld-v" style={{ fontSize: 13 }}>{p.name}</div></div>
            <div><div className="rcv-ld-k">Current cost → new</div><div className="rcv-ld-v">{oMoney(l.cost)} → {oMoney(l.recCost)}</div></div>
            <div><div className="rcv-ld-k">Current sell</div><div className="rcv-ld-v">{oMoney(l.sell)}</div></div>
            <div><div className="rcv-ld-k">New markup</div><div className="rcv-ld-v">{l.markup.toFixed(1)}%</div></div>
            <div><div className="rcv-ld-k">Ordered (units)</div><div className="rcv-ld-v">{l.ord * l.ctn}</div></div>
            <div><div className="rcv-ld-k">Received (units)</div><div className="rcv-ld-v">{l.rec * l.ctn}</div></div>
            <div><div className="rcv-ld-k">SOH after receipt</div><div className="rcv-ld-v">{(l.soh + l.rec * l.ctn).toFixed(2)}</div></div>
            <div><div className="rcv-ld-k">Line total ex GST</div><div className="rcv-ld-v">{oMoney(R.lineTotal(l))}</div></div>
          </div>
        );
      })()}

      {/* reconciliation */}
      <div className="rcv-recon">
        <div className="off-card" style={{ padding: "14px 18px" }}>
          <div className="off-cell-strong" style={{ fontSize: 13, marginBottom: 4 }}>Stock-line order notes</div>
          <div className="off-muted" style={{ fontSize: 13, lineHeight: 1.5 }}>
            {d.status === "received"
              ? "Received in full and posted to stock on hand. Cost and sell prices updated on the catalogue."
              : "Set received quantities against the invoice, then Receive to post stock on hand and update costs. Short-supplied lines stay on backorder."}
          </div>
        </div>
        <div className="rcv-recon-totals">
          <div className="rcv-recon-row"><span className="rcv-recon-k">Total ex GST</span><span className="rcv-recon-v">{oMoney(t.ex)}</span></div>
          <div className="rcv-recon-row"><span className="rcv-recon-k">GST</span><span className="rcv-recon-v">{oMoney(t.gst)}</span></div>
          <div className="rcv-recon-row rcv-recon-row--total"><span className="rcv-recon-k">Total inc GST</span><span className="rcv-recon-v">{oMoney(t.inc)}</span></div>
          <div className="rcv-recon-row" style={{ borderBottom: "none", paddingTop: 6 }}>
            <span className="rcv-recon-k">Invoice declared</span>
            <span className="rcv-recon-v" style={{ fontWeight: 500 }}>{oMoney(declared)}</span>
          </div>
          <div className="rcv-recon-row" style={{ borderBottom: "none", paddingTop: 0 }}>
            <span className="rcv-recon-k">Variance</span>
            <span className={"rcv-var " + (Math.abs(variance) < 0.01 ? "rcv-var--ok" : "rcv-var--off")}>
              {Math.abs(variance) < 0.01 ? "Matches invoice ✓" : (variance > 0 ? "+" : "") + oMoney(variance)}
            </span>
          </div>
        </div>
      </div>
    </Screen>
  );
}

// =================================================================
// PRODUCT ORDERS/INVOICES HISTORY
// =================================================================
function ProductOrderHistory() {
  const { screenState, setScreen } = window.useOffice();
  const R = window.RCV;
  const pid = screenState.historyProductId || screenState.activeProductId || "p016";
  const p = findP(pid);
  const [q, setQ] = rcvUseState("");
  const [supF, setSupF] = rcvUseState("all");
  const rows = rcvUseMemo(() => R.productHistory(pid), [pid]);

  const suppliers = ["all"].concat(Array.from(new Set(rows.map(r => r.supplier))));
  const shown = rows.filter(r => (supF === "all" || r.supplier === supF) && (!q || (r.orderNo + r.invoice + r.notes + r.supplier).toLowerCase().includes(q.toLowerCase())));

  const cols = "92px 96px 150px 130px 1.3fr 130px 64px 64px 90px 84px 74px 84px";
  const heads = ["Order No", "Status", "Created", "Invoice No", "Supplier · notes", "Received", "Ord", "Sup", "Inv cost", "Cost", "M/up%", "Sell"];

  // averages
  const recd = rows.filter(r => r.status === "Received");
  const avgCost = recd.length ? recd.reduce((s, r) => s + r.cost, 0) / recd.length : 0;
  const avgMarkup = recd.length ? recd.reduce((s, r) => s + r.markup, 0) / recd.length : 0;
  const totalOrdered = recd.reduce((s, r) => s + r.ordU, 0);

  return (
    <Screen eyebrow="Stock · purchase history" title={"Orders / invoices · " + p.name}
      actions={<>
        <button className="btn btn--ghost btn--sm" onClick={() => { setScreen("productDetail"); }}><OIcon name="chevron-left"/> Product</button>
        <button className="btn btn--secondary btn--sm"><OIcon name="printer"/> Print list</button>
      </>}>
      <div className="rcv-wl-stat-row">
        <KpiCard label="Order lines" value={rows.length} delta={{ text: recd.length + " received" }}/>
        <KpiCard label="Units received" value={totalOrdered.toLocaleString()} delta={{ text: "all suppliers" }}/>
        <KpiCard label="Avg invoice cost" value={oMoney(avgCost)} delta={{ dir: "up", text: "ex GST" }}/>
        <KpiCard label="Avg markup" value={avgMarkup.toFixed(1) + "%"} delta={{ text: "sell " + oMoney(p.price) }}/>
      </div>

      <div className="off-table">
        <div className="off-table-toolbar">
          <div className="off-filters">
            {suppliers.slice(0, 6).map(s => (
              <button key={s} className={"off-filter" + (supF === s ? " off-filter--active" : "")} onClick={() => setSupF(s)}>{s === "all" ? "All suppliers" : s}</button>
            ))}
          </div>
          <div style={{ flex: 1 }}></div>
          <div className="input-wrap" style={{ width: 220 }}>
            <OIcon name="search" className="input-wrap-icon"/>
            <input className="input" placeholder="Find order / invoice…" value={q} onChange={e => setQ(e.target.value)}/>
          </div>
        </div>
        <div style={{ overflowX: "auto" }}>
          <div className="rcv-hist-row rcv-hist-row--head" style={{ gridTemplateColumns: cols }}>
            {heads.map((h, i) => <div key={i} className={"rcv-cell rcv-cell--head" + (["Ord", "Sup", "Inv cost", "Cost", "M/up%", "Sell"].includes(h) ? " rcv-cell--num" : "")}>{h}</div>)}
          </div>
          {shown.map((r, i) => (
            <div key={i} className="rcv-hist-row rcv-hist-row--body" style={{ gridTemplateColumns: cols }}>
              <div className="rcv-cell rcv-cell--mono rcv-cell--strong">{r.orderNo}</div>
              <div className="rcv-cell">{r.status === "Received" ? <StatusPill kind="paid" label="Received"/> : <StatusPill kind="neutral" label="Saved"/>}</div>
              <div className="rcv-cell rcv-cell--mono off-muted">{r.created}</div>
              <div className="rcv-cell rcv-cell--mono">{r.invoice || "—"}</div>
              <div className="rcv-cell">{r.supplier}<div className="off-muted" style={{ fontSize: 11, marginTop: 1 }}>{r.notes}</div></div>
              <div className="rcv-cell rcv-cell--mono off-muted">{r.received || "—"}</div>
              <div className="rcv-cell rcv-cell--num">{r.ordU}</div>
              <div className="rcv-cell rcv-cell--num">{r.supU}{r.split && <span className="rcv-hist-split">split</span>}</div>
              <div className="rcv-cell rcv-cell--num">{oMoney(r.invCost)}</div>
              <div className="rcv-cell rcv-cell--num">{oMoney(r.cost)}</div>
              <div className="rcv-cell rcv-cell--num">{r.markup.toFixed(2)}</div>
              <div className="rcv-cell rcv-cell--num rcv-cell--sell">{oMoney(r.sell)}</div>
            </div>
          ))}
        </div>
      </div>
      <div className="off-muted" style={{ fontSize: 12, marginTop: 10 }}>{shown.length} lines</div>
    </Screen>
  );
}

window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, {
  receiving: ReceivingWorklist,
  receiveOrder: ReceiveOrder,
  productHistory: ProductOrderHistory,
});
