/* Listing — filter rail + product grid. */
function SF_Listing({ go, category, wish, toggleWish }) {
  const { Chip, ProductCard } = window.SS;
  const [cat, setCat] = React.useState(category || 'all');
  const [occasion, setOccasion] = React.useState('all');
  const [sort, setSort] = React.useState('featured');
  const [sheetOpen, setSheetOpen] = React.useState(false);
  React.useEffect(() => setCat(category || 'all'), [category]);

  const OCCASIONS = ['all', 'Festive', 'Bridal', 'Daily', 'Gifting'];
  const TITLES = { new: 'New drop', sale: 'Top Picks', gifting: 'Gifting', all: 'All jewellery' };

  let products = window.SS_PRODUCTS;
  if (cat === 'new') products = products.filter((p) => p.badge === 'NEW');
  else if (cat === 'sale') products = products.filter((p) => p.badge === 'BESTSELLER' || (p.rating || 0) >= 4.5);
  else if (cat === 'gifting') products = products.filter((p) => p.occasion === 'Gifting');
  else if (cat !== 'all') products = products.filter((p) => p.category === cat);
  if (occasion !== 'all') products = products.filter((p) => p.occasion === occasion);
  products = [...products].sort((a, b) => {
    if (sort === 'price-asc') return a.price - b.price;
    if (sort === 'price-desc') return b.price - a.price;
    if (sort === 'rating') return (b.rating || 0) - (a.rating || 0);
    return 0;
  });

  const label = { fontSize: 11, fontWeight: 500, letterSpacing: '.2em', textTransform: 'uppercase', color: 'var(--sf-text-muted)', marginBottom: 10 };
  const sidebarSection = { display: 'flex', flexDirection: 'column', gap: 10, paddingBottom: 22, marginBottom: 22, borderBottom: '1px solid var(--sf-border-soft)' };

  const filterBody = (
    <React.Fragment>
      <div style={sidebarSection}>
        <div style={label}>CATEGORY</div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {['all', ...window.SS_CATEGORIES.map((c) => c.id)].map((c) => (
            <Chip key={c} selected={cat === c} onClick={() => setCat(c)}>{c === 'all' ? 'All' : c}</Chip>
          ))}
        </div>
      </div>
      <div style={sidebarSection}>
        <div style={label}>OCCASION</div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {OCCASIONS.map((o) => (
            <Chip key={o} selected={occasion === o} onClick={() => setOccasion(o)}>{o === 'all' ? 'All' : o}</Chip>
          ))}
        </div>
      </div>
      <div>
        <div style={label}>SORT BY</div>
        <select value={sort} onChange={(e) => setSort(e.target.value)} style={{
          all: 'unset', boxSizing: 'border-box', width: '100%', padding: '10px 16px', borderRadius: 'var(--sf-radius-pill)',
          background: 'var(--sf-well)', color: 'var(--sf-text)', boxShadow: 'inset 0 0 0 1px var(--sf-border-soft)',
          fontSize: 12.5, letterSpacing: '.06em',
        }}>
          <option value="featured">Featured</option>
          <option value="price-asc">Price: low to high</option>
          <option value="price-desc">Price: high to low</option>
          <option value="rating">Top rated</option>
        </select>
      </div>
    </React.Fragment>
  );

  return (
    <div className="sf-maxw" style={{ paddingTop: 44, paddingBottom: 96 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 34, fontWeight: 600, color: 'var(--sf-text)', textTransform: 'capitalize' }}>{TITLES[cat] || cat}</div>
          <div style={{ fontSize: 13, fontWeight: 300, color: 'var(--sf-text-faint)', marginTop: 6 }}>{products.length} pieces</div>
        </div>
        <button className="sf-show-mobile" onClick={() => setSheetOpen(true)} style={{
          all: 'unset', cursor: 'pointer', minHeight: 44, padding: '0 18px', borderRadius: 'var(--sf-radius-pill)',
          alignItems: 'center', gap: 8, background: 'var(--sf-well)', boxShadow: 'inset 0 0 0 1px var(--sf-border-soft)',
          color: 'var(--sf-text)', fontSize: 12.5, fontWeight: 500, letterSpacing: '.08em', textTransform: 'uppercase', marginTop: 4,
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M4 6h16M7 12h10M10 18h4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
          Filters
        </button>
      </div>

      <div className="sf-listing-cols" style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 32, marginTop: 30, alignItems: 'start' }}>
        <aside className="sf-hide-mobile" style={{ position: 'sticky', top: 96 }}>
          {filterBody}
        </aside>

        <div className="sf-listing-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18 }}>
          {products.map((p) => (
            <ProductCard key={p.id} {...p} wished={!!wish[p.id]} onWish={() => toggleWish(p.id)} onQuickView={() => go('pdp', p.id)} style={{ cursor: 'pointer' }} />
          ))}
          {products.length === 0 && (
            <div style={{ gridColumn: '1 / -1', textAlign: 'center', padding: '60px 0', color: 'var(--sf-text-faint)', fontSize: 14 }}>No pieces match those filters yet.</div>
          )}
        </div>
      </div>

      {sheetOpen && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 60, display: 'flex', alignItems: 'flex-end' }}>
          <div onClick={() => setSheetOpen(false)} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.55)' }} />
          <div style={{
            position: 'relative', width: '100%', maxHeight: '80vh', overflowY: 'auto',
            background: 'var(--sf-surface)', borderTop: '1px solid var(--sf-border-soft)',
            borderTopLeftRadius: 'var(--sf-radius-lg)', borderTopRightRadius: 'var(--sf-radius-lg)',
            padding: '20px 22px 28px', boxShadow: 'var(--sf-shadow)',
          }}>
            <div style={{ width: 40, height: 4, borderRadius: 999, background: 'var(--sf-border-strong)', margin: '0 auto 18px' }} />
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, color: 'var(--sf-text)' }}>Filters</div>
              <button onClick={() => setSheetOpen(false)} style={{ all: 'unset', cursor: 'pointer', minHeight: 44, minWidth: 44, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, letterSpacing: '.1em', color: 'var(--sf-gold-hi)', textTransform: 'uppercase' }}>Done</button>
            </div>
            {filterBody}
          </div>
        </div>
      )}
    </div>
  );
}
window.SF_Listing = SF_Listing;
