/* ============================================================
   GlowMerald — Shop (filter, sort, grid)
   ============================================================ */
const { useState:useStateS, useEffect:useEffectS } = React;

function ShopPage(){
  const [types,setTypes] = useStateS([]);
  const [concerns,setConcerns] = useStateS([]);
  const [maxPrice,setMaxPrice] = useStateS(1300000);
  const [sort,setSort] = useStateS('best');
  const [loading,setLoading] = useStateS(true);
  const [filterOpen,setFilterOpen] = useStateS(false);

  useEffectS(()=>{ setLoading(true); const t=setTimeout(()=>setLoading(false),650); return ()=>clearTimeout(t); },[types,concerns,maxPrice,sort]);

  const toggle = (arr,set,v)=> set(arr.includes(v)?arr.filter(x=>x!==v):[...arr,v]);

  let items = ALL_ITEMS.filter(p=>{
    if(types.length && !types.includes(p.type)) return false;
    if(p.price>maxPrice) return false;
    if(concerns.length && !concerns.some(c=>(p.concerns||[]).includes(c))) return false;
    return true;
  });
  items = [...items].sort((a,b)=>{
    if(sort==='low') return a.price-b.price;
    if(sort==='new') return ALL_ITEMS.indexOf(b)-ALL_ITEMS.indexOf(a);
    return (b.bestSeller?1:0)-(a.bestSeller?1:0) || b.rating-a.rating;
  });

  const clearAll = ()=>{ setTypes([]); setConcerns([]); setMaxPrice(1300000); };
  const activeCount = types.length+concerns.length+(maxPrice<1300000?1:0);

  const FilterPanel = (
    <div className="filter-panel">
      <div className="filter-block">
        <h4>Tipe Produk</h4>
        {TYPES.map(t=>(
          <label key={t} className="check"><input type="checkbox" checked={types.includes(t)} onChange={()=>toggle(types,setTypes,t)}/><span className="box"></span>{t}</label>
        ))}
      </div>
      <div className="filter-block">
        <h4>Kebutuhan Kulit</h4>
        {CONCERNS.map(c=>(
          <label key={c} className="check"><input type="checkbox" checked={concerns.includes(c)} onChange={()=>toggle(concerns,setConcerns,c)}/><span className="box"></span>{c}</label>
        ))}
      </div>
      <div className="filter-block">
        <h4>Harga Maksimum</h4>
        <input type="range" min="70000" max="1300000" step="5000" value={maxPrice} onChange={e=>setMaxPrice(+e.target.value)} className="range"/>
        <div className="muted" style={{ fontSize:'.8rem', marginTop:8 }}>Hingga {formatRp(maxPrice)}</div>
      </div>
      {activeCount>0 && <button className="link-gold" onClick={clearAll} style={{ marginTop:8 }}>Reset Filter</button>}
    </div>
  );

  return (
    <div>
      <div className="page-head">
        <div className="container">
          <div className="eyebrow">Shop</div>
          <h1 style={{ fontSize:'clamp(2rem,6vw,3rem)' }}>Koleksi GlowMerald</h1>
          <p className="muted" style={{ maxWidth:520 }}>Serum, masker, dan bundle — diformulasikan untuk ritual yang efisien dan terasa premium.</p>
        </div>
      </div>

      <div className="container shop-layout">
        <aside className="shop-aside">{FilterPanel}</aside>

        <div className="shop-main">
          <div className="shop-toolbar">
            <button className="btn btn-ghost btn-sm filter-toggle" onClick={()=>setFilterOpen(true)}>
              <Icon name="filter" size={16}/> Filter {activeCount>0 && <span className="t-count">{activeCount}</span>}
            </button>
            <span className="muted" style={{ fontSize:'.82rem' }}>{loading?'…':items.length} produk</span>
            <label className="sort-select">
              <span className="muted" style={{ fontSize:'.74rem', letterSpacing:'.1em', textTransform:'uppercase' }}>Urutkan</span>
              <select value={sort} onChange={e=>setSort(e.target.value)}>
                <option value="best">Best Seller</option>
                <option value="low">Harga Terendah</option>
                <option value="new">Terbaru</option>
              </select>
            </label>
          </div>

          {loading ? (
            <div className="grid grid-3">{[0,1,2,3,4,5].map(i=><SkeletonCard key={i}/>)}</div>
          ) : items.length===0 ? (
            <div className="center" style={{ padding:'60px 0' }}>
              <p className="ital muted" style={{ fontSize:'1.2rem' }}>Tidak ada produk yang cocok dengan filter.</p>
              <button className="btn btn-ghost" onClick={clearAll}>Reset Filter</button>
            </div>
          ) : (
            <div className="grid grid-3">{items.map(p=><ProductCard key={p.id} item={p}/>)}</div>
          )}
        </div>
      </div>

      {filterOpen && (
        <div className="drawer-overlay" onClick={()=>setFilterOpen(false)} style={{ alignItems:'flex-end', display:'flex' }}>
          <div className="filter-sheet" onClick={e=>e.stopPropagation()}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:18 }}>
              <h3 className="serif" style={{ fontSize:'1.3rem' }}>Filter</h3>
              <button onClick={()=>setFilterOpen(false)} style={{ background:'none', border:0, color:'var(--ink)' }}><Icon name="close" size={22}/></button>
            </div>
            {FilterPanel}
            <button className="btn btn-gold btn-block" style={{ marginTop:20 }} onClick={()=>setFilterOpen(false)}>Lihat {items.length} Produk</button>
          </div>
        </div>
      )}
    </div>
  );
}

window.ShopPage = ShopPage;
