// Reorder screen (Phase C; docs/FORECASTING.md). Shows what to make / buy now — demand-driven
// reorder suggestions (critical first) — plus a one-tap button to load/refresh sales history
// from Shopify so the forecast has data. Manager/admin only.
const { useState: useStateRO, useEffect: useEffectRO } = React;

function ReorderTab({ user }) {
  const [rows, setRows] = useStateRO(null);        // null = loading
  const [unmatched, setUnmatched] = useStateRO(0);
  const [busy, setBusy] = useStateRO(false);

  function load() {
    fetch("/api/forecasting/reorder").then((r) => r.json()).then((d) => setRows(Array.isArray(d) ? d : [])).catch(() => setRows([]));
    fetch("/api/forecasting/unmatched").then((r) => r.json()).then((d) => setUnmatched(Array.isArray(d) ? d.length : 0)).catch(() => {});
  }
  useEffectRO(() => { load(); }, []);

  async function loadHistory() {
    setBusy(true);
    try {
      const r = await fetch("/api/forecasting/backfill", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ since: "2025-10-01" }) });
      const d = await r.json().catch(() => ({}));
      if (r.ok) window.gpsToast && window.gpsToast({ message: `Loaded ${d.lines} sales lines · ${d.matched} matched to SKUs`, tone: "ok" });
      else window.gpsToast && window.gpsToast({ message: d.error || "Couldn't load sales history", tone: "warn" });
    } catch (_) { window.gpsToast && window.gpsToast({ message: "Couldn't reach the server", tone: "warn" }); }
    setBusy(false);
    load();
  }

  const criticalCount = (rows || []).filter((r) => r.critical).length;

  return (
    <div className="flex-1 px-4 sm:px-8 py-5 sm:py-6 overflow-y-auto">
      <div className="max-w-[1100px] mx-auto space-y-6">
        <div className="flex items-end justify-between gap-3 flex-wrap">
          <div>
            <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Reorder</div>
            <h1 className="font-display text-[32px] sm:text-[44px] tracking-tight leading-none mt-1">What to make &amp; buy</h1>
            <p className="text-[13px] text-zinc-500 mt-1">Demand-driven suggestions from your sales history. Red = will run out within its lead time.</p>
          </div>
          <button onClick={loadHistory} disabled={busy}
            className="h-11 px-4 rounded-lg bg-cyan-500/10 border border-cyan-500/30 text-cyan-300 text-[13px] font-display tracking-wider hover:bg-cyan-500/20 disabled:opacity-50 whitespace-nowrap">
            {busy ? "Loading…" : "↻ Load / refresh sales history"}
          </button>
        </div>

        {unmatched > 0 && (
          <div className="text-[12px] text-amber-300/90 bg-amber-500/10 border border-amber-500/30 rounded-lg px-3 py-2">
            ⚠ {unmatched} SKU{unmatched !== 1 ? "s" : ""} of demand {unmatched !== 1 ? "don't" : "doesn't"} match a boxd part — excluded from forecasting. (Catalog/SKU gaps.)
          </div>
        )}

        {rows === null ? (
          <div className="text-zinc-600 text-[14px] py-10 text-center">Loading…</div>
        ) : rows.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 text-center gap-3">
            <div className="text-[40px]">📊</div>
            <div className="font-display text-[22px] text-zinc-300">Nothing to reorder</div>
            <div className="text-[13px] text-zinc-500 max-w-md">Either everything's well-stocked, or there's no sales history loaded yet. Hit <span className="text-cyan-300">Load sales history</span> above to pull your Shopify orders and generate suggestions.</div>
          </div>
        ) : (
          <>
            <div className="text-[13px] text-zinc-400">{rows.length} suggestion{rows.length !== 1 ? "s" : ""}{criticalCount ? <span className="text-red-400"> · {criticalCount} critical</span> : null}</div>
            <div className="bg-zinc-900 border border-zinc-800 rounded-2xl overflow-hidden">
              <div className="hidden sm:grid grid-cols-[1.6fr_0.8fr_0.7fr_0.7fr_0.7fr_0.8fr] gap-3 px-5 py-3 border-b border-zinc-800 text-[11px] uppercase tracking-wider text-zinc-500">
                <div>Item</div><div>Source</div><div>Demand/wk</div><div>Cover</div><div>Lead</div><div className="text-right">Order</div>
              </div>
              <div className="divide-y divide-zinc-800/80">
                {rows.map((r) => (
                  <div key={r.sku} className="grid grid-cols-2 sm:grid-cols-[1.6fr_0.8fr_0.7fr_0.7fr_0.7fr_0.8fr] gap-2 sm:gap-3 px-5 py-3 items-center">
                    <div className="col-span-2 sm:col-span-1 min-w-0 flex items-center gap-2">
                      {r.critical && <span className="h-2 w-2 rounded-full bg-red-500 flex-shrink-0" title="Stocks out within lead time" />}
                      <div className="min-w-0">
                        <div className="text-[14px] text-zinc-100 truncate">{r.name || r.sku}</div>
                        <div className="font-mono text-[11px] text-zinc-500 truncate">{r.sku} · class {r.class}</div>
                      </div>
                    </div>
                    <div>
                      <span className={`px-2 py-0.5 rounded text-[11px] font-bold uppercase tracking-wider border ${r.mode === "make" ? "bg-violet-500/10 text-violet-300 border-violet-500/30" : "bg-teal-500/10 text-teal-300 border-teal-500/30"}`}>{r.mode}</span>
                      {r.vendor && <div className="text-[11px] text-zinc-500 mt-0.5 truncate">{r.vendor}</div>}
                    </div>
                    <div className="font-mono text-[13px] text-zinc-300">{r.demand_per_week}</div>
                    <div className={`font-mono text-[13px] ${r.critical ? "text-red-400" : "text-zinc-300"}`}>{r.weeks_of_cover != null ? `${r.weeks_of_cover}w` : "—"}</div>
                    <div className="font-mono text-[13px] text-zinc-400">{r.lead_weeks}w</div>
                    <div className="text-right font-display text-[22px] text-zinc-100">{r.suggested_qty}</div>
                  </div>
                ))}
              </div>
            </div>
            <div className="text-[11px] text-zinc-600">Suggestions are advisory — review before creating a build job or PO. "Make" rounds to the billet batch (~50); "Buy" uses the vendor's learned lead time.</div>
          </>
        )}
      </div>
    </div>
  );
}

window.ReorderTab = ReorderTab;
