function Shop({ go, initialCat }) {
  const { PRODUCTS, CATEGORIES } = window.FURN;
  const [cat, setCat] = useState(initialCat || "all");
  const [sort, setSort] = useState("featured");
  const [openFilter, setOpenFilter] = useState(false);

  useEffect(() => { setCat(initialCat || "all"); }, [initialCat]);
  useReveal();

  const prices = PRODUCTS.map((p) => p.price);
  const minLimit = prices.length > 0 ? Math.min(...prices) : 0;
  const maxLimit = prices.length > 0 ? Math.max(...prices) : 10000;

  const [minPrice, setMinPrice] = useState(minLimit);
  const [maxPrice, setMaxPrice] = useState(maxLimit);
  const [inStock, setInStock] = useState(false);
  const [onSale, setOnSale] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");

  // Sync price limits if PRODUCTS changes
  useEffect(() => {
    setMinPrice(minLimit);
    setMaxPrice(maxLimit);
  }, [minLimit, maxLimit]);

  const childSlugs = CATEGORIES.filter((c) => c.parent === cat).map((c) => c.id);

  let list = PRODUCTS.filter((p) => {
    const matchesCat = cat === "all" || p.cat === cat || childSlugs.includes(p.cat);
    const matchesPrice = p.price >= minPrice && p.price <= maxPrice;
    const matchesStock = !inStock || p.in_stock;
    const matchesSale = !onSale || (p.old !== null && p.old > p.price);
    const matchesSearch = !searchQuery.trim() || 
      p.en.toLowerCase().includes(searchQuery.toLowerCase()) || 
      p.ar.includes(searchQuery);

    return matchesCat && matchesPrice && matchesStock && matchesSale && matchesSearch;
  });

  if (sort === "low")  list = [...list].sort((a, b) => a.price - b.price);
  else if (sort === "high") list = [...list].sort((a, b) => b.price - a.price);
  else if (sort === "new")  list = [...list].sort((a, b) => (b.badge?.en === "New") - (a.badge?.en === "New"));

  const sorts = [
    { id: "featured", label: "Featured" },
    { id: "low",      label: "Price ↑" },
    { id: "high",     label: "Price ↓" },
    { id: "new",      label: "Newest" },
  ];

  const parents = CATEGORIES.filter((c) => !c.parent);

  const getCatCount = (catId) => {
    const childIds = CATEGORIES.filter((c) => c.parent === catId).map((c) => c.id);
    return PRODUCTS.filter((p) => p.cat === catId || childIds.includes(p.cat)).length;
  };

  const getSubCatCount = (subId) => PRODUCTS.filter((p) => p.cat === subId).length;

  const activeParent = cat !== "all"
    ? (CATEGORIES.find((c) => c.id === cat && !c.parent) || CATEGORIES.find((c) => c.id === (CATEGORIES.find((x) => x.id === cat)?.parent)))
    : null;

  const FilterPanel = () => (
    <div style={{ display: "flex", flexDirection: "column", gap: 32 }}>
      {/* Search Filter */}
      <div>
        <h4 style={{ fontFamily: "var(--font-ui)", fontSize: 12, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--gold)", marginBottom: 12, fontWeight: 500 }}>
          Search Collection
        </h4>
        <div style={{ position: "relative" }}>
          <input 
            type="text" 
            placeholder="Search by name..." 
            value={searchQuery} 
            onChange={(e) => setSearchQuery(e.target.value)} 
            style={{ width: "100%", padding: "10px 12px", paddingRight: 36, background: "var(--surface)", border: "1px solid var(--line)", color: "var(--ink)", borderRadius: 4, fontSize: 14 }}
          />
          {searchQuery && (
            <button 
              onClick={() => setSearchQuery("")} 
              style={{ position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)", background: "none", border: "none", cursor: "pointer", color: "var(--muted)" }}
            >
              <Icon name="close" size={16} />
            </button>
          )}
        </div>
      </div>

      {/* Category Hierarchy */}
      <div>
        <h4 style={{ fontFamily: "var(--font-ui)", fontSize: 12, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--gold)", marginBottom: 16, fontWeight: 500 }}>
          Category
        </h4>
        <ul style={{ listStyle: "none", display: "flex", flexDirection: "column", gap: 3 }}>
          {activeParent ? (
            <>
              {/* Back to all button */}
              <li>
                <button onClick={() => { setCat("all"); setOpenFilter(false); }} style={{
                  background: "none", border: "none", cursor: "pointer", textAlign: "left",
                  width: "100%", padding: "6px 0", fontSize: 13, fontFamily: "var(--font-ui)",
                  color: "var(--muted)", display: "inline-flex", alignItems: "center", gap: 6,
                  transition: "color .25s"
                }}>
                  <Icon name="arrowL" size={12} />
                  <span>All pieces</span>
                </button>
              </li>
              {/* Active Parent category item */}
              <li style={{ marginTop: 6, marginBottom: 8 }}>
                <button onClick={() => { setCat(activeParent.id); setOpenFilter(false); }} style={{
                  background: "none", border: "none", cursor: "pointer", textAlign: "left",
                  width: "100%", padding: "6px 0", fontSize: 16, fontFamily: "var(--font-display)",
                  color: cat === activeParent.id ? "var(--gold)" : "var(--ink)",
                  display: "flex", justifyContent: "space-between", alignItems: "center",
                  fontWeight: 600, borderBottom: "1px solid var(--line)"
                }}>
                  <span>{activeParent.en}</span>
                  <span style={{ color: "var(--faint)", fontSize: 12.5, fontFamily: "var(--font-ui)", fontWeight: 400 }}>
                    {getCatCount(activeParent.id)}
                  </span>
                </button>
              </li>
              {/* Subcategories under this parent */}
              {CATEGORIES.filter((sub) => sub.parent === activeParent.id).map((sub) => {
                const subCount = getSubCatCount(sub.id);
                if (subCount === 0) return null;
                return (
                  <li key={sub.id}>
                    <button onClick={() => { setCat(sub.id); setOpenFilter(false); }} style={{
                      background: "none", border: "none", cursor: "pointer", textAlign: "left",
                      width: "100%", padding: "6px 0", fontSize: 14, fontFamily: "var(--font-ui)",
                      color: cat === sub.id ? "var(--ink)" : "var(--muted)",
                      display: "flex", justifyContent: "space-between", alignItems: "center",
                      transition: "color .25s", fontWeight: cat === sub.id ? 600 : 400,
                      paddingLeft: 10
                    }}>
                      <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        {cat === sub.id && <span style={{ width: 5, height: 5, background: "var(--gold)", borderRadius: "50%" }} />}
                        {sub.en}
                      </span>
                      <span style={{ color: "var(--faint)", fontSize: 12 }}>
                        {subCount}
                      </span>
                    </button>
                  </li>
                );
              })}
            </>
          ) : (
            <>
              {/* All pieces button when no parent is selected */}
              <li>
                <button onClick={() => { setCat("all"); setOpenFilter(false); }} style={{
                  background: "none", border: "none", cursor: "pointer", textAlign: "left",
                  width: "100%", padding: "6px 0", fontSize: 14.5, fontFamily: "var(--font-ui)",
                  color: cat === "all" ? "var(--ink)" : "var(--muted)",
                  display: "flex", justifyContent: "space-between", alignItems: "center",
                  transition: "color .25s", fontWeight: cat === "all" ? 600 : 400
                }}>
                  <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    {cat === "all" && <span style={{ width: 6, height: 6, background: "var(--gold)", borderRadius: "50%" }} />}
                    All pieces
                  </span>
                  <span style={{ color: "var(--faint)", fontSize: 12 }}>
                    {PRODUCTS.length}
                  </span>
                </button>
              </li>
              {/* List of all parent categories */}
              {parents.map((c) => {
                const count = getCatCount(c.id);
                if (count === 0) return null;
                return (
                  <li key={c.id}>
                    <button onClick={() => { setCat(c.id); setOpenFilter(false); }} style={{
                      background: "none", border: "none", cursor: "pointer", textAlign: "left",
                      width: "100%", padding: "6px 0", fontSize: 14.5, fontFamily: "var(--font-ui)",
                      color: cat === c.id ? "var(--ink)" : "var(--muted)",
                      display: "flex", justifyContent: "space-between", alignItems: "center",
                      transition: "color .25s", fontWeight: cat === c.id ? 600 : 400
                    }}>
                      <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        {cat === c.id && <span style={{ width: 6, height: 6, background: "var(--gold)", borderRadius: "50%" }} />}
                        {c.en}
                      </span>
                      <span style={{ color: "var(--faint)", fontSize: 12 }}>
                        {count}
                      </span>
                    </button>
                  </li>
                );
              })}
            </>
          )}
        </ul>
      </div>

      {/* Dynamic Price Range */}
      <div>
        <h4 style={{ fontFamily: "var(--font-ui)", fontSize: 12, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--gold)", marginBottom: 18, fontWeight: 500 }}>
          Price Range
        </h4>
        <div style={{ display: "flex", gap: 10, marginBottom: 16 }}>
          <div style={{ flex: 1 }}>
            <label style={{ fontSize: 11, color: "var(--faint)", display: "block", marginBottom: 4 }}>Min Price</label>
            <input 
              type="number" 
              min={minLimit} 
              max={maxPrice} 
              value={minPrice} 
              onChange={(e) => setMinPrice(Math.max(minLimit, Math.min(maxPrice, +e.target.value)))} 
              style={{ width: "100%", padding: "6px 8px", background: "var(--surface)", border: "1px solid var(--line)", color: "var(--ink)", borderRadius: 3, fontSize: 13 }}
            />
          </div>
          <div style={{ flex: 1 }}>
            <label style={{ fontSize: 11, color: "var(--faint)", display: "block", marginBottom: 4 }}>Max Price</label>
            <input 
              type="number" 
              min={minPrice} 
              max={maxLimit} 
              value={maxPrice} 
              onChange={(e) => setMaxPrice(Math.min(maxLimit, Math.max(minPrice, +e.target.value)))} 
              style={{ width: "100%", padding: "6px 8px", background: "var(--surface)", border: "1px solid var(--line)", color: "var(--ink)", borderRadius: 3, fontSize: 13 }}
            />
          </div>
        </div>
        <input 
          type="range" 
          min={minLimit} 
          max={maxLimit} 
          step="10" 
          value={maxPrice} 
          onChange={(e) => setMaxPrice(+e.target.value)} 
          className="range" 
          style={{ width: "100%" }} 
        />
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontSize: 12.5, color: "var(--faint)" }}>
          <span>{money(minLimit)}</span>
          <span>{money(maxLimit)}</span>
        </div>
      </div>

      {/* Availability & Sale */}
      <div>
        <h4 style={{ fontFamily: "var(--font-ui)", fontSize: 12, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--gold)", marginBottom: 14, fontWeight: 500 }}>
          Availability & Offers
        </h4>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <label style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer", fontSize: 14, color: "var(--muted)" }}>
            <input 
              type="checkbox" 
              checked={inStock} 
              onChange={(e) => setInStock(e.target.checked)} 
              style={{ width: 16, height: 16, accentColor: "var(--gold)" }}
            />
            In Stock only
          </label>
          <label style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer", fontSize: 14, color: "var(--muted)" }}>
            <input 
              type="checkbox" 
              checked={onSale} 
              onChange={(e) => setOnSale(e.target.checked)} 
              style={{ width: 16, height: 16, accentColor: "var(--gold)" }}
            />
            Discounted / Sale
          </label>
        </div>
      </div>

      {/* Sort Options */}
      <div>
        <h4 style={{ fontFamily: "var(--font-ui)", fontSize: 12, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--gold)", marginBottom: 16, fontWeight: 500 }}>
          Sort
        </h4>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          {sorts.map((s) => (
            <button key={s.id} onClick={() => setSort(s.id)} className="chip" data-on={sort === s.id}>{s.label}</button>
          ))}
        </div>
      </div>

      {/* Reset Filter Button */}
      {(cat !== "all" || minPrice !== minLimit || maxPrice !== maxLimit || inStock || onSale || searchQuery) && (
        <button 
          onClick={() => {
            setCat("all");
            setMinPrice(minLimit);
            setMaxPrice(maxLimit);
            setInStock(false);
            setOnSale(false);
            setSearchQuery("");
            setSort("featured");
          }} 
          className="btn btn--ghost" 
          style={{ width: "100%", padding: "10px", fontSize: 13, display: "flex", justifyContent: "center", alignItems: "center", gap: 6 }}
        >
          <Icon name="close" size={14} />
          <span>Reset Filters</span>
        </button>
      )}
    </div>
  );

  return (
    <main className="page-fade" style={{ paddingTop: 92 }}>
      {/* header band */}
      <section className="wrap" style={{ padding: "64px 40px 40px", borderBottom: "1px solid var(--line)" }}>
        <div className="eyebrow">The full collection</div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 16, marginTop: 16 }}>
          <h1 style={{ fontSize: "clamp(38px,6vw,76px)" }}>
            {cat === "all" ? "Every piece" : (CATEGORIES.find((c) => c.id === cat)?.en || "Collection")}
          </h1>
          <button className="btn btn--ghost filter-toggle" onClick={() => setOpenFilter(true)} style={{ display: "none" }}>
            <span><Icon name="menu" size={16} /> Filter</span>
          </button>
        </div>
      </section>

      <section className="wrap shop-layout" style={{ padding: "44px 40px 110px", display: "grid", gridTemplateColumns: "240px 1fr", gap: 56, alignItems: "start" }}>
        {/* sidebar */}
        <aside className="shop-aside" style={{ position: "sticky", top: 100, maxHeight: "calc(100vh - 140px)", overflowY: "auto", paddingRight: 12 }}>
          <FilterPanel />
        </aside>

        {/* grid */}
        <div>
          <div style={{ color: "var(--muted)", fontSize: 13.5, marginBottom: 24 }}>
            {list.length} {list.length === 1 ? "piece" : "pieces"}
          </div>
          {list.length === 0 ? (
            <div style={{ padding: "80px 0", textAlign: "center", color: "var(--muted)" }}>
              <p style={{ fontFamily: "var(--font-display)", fontSize: 24 }}>No pieces match this filter.</p>
            </div>
          ) : (
            <div className="grid-3 shop-grid">
              {list.map((p, i) => <ProductCard key={p.id} p={p} go={go} index={i} />)}
            </div>
          )}
        </div>
      </section>

      {/* mobile filter drawer */}
      <div onClick={() => setOpenFilter(false)} style={{ position: "fixed", inset: 0, zIndex: 70, background: "oklch(0 0 0 /.5)", opacity: openFilter ? 1 : 0, pointerEvents: openFilter ? "auto" : "none", transition: "opacity .35s" }} />
      <aside style={{ position: "fixed", top: 0, bottom: 0, left: 0, width: "min(340px,88vw)", zIndex: 71, background: "var(--bg-deep)", borderRight: "1px solid var(--line)", padding: "28px 26px", overflowY: "auto", transform: openFilter ? "none" : "translateX(-102%)", transition: "transform .45s var(--ease)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 28 }}>
          <h3 style={{ fontSize: 22 }}>Filter</h3>
          <button className="icon-btn" onClick={() => setOpenFilter(false)}><Icon name="close" size={22} /></button>
        </div>
        <FilterPanel />
      </aside>

      <style>{`
        .range { -webkit-appearance:none; appearance:none; height:2px; background:var(--line); border-radius:2px; outline:none; }
        .range::-webkit-slider-thumb { -webkit-appearance:none; width:16px; height:16px; border-radius:50%; background:var(--gold); cursor:pointer; border:2px solid var(--bg-deep); }
        .range::-moz-range-thumb { width:16px; height:16px; border-radius:50%; background:var(--gold); cursor:pointer; border:2px solid var(--bg-deep); }
        .chip { background:none; border:1px solid var(--line); color:var(--muted); padding:9px 15px; border-radius:2px; font-size:13px; cursor:pointer; font-family:var(--font-ui); transition:all .25s; }
        .chip:hover { color:var(--ink); border-color:var(--muted); }
        .chip[data-on="true"] { background:var(--gold); color:var(--bg-deep); border-color:var(--gold); }
        .shop-aside::-webkit-scrollbar { width: 5px; }
        .shop-aside::-webkit-scrollbar-track { background: transparent; }
        .shop-aside::-webkit-scrollbar-thumb { background: var(--line); border-radius: 4px; }
        @media (max-width: 860px){
          .shop-aside { display:none; }
          .shop-layout { grid-template-columns: 1fr !important; }
          .filter-toggle { display:inline-flex !important; }
        }
      `}</style>
    </main>
  );
}
Object.assign(window, { Shop });
