/* SUPERMEDIA storefront — Category / PLP with filters + sort
 * (povezano na prave podatke: filtrira po potkategoriji2 + dinamički filteri iz baze) */
const { useState: useStateCat } = React;

function CategoryPage({ slug, brand, potkat, potkat2, query, onNav, onAdd, onWish, wishlist, openProduct }) {
  const { CATEGORIES, BRANDS, PRODUCTS, FILTERS } = SM_DATA;
  const cat = CATEGORIES.find(c => c.slug === slug);
  const brandLogo = brand ? (window.BRAND_LOGOS || []).find(b => b.name.toLowerCase() === brand.toLowerCase()) : null;
  const isMobile = useIsMobile();
  const lc = (s) => (s == null ? '' : String(s).toLowerCase());
  // PRETRAGA: koristi zajedničku smSearch (aliasi ajfon→iphone, šifra proizvoda, typo tolerancija, rangiranje)
  const sHits = (query && window.smSearch) ? window.smSearch(query, 5000) : null;
  const sHitIds = sHits ? new Set(sHits.map(p => p.id)) : null;
  const sRank = {};
  if (sHits) sHits.forEach((p, i) => { sRank[p.id] = i; });

  const [sort, setSort] = useStateCat('reco');
  const [brandSel, setBrandSel] = useStateCat([]);
  const [catSel, setCatSel] = useStateCat([]);
  const [onlySale, setOnlySale] = useStateCat(false);
  const [priceMin, setPriceMin] = useStateCat(null);
  const [priceMax, setPriceMax] = useStateCat(null);
  const [dynSel, setDynSel] = useStateCat({});
  const [filtersOpen, setFiltersOpen] = useStateCat(false);
  const [page, setPage] = useStateCat(1);
  const PAGE_SIZE = 24;

  // dinamičke definicije filtera za aktivnu potkategoriju2 (ili potkategoriju)
  const F = FILTERS || { byPotkat2: {}, byPotkat: {} };
  const defs = potkat2 ? (F.byPotkat2[lc(potkat2)] || [])
    : potkat ? (F.byPotkat[lc(potkat)] || [])
    : [];

  // proizvodi u opsegu trenutne kategorije/podkategorije (bez brend/dyn/cena/akcija filtera) — za listu brendova i prisutne vrednosti
  const inScope = PRODUCTS.filter(p => {
    if (brand) return p.brand.toLowerCase() === brand.toLowerCase();
    if (slug && p.cat !== slug) return false;
    if (potkat2) { if (lc(p.potkat2) !== lc(potkat2)) return false; }
    else if (potkat) { if (lc(p.potkat) !== lc(potkat)) return false; }
    if (query && sHitIds && !sHitIds.has(p.id)) return false;
    return true;
  });

  // opseg cena IZ TRENUTNE kategorije (ne globalni katalog), otporan na ekstreme (97. percentil gore)
  const _prices = inScope.map(p => p.price || 0).filter(v => v > 0).sort((a, b) => a - b);
  const _pct = (q) => _prices.length ? _prices[Math.min(_prices.length - 1, Math.floor(q * (_prices.length - 1)))] : 0;
  const niceCeil = (v) => { const s = v <= 5000 ? 500 : v <= 50000 ? 1000 : v <= 200000 ? 5000 : v <= 1000000 ? 10000 : 50000; return Math.ceil(v / s) * s; };
  const PLO = Math.max(0, Math.floor((_prices[0] || 0) / 100) * 100);
  const PHI = Math.max(PLO + 100, niceCeil(_pct(0.97)));
  const effMin = priceMin != null ? priceMin : 0;
  const effMax = priceMax != null ? priceMax : Infinity;

  let list = inScope.slice();
  if (brandSel.length) list = list.filter(p => brandSel.includes(p.brand));
  if (catSel.length) list = list.filter(p => catSel.includes(p.cat));
  if (onlySale) list = list.filter(p => p.old != null);
  list = list.filter(p => p.price >= effMin && p.price <= effMax);
  // dinamički filteri (poredi sa p.filters[key])
  Object.keys(dynSel).forEach(key => {
    const vals = dynSel[key];
    if (!vals || !vals.length) return;
    list = list.filter(p => {
      const pv = p.filters && p.filters[key];
      return Array.isArray(pv) && pv.some(v => vals.includes(v));
    });
  });
  if (query && sort === 'reco' && sHits) list.sort((a, b) => (sRank[a.id] == null ? 1e9 : sRank[a.id]) - (sRank[b.id] == null ? 1e9 : sRank[b.id]));
  if (sort === 'asc') list.sort((a, b) => a.price - b.price);
  if (sort === 'desc') list.sort((a, b) => b.price - a.price);
  if (sort === 'az') list.sort((a, b) => a.title.localeCompare(b.title));
  if (sort === 'za') list.sort((a, b) => b.title.localeCompare(a.title));

  const totalPages = Math.max(1, Math.ceil(list.length / PAGE_SIZE));
  const curPage = Math.min(page, totalPages);
  const pageItems = list.slice((curPage - 1) * PAGE_SIZE, curPage * PAGE_SIZE);
  const goPage = (n) => { setPage(n); try { window.scrollTo({ top: 0, behavior: 'smooth' }); } catch (e) {} };

  const catBrands = [...new Set(inScope.map(p => p.brand))].sort((a, b) => a.localeCompare(b));
  const brandCats = brand ? [...new Set(PRODUCTS.filter(p => p.brand.toLowerCase() === brand.toLowerCase()).map(p => p.cat))] : [];
  const catTitle = (s) => { const c = CATEGORIES.find(x => x.slug === s); return c ? c.title : s; };
  const title = brand ? brand : query ? `Rezultati za „${query}”` : potkat2 ? potkat2 : potkat ? potkat : cat ? cat.title : 'Svi proizvodi';
  const wide = { maxWidth: 1440, margin: '0 auto', padding: '0 24px' };
  const toggleBrand = b => setBrandSel(s => s.includes(b) ? s.filter(x => x !== b) : [...s, b]);
  const toggleCat = c => setCatSel(s => s.includes(c) ? s.filter(x => x !== c) : [...s, c]);
  const toggleDyn = (key, val) => setDynSel(s => {
    const cur = s[key] || [];
    const next = cur.includes(val) ? cur.filter(x => x !== val) : [...cur, val];
    const out = { ...s, [key]: next };
    if (!next.length) delete out[key];
    return out;
  });
  const clearAll = () => { setBrandSel([]); setCatSel([]); setOnlySale(false); setPriceMin(null); setPriceMax(null); setDynSel({}); };
  const dynCount = Object.keys(dynSel).reduce((n, k) => n + (dynSel[k] ? dynSel[k].length : 0), 0);
  const activeCount = brandSel.length + catSel.length + (onlySale ? 1 : 0) + ((priceMin != null || priceMax != null) ? 1 : 0) + dynCount;
  // vrati na 1. stranu kad se promeni kategorija/filter/sort
  React.useEffect(() => { setPage(1); }, [slug, brand, potkat, potkat2, query, sort, onlySale, priceMin, priceMax, brandSel.join(','), catSel.join(','), JSON.stringify(dynSel)]);
  React.useEffect(() => { setPriceMin(null); setPriceMax(null); }, [slug, brand, potkat, potkat2, query]);
  // boja pozadine samo na nivou kategorije; potkategorija/potkategorija2 -> normalna (bela)
  const tintColor = (!brand && cat && !potkat && !potkat2) ? (cat.color || 'blue') : null;
  const pageBg = tintColor ? { background: `linear-gradient(180deg, color-mix(in srgb, var(--sm-cat-${tintColor}-1) 56%, #fff), color-mix(in srgb, var(--sm-cat-${tintColor}-1) 34%, var(--sm-bg)) 320px)`, minHeight: '70vh' } : {};

  // prisutne vrednosti za dati filter ključ (da ne prikazujemo prazne opcije)
  const presentVals = (key) => { const set = new Set(); inScope.forEach(p => { const pv = p.filters && p.filters[key]; if (Array.isArray(pv)) pv.forEach(v => set.add(v)); }); return set; };

  return (
    <div style={pageBg}>
    <div style={{ ...wide, paddingTop: 22, paddingBottom: 8 }}>
      {/* breadcrumb */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--sm-text-muted)', marginBottom: 14, flexWrap: 'wrap' }}>
        <a onClick={() => onNav({ view: 'home' })} style={{ cursor: 'pointer', color: 'var(--sm-text-muted)' }}>Početna</a>
        {brand && <React.Fragment>{I('chevron-right', 14)}<a onClick={() => onNav({ view: 'page', key: 'brendovi' })} style={{ cursor: 'pointer', color: 'var(--sm-text-muted)' }}>Brendovi</a></React.Fragment>}
        {!brand && cat && <React.Fragment>{I('chevron-right', 14)}<a onClick={() => onNav({ view: 'cathub', slug: cat.slug })} style={{ cursor: 'pointer', color: 'var(--sm-text-muted)' }}>{cat.title}</a></React.Fragment>}
        {!brand && cat && potkat && <React.Fragment>{I('chevron-right', 14)}<a onClick={() => onNav({ view: 'category', slug: cat.slug, potkat })} style={{ cursor: 'pointer', color: 'var(--sm-text-muted)' }}>{potkat}</a></React.Fragment>}
        {I('chevron-right', 14)}<span style={{ color: 'var(--sm-text)', fontWeight: 600 }}>{title}</span>
      </div>

      {/* brand header */}
      {brand && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 18, background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-lg)', boxShadow: 'var(--sm-shadow-xs)', padding: '18px 22px', marginBottom: 22 }}>
          {brandLogo && <span style={{ width: 120, height: 60, flex: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', borderRight: '1px solid var(--sm-border)', paddingRight: 18 }}><img src={SM_DATA.A + '/' + brandLogo.src} alt={brand} style={{ maxWidth: '100%', maxHeight: 44, objectFit: 'contain' }} /></span>}
          <div>
            <div style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 800, fontSize: 22, letterSpacing: '-.01em' }}>{brand}</div>
            <div style={{ fontSize: 14, color: 'var(--sm-text-muted)', marginTop: 2 }}>Zvanični asortiman · {list.length} {list.length === 1 ? 'proizvod' : 'proizvoda'} na stanju</div>
          </div>
        </div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: '264px 1fr', gap: 28, alignItems: 'start' }}>
        {/* filters column */}
        <div>
          {isMobile && (
            <button onClick={() => setFiltersOpen(o => !o)} style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-pill)', boxShadow: 'var(--sm-shadow-xs)', padding: '13px 18px', cursor: 'pointer', marginBottom: filtersOpen ? 14 : 0 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9, fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 15.5, color: 'var(--sm-text)' }}>{I('sliders-horizontal', 18)} Filteri{activeCount ? <span style={{ minWidth: 20, height: 20, padding: '0 6px', borderRadius: 10, background: 'var(--sm-primary)', color: '#fff', fontSize: 12, fontWeight: 800, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{activeCount}</span> : null}</span>
              {I(filtersOpen ? 'chevron-up' : 'chevron-down', 20)}
            </button>
          )}
          {(!isMobile || filtersOpen) && (
            <aside style={{ background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-lg)', padding: 22, position: isMobile ? 'static' : 'sticky', top: 72 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
                <span style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 17, display: 'inline-flex', alignItems: 'center', gap: 8 }}>{I('sliders-horizontal', 18)} Filteri</span>
                <a onClick={clearAll} style={{ fontSize: 12, color: 'var(--sm-primary)', cursor: 'pointer', fontWeight: 600 }}>Očisti sve</a>
              </div>

              {brand ? (
                <FilterGroup title="Kategorija">
                  {brandCats.length ? brandCats.map(c => (
                    <label key={c} onClick={() => toggleCat(c)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0', cursor: 'pointer', fontSize: 14, userSelect: 'none' }}>
                      <Check checked={catSel.includes(c)} />{catTitle(c)}
                    </label>
                  )) : <div style={{ fontSize: 13.5, color: 'var(--sm-text-muted)' }}>Nema dostupnih kategorija.</div>}
                </FilterGroup>
              ) : (
                <FilterGroup title="Brend">
                  <div style={{ maxHeight: 230, overflowY: catBrands.length > 9 ? 'auto' : 'visible', marginRight: -6, paddingRight: 6 }}>
                    {catBrands.map(b => (
                      <label key={b} onClick={() => toggleBrand(b)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0', cursor: 'pointer', fontSize: 14, userSelect: 'none' }}>
                        <Check checked={brandSel.includes(b)} />{b}
                      </label>
                    ))}
                  </div>
                </FilterGroup>
              )}

              {/* dinamički filteri iz baze (za aktivnu potkategoriju2) */}
              {!brand && defs.map(def => {
                const present = presentVals(def.key);
                const vals = def.vrednosti.filter(v => present.has(v));
                if (!vals.length) return null;
                return (
                  <FilterGroup key={def.key} title={def.naziv}>
                    <div style={{ maxHeight: 230, overflowY: vals.length > 9 ? 'auto' : 'visible', marginRight: -6, paddingRight: 6 }}>
                      {vals.map(v => (
                        <label key={v} onClick={() => toggleDyn(def.key, v)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0', cursor: 'pointer', fontSize: 14, userSelect: 'none' }}>
                          <Check checked={(dynSel[def.key] || []).includes(v)} />{v}
                        </label>
                      ))}
                    </div>
                  </FilterGroup>
                );
              })}

              <FilterGroup title="Cena (din.)">
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <input type="number" inputMode="numeric" min={0} placeholder={'Od ' + fmt(PLO)} value={priceMin == null ? '' : priceMin}
                    onChange={e => setPriceMin(e.target.value === '' ? null : Math.max(0, Math.round(+e.target.value)))}
                    style={{ width: '50%', height: 38, padding: '0 10px', border: '1px solid var(--sm-border)', borderRadius: 8, fontSize: 14, fontFamily: 'var(--sm-font-body)', outline: 'none', boxSizing: 'border-box' }} />
                  <span style={{ color: 'var(--sm-text-muted)' }}>—</span>
                  <input type="number" inputMode="numeric" min={0} placeholder={'Do ' + fmt(PHI)} value={priceMax == null ? '' : priceMax}
                    onChange={e => setPriceMax(e.target.value === '' ? null : Math.max(0, Math.round(+e.target.value)))}
                    style={{ width: '50%', height: 38, padding: '0 10px', border: '1px solid var(--sm-border)', borderRadius: 8, fontSize: 14, fontFamily: 'var(--sm-font-body)', outline: 'none', boxSizing: 'border-box' }} />
                </div>
                <div style={{ marginTop: 8, fontSize: 12.5, color: 'var(--sm-text-muted)' }}>U ovoj kategoriji: {fmt(PLO)} – {fmt(PHI)} din.</div>
              </FilterGroup>

              <FilterGroup title="Akcije" last>
                <label onClick={() => setOnlySale(v => !v)} style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', fontSize: 14, userSelect: 'none' }}>
                  <Check checked={onlySale} />Samo sniženo
                </label>
              </FilterGroup>
            </aside>
          )}
        </div>

        {/* results */}
        <div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
            <h1 style={{ fontSize: 30, margin: 0 }}>{title} <span style={{ fontSize: 16, color: 'var(--sm-text-muted)', fontWeight: 400, fontFamily: 'var(--sm-font-body)' }}>({list.length})</span></h1>
            <label style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 14, color: 'var(--sm-text-muted)' }}>
              Sortiraj po:
              <select value={sort} onChange={e => setSort(e.target.value)} style={{ fontFamily: 'var(--sm-font-body)', fontSize: 14, fontWeight: 600, color: 'var(--sm-text)', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-pill)', padding: '8px 14px', background: '#fff', cursor: 'pointer' }}>
                <option value="reco">Preporučeno</option>
                <option value="asc">Cena: Od najniže</option>
                <option value="desc">Cena: Od najviše</option>
                <option value="az">Naziv: A-Z</option>
                <option value="za">Naziv: Z-A</option>
              </select>
            </label>
          </div>

          {list.length === 0 ? (
            <Empty brand={brand} />
          ) : (
            <React.Fragment>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(264px, 1fr))', gap: 16 }}>
                {pageItems.map(p => <ProductCard key={p.id} p={p} onAdd={onAdd} onWish={onWish} wished={wishlist.includes(p.id)} onOpen={openProduct} />)}
              </div>
              <Pagination page={curPage} totalPages={totalPages} onPage={goPage} />
            </React.Fragment>
          )}
        </div>
      </div>
    </div>
    </div>
  );
}

function FilterGroup({ title, last, children }) {
  return (
    <div style={{ paddingBottom: last ? 0 : 18, marginBottom: last ? 0 : 18, borderBottom: last ? 'none' : '1px solid var(--sm-border)' }}>
      <div style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 14, marginBottom: 10 }}>{title}</div>
      {children}
    </div>
  );
}
function Check({ checked, onClick }) {
  return (
    <span onClick={onClick} style={{ width: 20, height: 20, borderRadius: 6, border: checked ? 'none' : '1.5px solid var(--sm-border-strong)', background: checked ? 'var(--sm-primary)' : '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: 'none', color: '#fff' }}>
      {checked && I('check', 14)}
    </span>
  );
}
function Empty({ brand }) {
  return (
    <div style={{ textAlign: 'center', padding: '70px 20px', color: 'var(--sm-text-muted)' }}>
      <img src={SM_DATA.A + '/mascot-genie.png'} alt="" style={{ height: 130, opacity: .9, marginBottom: 16 }} />
      <div style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 20, color: 'var(--sm-text)' }}>{brand ? `Trenutno nema ${brand} proizvoda na stanju` : 'Nema rezultata za izabrane filtere'}</div>
      <div style={{ fontSize: 15, marginTop: 6 }}>{brand ? 'Uskoro stižu novi modeli — proveri ponovo ili istraži slične brendove.' : 'Probaj da očistiš filtere ili promeniš pretragu.'}</div>
    </div>
  );
}

function Pagination({ page, totalPages, onPage }) {
  if (totalPages <= 1) return null;
  const nums = [];
  for (let i = 1; i <= totalPages; i++) {
    if (i === 1 || i === totalPages || (i >= page - 1 && i <= page + 1)) nums.push(i);
    else if (nums[nums.length - 1] !== '…') nums.push('…');
  }
  const cell = (active) => ({ minWidth: 40, height: 40, padding: '0 13px', borderRadius: 'var(--sm-radius-pill)', border: active ? 'none' : '1px solid var(--sm-border)', background: active ? 'var(--sm-primary)' : '#fff', color: active ? '#fff' : 'var(--sm-text)', fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 14, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6 });
  const arrow = (disabled) => ({ ...cell(false), opacity: disabled ? 0.45 : 1, cursor: disabled ? 'not-allowed' : 'pointer' });
  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8, flexWrap: 'wrap', padding: '34px 0 8px' }}>
      <button disabled={page <= 1} onClick={() => page > 1 && onPage(page - 1)} style={arrow(page <= 1)}>{I('chevron-left', 16)} Prethodna</button>
      {nums.map((n, i) => n === '…'
        ? <span key={'e' + i} style={{ padding: '0 4px', color: 'var(--sm-text-muted)' }}>…</span>
        : <button key={n} onClick={() => onPage(n)} style={cell(n === page)}>{n}</button>)}
      <button disabled={page >= totalPages} onClick={() => page < totalPages && onPage(page + 1)} style={arrow(page >= totalPages)}>Sledeća {I('chevron-right', 16)}</button>
    </div>
  );
}

Object.assign(window, { CategoryPage });
