// Map category IDs to one or more product cat tags
const CAT_MAP = {
  gpu: ["GPU"],
  cpu: ["CPU"],
  mb: ["MOBO"],
  ram: ["RAM"],
  ssd: ["SSD"],
  psu: ["PSU"],
  case: ["CASE", "GAMING PC", "MINI PC", "STREAMER"],
  cool: ["COOLING"],
  mon: ["MONITOR"],
  kb: ["KEYBOARD"],
  ms: ["MOUSE"],
  head: ["AUDIO"],
};

const ShopPage = () => {
  const params = new URLSearchParams(location.search);
  const catId = params.get("cat") || "gpu";
  const meta = CATEGORIES.find(c => c.id === catId) || CATEGORIES[0];

  const [sort, setSort] = React.useState("popular");
  const [view, setView] = React.useState("grid");
  const [priceMax, setPriceMax] = React.useState(400000);
  const [brandFilter, setBrandFilter] = React.useState(new Set());
  const [stockOnly, setStockOnly] = React.useState(false);
  const [saleOnly, setSaleOnly] = React.useState(false);

  const allCatProducts = React.useMemo(() => {
    const tags = CAT_MAP[catId] || [];
    return [...PRODUCTS, ...PREBUILT].filter(p => tags.includes(p.cat));
  }, [catId]);
  const brands = React.useMemo(() => [...new Set(allCatProducts.map(p => p.brand))], [allCatProducts]);

  const products = React.useMemo(() => {
    let list = allCatProducts.filter(p => p.price <= priceMax);
    if (brandFilter.size) list = list.filter(p => brandFilter.has(p.brand));
    if (stockOnly) list = list.filter(p => p.stock > 0);
    if (saleOnly) list = list.filter(p => p.was);
    if (sort === "lowhigh") list.sort((a,b) => a.price - b.price);
    if (sort === "highlow") list.sort((a,b) => b.price - a.price);
    if (sort === "rating") list.sort((a,b) => b.rating - a.rating);
    if (sort === "new") list.sort((a,b) => b.id - a.id);
    return list;
  }, [allCatProducts, sort, priceMax, brandFilter, stockOnly, saleOnly]);

  const toggleBrand = (b) => setBrandFilter(prev => {
    const n = new Set(prev);
    n.has(b) ? n.delete(b) : n.add(b);
    return n;
  });

  return (
    <PageWrapper>
      {({ addToCart, openModal, faves, toggleFav }) => (
        <main>
          {/* Hero header */}
          <section className="page-hero shell">
            <div className="breadcrumb">
              <a href="index.html">Home</a>
              <Icon name="chevR" />
              <a href="shop.html">Shop</a>
              <Icon name="chevR" />
              <span>{meta.label}</span>
            </div>
            <div className="page-hero-row">
              <div>
                <h1 className="page-title">{meta.label}</h1>
                <p className="page-sub">
                  {allCatProducts.length} products from {brands.length} brands ·
                  All compatibility-checked, 2-year warranty, free delivery on 50K+.
                </p>
              </div>
              <div className="cat-jump">
                {CATEGORIES.slice(0,8).map(c => (
                  <a key={c.id} href={`shop.html?cat=${c.id}`} className={`cat-jump-chip ${c.id === catId ? "active" : ""}`}>
                    <Icon name={c.icon} />
                    {c.label}
                  </a>
                ))}
              </div>
            </div>
          </section>

          {/* Listing */}
          <section className="shell shop-layout">
            {/* Sidebar */}
            <aside className="shop-side">
              <div className="side-block">
                <h4>Price (DZD)</h4>
                <div className="price-show">
                  <span>0</span>
                  <span style={{ color: "var(--purple)", fontWeight: 600 }}>{money(priceMax)}</span>
                </div>
                <input
                  type="range"
                  min="5000"
                  max="500000"
                  step="5000"
                  value={priceMax}
                  onChange={(e) => setPriceMax(+e.target.value)}
                  className="price-range"
                />
              </div>

              <div className="side-block">
                <h4>Brand</h4>
                <div className="side-list">
                  {brands.map(b => (
                    <label key={b} className="side-check">
                      <input type="checkbox" checked={brandFilter.has(b)} onChange={() => toggleBrand(b)} />
                      <span className="check-box"></span>
                      {b}
                      <span className="count">{allCatProducts.filter(p => p.brand === b).length}</span>
                    </label>
                  ))}
                </div>
              </div>

              <div className="side-block">
                <h4>Availability</h4>
                <div className="side-list">
                  <label className="side-check">
                    <input type="checkbox" checked={stockOnly} onChange={(e) => setStockOnly(e.target.checked)} />
                    <span className="check-box"></span>
                    In stock only
                  </label>
                  <label className="side-check">
                    <input type="checkbox" checked={saleOnly} onChange={(e) => setSaleOnly(e.target.checked)} />
                    <span className="check-box"></span>
                    On sale
                  </label>
                </div>
              </div>

              <div className="side-block">
                <h4>Rating</h4>
                <div className="side-list">
                  {[5,4,3].map(r => (
                    <label key={r} className="side-check">
                      <input type="radio" name="rate" />
                      <span className="check-box round"></span>
                      <Stars value={r} />
                      <span style={{ fontSize: 12, color: "var(--ink-mute)" }}>& up</span>
                    </label>
                  ))}
                </div>
              </div>

              <div className="side-promo">
                <Icon name="sparkle" style={{ width: 20, height: 20, color: "var(--purple)" }} />
                <div>
                  <div className="t">Need help choosing?</div>
                  <div className="s">Our gear experts respond in &lt; 5 min on chat.</div>
                </div>
              </div>
            </aside>

            {/* Main listing */}
            <div className="shop-main">
              <div className="shop-toolbar">
                <div className="active-filters">
                  <span className="result-count">
                    <strong>{products.length}</strong> result{products.length === 1 ? "" : "s"}
                  </span>
                  {[...brandFilter].map(b => (
                    <span key={b} className="active-chip">
                      {b}
                      <button onClick={() => toggleBrand(b)}><Icon name="close" style={{ width: 12, height: 12 }} /></button>
                    </span>
                  ))}
                  {stockOnly && (
                    <span className="active-chip">In stock<button onClick={() => setStockOnly(false)}><Icon name="close" style={{ width: 12, height: 12 }} /></button></span>
                  )}
                  {saleOnly && (
                    <span className="active-chip">On sale<button onClick={() => setSaleOnly(false)}><Icon name="close" style={{ width: 12, height: 12 }} /></button></span>
                  )}
                </div>
                <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                  <div className="view-toggle">
                    <button className={view === "grid" ? "active" : ""} onClick={() => setView("grid")}>
                      <Icon name="grid" />
                    </button>
                    <button className={view === "list" ? "active" : ""} onClick={() => setView("list")}>
                      <svg viewBox="0 0 24 24" width="16" height="16"><g fill="currentColor"><rect x="3" y="5" width="18" height="3" rx="1"/><rect x="3" y="11" width="18" height="3" rx="1"/><rect x="3" y="17" width="18" height="3" rx="1"/></g></svg>
                    </button>
                  </div>
                  <select className="sort-select" value={sort} onChange={(e) => setSort(e.target.value)}>
                    <option value="popular">Most popular</option>
                    <option value="lowhigh">Price: low to high</option>
                    <option value="highlow">Price: high to low</option>
                    <option value="rating">Top rated</option>
                    <option value="new">Newest first</option>
                  </select>
                </div>
              </div>

              {products.length === 0 ? (
                <div className="empty-result">
                  <Icon name="search" style={{ width: 48, height: 48, color: "var(--ink-mute)" }} />
                  <h3>No products match these filters</h3>
                  <p>Try widening your price range or clearing brand filters.</p>
                  <button className="btn btn-primary" onClick={() => { setBrandFilter(new Set()); setPriceMax(500000); setStockOnly(false); setSaleOnly(false); }}>
                    Reset filters
                  </button>
                </div>
              ) : view === "grid" ? (
                <div className="product-grid">
                  {products.map(p => (
                    <ProductCard
                      key={p.id} p={p}
                      onOpen={openModal} onAdd={addToCart}
                      faved={faves.has(p.id)} onFav={toggleFav}
                    />
                  ))}
                </div>
              ) : (
                <div className="product-list">
                  {products.map(p => <ProductListRow key={p.id} p={p} onOpen={openModal} onAdd={addToCart} faved={faves.has(p.id)} onFav={toggleFav} />)}
                </div>
              )}

              {products.length > 0 && (
                <div className="pagination">
                  <button className="pg-btn"><Icon name="chev" style={{ transform: "rotate(90deg)" }} /></button>
                  <button className="pg-btn active">1</button>
                  <button className="pg-btn">2</button>
                  <button className="pg-btn">3</button>
                  <span style={{ color: "var(--ink-mute)" }}>…</span>
                  <button className="pg-btn">8</button>
                  <button className="pg-btn"><Icon name="chev" style={{ transform: "rotate(-90deg)" }} /></button>
                </div>
              )}
            </div>
          </section>

          <Footer />
        </main>
      )}
    </PageWrapper>
  );
};

const ProductListRow = ({ p, onOpen, onAdd, faved, onFav }) => {
  const discount = p.was ? Math.round((1 - p.price / p.was) * 100) : 0;
  return (
    <div className="list-row">
      <a className="list-media" href={`product.html?id=${p.id}`}>
        {p.img && <img src={p.img} alt={p.name} loading="lazy" />}
        <div className="product-badges">
          {p.badges.map((b, i) => {
            const cls = b.includes("%") ? "sale" : b === "NEW" ? "new" : "hot";
            return <span key={i} className={`badge ${cls}`}>{b}</span>;
          })}
        </div>
      </a>
      <div className="list-info">
        <div className="product-brand">{p.brand}</div>
        <a href={`product.html?id=${p.id}`} className="product-name-link"><h3 className="product-name" style={{ minHeight: 0 }}>{p.name}</h3></a>
        <div className="product-rating">
          <Stars value={p.rating} />
          <span>{p.rating.toFixed(1)} · {p.reviews} reviews</span>
          <span style={{ color: "var(--ink-mute)", margin: "0 6px" }}>·</span>
          <span className="in-stock" style={{ fontSize: 11.5, fontWeight: 600 }}>In stock</span>
        </div>
        <div className="product-specs">
          {p.specs.map((s, i) => <span key={i} className="spec-chip">{s}</span>)}
        </div>
        <div className="list-extras">
          <span><Icon name="truck" /> Free delivery</span>
          <span><Icon name="shield" /> 2y warranty</span>
          <span><Icon name="refresh" /> 14d returns</span>
        </div>
      </div>
      <div className="list-price">
        <div className="price-block" style={{ textAlign: "right" }}>
          {p.was && (
            <div>
              <span className="was">{money(p.was)}</span>
              <span className="save">save {discount}%</span>
            </div>
          )}
          <div className="now" style={{ fontSize: 22 }}>{money(p.price)}<span className="cur"> {p.currency}</span></div>
          <div style={{ fontSize: 11, color: "var(--ink-mute)" }}>VAT inc.</div>
        </div>
        <button className="btn btn-primary" style={{ width: "100%", justifyContent: "center" }} onClick={() => onAdd(p)}>
          <Icon name="cart" /> Add to cart
        </button>
        <button className="btn btn-ghost" style={{ width: "100%", justifyContent: "center" }} onClick={() => onOpen(p)}>
          <Icon name="eye" /> Quick view
        </button>
      </div>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<ShopPage />);
