/**
 * Уведомления в шапке админки (1.0.5).
 */
(function () {
  'use strict';

  var REFRESH_MS = 60000;
  var panel = document.getElementById('notificationsPanel');
  var badge = document.getElementById('notificationsBadge');
  var list = document.getElementById('notificationsList');
  var emptyEl = document.getElementById('notificationsEmpty');
  var footerLink = document.getElementById('notificationsFooterLink');
  var dropdownWrap = document.querySelector('.notifications-dropdown-wrap');

  if (!panel || !list) {
    return;
  }

  function t(key, fallback) {
    if (typeof window.__t === 'function') {
      var value = window.__t(key);
      if (value && value !== key) {
        return value;
      }
    }
    return fallback != null ? fallback : key;
  }

  function escapeHtml(value) {
    var div = document.createElement('div');
    div.textContent = value == null ? '' : String(value);
    return div.innerHTML;
  }

  function severityClass(severity) {
    var map = {
      critical: 'danger',
      error: 'danger',
      warning: 'warning',
      info: 'info',
    };
    return map[severity] || 'secondary';
  }

  function formatTime(timestamp) {
    if (!timestamp) {
      return '';
    }
    try {
      return new Date(Number(timestamp) * 1000).toLocaleString();
    } catch (e) {
      return '';
    }
  }

  function updateBadge(count) {
    if (!badge) {
      return;
    }
    if (!count) {
      badge.hidden = true;
      badge.textContent = '';
      badge.removeAttribute('data-count');
      return;
    }
    badge.hidden = false;
    badge.textContent = count > 99 ? '99+' : String(count);
    badge.setAttribute('data-count', String(count));
  }

  function renderNotifications(notifications) {
    list.innerHTML = '';
    var count = notifications.length;
    updateBadge(count);

    if (!count) {
      if (emptyEl) {
        emptyEl.hidden = false;
      }
      if (footerLink) {
        footerLink.hidden = true;
      }
      return;
    }

    if (emptyEl) {
      emptyEl.hidden = true;
    }
    if (footerLink) {
      footerLink.hidden = false;
    }

    notifications.forEach(function (item) {
      var li = document.createElement('li');
      var link = document.createElement('a');
      link.className = 'dropdown-item notifications-item notifications-item--' + severityClass(item.severity);
      link.href = item.url || '#';
      var time = formatTime(item.timestamp);
      link.innerHTML =
        '<span class="notifications-item__title">' + escapeHtml(item.title) + '</span>' +
        (item.message
          ? '<span class="notifications-item__message">' + escapeHtml(item.message) + '</span>'
          : '') +
        (time ? '<span class="notifications-item__time">' + escapeHtml(time) + '</span>' : '');
      li.appendChild(link);
      list.appendChild(li);
    });
  }

  async function loadNotifications() {
    try {
      var response = await fetch('/api/v1/admin/notifications', { credentials: 'same-origin' });
      if (response.status === 401) {
        updateBadge(0);
        return;
      }
      if (!response.ok) {
        throw new Error('HTTP ' + response.status);
      }
      var payload = await response.json();
      var data = payload.data || payload;
      renderNotifications(data.notifications || []);
    } catch (err) {
      console.error('Notifications load failed', err);
      if (emptyEl) {
        emptyEl.hidden = false;
        emptyEl.textContent = t('notifications.load_error', 'Не удалось загрузить уведомления');
      }
      updateBadge(0);
    }
  }

  document.addEventListener('DOMContentLoaded', function () {
    loadNotifications();
    setInterval(loadNotifications, REFRESH_MS);
  });

  if (dropdownWrap) {
    dropdownWrap.addEventListener('show.bs.dropdown', loadNotifications);
  }
})();
