// ============================================================
// Shop page — full catalog with filters (category, material,
// collection, price) and sort. Mobile keeps filters in a
// collapsible drawer.
// ============================================================

function JmShop({ lang, initialCategory = 'all', onOpenProduct, onAdd }) {
  const t = JM.t[lang];

  const [cat, setCat]               = React.useState(initialCategory);
  const [material, setMaterial]     = React.useState('all');
  const [collection, setCollection] = React.useState('all');
  const priceCap = Math.ceil(Math.max(...JM.products.map(p => p.price), 100000) / 50000) * 50000;
  const [maxPrice, setMaxPrice]     = React.useState(priceCap);
  const [sort, setSort]             = React.useState('featured');
  const [filtersOpen, setFiltersOpen] = React.useState(false);

  React.useEffect(() => { setCat(initialCategory); }, [initialCategory]);
  React.useEffect(() => { if (window.lucide) lucide.createIcons(); });

  const filtered = React.useMemo(() => {
    let list = JM.products.slice();
    if (cat !== 'all')        list = list.filter(p => p.category === cat);
    if (material !== 'all')   list = list.filter(p => p.material === material);
    if (collection !== 'all') list = list.filter(p => JM.inCollection(p, collection));
    list = list.filter(p => p.price <= maxPrice);

    if (sort === 'featured')  list.sort(JM.featuredSort);
    if (sort === 'priceAsc')  list.sort((a,b) => a.price - b.price);
    if (sort === 'priceDesc') list.sort((a,b) => b.price - a.price);
    if (sort === 'new')       list.sort((a,b) => (a.badge === 'Mới' ? -1 : 1) - (b.badge === 'Mới' ? -1 : 1));
    return list;
  }, [cat, material, collection, maxPrice, sort]);

  return (
    <div data-screen-label="Shop">
      {/* Title block */}
      <section className="jm-shop__hero">
        <div className="jm-container">
          <div className="jm-label" style={{ color: 'var(--jm-cam-dat)' }}>{lang === 'vi' ? 'Cửa hàng' : 'Shop'}</div>
          <h1 className="jm-h1" style={{ marginTop: 12 }}>
            {lang === 'vi' ? 'Mỗi món, một dấu ấn' : 'Each piece, a mark'}
          </h1>
          <p className="jm-small" style={{ maxWidth: 540, marginTop: 16 }}>
            {lang === 'vi'
              ? `${JM.products.length} thiết kế đang mở bán. Đổi mới trong 15 ngày.`
              : `${JM.products.length} designs available. 15-day exchange.`}
          </p>
        </div>
      </section>

      <div className="jm-container jm-shop__main">
        {/* Sidebar */}
        <aside className={`jm-shop__side ${filtersOpen ? 'is-open' : ''}`}>
          <div className="jm-shop__side-head">
            <span className="jm-label">{t['shop.filter']}</span>
            <button className="jm-icon-btn jm-shop__side-close" onClick={() => setFiltersOpen(false)} aria-label="Đóng">
              <i data-lucide="x" className="jm-icon"></i>
            </button>
          </div>

          <FilterGroup title={lang === 'vi' ? 'Loại trang sức' : 'Category'}>
            {JM.categories.map(c => (
              <FilterRadio key={c.id} checked={cat === c.id} label={lang === 'vi' ? c.vi : c.en} onSelect={() => setCat(c.id)}/>
            ))}
          </FilterGroup>

          <FilterGroup title={t['filter.material']}>
            <FilterRadio checked={material === 'all'} label={lang === 'vi' ? 'Tất cả' : 'All'} onSelect={() => setMaterial('all')}/>
            {JM.materials.map(m => (
              <FilterRadio key={m.id} checked={material === m.id} label={lang === 'vi' ? m.vi : m.en} onSelect={() => setMaterial(m.id)}/>
            ))}
          </FilterGroup>

          <FilterGroup title={t['filter.collection']}>
            <FilterRadio checked={collection === 'all'} label={lang === 'vi' ? 'Tất cả' : 'All'} onSelect={() => setCollection('all')}/>
            {JM.collections.filter(c => c.pieces > 0).map(c => (
              <FilterRadio key={c.id} checked={collection === c.id} label={lang === 'vi' ? c.name : c.en} onSelect={() => setCollection(c.id)}/>
            ))}
          </FilterGroup>

          <FilterGroup title={t['filter.price']}>
            <div className="jm-shop__range">
              <input
                type="range"
                min={100000} max={priceCap} step={10000}
                value={maxPrice}
                onChange={e => setMaxPrice(Number(e.target.value))}
                aria-label={t['filter.price']}
              />
              <div className="jm-shop__range-labels">
                <span className="jm-small">100.000đ</span>
                <span className="jm-label" style={{ color: 'var(--jm-cam-dat)' }}>≤ {JM.formatPrice(maxPrice)}</span>
              </div>
            </div>
          </FilterGroup>
        </aside>

        {/* Main */}
        <div className="jm-shop__list">
          <div className="jm-shop__toolbar">
            <button className="jm-shop__filters-toggle" onClick={() => setFiltersOpen(true)}>
              <i data-lucide="sliders-horizontal" className="jm-icon jm-icon-sm"></i>
              <span className="jm-label">{t['shop.filter']}</span>
            </button>
            <span className="jm-small jm-shop__count">{filtered.length} {t['shop.results']}</span>
            <div className="jm-shop__sort">
              <label className="jm-label" htmlFor="jm-sort">{t['shop.sort']}</label>
              <select id="jm-sort" className="jm-input jm-input--select" value={sort} onChange={e => setSort(e.target.value)}>
                <option value="featured">{t['sort.featured']}</option>
                <option value="priceAsc">{t['sort.priceAsc']}</option>
                <option value="priceDesc">{t['sort.priceDesc']}</option>
                <option value="new">{t['sort.new']}</option>
              </select>
            </div>
          </div>

          {filtered.length === 0 ? (
            <div className="jm-shop__empty">
              <i data-lucide="search" className="jm-icon jm-icon-lg" style={{ color: 'var(--jm-muted)' }}></i>
              <p className="jm-body" style={{ marginTop: 16 }}>
                {lang === 'vi' ? 'Không có sản phẩm phù hợp. Thử bớt một bộ lọc?' : 'No matches. Try removing a filter.'}
              </p>
            </div>
          ) : (
            <div className="jm-grid jm-grid--shop">
              {filtered.map(p => (
                <JmProductCard key={p.id} product={p} lang={lang} onOpen={onOpenProduct} onAdd={onAdd}/>
              ))}
            </div>
          )}
        </div>
      </div>

      {filtersOpen && <div className="jm-scrim is-open" onClick={() => setFiltersOpen(false)}></div>}
    </div>
  );
}

function FilterGroup({ title, children }) {
  return (
    <div className="jm-shop__group">
      <div className="jm-shop__group-title">{title}</div>
      <div className="jm-shop__group-body">{children}</div>
    </div>
  );
}

function FilterRadio({ checked, label, onSelect }) {
  return (
    <button className={`jm-filter-radio ${checked ? 'is-active' : ''}`} onClick={onSelect}>
      <span className="jm-filter-radio__dot" aria-hidden="true"></span>
      <span>{label}</span>
    </button>
  );
}

window.JmShop = JmShop;
