(function(){
  // ===== Filters =====
  const filters = document.querySelectorAll('.filter-btn');
  const cards   = document.querySelectorAll('.g-card');

  function applyFilter(type){
    filters.forEach(btn => btn.classList.toggle('is-active', btn.dataset.filter === type || (type==='all' && btn.dataset.filter==='all')));
    cards.forEach(card => {
      const ok = (type === 'all') || (card.getAttribute('data-type') === type);
      card.style.display = ok ? '' : 'none';
    });
  }

  filters.forEach(btn => {
    btn.addEventListener('click', () => applyFilter(btn.dataset.filter));
  });

  // ===== Lightbox =====
  const lb = document.getElementById('lightbox');
  const lbBody = lb?.querySelector('.lb-body');
  const lbCaption = lb?.querySelector('#lb-caption');
  const closeBtn = lb?.querySelector('.lb-close');

  function openLB({type, src, title}){
    if (!lb || !lbBody) return;
    lbBody.innerHTML = ''; // reset

    if (type === 'video'){
      const v = document.createElement('video');
      v.src = src;
      v.controls = true;
      v.autoplay = true;
      v.playsInline = true;
      v.setAttribute('preload','metadata');
      lbBody.appendChild(v);
    } else {
      const img = document.createElement('img');
      img.src = src;
      img.alt = title || '';
      lbBody.appendChild(img);
    }
    if (lbCaption) lbCaption.textContent = title || '';
    lb.hidden = false;
    document.body.style.overflow = 'hidden';
  }

  function closeLB(){
    if (!lb || !lbBody) return;
    const v = lbBody.querySelector('video');
    if (v){ try { v.pause(); } catch(_){} }
    lb.hidden = true;
    lbBody.innerHTML = '';
    document.body.style.overflow = '';
  }

  document.addEventListener('click', (e)=>{
    const a = e.target.closest('.g-link');
    if (a){
      e.preventDefault();
      openLB({
        type: a.dataset.type,
        src:  a.dataset.src,
        title:a.dataset.title
      });
    }
    if (e.target === lb) closeLB(); // click backdrop
  });

  closeBtn?.addEventListener('click', closeLB);
  document.addEventListener('keydown', (e)=>{ if (e.key === 'Escape') closeLB(); });

  // Default filter on load
  applyFilter('all');
})();
