(function () {
'use strict';

const qs  = (s, ctx) => (ctx || document).querySelector(s);
const qsa = (s, ctx) => [...(ctx || document).querySelectorAll(s)];

/* ── Insight filter */
const filterBtns = qsa('.port-filter-btn');
const insItems   = qsa('.port-item[data-category]');
const totalEl    = qs('#insGridTotal');

filterBtns.forEach(btn => {
  btn.addEventListener('click', () => {
    const filter = btn.dataset.filter;
    filterBtns.forEach(b => b.classList.remove('active'));
    btn.classList.add('active');

    let count = 0;
    insItems.forEach(item => {
      const match = filter === 'all' || item.dataset.category === filter;
      if (match) {
        item.classList.remove('hidden');
        item.style.opacity = '0';
        item.style.transform = 'translateY(18px)';
        requestAnimationFrame(() => {
          item.style.transition = 'opacity .4s ease, transform .4s ease';
          item.style.opacity = '1';
          item.style.transform = 'translateY(0)';
        });
        count++;
      } else {
        item.classList.add('hidden');
      }
    });

    if (totalEl) {
      totalEl.textContent = `Showing ${count} article${count !== 1 ? 's' : ''}`;
    }
  });
});

/* ── Newsletter subscribe */
const nlEmail  = qs('#nlEmail');
const nlSubmit = qs('#nlSubmit');

if (nlSubmit && nlEmail) {
  nlSubmit.addEventListener('click', () => {
    const val = nlEmail.value.trim();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val)) {
      nlEmail.style.borderColor = 'rgba(255,255,255,.5)';
      nlEmail.focus();
      setTimeout(() => { nlEmail.style.borderColor = ''; }, 1800);
      return;
    }
    nlSubmit.disabled = true;
    nlSubmit.innerHTML = '<i class="fas fa-check"></i> Subscribed!';
    nlEmail.value = '';
    nlEmail.disabled = true;
    nlEmail.placeholder = 'You\'re on the list.';
  });
  nlEmail.addEventListener('keydown', e => {
    if (e.key === 'Enter') nlSubmit.click();
  });
}

})();
