// Inventory page — search, filters, tabs, listing grid/rows

function InventoryPage({ onNav, state, inventory, projects, watching, onWatch }) {
  const [tab, setTab] = React.useState(() => {
    try { return localStorage.getItem("cs_inv_tab") || "all"; }
    catch { return "all"; }
  });
  React.useEffect(() => { try { localStorage.setItem("cs_inv_tab", tab); } catch {} }, [tab]);
  const [query, setQuery] = React.useState("");
  const [sort, setSort] = React.useState("closing");
  const [location, setLocation] = React.useState("all");
  const [category, setCategory] = React.useState("all");
  const [brand, setBrand] = React.useState("all");
  const [qtyMin, setQtyMin] = React.useState("");
  const [qtyMax, setQtyMax] = React.useState("");
  const [priceMin, setPriceMin] = React.useState("");
  const [priceMax, setPriceMax] = React.useState("");
  const [filterOpen, setFilterOpen] = React.useState(false);

  projects = projects || window.CLEARSPACE_PROJECTS || [];

  // Build dynamic options from the actual dataset.
  const locations = React.useMemo(() => {
    const s = new Set();
    inventory.forEach((x) => s.add(x.location.split(",")[0].trim()));
    return [...s].sort();
  }, [inventory]);
  const brands = React.useMemo(() => {
    const s = new Set();
    inventory.forEach((x) => {
      const b = x.brand.split(" (")[0].split(",")[0].trim();
      if (b && b !== "Mixed") s.add(b);
      if (x.brand.toLowerCase().includes("mixed")) s.add("Mixed");
    });
    return [...s].sort();
  }, [inventory]);
  const categories = ["Workstations", "Task seating", "Conference", "Executive", "Storage", "Electronics", "Lounge"];

  const activeFilterCount =
    (location !== "all" ? 1 : 0) +
    (category !== "all" ? 1 : 0) +
    (brand !== "all" ? 1 : 0) +
    (qtyMin || qtyMax ? 1 : 0) +
    (priceMin || priceMax ? 1 : 0);

  const clearAll = () => {
    setLocation("all"); setCategory("all"); setBrand("all");
    setQtyMin(""); setQtyMax(""); setPriceMin(""); setPriceMax(""); setQuery("");
  };

  const filtered = React.useMemo(() => {
    let r = inventory.slice();
    if (tab !== "all" && tab !== "projects") r = r.filter((x) => x.type === tab);
    if (location !== "all") r = r.filter((x) => x.location.toLowerCase().includes(location.toLowerCase()));
    if (category !== "all") {
      const c = category.toLowerCase();
      r = r.filter((x) =>
        x.tags.some((t) => t.toLowerCase().includes(c)) ||
        x.title.toLowerCase().includes(c) ||
        (x.manifest && x.manifest.some((m) => (m.category || "").toLowerCase().includes(c)))
      );
    }
    if (brand !== "all") {
      const b = brand.toLowerCase();
      r = r.filter((x) => x.brand.toLowerCase().includes(b));
    }
    const qmin = qtyMin ? parseInt(qtyMin, 10) : null;
    const qmax = qtyMax ? parseInt(qtyMax, 10) : null;
    if (qmin != null) r = r.filter((x) => x.quantity >= qmin);
    if (qmax != null) r = r.filter((x) => x.quantity <= qmax);
    const pmin = priceMin ? parseInt(priceMin, 10) : null;
    const pmax = priceMax ? parseInt(priceMax, 10) : null;
    if (pmin != null) r = r.filter((x) => x.currentBid >= pmin);
    if (pmax != null) r = r.filter((x) => x.currentBid <= pmax);
    if (query) {
      const q = query.toLowerCase();
      r = r.filter((x) =>
        x.title.toLowerCase().includes(q) ||
        x.brand.toLowerCase().includes(q) ||
        x.id.toLowerCase().includes(q) ||
        x.tags.join(" ").toLowerCase().includes(q) ||
        (x.manifest && x.manifest.some((m) => (m.item || "").toLowerCase().includes(q)))
      );
    }
    if (sort === "closing") r.sort((a, b) => a.closesAt - b.closesAt);
    if (sort === "bid-low") r.sort((a, b) => a.currentBid - b.currentBid);
    if (sort === "bid-high") r.sort((a, b) => b.currentBid - a.currentBid);
    if (sort === "qty") r.sort((a, b) => b.quantity - a.quantity);
    return r;
  }, [inventory, tab, query, sort, location, category, brand, qtyMin, qtyMax, priceMin, priceMax]);

  const counts = {
    all: inventory.length,
    "whole-lot": inventory.filter((x) => x.type === "whole-lot").length,
    "premium": inventory.filter((x) => x.type === "premium").length,
  };

  const projectsList = projects;

  return (
    <div className="container" style={{ padding: "40px 32px 80px" }}>
      <div className="row between" style={{ alignItems: "flex-end", marginBottom: 28, flexWrap: "wrap", gap: 20 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Live bidding</div>
          <h1 className="display" style={{ fontSize: 40, margin: 0 }}>Available inventory</h1>
          <p style={{ color: "var(--ink-3)", fontSize: 14, margin: "8px 0 0" }}>
            {inventory.length} active lots · {inventory.reduce((s, x) => s + x.quantity, 0).toLocaleString()} units · refreshed just now
          </p>
        </div>
        <div className="row gap-12 center">
          <div className="input-icon" style={{ width: 320 }}>
            <IcSearch size={16} />
            <input className="input" placeholder="Search by lot, brand, model…" style={{ width: "100%" }}
              value={query} onChange={(e) => setQuery(e.target.value)} />
          </div>
          <select className="select" value={sort} onChange={(e) => setSort(e.target.value)}>
            <option value="closing">Closing soonest</option>
            <option value="bid-low">Current bid: low → high</option>
            <option value="bid-high">Current bid: high → low</option>
            <option value="qty">Largest quantity</option>
          </select>
        </div>
      </div>

      {/* Filters */}
      <div className="filter-bar">
        <button className="filter-chip" data-active={filterOpen || activeFilterCount > 0}
          onClick={() => setFilterOpen((v) => !v)}
          style={{ fontWeight: 500 }}>
          <IcFilter size={13} /> Filters
          {activeFilterCount > 0 && (
            <span className="mono" style={{ background: "var(--primary)", color: "white", padding: "1px 6px", borderRadius: 10, fontSize: 10, marginLeft: 2 }}>
              {activeFilterCount}
            </span>
          )}
        </button>
        <div style={{ width: 1, height: 22, background: "var(--line)", margin: "0 4px" }} />
        {["all", ...locations].map((l) => (
          <button key={l} className="filter-chip" data-active={location === l}
            onClick={() => setLocation(l)}>
            {l === "all" ? "All locations" : l}
          </button>
        ))}
        {(category !== "all" || brand !== "all" || qtyMin || qtyMax || priceMin || priceMax) && (
          <>
            <div style={{ width: 1, height: 22, background: "var(--line)", margin: "0 4px" }} />
            {category !== "all" && <FilterPill label={`Category: ${category}`} onClear={() => setCategory("all")} />}
            {brand !== "all" && <FilterPill label={`Brand: ${brand}`} onClear={() => setBrand("all")} />}
            {(qtyMin || qtyMax) && <FilterPill label={`Qty: ${qtyMin || "0"}–${qtyMax || "∞"}`} onClear={() => { setQtyMin(""); setQtyMax(""); }} />}
            {(priceMin || priceMax) && <FilterPill label={`Price: ${priceMin ? "$" + parseInt(priceMin).toLocaleString() : "$0"}–${priceMax ? "$" + parseInt(priceMax).toLocaleString() : "∞"}`} onClear={() => { setPriceMin(""); setPriceMax(""); }} />}
          </>
        )}
        {activeFilterCount > 0 && (
          <button className="filter-chip" onClick={clearAll} style={{ color: "var(--ink-3)" }}>
            Clear all
          </button>
        )}
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 12, color: "var(--ink-3)" }} className="mono">{filtered.length} match{filtered.length === 1 ? "" : "es"}</span>
      </div>

      {filterOpen && (
        <FilterPanel
          locations={locations} brands={brands} categories={categories}
          location={location} setLocation={setLocation}
          category={category} setCategory={setCategory}
          brand={brand} setBrand={setBrand}
          qtyMin={qtyMin} setQtyMin={setQtyMin} qtyMax={qtyMax} setQtyMax={setQtyMax}
          priceMin={priceMin} setPriceMin={setPriceMin} priceMax={priceMax} setPriceMax={setPriceMax}
          onClose={() => setFilterOpen(false)} onClear={clearAll}
          matches={filtered.length}
        />
      )}

      {/* Tabs */}
      <div className="tabs">
        {[
          { id: "all", label: "All inventory" },
          { id: "whole-lot", label: "Whole lots" },
          { id: "premium", label: "Premium items" },
        ].map((t) => (
          <button key={t.id} className="tab" data-active={tab === t.id} onClick={() => setTab(t.id)}>
            {t.label}
            {counts[t.id] != null && <span className="tab-count mono">{counts[t.id]}</span>}
            {t.n != null && <span className="tab-count mono">{t.n}</span>}
          </button>
        ))}
      </div>

      {tab === "projects" ? (
        <ProjectsGrid projects={projectsList} inventory={inventory} onNav={onNav} />
      ) : state.cardVariant === "dense" ? (
        <div style={{ border: "1px solid var(--line)", borderRadius: 12, overflow: "hidden", background: "var(--bg-elev)" }}>
          <div className="row-card header">
            <span></span>
            <span>Lot</span>
            <span>Type</span>
            <span>Qty</span>
            <span>Start</span>
            <span>Current</span>
            <span>Buy now</span>
            <span>Closes</span>
          </div>
          {filtered.map((item) => (
            <ListingCard key={item.id} item={item} variant="dense"
              onClick={(id) => onNav("listing", { id })}
              onWatch={onWatch} watching={watching.has(item.id)} />
          ))}
        </div>
      ) : (
        <div className="inv-grid">
          {filtered.map((item) => (
            <ListingCard key={item.id} item={item}
              onClick={(id) => onNav("listing", { id })}
              onWatch={onWatch} watching={watching.has(item.id)} />
          ))}
        </div>
      )}

      {tab !== "projects" && filtered.length === 0 && (
        <div style={{ textAlign: "center", padding: "80px 20px", color: "var(--ink-3)" }}>
          No lots match these filters.
        </div>
      )}
    </div>
  );
}

function ProjectsGrid({ projects, inventory, onNav }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(340px, 1fr))", gridAutoRows: "1fr", gap: 20, alignItems: "stretch" }}>
      {projects.map((p) => {
        const lots = inventory.filter((i) => i.projectId === p.id);
        const whole = lots.find((l) => l.type === "whole-lot");
        const premiums = lots.filter((l) => l.type === "premium");
        const nextClose = Math.min(...lots.map((l) => l.closesAt));
        const h = Math.floor(Math.max(0, nextClose - Date.now()) / 3600000);
        return (
          <article key={p.id} className="card" style={{ cursor: "pointer", display: "flex", flexDirection: "column" }}
            onClick={() => onNav("project", { id: p.id })}>
            <div style={{ position: "relative", aspectRatio: "4/3", background: "var(--bg-sunken)", overflow: "hidden" }}>
              <img src={p.hero} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, transparent 55%, rgba(0,0,0,0.55))" }} />
              <div style={{ position: "absolute", top: 14, left: 14 }}>
                <span className="mono" style={{ background: "rgba(0,0,0,0.55)", color: "white", padding: "4px 8px", borderRadius: 4, fontSize: 10, letterSpacing: "0.1em" }}>{p.id}</span>
              </div>
              <div style={{ position: "absolute", bottom: 16, left: 16, right: 16, color: "white" }}>
                <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: "-0.01em", marginBottom: 4 }}>{p.name}</div>
                <div style={{ fontSize: 12, opacity: 0.85 }}>{p.address}</div>
              </div>
            </div>
            <div style={{ padding: "14px 18px", display: "flex", flexDirection: "column", gap: 10, flex: 1 }}>
              <div style={{
                fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5,
                display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical",
                overflow: "hidden",
              }}>{p.tenant}</div>
              <div className="row gap-8" style={{ flexWrap: "wrap", marginTop: "auto" }}>
                {whole && <span className="tag tag-whole">1 whole lot</span>}
                {premiums.length > 0 && <span className="tag tag-premium">{premiums.length} premium</span>}
                <span className="tag">{p.totalUnits.toLocaleString()} units</span>
              </div>
            </div>
            <div className="listing-footer">
              <div className="countdown"><IcClock size={13} /> Next closes in {h}h</div>
              <span style={{ color: "var(--ink-3)" }}>{lots.length} listing{lots.length === 1 ? "" : "s"}</span>
            </div>
          </article>
        );
      })}
    </div>
  );
}

Object.assign(window, { InventoryPage, ProjectsGrid, FilterPill, FilterPanel });

function FilterPill({ label, onClear }) {
  return (
    <span className="filter-chip" data-active="true" style={{ gap: 8, paddingRight: 4 }}>
      {label}
      <button onClick={onClear} style={{
        width: 18, height: 18, borderRadius: 999, border: "none", cursor: "pointer",
        display: "grid", placeItems: "center", background: "rgba(0,0,0,0.08)", color: "inherit", padding: 0,
      }} title="Remove">
        <IcX size={11} />
      </button>
    </span>
  );
}

function FilterPanel({
  locations, brands, categories,
  location, setLocation, category, setCategory, brand, setBrand,
  qtyMin, setQtyMin, qtyMax, setQtyMax,
  priceMin, setPriceMin, priceMax, setPriceMax,
  onClose, onClear, matches,
}) {
  return (
    <div style={{
      border: "1px solid var(--line)", borderRadius: 12, background: "var(--bg-elev)",
      padding: 20, marginBottom: 24, boxShadow: "var(--shadow-sm)",
    }}>
      <div className="row between" style={{ alignItems: "flex-start", marginBottom: 18 }}>
        <div>
          <div className="stat-kicker">Refine inventory</div>
          <div style={{ fontSize: 15, fontWeight: 600, marginTop: 4 }}>Filter by item, quantity and price</div>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={onClose} style={{ width: 32, padding: 0 }}>
          <IcX size={15} />
        </button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20 }}>
        <FilterField label="Category">
          <select className="select" value={category} onChange={(e) => setCategory(e.target.value)} style={{ width: "100%" }}>
            <option value="all">All categories</option>
            {categories.map((c) => <option key={c} value={c}>{c}</option>)}
          </select>
        </FilterField>

        <FilterField label="Brand / manufacturer">
          <select className="select" value={brand} onChange={(e) => setBrand(e.target.value)} style={{ width: "100%" }}>
            <option value="all">Any brand</option>
            {brands.map((b) => <option key={b} value={b}>{b}</option>)}
          </select>
        </FilterField>

        <FilterField label="Quantity">
          <div className="row gap-8 center">
            <input className="input" inputMode="numeric" placeholder="Min" value={qtyMin}
              onChange={(e) => setQtyMin(e.target.value.replace(/\D/g, ""))} style={{ width: "100%" }} />
            <span style={{ color: "var(--ink-3)" }}>–</span>
            <input className="input" inputMode="numeric" placeholder="Max" value={qtyMax}
              onChange={(e) => setQtyMax(e.target.value.replace(/\D/g, ""))} style={{ width: "100%" }} />
          </div>
        </FilterField>

        <FilterField label="Current bid (USD)" span={3}>
          <div className="row gap-8 center">
            <div style={{ position: "relative", flex: 1 }}>
              <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)", fontSize: 13 }}>$</span>
              <input className="input" inputMode="numeric" placeholder="Min" value={priceMin}
                onChange={(e) => setPriceMin(e.target.value.replace(/\D/g, ""))} style={{ width: "100%", paddingLeft: 22 }} />
            </div>
            <span style={{ color: "var(--ink-3)" }}>–</span>
            <div style={{ position: "relative", flex: 1 }}>
              <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)", fontSize: 13 }}>$</span>
              <input className="input" inputMode="numeric" placeholder="Max" value={priceMax}
                onChange={(e) => setPriceMax(e.target.value.replace(/\D/g, ""))} style={{ width: "100%", paddingLeft: 22 }} />
            </div>
            {/* Quick ranges */}
            <div className="row gap-4">
              {[
                ["Under $5k", "", "5000"],
                ["$5k–25k", "5000", "25000"],
                ["$25k+", "25000", ""],
              ].map(([lbl, lo, hi]) => (
                <button key={lbl} className="filter-chip"
                  data-active={priceMin === lo && priceMax === hi}
                  onClick={() => { setPriceMin(lo); setPriceMax(hi); }}
                  style={{ fontSize: 11, whiteSpace: "nowrap" }}>
                  {lbl}
                </button>
              ))}
            </div>
          </div>
        </FilterField>
      </div>

      <div className="row between center" style={{ marginTop: 20, paddingTop: 16, borderTop: "1px solid var(--line)" }}>
        <button className="btn btn-ghost btn-sm" onClick={onClear}>Reset all filters</button>
        <div className="row gap-12 center">
          <span className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>
            {matches} match{matches === 1 ? "" : "es"}
          </span>
          <button className="btn btn-primary btn-sm" onClick={onClose}>Apply</button>
        </div>
      </div>
    </div>
  );
}

function FilterField({ label, children, span }) {
  return (
    <div style={{ gridColumn: span ? `span ${span}` : "auto" }}>
      <div className="stat-kicker" style={{ marginBottom: 8 }}>{label}</div>
      {children}
    </div>
  );
}
