/**
 * NEWS SEARCH AND CATEGORY FILTERING JAVASCRIPT
 */

document.addEventListener('DOMContentLoaded', () => {
  const searchInput = document.getElementById('newsSearchInput');
  const catButtons = document.querySelectorAll('.cat-btn');
  const newsCards = document.querySelectorAll('.news-card-item');

  let currentCategory = 'semua';
  let searchQuery = '';

  const filterNews = () => {
    newsCards.forEach(card => {
      const category = card.getAttribute('data-category').toLowerCase();
      const title = card.querySelector('.news-title').textContent.toLowerCase();
      const summary = card.querySelector('.news-summary').textContent.toLowerCase();

      const matchesCat = currentCategory === 'semua' || category === currentCategory;
      const matchesSearch = !searchQuery || title.includes(searchQuery) || summary.includes(searchQuery);

      if (matchesCat && matchesSearch) {
        card.style.display = 'flex';
      } else {
        card.style.display = 'none';
      }
    });
  };

  if (searchInput) {
    searchInput.addEventListener('input', (e) => {
      searchQuery = e.target.value.trim().toLowerCase();
      filterNews();
    });
  }

  if (catButtons.length > 0) {
    catButtons.forEach(btn => {
      btn.addEventListener('click', () => {
        catButtons.forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        currentCategory = btn.getAttribute('data-category').toLowerCase();
        filterNews();
      });
    });
  }
});
