// Shop page — filters sidebar + adjustable column grid + sort.

const { useI18n, fmtNum, fmtPrice } = window.RBI18n;
const { Reveal } = window.RBAnim;
const { ProductCard } = window.RBHome;
const { Swatch, ProductImg } = window.RBImg;
const { IconFilter, IconGrid, IconList, IconX, IconChevD } = window.RBIcons;

// Column-count selector (1/2/3 on mobile, 2/3/4 desktop)
const ColumnSelector = ({ cols, setCols, lang }) => {
  // Icon = small grid of squares matching count
  const Icon = ({ n }) => (
    <svg width="22" height="14" viewBox="0 0 22 14" fill="none" aria-hidden="true">
      {Array.from({ length: n }).map((_, i) => {
        const w = (22 - (n + 1) * 1.5) / n;
        return (
          <rect key={i}
                x={1.5 + i * (w + 1.5)}
                y="1.5"
                width={w}
                height="11"
                fill="currentColor"
                rx="0.5"/>
        );
      })}
    </svg>
  );
  const opts = [1,2,3];
  return (
    <div className="inline-flex items-center gap-2">
      <span className="text-[10px] text-ink-mute tracking-[0.25em] uppercase hidden md:inline">
        {lang === 'ar' ? 'عرض' : 'View'}
      </span>
      <div className="inline-flex items-center border hairline">
        {opts.map(n => (
          <button key={n} onClick={() => setCols(n)} aria-label={`${n} columns`}
                  className={`px-2.5 py-2 border-s first:border-s-0 hairline transition
                              ${cols === n ? 'bg-ink text-paper' : 'text-ink-mute hover:text-ink'}`}>
            <Icon n={n}/>
          </button>
        ))}
      </div>
    </div>
  );
};

const ShopPage = ({ initialCat }) => {
  const { t, lang } = useI18n();
  const [cat, setCat] = React.useState(initialCat || 'all');
  const [openMobileFilter, setOpenMobileFilter] = React.useState(false);
  // mobile columns (1-3), desktop columns (2-4) — single value for simplicity, desktop adds +1
  const [cols, setCols] = React.useState(2);
  const [sort, setSort] = React.useState('featured');
  const [priceMax, setPriceMax] = React.useState(700);
  const [selSizes, setSelSizes] = React.useState([]);
  const [selColors, setSelColors] = React.useState([]);
  React.useEffect(() => { setCat(initialCat || 'all'); }, [initialCat]);

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

  let list = window.RB.PRODUCTS.filter(p => cat === 'all' || p.cat === cat);
  list = list.filter(p => p.price <= priceMax);
  if (sort === 'price_asc')  list = [...list].sort((a,b) => a.price - b.price);
  if (sort === 'price_desc') list = [...list].sort((a,b) => b.price - a.price);

  const currentCatTitle = cat === 'all'
    ? (lang === 'ar' ? 'كل المنتجات' : 'All products')
    : (window.RB.CATEGORIES.find(c => c.id === cat)?.[lang] || '');

  // Build the grid class based on selected column count
  const gridClass = {
    1: 'grid-cols-1 md:grid-cols-2',
    2: 'grid-cols-2 md:grid-cols-3',
    3: 'grid-cols-3 md:grid-cols-4'
  }[cols] || 'grid-cols-2 md:grid-cols-3';

  const Sidebar = ({ inDrawer = false }) => (
    <aside className={inDrawer ? 'p-6 space-y-7' : 'space-y-7 sticky top-28'}>
      <div>
        <h4 className="ff-serif text-xl mb-3">{t('shop.cat')}</h4>
        <div className="space-y-1 text-sm">
          <button onClick={() => setCat('all')}
                  className={`flex items-center justify-between w-full py-1.5 transition ${cat==='all' ? 'text-rose-500 font-medium' : 'text-ink-soft hover:text-ink'}`}>
            <span>{lang==='ar'?'الكل':'All'}</span>
            <span className="text-xs text-ink-mute ltr-nums">{fmtNum(window.RB.PRODUCTS.length, lang)}</span>
          </button>
          {window.RB.CATEGORIES.map(c => (
            <button key={c.id} onClick={() => setCat(c.id)}
                    className={`flex items-center justify-between w-full py-1.5 transition ${cat===c.id ? 'text-rose-500 font-medium' : 'text-ink-soft hover:text-ink'}`}>
              <span>{c[lang]}</span>
              <span className="text-xs text-ink-mute ltr-nums">{fmtNum(c.count, lang)}</span>
            </button>
          ))}
        </div>
      </div>

      <div>
        <h4 className="ff-serif text-xl mb-3">{t('shop.price')}</h4>
        <input type="range" min="50" max="700" step="10" value={priceMax}
               onChange={(e) => setPriceMax(+e.target.value)}
               className="w-full accent-rose-500"/>
        <div className="flex items-center justify-between text-xs text-ink-mute mt-2 ltr-nums">
          <span>{fmtPrice(50, lang)}</span>
          <span className="text-ink font-medium">{lang==='ar'?'حتى':'up to'} {fmtPrice(priceMax, lang)}</span>
        </div>
      </div>

      <div>
        <h4 className="ff-serif text-xl mb-3">{t('shop.size')}</h4>
        <div className="grid grid-cols-5 gap-1.5">
          {window.RB.SIZE_OPTS.map(s => (
            <button key={s} onClick={() => toggle(selSizes, setSelSizes, s)}
                    className={`text-xs py-2 border transition
                      ${selSizes.includes(s) ? 'border-ink bg-ink text-paper' : 'border-ink/15 hover:border-ink text-ink'}`}>
              {s}
            </button>
          ))}
        </div>
      </div>

      <div>
        <h4 className="ff-serif text-xl mb-3">{t('shop.color')}</h4>
        <div className="flex flex-wrap gap-2.5">
          {window.RB.COLOR_OPTS.map(c => (
            <button key={c.id} onClick={() => toggle(selColors, setSelColors, c.id)}
                    className="group flex flex-col items-center gap-1" title={c[lang]}>
              <Swatch hex={c.hex} size={22} ring={selColors.includes(c.id)}/>
              <span className="text-[10px] text-ink-mute group-hover:text-ink">{c[lang]}</span>
            </button>
          ))}
        </div>
      </div>

      <button onClick={() => { setCat('all'); setPriceMax(700); setSelSizes([]); setSelColors([]); }}
              className="text-xs text-ink-mute hover:text-rose-500 underline underline-offset-4">
        {t('shop.clear')}
      </button>
    </aside>
  );

  return (
    <main className="bg-paper page-fade">
      <div className="bg-paper-warm border-b hairline">
        <div className="max-w-[1480px] mx-auto px-5 md:px-10 py-8 md:py-12">
          <nav className="text-xs text-ink-mute mb-2 flex items-center gap-2">
            <a href="#" onClick={(e)=>{e.preventDefault();window.RBNav.go('home')}} className="hover:text-ink">{t('shop.crumb_home')}</a>
            <span>/</span>
            <span className="text-ink">{currentCatTitle}</span>
          </nav>
          <Reveal>
            <h1 className="ff-serif text-4xl md:text-6xl text-ink">{currentCatTitle}</h1>
            <p className="text-sm text-ink-soft mt-2 ltr-nums">{fmtNum(list.length, lang)} {t('shop.products_n')}</p>
          </Reveal>
        </div>
      </div>

      <div className="max-w-[1480px] mx-auto px-5 md:px-10 py-8 md:py-12">
        <div className="grid md:grid-cols-[220px_1fr] gap-7 md:gap-12">
          <div className="hidden md:block"><Sidebar/></div>

          <div>
            <div className="flex items-center justify-between gap-3 mb-5 pb-3 border-b hairline flex-wrap">
              <div className="flex items-center gap-3">
                <button onClick={() => setOpenMobileFilter(true)}
                        className="md:hidden flex items-center gap-2 text-xs border hairline px-3 py-2">
                  <IconFilter size={14}/> {t('shop.filters')}
                </button>
                <ColumnSelector cols={cols} setCols={setCols} lang={lang}/>
              </div>
              <div className="flex items-center gap-3 text-sm">
                <span className="text-ink-mute hidden md:inline text-[10px] tracking-[0.25em] uppercase">{t('shop.sort')}</span>
                <select value={sort} onChange={(e) => setSort(e.target.value)}
                        className="border hairline py-2 pr-3 pl-9 text-sm bg-paper focus:border-ink outline-none">
                  <option value="featured">{lang==='ar'?'المميّز':'Featured'}</option>
                  <option value="new">{lang==='ar'?'الأحدث':'Newest'}</option>
                  <option value="price_asc">{lang==='ar'?'السعر: من الأقل':'Price: low to high'}</option>
                  <option value="price_desc">{lang==='ar'?'السعر: من الأعلى':'Price: high to low'}</option>
                  <option value="best">{lang==='ar'?'الأكثر مبيعاً':'Best selling'}</option>
                </select>
              </div>
            </div>

            {(selSizes.length || selColors.length || cat !== 'all') ? (
              <div className="flex flex-wrap gap-2 mb-5 text-xs">
                {cat !== 'all' && (
                  <span className="inline-flex items-center gap-1.5 bg-paper-warm border hairline px-3 py-1.5">
                    {currentCatTitle}
                    <button onClick={() => setCat('all')} className="hover:text-rose-500"><IconX size={12}/></button>
                  </span>
                )}
                {selSizes.map(s => (
                  <span key={s} className="inline-flex items-center gap-1.5 bg-paper-warm border hairline px-3 py-1.5">
                    {s} <button onClick={() => toggle(selSizes, setSelSizes, s)} className="hover:text-rose-500"><IconX size={12}/></button>
                  </span>
                ))}
                {selColors.map(c => (
                  <span key={c} className="inline-flex items-center gap-1.5 bg-paper-warm border hairline px-3 py-1.5">
                    {window.RB.COLOR_OPTS.find(x=>x.id===c)?.[lang]}
                    <button onClick={() => toggle(selColors, setSelColors, c)} className="hover:text-rose-500"><IconX size={12}/></button>
                  </span>
                ))}
              </div>
            ) : null}

            <div className={`grid ${gridClass} gap-x-3 gap-y-8 md:gap-x-5 md:gap-y-12`}>
              {list.map((p, i) => (
                <Reveal key={p.id} delay={(i%6)*50}>
                  <ProductCard p={p}/>
                </Reveal>
              ))}
            </div>

            <div className="flex items-center justify-center gap-1 mt-12 ltr-nums">
              {[1,2,3,4,5].map(n => (
                <button key={n} className={`w-9 h-9 text-sm ${n===1 ? 'bg-ink text-paper' : 'text-ink-soft hover:bg-paper-warm'}`}>
                  {fmtNum(n, lang)}
                </button>
              ))}
              <button className="px-3 h-9 text-sm text-ink-soft hover:bg-paper-warm">{lang==='ar'?'التالي ←':'Next →'}</button>
            </div>
          </div>
        </div>
      </div>

      {openMobileFilter && (
        <div className="fixed inset-0 z-50 md:hidden">
          <div className="absolute inset-0 bg-ink/40" onClick={() => setOpenMobileFilter(false)}/>
          <div className="absolute inset-y-0 end-0 w-[88%] max-w-sm bg-paper overflow-y-auto">
            <div className="flex items-center justify-between p-5 border-b hairline sticky top-0 bg-paper z-10">
              <h3 className="ff-serif text-2xl">{t('shop.filters')}</h3>
              <button onClick={() => setOpenMobileFilter(false)}><IconX/></button>
            </div>
            <Sidebar inDrawer/>
            <div className="p-5 border-t hairline sticky bottom-0 bg-paper">
              <button onClick={() => setOpenMobileFilter(false)}
                      className="w-full bg-ink text-paper py-3.5 text-[11px] tracking-[0.3em] uppercase hover:bg-rose-500 transition">
                {t('shop.show')} {fmtNum(list.length, lang)} {t('shop.products_n')}
              </button>
            </div>
          </div>
        </div>
      )}
    </main>
  );
};

window.RBShop = { ShopPage };
