(function(){
  function ready(fn){if(document.readyState!=='loading')fn();else document.addEventListener('DOMContentLoaded',fn);}
  ready(function(){
    var grid=document.getElementById('shop-grid'); if(!grid)return;
    var cards=Array.prototype.slice.call(grid.querySelectorAll('.pcard'));
    var sortSel=document.getElementById('sort'), countEl=document.getElementById('result-count'),
        emptyEl=document.getElementById('shop-empty'), clearBtn=document.getElementById('clear-filters');
    var ft=document.getElementById('filter-toggle'), fp=document.getElementById('filter-panel');
    function openPanel(){if(fp){fp.removeAttribute('hidden');}if(ft){ft.setAttribute('aria-expanded','true');}}
    if(ft&&fp){ft.addEventListener('click',function(){if(fp.hasAttribute('hidden')){openPanel();}else{fp.setAttribute('hidden','');ft.setAttribute('aria-expanded','false');}});}
    var params=new URLSearchParams(location.search);
    var pDevice=params.get('device'), pFlav=params.get('flavour');
    if(pDevice){var cb=document.querySelector('.f-device[value="'+pDevice+'"]');if(cb){cb.checked=true;openPanel();}}
    if(pFlav){var fb=document.querySelector('.f-flav[value="'+pFlav+'"]');if(fb){fb.checked=true;openPanel();}}
    function checkedVals(sel){return Array.prototype.slice.call(document.querySelectorAll(sel+':checked'));}
    var pager=document.getElementById('pagination');
    var PER=24, page=1;
    function render(){
      var devs=checkedVals('.f-device').map(function(c){return c.value;});
      var flavs=checkedVals('.f-flav').map(function(c){return c.value;});
      var puffs=checkedVals('.f-puff');
      var matched=cards.filter(function(card){
        var ok=true;
        if(devs.length&&devs.indexOf(card.dataset.device)<0)ok=false;
        if(ok&&flavs.length&&flavs.indexOf(card.dataset.flavour)<0)ok=false;
        if(ok&&puffs.length){var n=+card.dataset.puffs;ok=puffs.some(function(t){return n>=+t.dataset.min&&n<=+t.dataset.max;});}
        return ok;
      });
      var sort=sortSel?sortSel.value:'popularity';
      matched.sort(function(a,b){
        if(sort==='price-asc')return a.dataset.price-b.dataset.price;
        if(sort==='price-desc')return b.dataset.price-a.dataset.price;
        if(sort==='new')return (b.dataset.new-a.dataset.new)||(b.dataset.pop-a.dataset.pop);
        return b.dataset.pop-a.dataset.pop;
      });
      var totalPages=Math.max(1,Math.ceil(matched.length/PER));
      if(page>totalPages)page=totalPages; if(page<1)page=1;
      var start=(page-1)*PER, end=start+PER;
      cards.forEach(function(c){c.style.display='none';});
      matched.slice(start,end).forEach(function(c){c.style.display='';grid.appendChild(c);});
      if(countEl)countEl.textContent=matched.length?('Showing '+(start+1)+'–'+Math.min(end,matched.length)+' of '+matched.length):'No products match';
      if(emptyEl)emptyEl.style.display=matched.length?'none':'';
      grid.style.display=matched.length?'':'none';
      var any=devs.length||flavs.length||puffs.length;
      if(clearBtn)clearBtn.style.display=any?'':'none';
      renderPager(totalPages);
    }
    function renderPager(tp){
      if(!pager)return;
      if(tp<=1){pager.innerHTML='';return;}
      var html='<button '+(page<=1?'disabled':'')+' data-pg="'+(page-1)+'" aria-label="Previous page">‹</button>';
      var last=0;
      for(var i=1;i<=tp;i++){
        if(i===1||i===tp||Math.abs(i-page)<=1){
          if(i-last>1)html+='<button disabled>…</button>';
          html+='<button class="'+(i===page?'active':'')+'" data-pg="'+i+'">'+i+'</button>'; last=i;
        }
      }
      html+='<button '+(page>=tp?'disabled':'')+' data-pg="'+(page+1)+'" aria-label="Next page">›</button>';
      pager.innerHTML=html;
      pager.querySelectorAll('[data-pg]').forEach(function(btn){btn.addEventListener('click',function(){
        var n=+btn.getAttribute('data-pg'); if(n<1)return; page=n; render();
        window.scrollTo({top:Math.max(0,grid.getBoundingClientRect().top+window.pageYOffset-110),behavior:'smooth'});
      });});
    }
    function applyReset(){page=1;render();}
    document.querySelectorAll('.f-device,.f-flav,.f-puff').forEach(function(c){c.addEventListener('change',applyReset);});
    if(sortSel)sortSel.addEventListener('change',applyReset);
    if(clearBtn)clearBtn.addEventListener('click',function(){document.querySelectorAll('.f-device,.f-flav,.f-puff').forEach(function(c){c.checked=false;});applyReset();});
    render();
  });
})();
