/* ============================================================
   SHOP PAGE — multi-category browse, filters, sort, search
   ============================================================ */
function ShopPage({ params }) {
  const { nav } = useStore();
  const [cat, setCat] = useState(params.cat || 'all');
  const [sort, setSort] = useState('featured');
  const [q, setQ] = useState(params.q || '');

  useEffect(() => { setCat(params.cat || 'all'); if (params.q !== undefined) setQ(params.q); }, [params.cat, params.q]);

  const activeNavCat = BB.navCategories.find(c => c.id === cat);
  let list = BB.products.filter(p => cat === 'all' || (activeNavCat ? BB.matchesNavCat(p, activeNavCat) : p.cat === cat));
  if (q.trim()) {
    const hay = (p) => (p.name + ' ' + p.short + ' ' + (BB.catOf(p)?.name || '') + ' ' + Object.values(p.specs || {}).join(' ')).toLowerCase();
    list = list.filter(p => hay(p).includes(q.toLowerCase()));
  }
  list = [...list];
  if (sort === 'price-asc') list.sort((a, b) => a.price - b.price);
  if (sort === 'price-desc') list.sort((a, b) => b.price - a.price);
  if (sort === 'new') list.sort((a, b) => (b.tags.includes('new') ? 1 : 0) - (a.tags.includes('new') ? 1 : 0));
  if (sort === 'popular') list.sort((a, b) => (b.tags.includes('best') ? 1 : 0) - (a.tags.includes('best') ? 1 : 0));

  const activeCat = activeNavCat;
  const counts = { all: BB.products.length };
  BB.navCategories.forEach(c => counts[c.id] = BB.products.filter(p => BB.matchesNavCat(p, c)).length);

  return (
    <>
      {/* hero band */}
      <section style={{ background: 'linear-gradient(160deg, var(--cream-deep), var(--gold-soft))', padding: 'clamp(44px,6vw,80px) var(--gutter) clamp(36px,5vw,56px)', borderBottom: '1px solid var(--line)' }}>
        <div className="container wide">
          <h1 style={{ fontSize: 'clamp(40px,6vw,76px)' }}>{activeCat ? activeCat.name : <>Everything <em style={{ color: 'var(--gold-deep)' }}>in store</em></>}</h1>
        </div>
      </section>

      <div className="container wide" style={{ padding: 'clamp(28px,4vw,48px) var(--gutter) clamp(64px,9vw,110px)' }}>
        {/* category chips */}
        <div style={{ display: 'flex', gap: 9, flexWrap: 'wrap', marginBottom: 22 }}>
          <button className={`chip ${cat === 'all' ? 'active' : ''}`} onClick={() => { setCat('all'); nav('shop', {}); }}>All · {counts.all}</button>
          {BB.navCategories.map(c => (
            <button key={c.id} className={`chip ${cat === c.id ? 'active' : ''}`} onClick={() => { setCat(c.id); nav('shop', { cat: c.id }); }}>{c.short} · {counts[c.id]}</button>
          ))}
        </div>

        {/* toolbar */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap', paddingBottom: 22, borderBottom: '1px solid var(--line)', marginBottom: 36 }}>
          <div className="search-pill" style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'var(--ivory)', border: '1.5px solid var(--line)', borderRadius: 100, padding: '9px 8px 9px 16px', flex: '1 1 240px', maxWidth: 340 }}>
            <I.search width={18} height={18} style={{ color: 'var(--ink-soft)', flexShrink: 0 }} />
            <input value={q} onChange={e => setQ(e.target.value)} placeholder={activeCat ? `Search ${activeCat.short.toLowerCase()}…` : 'Search the whole store…'} style={{ border: 'none', background: 'transparent', outline: 'none', flex: 1, fontSize: 14, minWidth: 0 }} />
            {q && <button className="qbtn" onClick={() => setQ('')} aria-label="Clear search" style={{ color: 'var(--ink-faint)' }}><I.close width={15} height={15} /></button>}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span className="muted" style={{ fontSize: 13.5 }}>{list.length} item{list.length !== 1 ? 's' : ''}</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <label className="eyebrow" style={{ fontSize: 11 }}>Sort</label>
              <select value={sort} onChange={e => setSort(e.target.value)} className="input" style={{ padding: '10px 14px', borderRadius: 100, width: 'auto', fontSize: 13.5, cursor: 'pointer', minHeight: 44 }}>
                <option value="featured">Featured</option>
                <option value="popular">Most popular</option>
                <option value="new">Newest</option>
                <option value="price-asc">Price: low to high</option>
                <option value="price-desc">Price: high to low</option>
              </select>
            </div>
          </div>
        </div>

        {/* grid */}
        {list.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '80px 0' }}>
            <p style={{ fontFamily: 'var(--serif)', fontWeight: 600, fontSize: 28 }}>Nothing matched</p>
            <p className="muted" style={{ marginTop: 8 }}>Try another category or a simpler search — “Converse”, “Vans”.</p>
            <button className="btn btn-outline btn-sm" style={{ marginTop: 20 }} onClick={() => { setQ(''); setCat('all'); nav('shop', {}); }}>Reset filters</button>
          </div>
        ) : (
          <div className="prod-grid">
            {list.map((p, i) => <ProductCard key={p.id} p={p} delay={(i % 4) + 1} />)}
          </div>
        )}
      </div>
    </>
  );
}

Object.assign(window, { ShopPage });
