(function () {
  var badge = document.getElementById('js-notification-badge');
  var button = document.getElementById('js-notification-button');
  if (!badge || !button || typeof fetch !== 'function') return;

  var seenKey = 'orderproSeenNotificationIds';
  var seenIds = loadSeenIds();
  var permissionAsked = false;

  function loadSeenIds() {
    try {
      return JSON.parse(localStorage.getItem(seenKey) || '[]').map(String);
    } catch (e) {
      return [];
    }
  }

  function saveSeenIds() {
    try {
      localStorage.setItem(seenKey, JSON.stringify(seenIds.slice(-100)));
    } catch (e) {}
  }

  function updateBadge(count) {
    var value = Math.max(0, Number(count) || 0);
    badge.textContent = value > 99 ? '99+' : String(value);
    badge.hidden = value === 0;
  }

  function requestPermission() {
    if (permissionAsked || !('Notification' in window) || Notification.permission !== 'default') {
      return Promise.resolve();
    }
    permissionAsked = true;
    return Notification.requestPermission().catch(function () {});
  }

  function showBrowserNotification(item) {
    var id = String(item.id || '');
    if (id === '' || seenIds.indexOf(id) !== -1) return;

    seenIds.push(id);
    saveSeenIds();
    if (!('Notification' in window) || Notification.permission !== 'granted') return;

    var nativeNotification = new Notification(item.title || 'orderPRO', {
      body: item.body || '',
      tag: 'orderpro-notification-' + id
    });
    nativeNotification.onclick = function () {
      window.focus();
      if (item.target_url) {
        window.location.href = item.target_url;
      }
    };
  }

  function poll() {
    fetch('/api/notifications/unread', { credentials: 'same-origin' })
      .then(function (response) { return response.ok ? response.json() : null; })
      .then(function (data) {
        if (!data || !data.ok) return;
        updateBadge(data.count);
        if (Array.isArray(data.items)) {
          data.items.slice().reverse().forEach(showBrowserNotification);
        }
      })
      .catch(function () {});
  }

  button.addEventListener('click', function (event) {
    if ('Notification' in window && Notification.permission === 'default') {
      event.preventDefault();
      requestPermission().finally(function () {
        window.location.href = button.href;
      });
    }
  });
  poll();
  window.setInterval(poll, 30000);
})();
