// Shop (collection) page with filter + sort

const ShopPage = () => {
  const { route, setRoute } = useApp();
  const initCat = route.params?.cat || 'all';
  const [cat, setCat] = React.useState(initCat);
  const [sort, setSort] = React.useState('featured');
  const [view, setView] = React.useState('grid4');
  const [colorFilter, setColorFilter] = React.useState([]);
  const [sizeFilter, setSizeFilter] = React.useState([]);
  const [priceMax, setPriceMax] = React.useState(6000);
  const [openMobile, setOpenMobile] = React.useState(false);

  React.useEffect(() => { setCat(route.params?.cat || 'all'); }, [route.params?.cat]);

  const items = React.useMemo(() => {
    let list = [...PRODUCTS];
    if (cat === 'friday') list = list.filter(p => p.tag === 'FRIDAY DROP');
    else if (cat === 'new')    list = list.filter(p => p.tag === 'NEW' || p.tag === 'FRIDAY DROP');
    else if (cat !== 'all')    list = list.filter(p => p.cat === cat);
    if (colorFilter.length) list = list.filter(p => p.colors.some(c => colorFilter.includes(c)));
    if (sizeFilter.length)  list = list.filter(p => p.sizes.some(s => sizeFilter.includes(s)));
    list = list.filter(p => p.price <= priceMax);
    if (sort === 'low')   list.sort((a,b) => a.price - b.price);
    if (sort === 'high')  list.sort((a,b) => b.price - a.price);
    if (sort === 'new')   list.sort((a,b) => b.id.localeCompare(a.id));
    return list;
  }, [cat, sort, colorFilter, sizeFilter, priceMax]);

  const current = CATEGORIES.find(c => c.slug === cat);
  const title = cat === 'all' ? 'All Products' : (current?.name || 'Shop');
  const zh = cat === 'all' ? '全部商品' : current?.zh || '';

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

  const Filters = () => (
    <aside style={{ width: 240, flexShrink: 0 }}>
      <div style={{ marginBottom: 32 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>Category</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <button onClick={() => setCat('all')} style={{ textAlign: 'left', padding: '6px 0', fontSize: 13, color: cat === 'all' ? 'var(--ink)' : 'var(--mute)', fontWeight: cat === 'all' ? 600 : 400 }}>
            全部 <span style={{ color: 'var(--mute-2)', fontFamily: 'var(--f-mono)', fontSize: 11, marginLeft: 4 }}>{PRODUCTS.length}</span>
          </button>
          {CATEGORIES.map(c => {
            const n = c.slug === 'friday' ? PRODUCTS.filter(p => p.tag === 'FRIDAY DROP').length
                    : c.slug === 'new' ? PRODUCTS.filter(p => p.tag === 'NEW' || p.tag === 'FRIDAY DROP').length
                    : PRODUCTS.filter(p => p.cat === c.slug).length;
            return (
              <button key={c.slug} onClick={() => setCat(c.slug)}
                style={{ textAlign: 'left', padding: '6px 0', fontSize: 13, color: cat === c.slug ? 'var(--ink)' : 'var(--mute)', fontWeight: cat === c.slug ? 600 : 400 }}>
                {c.name} <span style={{ color: 'var(--mute-2)', fontFamily: 'var(--f-mono)', fontSize: 11, marginLeft: 4 }}>{n}</span>
              </button>
            );
          })}
        </div>
      </div>
      <div style={{ marginBottom: 32 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>Color</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {COLORS.map(c => (
            <button key={c.n} onClick={() => toggle(colorFilter, c.n, setColorFilter)}
              className={cx('swatch', colorFilter.includes(c.n) && 'active')}
              style={{ background: c.v, width: 24, height: 24 }} title={c.n}/>
          ))}
        </div>
      </div>
      <div style={{ marginBottom: 32 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>Size</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {SIZES.map(s => (
            <button key={s} onClick={() => toggle(sizeFilter, s, setSizeFilter)}
              className={cx('chip', sizeFilter.includes(s) && 'active')}
              style={{ minWidth: 36, height: 32, fontSize: 11 }}>{s}</button>
          ))}
        </div>
      </div>
      <div style={{ marginBottom: 32 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>Price</div>
        <input type="range" min={500} max={6000} step={100} value={priceMax} onChange={e => setPriceMax(+e.target.value)}
          style={{ width: '100%', accentColor: 'var(--ink)' }}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--f-mono)', fontSize: 11, color: 'var(--mute)', marginTop: 6 }}>
          <span>NT$500</span><span style={{ color: 'var(--ink)' }}>≤ NT${priceMax.toLocaleString()}</span>
        </div>
      </div>
      {(colorFilter.length > 0 || sizeFilter.length > 0 || priceMax < 6000) && (
        <button className="btn ghost sm" style={{ width: '100%' }}
          onClick={() => { setColorFilter([]); setSizeFilter([]); setPriceMax(6000); }}>
          Clear all filters
        </button>
      )}
    </aside>
  );

  return (
    <>
      <Breadcrumb items={[
        { label: 'Home', onClick: () => setRoute('home') },
        { label: 'Shop', onClick: () => setRoute('shop') },
        ...(cat !== 'all' ? [{ label: current?.name || '' }] : [])
      ]}/>
      <section style={{ padding: '8px 0 40px' }}>
        <div className="container-wide">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', flexWrap: 'wrap', gap: 16 }}>
            <div>
              <div className="eyebrow">Collection · SS26</div>
              <h1 className="display" style={{ fontSize: 'clamp(40px, 6vw, 72px)', marginTop: 8 }}>{title}</h1>
              {zh && <div style={{ fontSize: 14, color: 'var(--mute)', marginTop: 4 }}>{zh}</div>}
            </div>
            <div style={{ fontFamily: 'var(--f-mono)', fontSize: 11, color: 'var(--mute)', letterSpacing: '0.08em' }}>
              {items.length} PRODUCTS
            </div>
          </div>
        </div>
      </section>

      <section style={{ paddingBottom: 80 }}>
        <div className="container-wide" style={{ display: 'flex', gap: 48 }} className2="shop-layout">
          <div className="shop-aside" style={{ display: 'block' }}><Filters/></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)', marginBottom: 24 }}>
              <button className="btn ghost sm shop-mfilter" onClick={() => setOpenMobile(true)} style={{ display: 'none' }}>
                <IconFilter size={14}/> Filters
              </button>
              <div style={{ fontFamily: 'var(--f-mono)', fontSize: 11, color: 'var(--mute)', letterSpacing: '0.08em' }}>
                SHOWING {items.length}
              </div>
              <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
                <div style={{ display: 'flex', gap: 4 }}>
                  <button onClick={() => setView('grid4')} style={{ padding: 6, opacity: view === 'grid4' ? 1 : 0.35 }} aria-label="4 col">
                    <IconGrid size={14}/>
                  </button>
                  <button onClick={() => setView('grid3')} style={{ padding: 6, opacity: view === 'grid3' ? 1 : 0.35, fontSize: 11, fontFamily: 'var(--f-mono)' }}>III</button>
                </div>
                <select value={sort} onChange={e => setSort(e.target.value)}
                  style={{ height: 32, border: '1px solid var(--line-2)', padding: '0 10px', fontSize: 11, fontFamily: 'var(--f-mono)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                  <option value="featured">FEATURED</option>
                  <option value="new">NEWEST</option>
                  <option value="low">PRICE ↑</option>
                  <option value="high">PRICE ↓</option>
                </select>
              </div>
            </div>

            {items.length === 0 ? (
              <div style={{ padding: 80, textAlign: 'center', color: 'var(--mute)' }}>
                <div style={{ fontSize: 16, marginBottom: 12 }}>沒有符合條件的商品</div>
                <button className="btn ghost sm" onClick={() => { setColorFilter([]); setSizeFilter([]); setPriceMax(6000); setCat('all'); }}>Reset</button>
              </div>
            ) : (
              <div style={{ display: 'grid', gridTemplateColumns: view === 'grid4' ? 'repeat(4, 1fr)' : 'repeat(3, 1fr)', gap: 24 }} className="shop-grid">
                {items.map(p => <ProductCard key={p.id} p={p}/>)}
              </div>
            )}
          </div>
        </div>
        <style>{`
          @media (max-width: 900px) {
            .shop-aside { display: none !important; }
            .shop-mfilter { display: inline-flex !important; }
            .shop-grid { grid-template-columns: repeat(2, 1fr) !important; gap: 16px !important; }
          }
        `}</style>
      </section>

      {openMobile && (
        <>
          <div className="drawer-backdrop open" onClick={() => setOpenMobile(false)}/>
          <aside className="drawer open" style={{ left: 0, right: 'auto', transform: 'translateX(0)' }}>
            <div className="drawer-head"><h3>Filters</h3><button onClick={() => setOpenMobile(false)}><IconClose/></button></div>
            <div className="drawer-body"><Filters/></div>
            <div className="drawer-foot"><button className="btn full" onClick={() => setOpenMobile(false)}>Show {items.length} products</button></div>
          </aside>
        </>
      )}
    </>
  );
};

Object.assign(window, { ShopPage });
