// Catalog page with filters/sort

function CatalogPage({ initialCategory = 'all', initialQuery = '', go, onAddToCart }) {
  const [cat, setCat] = React.useState(initialCategory);
  const [sort, setSort] = React.useState('popular');
  const [q, setQ] = React.useState(initialQuery);
  const [stockOnly, setStockOnly] = React.useState(false);

  React.useEffect(() => { setCat(initialCategory); }, [initialCategory]);
  React.useEffect(() => { setQ(initialQuery); }, [initialQuery]);

  const results = React.useMemo(() => {
    let list = PRODUCTS.slice();
    if (cat !== 'all') list = list.filter(p => p.category === cat);
    if (q.trim()) list = list.filter(p => (p.name + ' ' + p.tagline).toLowerCase().includes(q.toLowerCase()));
    if (stockOnly) list = list.filter(p => p.stock > 0);
    if (sort === 'price_asc') list.sort((a, b) => a.priceFrom - b.priceFrom);
    else if (sort === 'price_desc') list.sort((a, b) => b.priceFrom - a.priceFrom);
    else if (sort === 'rating') list.sort((a, b) => b.rating - a.rating);
    else list.sort((a, b) => b.reviewCount - a.reviewCount);
    return list;
  }, [cat, sort, q, stockOnly]);

  return (
    <section className="max-w-[1280px] mx-auto px-5 md:px-8 pt-10 md:pt-14">
      <div className="flex items-end justify-between mb-8">
        <div>
          <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-2">Catalog</div>
          <h1 className="text-4xl md:text-5xl font-semibold tracking-tight">All products</h1>
          <p className="text-white/55 mt-2">{results.length} products · avg. delivery 2m 47s · auto-fulfilled</p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-[240px_1fr] gap-6 md:gap-10">
        {/* Sidebar filters */}
        <aside className="md:sticky md:top-20 md:self-start space-y-6">
          <div>
            <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-3">Category</div>
            <div className="space-y-1">
              {CATEGORIES.map(c => (
                <button
                  key={c.id}
                  onClick={() => setCat(c.id)}
                  className={`w-full text-left text-sm px-3 py-2 rounded-lg hairline transition-colors ${cat === c.id ? 'selected' : 'selectable'}`}
                  style={cat === c.id ? { borderColor: 'var(--accent)', background: 'rgba(168,123,255,0.06)' } : {}}
                >
                  <span className="flex items-center justify-between">
                    <span>{c.name}</span>
                    <span className="text-xs text-white/40 mono">
                      {c.id === 'all' ? PRODUCTS.length : PRODUCTS.filter(p => p.category === c.id).length}
                    </span>
                  </span>
                </button>
              ))}
            </div>
          </div>

          <div>
            <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-3">Search</div>
            <div className="hairline rounded-lg px-3 py-2 flex items-center gap-2 accent-ring">
              <Icon name="search" size={14} />
              <input
                value={q}
                onChange={(e) => setQ(e.target.value)}
                placeholder="Search products"
                className="bg-transparent outline-none text-sm flex-1 min-w-0"
              />
            </div>
          </div>

          <div>
            <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-3">Sort</div>
            <div className="space-y-1">
              {[
                { id: 'popular', label: 'Most popular' },
                { id: 'rating', label: 'Highest rated' },
                { id: 'price_asc', label: 'Price: low → high' },
                { id: 'price_desc', label: 'Price: high → low' },
              ].map(s => (
                <button
                  key={s.id}
                  onClick={() => setSort(s.id)}
                  className={`w-full text-left text-sm px-3 py-2 rounded-lg hairline transition-colors ${sort === s.id ? 'selected' : 'selectable'}`}
                  style={sort === s.id ? { borderColor: 'var(--accent)', background: 'rgba(168,123,255,0.06)' } : {}}
                >
                  {s.label}
                </button>
              ))}
            </div>
          </div>

          <div>
            <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-3">Availability</div>
            <label className="flex items-center gap-2 text-sm cursor-pointer">
              <span
                onClick={() => setStockOnly(v => !v)}
                className="relative w-9 h-5 rounded-full transition-colors"
                style={{ background: stockOnly ? 'var(--accent)' : 'rgba(255,255,255,0.1)' }}
              >
                <span
                  className="absolute top-0.5 w-4 h-4 rounded-full bg-white transition-all"
                  style={{ left: stockOnly ? '18px' : '2px' }}
                />
              </span>
              In stock only
            </label>
          </div>

          <div className="hairline rounded-xl p-4" style={{ background: 'var(--bg-1)' }}>
            <div className="flex items-center gap-2 mb-2" style={{ color: 'var(--accent)' }}>
              <Icon name="shield" size={14} /> <span className="text-xs mono uppercase tracking-widest">Warranty</span>
            </div>
            <p className="text-xs text-white/55">Every order covered for the full subscription term. Replacements auto-issued within 6h avg.</p>
          </div>
        </aside>

        {/* Results */}
        <div>
          {results.length === 0 ? (
            <div className="hairline rounded-2xl p-10 text-center text-white/50">No products match your filters.</div>
          ) : (
            <div key={cat + sort + q + stockOnly} className="grid grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-4 stagger">
              {results.map(p => <ProductCard key={p.id} product={p} go={go} onAddToCart={onAddToCart} />)}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { CatalogPage });
