/* ============================================================
   MyKollectOr® — notifications.js — Polling 30s
   ============================================================ */

const Notifications = (() => {
  let intervalId = null;
  let lastCount = 0;

  const updateBadge = (count) => {
    const badges = document.querySelectorAll('.notif-badge');
    badges.forEach(b => {
      b.textContent = count;
      b.style.display = count > 0 ? 'inline-flex' : 'none';
    });
  };

  const poll = async () => {
    try {
      const data = await Api.get('/api/fab/notifications');
      const unread = data.unread_count ?? data.nb_non_lus ?? (Array.isArray(data) ? data.filter(n => !n.lu).length : 0);
      if (unread > lastCount && lastCount >= 0) {
        const diff = unread - lastCount;
        if (diff > 0 && lastCount !== -1) {
          Toast.info(` ${diff} nouvelle${diff > 1 ? 's' : ''} notification${diff > 1 ? 's' : ''}`);
        }
      }
      lastCount = unread;
      updateBadge(unread);
    } catch { /* silent */ }
  };

  const start = () => {
    if (!Auth.isLoggedIn()) return;
    // Initial poll immediately
    lastCount = -1; // sentinel so first poll doesn't toast
    poll().then(() => { lastCount = lastCount === -1 ? 0 : lastCount; });
    intervalId = setInterval(poll, 30000);
  };

  const stop = () => {
    if (intervalId) { clearInterval(intervalId); intervalId = null; }
  };

  return { start, stop, poll, updateBadge };
})();
