// Screen 9: Inventory Tab — overview / table / build calculator
const { useState: useStateIT, useMemo: useMemoIT } = React;

const INV_STATUS = {
  OK: { label: "● OK", color: "text-emerald-300 bg-emerald-500/10 border-emerald-500/30" },
  WATCH: { label: "● WATCH", color: "text-amber-300 bg-amber-500/10 border-amber-500/30" },
  ORDER_NOW: { label: "● ORDER NOW", color: "text-red-300 bg-red-500/15 border-red-500/40" },
  CRITICAL: { label: "● CRITICAL", color: "text-red-300 bg-red-500/15 border-red-500/40" },
};

function InventoryTab({ user }) {
  const [sub, setSub] = useStateIT("OVERVIEW");
  return (
    <div className="flex-1 flex flex-col">
      <SubNav items={["OVERVIEW", "TABLE", "BUILD CALCULATOR"]} active={sub} onChange={setSub} />
      {sub === "OVERVIEW" && <InvOverview />}
      {sub === "TABLE" && <InvTable />}
      {sub === "BUILD CALCULATOR" && <BuildCalculator />}
    </div>
  );
}

function SubNav({ items, active, onChange }) {
  return (
    <div className="px-8 pt-5 pb-3 border-b border-zinc-800 flex gap-1">
      {items.map((i) => {
        const isActive = i === active;
        return (
          <button key={i} onClick={() => onChange(i)}
            className={`h-10 px-5 rounded-lg font-display text-[15px] tracking-wider transition ${
              isActive ? "bg-zinc-100 text-zinc-950" : "text-zinc-400 hover:bg-zinc-900 hover:text-zinc-200"
            }`}>
            {i}
          </button>
        );
      })}
    </div>
  );
}

function InvOverview() {
  const byType = useMemoIT(() => {
    const groups = { kit: [], assembly: [], hardware: [], consumable: [], 'packaging materials': [], electronic: [] };
    window.INVENTORY.forEach((it) => {
      const key = it.type || 'hardware';
      if (!groups[key]) groups[key] = [];
      groups[key].push(it);
    });
    return groups;
  }, []);

  return (
    <div className="flex-1 px-8 py-6 space-y-8 overflow-y-auto">
      <Section title="Kits" items={byType.kit} cols={3} renderItem={KitCard} />
      <Section title="Assemblies" items={byType.assembly} cols={3} renderItem={InvCard} />
      <Section title="Hardware" items={byType.hardware} cols={3} renderItem={InvCard} />
      <Section title="Consumables" items={byType.consumable} cols={3} renderItem={InvCard} />
      <Section title="Packaging" items={byType['packaging materials']} cols={3} renderItem={InvCard} />
      <Section title="Electronic" items={byType.electronic} cols={3} renderItem={InvCard} />
    </div>
  );
}

function Section({ title, items, cols = 3, renderItem }) {
  if (!items || items.length === 0) return null;
  return (
    <div>
      <div className="font-display text-[24px] tracking-wider text-zinc-300 mb-3">{title.toUpperCase()}</div>
      <div className={`grid grid-cols-${cols} gap-3`}>
        {items.map((it) => renderItem(it))}
      </div>
    </div>
  );
}

function InvCard(it) {
  const s = INV_STATUS[it.status];
  const pct = Math.min(100, (it.qty / it.par) * 100);
  const barColor = it.status === "ORDER_NOW" ? "bg-red-500" : it.status === "WATCH" ? "bg-amber-400" : "bg-emerald-500";
  return (
    <div key={it.sku} className="bg-zinc-900 border border-zinc-800 rounded-xl p-4 flex gap-3">
      <div className="h-[60px] w-[60px] flex-shrink-0 rounded-lg bg-zinc-800 border border-zinc-700/50 flex items-center justify-center text-zinc-600">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 21V9"/></svg>
      </div>
      <div className="flex-1 min-w-0">
        <div className="font-mono text-[11px] text-zinc-500">{it.sku}</div>
        <div className="text-[17px] font-medium leading-tight mt-0.5 truncate">{it.name}</div>
        <div className="flex items-center justify-between mt-2">
          <span className={`px-2 py-0.5 rounded text-[11px] font-bold tracking-wider uppercase border ${s.color}`}>{s.label}</span>
          <span className="text-[13px] text-zinc-400 tabular-nums">
            <span className="text-zinc-100 font-semibold">{it.qty}</span> / {it.par} par
          </span>
        </div>
        <div className="h-1.5 rounded-full bg-zinc-800 mt-2 overflow-hidden">
          <div className={`h-full ${barColor}`} style={{ width: `${pct}%` }} />
        </div>
      </div>
    </div>
  );
}

function KitCard(it) {
  const s = INV_STATUS[it.status];
  return (
    <div key={it.sku} className="bg-zinc-900 border border-zinc-800 rounded-xl p-4 relative">
      <div className="flex items-start justify-between">
        <div className="flex gap-3 min-w-0">
          <div className="h-[60px] w-[60px] flex-shrink-0 rounded-lg bg-zinc-800 border border-zinc-700/50 flex items-center justify-center text-zinc-600">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></svg>
          </div>
          <div className="min-w-0">
            <div className="font-mono text-[11px] text-zinc-500">{it.sku}</div>
            <div className="text-[16px] font-medium leading-tight mt-0.5 truncate">{it.name}</div>
            <span className={`inline-block mt-2 px-2 py-0.5 rounded text-[11px] font-bold tracking-wider uppercase border ${s.color}`}>{s.label}</span>
          </div>
        </div>
      </div>
      <div className="grid grid-cols-3 gap-2 mt-3 pt-3 border-t border-zinc-800">
        <Stat label="Can build" value={it.canBuild} color={it.canBuild >= it.needed ? "text-emerald-400" : "text-red-400"} />
        <Stat label="Kitted" value={it.kitted} />
        <Stat label="Needed" value={it.needed} />
      </div>
      {it.bottleneck && (
        <div className="mt-2 text-[12px] text-red-300 flex items-center gap-2">
          <span>⚠</span> Bottleneck: <span className="font-mono">{it.bottleneck}</span>
        </div>
      )}
    </div>
  );
}

function Stat({ label, value, color = "text-zinc-100" }) {
  return (
    <div>
      <div className="text-[10px] uppercase tracking-wider text-zinc-500">{label}</div>
      <div className={`font-display text-[28px] tabular-nums leading-none mt-1 ${color}`}>{value}</div>
    </div>
  );
}

function InvTable() {
  const [search, setSearch] = useStateIT("");
  const [typeFilter, setTypeFilter] = useStateIT("ALL");
  const [sortBy, setSortBy] = useStateIT("daysLeft");

  const rows = useMemoIT(() => {
    let r = window.INVENTORY.filter((it) => {
      if (typeFilter !== "ALL" && (it.type || 'hardware') !== typeFilter.toLowerCase()) return false;
      if (search && !`${it.sku} ${it.name}`.toLowerCase().includes(search.toLowerCase())) return false;
      return true;
    });
    r = [...r].sort((a, b) => {
      if (sortBy === "daysLeft") return (a.daysLeft ?? 999) - (b.daysLeft ?? 999);
      return String(a[sortBy] || "").localeCompare(String(b[sortBy] || ""));
    });
    return r;
  }, [search, typeFilter, sortBy]);

  return (
    <div className="flex-1 px-8 py-6 flex flex-col gap-4 overflow-hidden">
      <div className="flex items-center gap-3 flex-wrap">
        <input value={search} onChange={(e) => setSearch(e.target.value)}
          placeholder="Search SKU or name…"
          className="h-12 px-4 bg-zinc-900 border border-zinc-800 rounded-lg text-zinc-100 text-[15px] outline-none focus:border-zinc-600 w-[300px]" />
        <div className="flex gap-1">
          {["ALL", "Kit", "Assembly", "Hardware", "Consumable"].map((t) => (
            <button key={t} onClick={() => setTypeFilter(t)}
              className={`h-12 px-4 rounded-lg text-[13px] font-display tracking-wider transition ${
                typeFilter === t ? "bg-zinc-100 text-zinc-950" : "bg-zinc-900 border border-zinc-800 text-zinc-400 hover:bg-zinc-800"
              }`}>
              {t.toUpperCase()}
            </button>
          ))}
        </div>
        <button className="h-12 ml-auto px-4 rounded-lg bg-zinc-900 border border-zinc-800 text-zinc-300 text-[13px] font-display tracking-wider hover:bg-zinc-800">
          EXPORT CSV
        </button>
      </div>
      <div className="bg-zinc-900 border border-zinc-800 rounded-xl overflow-hidden flex flex-col flex-1 min-h-0">
        <div className="grid grid-cols-[1.4fr_2fr_0.8fr_0.7fr_0.7fr_0.7fr_0.8fr_0.8fr_0.8fr] text-[11px] uppercase tracking-wider text-zinc-500 px-4 py-3 border-b border-zinc-800 bg-zinc-950/50">
          <button onClick={() => setSortBy("sku")} className="text-left hover:text-zinc-200">SKU ↓</button>
          <button onClick={() => setSortBy("name")} className="text-left hover:text-zinc-200">Name</button>
          <div>Type</div>
          <div className="text-right">On hand</div>
          <div className="text-right">Reserved</div>
          <div className="text-right">Available</div>
          <div className="text-right">Par</div>
          <button onClick={() => setSortBy("daysLeft")} className="text-right hover:text-zinc-200">Days left</button>
          <div>Status</div>
        </div>
        <div className="overflow-y-auto flex-1 divide-y divide-zinc-800/80">
          {rows.map((it) => (
            <div key={it.sku} className="grid grid-cols-[1.4fr_2fr_0.8fr_0.7fr_0.7fr_0.7fr_0.8fr_0.8fr_0.8fr] items-center px-4 py-2.5 text-[14px] hover:bg-zinc-900/60">
              <div className="font-mono text-[13px] text-zinc-300">{it.sku}</div>
              <div className="truncate">{it.name}</div>
              <div className="text-zinc-400 text-[12px] uppercase tracking-wider">{it.type}</div>
              <div className="text-right tabular-nums">{it.qty}</div>
              <div className="text-right tabular-nums text-zinc-400">{it.reserved}</div>
              <div className="text-right tabular-nums">{it.qty - it.reserved}</div>
              <div className="text-right tabular-nums text-zinc-400">{it.par}</div>
              <div className="text-right tabular-nums">{it.daysLeft != null ? `${it.daysLeft}d` : "—"}</div>
              <div>
                <span className={`px-1.5 py-0.5 rounded text-[10px] font-bold tracking-wider uppercase border ${INV_STATUS[it.status].color}`}>
                  {INV_STATUS[it.status].label}
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function BuildCalculator() {
  const kits = window.INVENTORY.filter((it) => it.type === "kit");
  const [selSku, setSelSku] = useStateIT(kits[0]?.sku);
  const [wantQty, setWantQty] = useStateIT(6);
  const [showResult, setShowResult] = useStateIT(false);

  const kit = kits.find((k) => k.sku === selSku);
  const canFullyBuild = kit ? Math.min(wantQty, kit.canBuild) : 0;
  const gap = wantQty - canFullyBuild;

  // Fake component breakdown
  const components = [
    { part: "Tuning Box N63 — Main PCB Enclosure", sku: "GPS-PCB-N63-V2", needed: wantQty * 1, available: 42, ok: true },
    { part: "Wiring Harness — N63 4-Pin", sku: "GPS-WH-N63-4P", needed: wantQty * 1, available: 32, ok: true },
    { part: "T-Connector — MAP (3-pin Bosch)", sku: "GPS-CN-TMAP-3B", needed: wantQty * 2, available: 14, ok: false },
    { part: "Adapter Loom — N63 Throttle", sku: "GPS-AD-N63-TH", needed: wantQty * 1, available: 22, ok: true },
    { part: "Velcro Mount Strip — 50mm", sku: "GPS-MNT-VLC-50", needed: wantQty * 4, available: 480, ok: true },
    { part: "GPS Branded Outer Carton — Small", sku: "GPS-PKG-OC-S", needed: wantQty, available: 72, ok: true },
  ];

  return (
    <div className="flex-1 px-8 py-6 overflow-y-auto">
      <div className="max-w-[900px] mx-auto bg-zinc-900 border border-zinc-800 rounded-2xl p-8 space-y-6">
        <div>
          <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500 mb-2">Step 1 — pick a kit SKU</div>
          <select value={selSku} onChange={(e) => { setSelSku(e.target.value); setShowResult(false); }}
            className="w-full h-[64px] px-5 bg-zinc-950 border border-zinc-800 rounded-xl text-[20px] outline-none focus:border-zinc-600">
            {kits.map((k) => <option key={k.sku} value={k.sku}>{k.sku} · {k.name}</option>)}
          </select>
        </div>
        <div>
          <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500 mb-2">Step 2 — desired qty</div>
          <div className="flex items-center gap-3">
            <button onClick={() => { setWantQty(Math.max(1, wantQty - 1)); setShowResult(false); }}
              className="h-[80px] w-[80px] rounded-xl bg-zinc-800 border border-zinc-700 text-[32px] font-display">−</button>
            <input type="number" value={wantQty} onChange={(e) => { setWantQty(parseInt(e.target.value || "1", 10)); setShowResult(false); }}
              className="font-display text-[72px] tabular-nums text-center flex-1 h-[110px] bg-zinc-950 border border-zinc-800 rounded-xl outline-none focus:border-zinc-600" />
            <button onClick={() => { setWantQty(wantQty + 1); setShowResult(false); }}
              className="h-[80px] w-[80px] rounded-xl bg-zinc-800 border border-zinc-700 text-[32px] font-display">+</button>
          </div>
        </div>
        <button onClick={() => setShowResult(true)}
          className="w-full h-[80px] rounded-xl bg-zinc-100 text-zinc-950 font-display text-[24px] tracking-wider hover:bg-white">
          CHECK BUILDABILITY
        </button>

        {showResult && (
          <div className="space-y-4 pt-4 border-t border-zinc-800">
            <div>
              <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Result</div>
              <div className="font-display text-[40px] leading-tight mt-1">
                You can fully build{" "}
                <span className={canFullyBuild >= wantQty ? "text-emerald-400" : "text-red-400"}>
                  {canFullyBuild} of {wantQty}
                </span>
              </div>
              {gap > 0 && <div className="text-red-300 text-[16px] mt-2">⚠ Bottleneck: GPS-CN-TMAP-3B (need 12, have 14 — borderline)</div>}
            </div>
            <div className="bg-zinc-950 border border-zinc-800 rounded-xl divide-y divide-zinc-800">
              {components.map((c) => (
                <div key={c.sku} className="flex items-center gap-3 px-4 py-3">
                  {c.ok ? (
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10b981" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                  ) : (
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ef4444" strokeWidth="3"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                  )}
                  <div className="flex-1 min-w-0">
                    <div className="text-[14px] truncate">{c.part}</div>
                    <div className="font-mono text-[11px] text-zinc-500">{c.sku}</div>
                  </div>
                  <div className="text-right text-[13px]">
                    <div className="tabular-nums"><span className="text-zinc-400">need</span> {c.needed}</div>
                    <div className="tabular-nums"><span className="text-zinc-400">have</span> {c.available}</div>
                  </div>
                </div>
              ))}
            </div>
            {gap > 0 && (
              <button className="w-full h-[72px] rounded-xl bg-emerald-500 text-zinc-950 font-display text-[20px] tracking-wider hover:bg-emerald-400">
                GENERATE WORK ORDERS TO COVER GAP →
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

window.InventoryTab = InventoryTab;
