// shop.jsx — catalog with live filters

function Shop({ lang, openPDP, addToCart, filterPrefill }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [families, setFamilies] = React.useState(new Set(filterPrefill?.family ? [filterPrefill.family] : []));
  const [sizes, setSizes] = React.useState(new Set());
  const [concs, setConcs] = React.useState(new Set());
  const [price, setPrice] = React.useState([200, 1500]);
  const [sort, setSort] = React.useState('new');
  const [q, setQ] = React.useState('');

  const toggle = (set, setter, v) => {
    const next = new Set(set);
    if (next.has(v)) next.delete(v); else next.add(v);
    setter(next);
  };

  const filtered = React.useMemo(() => {
    let r = PRODUCTS.filter(p => {
      if (families.size && !families.has(p.family)) return false;
      if (concs.size && !concs.has(p.concentration)) return false;
      if (sizes.size) {
        const hasSize = p.sizes.some(s => sizes.has(s.ml));
        if (!hasSize) return false;
      }
      if (p.price < price[0] || p.price > price[1]) return false;
      if (q) {
        const ql = q.toLowerCase();
        if (!p.name_ar.includes(q) && !p.name_en.toLowerCase().includes(ql)) return false;
      }
      return true;
    });
    if (sort === 'price-asc')  r = [...r].sort((a, b) => a.price - b.price);
    if (sort === 'price-desc') r = [...r].sort((a, b) => b.price - a.price);
    if (sort === 'rating')     r = [...r].sort((a, b) => b.rating - a.rating);
    if (sort === 'new')        r = [...r].sort((a, b) => b.year - a.year);
    return r;
  }, [families, sizes, concs, price, sort, q]);

  const countByFamily = (f) => PRODUCTS.filter(p => p.family === f).length;
  const concentrations = ['EDT', 'EDP', 'Parfum', 'Extrait'];

  return (
    <div className="shop">
      <aside className="filters">
        <div className="search-box" style={{ width: '100%' }}>
          <I.search />
          <input placeholder={t('بحث فوري…', 'Search…')} value={q} onChange={(e) => setQ(e.target.value)} />
        </div>

        <div className="filter-group">
          <div className="filter-title">{t('العائلة العطرية', 'Scent Family')}</div>
          {SCENT_FAMILIES.map(f => (
            <div key={f.id}
                 className={'filter-chip' + (families.has(f.id) ? ' on' : '')}
                 onClick={() => toggle(families, setFamilies, f.id)}>
              <span style={{ display: 'flex', alignItems: 'center' }}>
                <span className="dot" style={{ background: families.has(f.id) ? f.tone : 'transparent', borderColor: f.tone }} />
                {lang === 'ar' ? f.ar : f.en}
              </span>
              <span className="count">{countByFamily(f.id)}</span>
            </div>
          ))}
        </div>

        <div className="filter-group">
          <div className="filter-title">{t('الحجم', 'Size')}</div>
          {[30, 50, 100].map(s => (
            <div key={s}
                 className={'filter-chip' + (sizes.has(s) ? ' on' : '')}
                 onClick={() => toggle(sizes, setSizes, s)}>
              <span><span className="dot" />{s}ml</span>
            </div>
          ))}
        </div>

        <div className="filter-group">
          <div className="filter-title">{t('التركيز', 'Concentration')}</div>
          {concentrations.map(c => (
            <div key={c}
                 className={'filter-chip' + (concs.has(c) ? ' on' : '')}
                 onClick={() => toggle(concs, setConcs, c)}>
              <span><span className="dot" />{c}</span>
            </div>
          ))}
        </div>

        <div className="filter-group">
          <div className="filter-title">{t('السعر', 'Price')}</div>
          <div className="price-range">
            <div className="price-range-track">
              <div className="price-range-fill"
                   style={{ insetInlineStart: `${((price[0] - 200) / 1300) * 100}%`,
                            width: `${((price[1] - price[0]) / 1300) * 100}%` }} />
            </div>
            <div className="price-range-row">
              <span>AED {price[0]}</span>
              <span>AED {price[1]}</span>
            </div>
            <input type="range" min="200" max="1500" step="10" value={price[0]}
                   onChange={(e) => setPrice([Math.min(+e.target.value, price[1] - 50), price[1]])}
                   style={{ width: '100%', accentColor: 'var(--ink)' }} />
            <input type="range" min="200" max="1500" step="10" value={price[1]}
                   onChange={(e) => setPrice([price[0], Math.max(+e.target.value, price[0] + 50)])}
                   style={{ width: '100%', accentColor: 'var(--ink)' }} />
          </div>
        </div>

        <button className="btn ghost sm" onClick={() => {
          setFamilies(new Set()); setSizes(new Set()); setConcs(new Set()); setPrice([200, 1500]); setQ('');
        }}>
          {t('مسح المرشحات', 'Clear filters')}
        </button>
      </aside>

      <main>
        <div className="shop-head">
          <div>
            <div className="eyebrow">{t('الكولكشن الكامل', 'The Full Collection')}</div>
            <h1 className="h-display">{t('كل العطور', 'All Fragrances')}</h1>
            <div className="count" style={{ marginTop: 10 }}>{filtered.length} {t('من', 'of')} {PRODUCTS.length}</div>
          </div>
          <div className="sort">
            <span className="eyebrow" style={{ fontSize: 10 }}>{t('ترتيب', 'Sort')}</span>
            <select value={sort} onChange={(e) => setSort(e.target.value)}>
              <option value="new">{t('الأحدث', 'Newest')}</option>
              <option value="price-asc">{t('السعر: من الأقل', 'Price: low → high')}</option>
              <option value="price-desc">{t('السعر: من الأعلى', 'Price: high → low')}</option>
              <option value="rating">{t('التقييم', 'Top rated')}</option>
            </select>
          </div>
        </div>

        {filtered.length === 0 ? (
          <div style={{ padding: '80px 0', textAlign: 'center', color: 'var(--ink-3)' }}>
            <div className="serif-en" style={{ fontSize: 28 }}>No match.</div>
            <div style={{ marginTop: 8, fontSize: 13 }}>{t('جرب توسيع التصفية', 'Try widening the filters.')}</div>
          </div>
        ) : (
          <div className="product-grid">
            {filtered.map(p => (
              <ProductCard key={p.id} product={p} lang={lang} onOpen={openPDP} onAddToCart={addToCart} />
            ))}
          </div>
        )}
      </main>
    </div>
  );
}

window.Shop = Shop;
