/* ============================================================ SHOP ============================================================ */
function Breadcrumb({ items }){
  const { go } = useContext(Nav);
  return (
    <div className="crumb wrap">
      {items.map((it,i)=>(
        <span key={i} className="crumb__item">
          {it.page ? <a href={rrRouteHref(it.page,it.params)} onClick={(e)=>{ e.preventDefault(); go(it.page,it.params); }}>{it.label}</a> : <span>{it.label}</span>}
          {i<items.length-1 && <Icon name="chevR" size={13}/>}
        </span>
      ))}
    </div>
  );
}

function ShopPage({ params={} }){
  const [cats,setCats] = useState(params.cat ? [params.cat] : []);
  const [purps,setPurps] = useState(params.purpose ? [params.purpose] : []);
  const [maxPrice,setMaxPrice] = useState(20000);
  const [sort,setSort] = useState('featured');
  const [openFilter,setOpenFilter] = useState(false);

  useEffect(()=>{
    setCats(params.cat?[params.cat]:[]);
    setPurps(params.purpose?[params.purpose]:[]);
  },[params.cat,params.purpose]);

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

  let list = RR.PRODUCTS.filter(p=>
    (cats.length===0 || cats.includes(p.cat)) &&
    (purps.length===0 || p.purposes.some(x=>purps.includes(x))) &&
    p.price<=maxPrice
  );
  if(sort==='low') list=[...list].sort((a,b)=>a.price-b.price);
  if(sort==='high') list=[...list].sort((a,b)=>b.price-a.price);
  if(sort==='purpose') list=[...list].sort((a,b)=>a.name.localeCompare(b.name));

  const activeCount = cats.length+purps.length+(maxPrice<20000?1:0);
  const clearAll=()=>{ setCats([]); setPurps([]); setMaxPrice(20000); };

  const Filters = (
    <div className="filters">
      <div className="filters__group">
        <h4>Category</h4>
        {RR.CATEGORIES.map(c=>(
          <label key={c.id} className="fcheck">
            <input type="checkbox" checked={cats.includes(c.id)} onChange={()=>toggle(cats,setCats,c.id)}/>
            <span className="fcheck__box"><Icon name="check" size={13}/></span>
            <span className="fcheck__lbl">{c.label}</span>
            <span className="fcheck__count">{RR.PRODUCTS.filter(p=>p.cat===c.id).length}</span>
          </label>
        ))}
      </div>
      <div className="filters__group">
        <h4>Purpose · <span className="deva">संकल्प</span></h4>
        {RR.PURPOSES.map(pp=>(
          <label key={pp.id} className="fcheck">
            <input type="checkbox" checked={purps.includes(pp.id)} onChange={()=>toggle(purps,setPurps,pp.id)}/>
            <span className="fcheck__box"><Icon name="check" size={13}/></span>
            <span className="fcheck__lbl">{pp.label}</span>
          </label>
        ))}
      </div>
      <div className="filters__group">
        <h4>Max price</h4>
        <input className="frange" type="range" min="500" max="20000" step="100" value={maxPrice} onChange={e=>setMaxPrice(+e.target.value)}/>
        <div className="frange__val">Up to <b>{RR.fmt(maxPrice)}</b></div>
      </div>
      <div className="filters__help card">
        <div className="row gap3" style={{ marginBottom:8 }}><span className="hf-ic" style={{ color:'var(--wa)' }}><WaGlyph size={18}/></span><b style={{ color:'var(--maroon-ink)' }}>Need help choosing?</b></div>
        <p className="muted" style={{ fontSize:13.5, marginBottom:12 }}>Tell us your purpose — we'll recommend the right piece, free.</p>
        <a className="btn btn-wa btn-sm btn-block" href={RR.wa("Hi Rudraa Ratna, please help me choose a product.")} target="_blank" rel="noopener"><WaGlyph size={15}/> Ask on WhatsApp</a>
      </div>
    </div>
  );

  return (
    <main>
      <Breadcrumb items={[{label:'Home',page:'home'},{label:'Shop'}]}/>
      <div className="wrap shop">
        <header className="shop__head">
          <div>
            <span className="eyebrow">The Collection · <span className="deva">संग्रह</span></span>
            <h1 className="h1" style={{ marginTop:10 }}>Spiritual products, chosen with care</h1>
            <p className="muted mt2">Authentic Rudraksha, gemstones, crystals & Vastu — filter by purpose to find your fit.</p>
          </div>
        </header>

        <div className="shop__bar">
          <button className="btn btn-ghost btn-sm shop__filterbtn" onClick={()=>setOpenFilter(true)}><Icon name="filter" size={16}/> Filters {activeCount>0 && <span className="shop__fcount">{activeCount}</span>}</button>
          <div className="shop__count"><b>{list.length}</b> products</div>
          <div className="shop__sort">
            <label>Sort</label>
            <select className="select" value={sort} onChange={e=>setSort(e.target.value)}>
              <option value="featured">Featured</option>
              <option value="low">Price: Low to High</option>
              <option value="high">Price: High to Low</option>
              <option value="purpose">Name: A to Z</option>
            </select>
          </div>
        </div>

        {activeCount>0 && (
          <div className="shop__active">
            {cats.map(c=><button key={c} className="chip" onClick={()=>toggle(cats,setCats,c)}>{RR.CATEGORIES.find(x=>x.id===c).label} <Icon name="close" size={13}/></button>)}
            {purps.map(p=><button key={p} className="chip" onClick={()=>toggle(purps,setPurps,p)}>{RR.purpose(p).label} <Icon name="close" size={13}/></button>)}
            {maxPrice<20000 && <button className="chip" onClick={()=>setMaxPrice(20000)}>≤ {RR.fmt(maxPrice)} <Icon name="close" size={13}/></button>}
            <button className="shop__clear" onClick={clearAll}>Clear all</button>
          </div>
        )}

        <div className="shop__layout">
          <aside className="shop__aside">{Filters}</aside>
          <div>
            {list.length>0 ? (
              <div className="prod-grid shop__grid" key={cats.join()+purps.join()+sort+maxPrice}>
                {list.map((p,i)=><ProductCard key={p.id} p={p} delay={Math.min(i*0.04,0.3)}/>)}
              </div>
            ) : (
              <div className="shop__empty card">
                <h3 className="h3">No matches — but we can still help.</h3>
                <p className="muted">Loosen a filter, or tell us what you're looking for and we'll source it.</p>
                <a className="btn btn-wa" href={RR.wa("Hi Rudraa Ratna, I'm looking for a specific product.")} target="_blank" rel="noopener"><WaGlyph/> Ask on WhatsApp</a>
              </div>
            )}
          </div>
        </div>
      </div>

      <CrystalGuideSection/>
      <BeforeYouBuySection/>
      <PageAnswers page="shop"/>
      <TrustDisclaimer/>

      {/* mobile filter sheet */}
      <div className={`fsheet ${openFilter?'is-open':''}`}>
        <div className="fsheet__bg" onClick={()=>setOpenFilter(false)}/>
        <div className="fsheet__panel">
          <div className="fsheet__top"><h3 className="h3">Filters</h3><button className="rr-icbtn" onClick={()=>setOpenFilter(false)}><Icon name="close" size={24}/></button></div>
          <div className="fsheet__body">{Filters}</div>
          <div className="fsheet__foot">
            <button className="btn btn-ghost" onClick={clearAll}>Clear</button>
            <button className="btn btn-maroon btn-block" onClick={()=>setOpenFilter(false)}>Show {list.length} products</button>
          </div>
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { ShopPage, Breadcrumb });
