// store-catalog.jsx — Catalog page with sidebar filters + sort + grid.
// Route: { name: 'catalog', cat?: string } — optional preset category filter.

const { useState: useSc, useEffect: useEc, useMemo: useMc } = React;

function CatalogPage({ preset, tag, mobile }) {
  const { t, tr, lang, fmt, goto } = useStore();
  const cats = window.ECOPROF_CATEGORIES;
  const allProducts = window.ECOPROF_PRODUCTS;
  const maxPrice = useMc(() => Math.max(...allProducts.map(p => p.price)), []);

  // Filter state
  const initialCats = preset ? [preset] : [];
  const initialTags = tag ? [tag] : [];
  const [selCats, setSelCats] = useSc(initialCats);
  const [selTags, setSelTags] = useSc(initialTags); // 'new' | 'best' | 'sale' | 'award'
  const [priceMax, setPriceMax] = useSc(maxPrice);
  const [minRating, setMinRating] = useSc(0);
  const [sort, setSort] = useSc('pop');
  const [sortOpen, setSortOpen] = useSc(false);
  const [mobileFiltersOpen, setMobileFiltersOpen] = useSc(false);

  // Re-apply preset if it changes (e.g., navigate from one cat to another)
  React.useEffect(() => {
    setSelCats(preset ? [preset] : []);
  }, [preset]);
  React.useEffect(() => {
    setSelTags(tag ? [tag] : []);
  }, [tag]);

  const toggleCat = (id) => setSelCats(cs => cs.includes(id) ? cs.filter(x => x !== id) : [...cs, id]);
  const toggleTag = (id) => setSelTags(ts => ts.includes(id) ? ts.filter(x => x !== id) : [...ts, id]);
  const resetAll = () => { setSelCats([]); setSelTags([]); setPriceMax(maxPrice); setMinRating(0); };

  const filtered = useMc(() => {
    let list = allProducts;
    if (selCats.length) list = list.filter(p => selCats.includes(p.cat));
    if (selTags.length) {
      list = list.filter(p => {
        return selTags.every(tag => {
          if (tag === 'sale') return !!p.oldPrice;
          if (tag === 'award') return !!p.award;
          return p.badges.includes(tag);
        });
      });
    }
    list = list.filter(p => p.price <= priceMax);
    if (minRating > 0) list = list.filter(p => p.rating >= minRating);

    const sorted = [...list];
    if (sort === 'pop')          sorted.sort((a,b) => b.reviews - a.reviews);
    else if (sort === 'new')     sorted.sort((a,b) => (b.badges.includes('new')?1:0) - (a.badges.includes('new')?1:0));
    else if (sort === 'cheap')   sorted.sort((a,b) => a.price - b.price);
    else if (sort === 'expensive') sorted.sort((a,b) => b.price - a.price);
    else if (sort === 'rating')  sorted.sort((a,b) => b.rating - a.rating);
    return sorted;
  }, [selCats, selTags, priceMax, minRating, sort, allProducts]);

  const sortOptions = [
    { id:'pop', label: t('cat.sort.pop') },
    { id:'new', label: t('cat.sort.new') },
    { id:'cheap', label: t('cat.sort.cheap') },
    { id:'expensive', label: t('cat.sort.expensive') },
    { id:'rating', label: t('cat.sort.rating') },
  ];
  const currentSort = sortOptions.find(s => s.id === sort);

  const presetCat = preset && cats.find(c => c.id === preset);

  // Sidebar contents (reused in mobile bottom sheet)
  const Sidebar = ({ inDrawer = false }) => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
      {/* Reset */}
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
        <div className="ep-mono" style={{ fontWeight: 600, color:'var(--ep-ink)', fontSize: 11 }}>{t('cat.filters')}</div>
        <button onClick={resetAll}
          style={{ background:'transparent', border:0, color:'var(--ep-ink-2)', fontSize: 12, cursor:'pointer', padding:0, textDecoration:'underline', textUnderlineOffset: 3 }}>
          {t('cat.reset')}
        </button>
      </div>

      {/* Categories */}
      <div>
        <div className="ep-mono" style={{ marginBottom: 12, color:'var(--ep-ink-2)' }}>{t('cat.f.cats')}</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {cats.map(c => {
            const count = allProducts.filter(p => p.cat === c.id).length;
            const checked = selCats.includes(c.id);
            return (
              <label key={c.id}
                style={{ display:'flex', alignItems:'center', gap: 10, fontSize: 13.5, color:'var(--ep-ink)', cursor:'pointer' }}>
                <span style={{
                  width: 16, height: 16, borderRadius: 4,
                  border: checked ? '1.5px solid var(--ep-ink)' : '1.5px solid var(--ep-line)',
                  background: checked ? 'var(--ep-ink)' : '#fff',
                  display:'inline-flex', alignItems:'center', justifyContent:'center', flex:'none',
                  transition: 'all .15s var(--ep-ease)',
                }}>
                  {checked && <svg width="9" height="9" viewBox="0 0 9 9" fill="none" stroke="#fff" strokeWidth="1.8" strokeLinecap="round"><path d="M1 4.5l2.5 2.5L8 1.5"/></svg>}
                </span>
                <input type="checkbox" checked={checked} onChange={() => toggleCat(c.id)} style={{ position:'absolute', opacity:0, pointerEvents:'none' }}/>
                <span style={{ flex: 1 }}>{tr(c.name)}</span>
                <span style={{ color:'var(--ep-ink-3)', fontSize: 12, fontVariantNumeric:'tabular-nums' }}>{count}</span>
              </label>
            );
          })}
        </div>
      </div>

      {/* Tags */}
      <div>
        <div className="ep-mono" style={{ marginBottom: 12, color:'var(--ep-ink-2)' }}>{t('cat.f.tags')}</div>
        <div style={{ display:'flex', flexWrap:'wrap', gap: 6 }}>
          {[
            {id:'new',   label:t('cat.t.new')},
            {id:'best',  label:t('cat.t.best')},
            {id:'sale',  label:t('cat.t.sale')},
            {id:'award', label:t('cat.t.award')},
          ].map(tg => {
            const active = selTags.includes(tg.id);
            return (
              <button key={tg.id} onClick={() => toggleTag(tg.id)}
                style={{
                  padding:'7px 12px', borderRadius: 999,
                  border: active ? '1px solid var(--ep-ink)' : '1px solid var(--ep-line-2)',
                  background: active ? 'var(--ep-ink)' : '#fff',
                  color: active ? '#fff' : 'var(--ep-ink)',
                  fontSize: 12, fontWeight: 500, cursor:'pointer',
                  transition: 'all .15s var(--ep-ease)',
                }}>{tg.label}</button>
            );
          })}
        </div>
      </div>

      {/* Price */}
      <div>
        <div className="ep-mono" style={{ marginBottom: 12, display:'flex', justifyContent:'space-between' }}>
          <span style={{ color:'var(--ep-ink-2)' }}>{t('cat.f.price')}</span>
          <span style={{ color:'var(--ep-ink)', textTransform:'none', letterSpacing: 0 }}>до {fmt(priceMax)}</span>
        </div>
        <input type="range" min="200" max={maxPrice} step="50" value={priceMax}
          onChange={(e) => setPriceMax(Number(e.target.value))}
          style={{ width:'100%' }}/>
        <div style={{ display:'flex', justifyContent:'space-between', fontSize: 11, color:'var(--ep-ink-3)', marginTop: 4 }}>
          <span>{fmt(200)}</span>
          <span>{fmt(maxPrice)}</span>
        </div>
      </div>

      {/* Rating */}
      <div>
        <div className="ep-mono" style={{ marginBottom: 12, color:'var(--ep-ink-2)' }}>{t('cat.f.rating')}</div>
        <div style={{ display:'flex', gap: 6 }}>
          {[0, 4, 4.5, 4.8].map(r => (
            <button key={r} onClick={() => setMinRating(r)}
              style={{
                padding:'7px 12px', borderRadius: 999,
                border: minRating === r ? '1px solid var(--ep-ink)' : '1px solid var(--ep-line-2)',
                background: minRating === r ? 'var(--ep-ink)' : '#fff',
                color: minRating === r ? '#fff' : 'var(--ep-ink)',
                fontSize: 12, fontWeight: 500, cursor:'pointer',
                display: 'inline-flex', alignItems:'center', gap: 4,
              }}>
              {r === 0 ? (lang === 'uk' ? 'Усі' : 'Any') : <><svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3 7 7 .8-5.3 4.9 1.6 7.3L12 18l-6.3 4 1.6-7.3L2 9.8 9 9z"/></svg> {r}+</>}
            </button>
          ))}
        </div>
      </div>
    </div>
  );

  return (
    <div className="ep-container" style={{ paddingTop: 24, paddingBottom: 64 }}>
      {/* Breadcrumb + Title */}
      <div className="ep-mono" style={{ fontSize: 11, marginBottom: 16 }}>
        <a onClick={() => goto({name:'home'})} style={{ cursor:'pointer' }}>Ecoprof</a>
        <span style={{ margin:'0 8px' }}>/</span>
        <span style={{ color:'var(--ep-ink)' }}>{presetCat ? tr(presetCat.name) : t('cat.title')}</span>
      </div>

      <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', gap: 24, flexWrap:'wrap', marginBottom: 32 }}>
        <div>
          <div className="ep-eyebrow">{t('cat.eyebrow')}</div>
          <h1 className="ep-section-title" style={{ marginTop: 8 }}>{presetCat ? tr(presetCat.name) : t('cat.title')}</h1>
          <p className="ep-section-sub" style={{ marginTop: 6, maxWidth: 540 }}>
            {presetCat ? tr(presetCat.sub) : t('cat.sub')}
          </p>
        </div>
      </div>

      {/* Toolbar: count + sort */}
      <div style={{
        display:'flex', alignItems:'center', justifyContent:'space-between', gap: 12,
        padding: '14px 0', borderTop:'1px solid var(--ep-line-2)', borderBottom:'1px solid var(--ep-line-2)',
        marginBottom: 32,
      }}>
        <div style={{ fontSize: 13, color:'var(--ep-ink-2)', fontVariantNumeric:'tabular-nums' }}>
          {filtered.length} {t('cat.found')}
        </div>

        {/* Active filter chips */}
        <div style={{ display:'flex', gap: 6, flexWrap:'wrap', flex: 1, justifyContent:'center', overflow:'hidden' }}>
          {selCats.map(cid => {
            const c = cats.find(x => x.id === cid);
            return (
              <button key={cid} onClick={() => toggleCat(cid)}
                style={{ display:'inline-flex', alignItems:'center', gap: 6, padding:'4px 6px 4px 10px', borderRadius: 999, background:'var(--ep-surface-3)', color:'var(--ep-ink)', border:0, fontSize: 12, cursor:'pointer' }}>
                {tr(c.name)} <span style={{ opacity: 0.5, fontSize: 14 }}>×</span>
              </button>
            );
          })}
          {selTags.map(tg => (
            <button key={tg} onClick={() => toggleTag(tg)}
              style={{ display:'inline-flex', alignItems:'center', gap: 6, padding:'4px 6px 4px 10px', borderRadius: 999, background:'var(--ep-surface-3)', color:'var(--ep-ink)', border:0, fontSize: 12, cursor:'pointer' }}>
              {t('cat.t.' + tg)} <span style={{ opacity: 0.5, fontSize: 14 }}>×</span>
            </button>
          ))}
        </div>

        {/* Sort */}
        <div style={{ position:'relative' }}>
          {mobile && (
            <button onClick={() => setMobileFiltersOpen(true)}
              style={{ marginRight: 8, padding:'7px 14px', borderRadius: 999, border:'1px solid var(--ep-line-2)', background:'#fff', cursor:'pointer', fontSize: 12.5, fontWeight: 500 }}>
              ☰ {t('cat.mobile.cta')}
            </button>
          )}
          <button onClick={() => setSortOpen(o => !o)}
            style={{ padding:'7px 14px', borderRadius: 999, border:'1px solid var(--ep-line-2)', background:'#fff', cursor:'pointer', fontSize: 12.5, fontWeight: 500, display:'inline-flex', alignItems:'center', gap: 6 }}>
            {t('cat.sort')}: {currentSort?.label} <span style={{ fontSize: 9, marginTop: 1 }}>▼</span>
          </button>
          {sortOpen && (
            <>
              <div onClick={() => setSortOpen(false)} style={{ position:'fixed', inset: 0, zIndex: 10 }}/>
              <div style={{
                position:'absolute', top:'100%', right: 0, marginTop: 6,
                background:'#fff', border:'1px solid var(--ep-line-2)', borderRadius: 10,
                minWidth: 180, zIndex: 11,
                boxShadow:'0 8px 24px rgba(0,0,0,0.08)', overflow:'hidden',
              }}>
                {sortOptions.map(opt => (
                  <button key={opt.id} onClick={() => { setSort(opt.id); setSortOpen(false); }}
                    className={`ep-sort-opt ${sort === opt.id ? 'active' : ''}`}>{opt.label}</button>
                ))}
              </div>
            </>
          )}
        </div>
      </div>

      {/* Body: sidebar + grid */}
      <div style={{ display:'grid', gridTemplateColumns: mobile ? '1fr' : '240px 1fr', gap: 48, alignItems:'flex-start' }}>
        {!mobile && (
          <aside style={{ position:'sticky', top: 96 }}>
            <Sidebar/>
          </aside>
        )}

        <div>
          {filtered.length === 0 && (
            <div style={{ padding: '64px 24px', textAlign:'center', border:'1px dashed var(--ep-line)', borderRadius: 18 }}>
              <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 22, fontWeight: 500, marginBottom: 6 }}>{t('cat.empty.t')}</div>
              <div style={{ fontSize: 13.5, color:'var(--ep-ink-2)', marginBottom: 18 }}>{t('cat.empty.s')}</div>
              <button onClick={resetAll} className="ep-btn ghost sm">{t('cat.reset')}</button>
            </div>
          )}
          {filtered.length > 0 && (
            <div className="ep-grid" style={{ gridTemplateColumns: mobile ? 'repeat(2, 1fr)' : 'repeat(3, 1fr)' }}>
              {filtered.map(p => <ProductCard key={p.id} p={p}/>)}
            </div>
          )}
        </div>
      </div>

      {/* Mobile filter bottom sheet */}
      {mobile && mobileFiltersOpen && (
        <>
          <div onClick={() => setMobileFiltersOpen(false)} style={{ position:'fixed', inset: 0, background:'rgba(42,36,30,0.4)', zIndex: 90 }}/>
          <div style={{
            position:'fixed', left:0, right:0, bottom: 0, maxHeight:'85vh', overflowY:'auto',
            background:'var(--ep-bg)', borderTopLeftRadius: 20, borderTopRightRadius: 20,
            padding: '20px 20px 24px', zIndex: 91,
          }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 18 }}>
              <div style={{ fontFamily:'var(--ep-font-display)', fontSize: 22, fontWeight: 500 }}>{t('cat.filters')}</div>
              <button onClick={() => setMobileFiltersOpen(false)} className="ep-icon-btn"><I.x/></button>
            </div>
            <Sidebar inDrawer/>
            <button onClick={() => setMobileFiltersOpen(false)} className="ep-btn accent full" style={{ marginTop: 24 }}>
              {lang==='uk'?'Показати':'Show'} {filtered.length} {t('cat.found')}
            </button>
          </div>
        </>
      )}
    </div>
  );
}

// ───────────────────────── Lines (collections) page ─────────────────
function LinesPage({ mobile }) {
  const { t, tr, lang, goto } = useStore();
  const cats = window.ECOPROF_CATEGORIES;
  const all = window.ECOPROF_PRODUCTS;
  const repFor = (catId) => all.find(p => p.cat === catId);
  const countFor = (catId) => all.filter(p => p.cat === catId).length;
  const countLabel = (n) => lang === 'uk'
    ? `${n} ${n === 1 ? 'продукт' : (n >= 2 && n <= 4 ? 'продукти' : 'продуктів')}`
    : `${n} ${n === 1 ? 'product' : 'products'}`;

  return (
    <div className="ep-container" style={{ paddingTop: 24, paddingBottom: 64 }}>
      {/* Breadcrumb */}
      <div className="ep-mono" style={{ fontSize: 11, marginBottom: 16 }}>
        <a onClick={() => goto({name:'home'})} style={{ cursor:'pointer' }}>Ecoprof</a>
        <span style={{ margin:'0 8px' }}>/</span>
        <span style={{ color:'var(--ep-ink)' }}>{lang === 'uk' ? 'Лінійки' : 'Lines'}</span>
      </div>

      {/* Editorial hero — title + description stacked */}
      <div style={{ maxWidth: 980, marginBottom: 56 }}>
        <div className="ep-eyebrow">{lang === 'uk' ? '10 окремих лінійок' : '10 distinct lines'}</div>
        <h1 className="ep-section-title" style={{ marginTop: 14, fontSize: mobile ? 38 : 64, lineHeight: 1.02, marginBottom: 20 }}>
          {lang === 'uk' ? (
            <>Лінійка — це <em className="ep-serif" style={{ color:'var(--ep-ink-2)' }}>цілісний</em> ритуал.</>
          ) : (
            <>A line is <em className="ep-serif" style={{ color:'var(--ep-ink-2)' }}>a complete</em> ritual.</>
          )}
        </h1>
        <p style={{ fontSize: 16, color:'var(--ep-ink-2)', lineHeight: 1.55, maxWidth: 680, margin: 0 }}>
          {lang === 'uk'
            ? 'Кожна лінійка — окрема система активів і формул, які працюють разом. Ритуал з 3–4 кроків замість випадкових SKU. Обери задачу — і отримай готовий протокол.'
            : 'Each line is its own system of actives and formulas that work together. A 3–4 step ritual instead of a random SKU collection. Pick the concern — get a complete protocol.'}
        </p>
      </div>

      {/* 5×2 grid of category circles (same look as home strip) */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: mobile ? 'repeat(2, 1fr)' : 'repeat(5, 1fr)',
        gap: mobile ? 24 : 40,
        justifyItems: 'center',
      }}>
        {cats.map((c) => {
          const rep = repFor(c.id);
          return (
            <div key={c.id} className="ep-cat-circle"
              onClick={() => goto({ name: 'catalog', cat: c.id })}
              style={{ '--ring-bg': c.color }}>
              <div className="ring">
                {rep ? <img src={rep.image} alt={tr(c.name)} loading="lazy"/> : <CategoryIcon shape={c.shape} color={c.ink}/>}
              </div>
              <div className="label">{tr(c.name)}</div>
              <div className="count">{countLabel(countFor(c.id))}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { CatalogPage, LinesPage });
