(() => {
  'use strict';

  const buttons = document.querySelectorAll('.filter-btn');
  const projects = document.querySelectorAll('.project-grid-item');
  const search = document.querySelector('#projectSearch');

  let activeFilter = 'all';

  const applyFilters = () => {
    const query = (search?.value || '').trim().toLowerCase();

    projects.forEach((project) => {
      const category = project.dataset.category || '';
      const haystack = project.textContent.toLowerCase();
      const matchesCategory = activeFilter === 'all' || category.includes(activeFilter);
      const matchesSearch = !query || haystack.includes(query);
      project.classList.toggle('hide', !(matchesCategory && matchesSearch));
    });
  };

  buttons.forEach((button) => {
    button.addEventListener('click', () => {
      activeFilter = button.dataset.filter || 'all';
      buttons.forEach((item) => item.classList.remove('active'));
      button.classList.add('active');
      applyFilters();
    });
  });

  search?.addEventListener('input', applyFilters);
})();
