/**
 * Ragreen - Notifications page logic
 * Requires config.js + jQuery loaded first.
 */

const Notifications = {
  init() {
    this.load();
    $('#markAllReadBtn').on('click', () => this.markAllRead());
  },

  load(page = 1) {
    $.get(`${API_BASE}/notifications/list.php`, { page })
      .done((res) => this.render(res.data.notifications, res.data.pagination))
      .fail(() => {
        $('#notifList').html('<div class="empty-state"><h3>Could not load notifications</h3></div>');
      });
  },

  render(items, pagination) {
    const $list = $('#notifList');
    if (!items.length) {
      $list.html('<div class="empty-state"><h3>No notifications yet</h3><p>Order updates and expiry reminders will show up here.</p></div>');
      renderPaginationControls('#notifPagination', null);
      return;
    }

    const typeLabels = {
      order_confirmed: 'Order', order_sold: 'Sale', listing_hidden: 'Moderation',
      account_reactivated: 'Account', listing_expiry: 'Expiry reminder', pantry_expiry: 'Expiry reminder',
      admin_promoted: 'Account', order_placed: 'Order', order_pending: 'Sale',
      order_fulfilled: 'Sale complete', order_item_cancelled: 'Order cancelled',
    };

    $list.html(items.map(n => `
      <div class="notif-row ${n.is_read ? 'read' : 'unread'}" data-id="${n.id}">
        <div class="notif-dot"></div>
        <div style="flex:1;">
          <div class="message">${escapeHtml(n.message.replace(/\s*\(#[\w-]+\)\s*$/, ''))}</div>
          <div class="date">${typeLabels[n.type] || n.type} · ${new Date(n.created_at.replace(' ', 'T')).toLocaleString()}</div>
        </div>
      </div>
    `).join(''));

    $list.find('.notif-row.unread').on('click', function () {
      const id = $(this).data('id');
      $.ajax({
        url: `${API_BASE}/notifications/mark_read.php`, method: 'POST', contentType: 'application/json',
        data: JSON.stringify({ id }),
      }).done(() => {
        $(this).removeClass('unread').addClass('read');
        if (typeof updateBellBadge === 'function') updateBellBadge();
      });
    });

    renderPaginationControls('#notifPagination', pagination, (p) => this.load(p));
  },

  markAllRead() {
    $.ajax({
      url: `${API_BASE}/notifications/mark_read.php`, method: 'POST', contentType: 'application/json',
      data: JSON.stringify({ mark_all: true }),
    }).done(() => {
      this.load();
      if (typeof updateBellBadge === 'function') updateBellBadge();
    });
  },
};
