console.log("✅ Notification listener active");

let lastCount = typeof window.unreadNotifications !== "undefined" ? window.unreadNotifications : 0;

function checkNotifications() {
  fetch("/actions/fetch_unread_count.php") // Make sure this path is correct
    .then(res => res.json())
    .then(data => {
      let newCount = parseInt(data.unread);

      console.log("🔄 Checking notifications:", { lastCount, newCount });

      // New notification detected → Play sound
      if (newCount > lastCount) {
        const sound = document.getElementById("notifySound");
        if (sound) sound.play().catch(err => console.warn("🎧 Autoplay blocked:", err));

        if (navigator.vibrate) navigator.vibrate([200, 100, 200]); // optional
      }

      lastCount = newCount;
    })
    .catch(err => console.warn("⚠️ Notification check failed", err));
}

// Check every 1 seconds
setInterval(checkNotifications, 1000);

// Unlock audio
document.addEventListener("click", () => {
  const sound = document.getElementById("notifySound");
  if (sound) sound.play().catch(()=>{});
}, { once: true });
