// Weekly Inventory Audit Session — worker walks floor, confirms qty + bin.
const { useState: useStateAU, useEffect: useEffectAU, useMemo: useMemoAU } = React;

function AuditSession({ wo, user, onExit, onComplete }) {
  const inv = window.INVENTORY || [];
  // Per-SKU state: { qtyChecked, binChecked, qty, bin, dirty }
  const [items, setItems] = useStateAU(() =>
    inv.map((it) => ({
      sku: it.sku, name: it.name, type: it.type,
      systemQty: it.qty, qty: it.qty,
      systemBin: it.bin || "—", bin: it.bin || "",
      qtyChecked: false, binChecked: false,
      dirty: false,
    }))
  );
  const [filter, setFilter] = useStateAU("REMAINING"); // REMAINING | ALL | DIFF
  const [search, setSearch] = useStateAU("");
  const [pauseModal, setPauseModal] = useStateAU(false);
  const [elapsed, setElapsed] = useStateAU(0);

  useEffectAU(() => {
    const t = setInterval(() => setElapsed((e) => e + 1), 1000);
    return () => clearInterval(t);
  }, []);

  function elapsedFmt() {
    const m = Math.floor(elapsed / 60); const s = elapsed % 60;
    return `00:${String(m).padStart(2,"0")}:${String(s).padStart(2,"0")}`;
  }

  const counts = useMemoAU(() => {
    const done = items.filter((i) => i.qtyChecked && i.binChecked).length;
    const remaining = items.length - done;
    const diffs = items.filter((i) => i.qty !== i.systemQty || (i.bin && i.bin !== i.systemBin)).length;
    return { total: items.length, done, remaining, diffs };
  }, [items]);

  const filtered = useMemoAU(() => {
    const q = search.trim().toLowerCase();
    return items.filter((it) => {
      if (filter === "REMAINING" && it.qtyChecked && it.binChecked) return false;
      if (filter === "DIFF" && it.qty === it.systemQty && it.bin === it.systemBin) return false;
      if (q && !`${it.sku} ${it.name}`.toLowerCase().includes(q)) return false;
      return true;
    });
  }, [items, filter, search]);

  function updateItem(sku, patch) {
    setItems((arr) => arr.map((it) => it.sku === sku ? { ...it, ...patch, dirty: true } : it));
  }

  function submit() {
    onComplete({
      counts,
      diffs: items.filter((i) => i.qty !== i.systemQty || (i.bin && i.bin !== i.systemBin)).map((i) => ({
        sku: i.sku, qtyDelta: i.qty - i.systemQty,
        binChanged: i.bin && i.bin !== i.systemBin, newBin: i.bin,
      })),
    });
  }

  return (
    <div className="min-h-screen bg-zinc-950 text-zinc-100 flex flex-col relative">
      <window.TopStripe />

      <header className="border-b border-zinc-800 bg-zinc-900/40 px-6 h-[64px] flex items-center justify-between flex-shrink-0">
        <div className="flex items-center gap-3">
          <button onClick={() => setPauseModal(true)}
            className="h-10 px-3 rounded-lg bg-amber-500/15 border border-amber-500/40 text-amber-200 text-[13px] font-medium hover:bg-amber-500/25 uppercase tracking-wider flex items-center gap-2">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>
            Pause
          </button>
          <button onClick={onExit}
            className="h-10 px-3 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-200 text-[13px] font-medium hover:bg-zinc-700 uppercase tracking-wider">
            ← Queue
          </button>
          <span className="font-mono text-[13px] text-zinc-500">{wo.id}</span>
          <span className="px-2 py-1 rounded text-[11px] font-bold uppercase tracking-wider bg-zinc-700/30 text-zinc-200 border border-zinc-600/50">AUDIT</span>
        </div>
        <div className="flex items-center gap-5 text-[14px]">
          <div className="text-zinc-400">Elapsed <span className="font-mono text-zinc-200">{elapsedFmt()}</span></div>
          <div className="text-zinc-300">{user.name}</div>
        </div>
      </header>

      {/* Progress bar + counts */}
      <div className="px-6 pt-4 pb-3 border-b border-zinc-800/50 flex-shrink-0 space-y-3">
        <div className="flex items-end justify-between">
          <div>
            <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Weekly inventory walk</div>
            <div className="font-display text-[36px] tracking-tight leading-tight mt-1">{wo.name}</div>
          </div>
          <div className="flex items-center gap-3">
            <Counter label="Done" value={counts.done} tone="ok" />
            <Counter label="Remaining" value={counts.remaining} />
            <Counter label="Differences" value={counts.diffs} tone={counts.diffs > 0 ? "warn" : "neutral"} />
            <Counter label="Total" value={counts.total} />
          </div>
        </div>
        <div className="h-2.5 rounded-full bg-zinc-800 overflow-hidden">
          <div className="h-full bg-emerald-500 transition-all" style={{ width: `${(counts.done / counts.total) * 100}%` }} />
        </div>
      </div>

      {/* Filters */}
      <div className="px-6 py-3 border-b border-zinc-800/50 flex items-center gap-3 flex-shrink-0">
        <input value={search} onChange={(e) => setSearch(e.target.value)}
          placeholder="Search SKU or part…"
          className="h-11 px-3 bg-zinc-900 border border-zinc-800 rounded-lg text-zinc-100 text-[14px] outline-none focus:border-zinc-600 w-[280px]" />
        <div className="flex gap-1 bg-zinc-900 border border-zinc-800 rounded-lg p-1">
          {[["REMAINING", "Remaining"], ["DIFF", "Differences"], ["ALL", "All"]].map(([k, label]) => (
            <button key={k} onClick={() => setFilter(k)}
              className={`h-9 px-3 rounded-md text-[12px] font-display tracking-wider transition ${
                filter === k ? "bg-zinc-100 text-zinc-950" : "text-zinc-400 hover:text-zinc-200"
              }`}>
              {label}
            </button>
          ))}
        </div>
        <div className="ml-auto text-[13px] text-zinc-500">
          Walk every bay and verify each SKU. Update if you find differences.
        </div>
      </div>

      {/* Table */}
      <div className="flex-1 overflow-y-auto px-6 py-4">
        <div className="max-w-[1300px] mx-auto bg-zinc-900 border border-zinc-800 rounded-xl overflow-hidden">
          <div className="grid grid-cols-[1.4fr_2fr_1.2fr_1.2fr_0.9fr] text-[11px] uppercase tracking-wider text-zinc-500 px-4 py-3 border-b border-zinc-800 bg-zinc-950/50">
            <div>SKU</div>
            <div>Part</div>
            <div>Qty on hand</div>
            <div>Bin / shelf</div>
            <div className="text-right">Status</div>
          </div>
          {filtered.length === 0 ? (
            <div className="px-4 py-12 text-center text-zinc-500 text-[14px]">
              {filter === "REMAINING" ? "✓ Everything checked." : "No matches."}
            </div>
          ) : (
            <div className="divide-y divide-zinc-800/80">
              {filtered.map((it) => <AuditRow key={it.sku} it={it} onChange={(p) => updateItem(it.sku, p)} />)}
            </div>
          )}
        </div>
      </div>

      {/* Footer CTA */}
      <div className="px-6 py-4 border-t border-zinc-800 bg-zinc-950 flex items-center gap-4 flex-shrink-0">
        <div className="flex-1 text-[13px] text-zinc-400">
          {counts.remaining > 0 ? (
            <>{counts.remaining} SKU{counts.remaining !== 1 ? "s" : ""} remaining. {counts.diffs} difference{counts.diffs !== 1 ? "s" : ""} to commit.</>
          ) : (
            <span className="text-emerald-400">All SKUs checked. Submit to commit {counts.diffs} update{counts.diffs !== 1 ? "s" : ""}.</span>
          )}
        </div>
        <window.HoldButton color="emerald" holdMs={500} onComplete={submit}
          disabled={counts.done === 0}
          className="h-[64px] px-6 min-w-[320px]"
          subText="submit audit · commits all updates">
          <div className="font-display text-[22px] tracking-wider">
            ✓ FINISH AUDIT ({counts.done}/{counts.total})
          </div>
        </window.HoldButton>
      </div>

      {pauseModal && (
        <window.PauseModal
          context={`Audit · ${counts.done}/${counts.total} checked · ${counts.diffs} differences logged`}
          onCancel={() => setPauseModal(false)}
          onPause={() => { setPauseModal(false); onExit(); }}
          onMaterialResolved={() => setPauseModal(false)}
        />
      )}
    </div>
  );
}

function AuditRow({ it, onChange }) {
  const qtyDiff = it.qty !== it.systemQty;
  const binDiff = it.bin && it.bin !== it.systemBin;
  const allChecked = it.qtyChecked && it.binChecked;

  function quickConfirm() {
    onChange({ qtyChecked: true, binChecked: true });
  }

  return (
    <div className={`grid grid-cols-[1.4fr_2fr_1.2fr_1.2fr_0.9fr] items-center gap-3 px-4 py-3 ${allChecked ? "bg-emerald-500/[0.04]" : ""}`}>
      <div>
        <div className="font-mono text-[12px] text-zinc-500">{it.type}</div>
        <div className="font-mono text-[13px] text-zinc-200">{it.sku}</div>
      </div>
      <div className="text-[14px] truncate">{it.name}</div>

      {/* Qty cell */}
      <div className="flex items-center gap-2">
        <button onClick={() => onChange({ qty: Math.max(0, it.qty - 1) })}
          className="h-[40px] w-[36px] rounded bg-zinc-800 border border-zinc-700 text-[16px] font-display flex-shrink-0">−</button>
        <input type="number" value={it.qty}
          onChange={(e) => onChange({ qty: Math.max(0, parseInt(e.target.value || "0", 10)) })}
          className={`h-[48px] flex-1 min-w-0 bg-zinc-950 border-2 rounded text-center font-display text-[20px] tabular-nums outline-none focus:border-zinc-500 ${
            qtyDiff ? "border-amber-500/50" : "border-zinc-800"
          }`} />
        <button onClick={() => onChange({ qty: it.qty + 1 })}
          className="h-[40px] w-[36px] rounded bg-zinc-800 border border-zinc-700 text-[16px] font-display flex-shrink-0">+</button>
      </div>

      {/* Bin cell */}
      <div>
        <input value={it.bin} onChange={(e) => onChange({ bin: e.target.value.toUpperCase() })}
          placeholder={it.systemBin}
          className={`h-[48px] w-full bg-zinc-950 border-2 rounded text-center font-mono text-[14px] tabular-nums outline-none focus:border-zinc-500 ${
            binDiff ? "border-amber-500/50" : "border-zinc-800"
          }`} />
        {binDiff && <div className="text-[10px] text-amber-400 mt-0.5">was {it.systemBin}</div>}
      </div>

      {/* Status */}
      <div className="flex items-center justify-end gap-1.5">
        {allChecked ? (
          qtyDiff || binDiff ? (
            <span className="px-2 py-1 rounded text-[10px] font-bold uppercase tracking-wider bg-amber-500/15 text-amber-300 border border-amber-500/40">
              ⚠ DIFF
            </span>
          ) : (
            <span className="px-2 py-1 rounded text-[10px] font-bold uppercase tracking-wider bg-emerald-500/15 text-emerald-300 border border-emerald-500/40">
              ✓ OK
            </span>
          )
        ) : (
          <button onClick={quickConfirm}
            className="h-9 px-3 rounded bg-emerald-500 text-zinc-950 text-[11px] font-display tracking-wider hover:bg-emerald-400">
            CONFIRM
          </button>
        )}
      </div>
    </div>
  );
}

function Counter({ label, value, tone = "neutral" }) {
  const color =
    tone === "ok" ? "text-emerald-400" :
    tone === "warn" ? "text-amber-400" :
    "text-zinc-100";
  return (
    <div className="bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 min-w-[80px] text-right">
      <div className="text-[10px] uppercase tracking-wider text-zinc-500">{label}</div>
      <div className={`font-display text-[22px] tabular-nums leading-none mt-0.5 ${color}`}>{value}</div>
    </div>
  );
}

window.AuditSession = AuditSession;
