window.onload = async () => {
  const container = document.getElementById('news-container');

  try {
    const response = await fetch('news.php');
    const data = await response.json();

    if (!Array.isArray(data) || data.length === 0) {
      container.innerHTML = "<p>No news found.</p>";
      return;
    }

    data.forEach(post => {
      const div = document.createElement('div');
      div.className = "news-card";
      div.innerHTML = `
      <img src="${post.imageurl}" alt="news image" class="news-img" />
        <h3>${post.title}</h3>
        <p>${new Date(post.published_at).toLocaleString()}</p>
        <p><small>Source: ${post.source || 'Unknown'}</small></p>
        <a href="postDetail.php?id=${post.id}" class="read-more">Read more</a>
      `;
      container.appendChild(div);
    });

    // Add search functionality
    document.getElementById('search').addEventListener('input', (e) => {
      const keyword = e.target.value.toLowerCase();
      document.querySelectorAll('.news-card').forEach(card => {
        const title = card.querySelector('h3').textContent.toLowerCase();
        card.style.display = title.includes(keyword) ? '' : 'none';
      });
    });

  } catch (error) {
    console.error("Failed to load news:", error);
    container.innerHTML = "<p>Error loading news. See console.</p>";
  }
};

