function esc(value){ return Pyrk.esc(value ?? ''); }

const memberNotificationsMobile = document.body?.dataset.mobileNotifications === '1';

function safeNotificationHtml(html) {
  const template = document.createElement('template');
  template.innerHTML = String(html || '');

  const allowed = new Set(['P','BR','STRONG','B','EM','I','U','UL','OL','LI','A','H3','H4','BLOCKQUOTE']);
  const walker = document.createTreeWalker(template.content, NodeFilter.SHOW_ELEMENT);
  const remove = [];

  while (walker.nextNode()) {
    const el = walker.currentNode;
    if (!allowed.has(el.tagName)) {
      remove.push(el);
      continue;
    }
    [...el.attributes].forEach(attr => {
      const name = attr.name.toLowerCase();
      if (name.startsWith('on') || name === 'style' || name === 'class' || name === 'id') el.removeAttribute(attr.name);
    });
    if (el.tagName === 'A') {
      const href = el.getAttribute('href') || '#';
      if (/^\s*javascript:/i.test(href)) el.setAttribute('href', '#');
      el.setAttribute('target', '_blank');
      el.setAttribute('rel', 'noopener noreferrer');
    }
  }
  remove.forEach(el => el.replaceWith(...el.childNodes));
  return template.innerHTML || esc(html);
}

function notificationDate(value) {
  if (!value) return '—';
  try {
    return new Date(String(value).replace(' ', 'T')).toLocaleString();
  } catch {
    return String(value);
  }
}

function updateNavNotificationBadge(count) {
  const value = Math.max(0, Number(count || 0));
  document.querySelectorAll('[data-notification-count], [data-mobile-unread-count]').forEach(badge => {
    badge.textContent = value > 99 ? '99+' : String(value);
    badge.hidden = value <= 0;
  });
}

function attachmentsHtml(row) {
  const files = row.attachments || [];
  if (!files.length) return '';
  return `<div class="member-notification-attachments">${files.map(file => {
    const href = String(file.file_path || '').replace(/^\/+/, '');
    return `<a href="${esc(href)}" target="_blank" rel="noopener noreferrer">📎 ${esc(file.original_name || 'Attachment')}</a>`;
  }).join('')}</div>`;
}

function mobileNotificationCard(row) {
  const id = Number(row.id || 0);
  const unread = !row.read_at;
  return `<article class="member-notification-card mobile-notification-accordion${unread ? ' is-unread' : ''}" data-notification-card="${id}">
    <button class="mobile-notification-summary" type="button" data-notification-toggle="${id}" aria-expanded="false">
      <span class="notification-icon">${unread ? '🔔' : '✓'}</span>
      <span class="mobile-notification-summary-copy"><strong>${esc(row.subject || 'Notification')}</strong><small>${esc(notificationDate(row.sent_at || row.created_at))}</small></span>
      <span class="mobile-notification-state">${unread ? 'Unread' : 'Read'}</span>
      <span class="mobile-notification-chevron">⌄</span>
    </button>
    <div class="mobile-notification-detail" hidden>
      <div class="notification-rich-body">${safeNotificationHtml(row.message || '')}</div>
      ${attachmentsHtml(row)}
      <div class="notification-actions-pro">
        <button class="btn btn-light btn-small" type="button" data-notification-unread="${id}">${unread ? 'Keep unread' : 'Mark unread'}</button>
      </div>
    </div>
  </article>`;
}

function desktopNotificationCard(row) {
  const unreadClass = row.read_at ? '' : ' is-unread';
  return `<article class="member-notification-card${unreadClass}" data-notification-card="${Number(row.id)}" tabindex="0" role="button" aria-label="Open notification">
    <div class="notification-icon">${row.read_at ? '✓' : '🔔'}</div>
    <div>
      <div class="notification-card-head">
        <strong>${esc(row.subject || 'Notification')}</strong>
        <small>${esc(notificationDate(row.sent_at || row.created_at))}</small>
      </div>
      <div class="notification-rich-body">${safeNotificationHtml(row.message || '')}</div>
      ${attachmentsHtml(row)}
      <div class="notification-actions-pro">
        ${row.read_at
          ? `<span class="pill pill-muted">Read</span><button class="btn btn-light btn-small" type="button" data-unread-id="${Number(row.id)}">Mark unread</button>`
          : `<span class="pill pill-green">Unread</span><button class="btn btn-light btn-small" type="button" data-read-id="${Number(row.id)}">Open / mark read</button>`}
      </div>
    </div>
  </article>`;
}

function renderNotifications(rows, unread) {
  document.getElementById('memberUnreadCount').textContent = String(unread || 0);
  updateNavNotificationBadge(unread || 0);
  document.getElementById('memberNotificationCount').textContent = String((rows || []).length);
  document.getElementById('memberNotificationStatus').textContent = rows?.length ? 'Loaded' : 'Empty';

  const list = document.getElementById('memberNotificationList');
  list.innerHTML = (rows || []).map(row => memberNotificationsMobile ? mobileNotificationCard(row) : desktopNotificationCard(row)).join('') || '<div class="empty-state"><strong>No notifications yet.</strong><span>Announcements sent by Pyrk will appear here.</span></div>';
}

async function loadMemberNotifications() {
  const res = await Pyrk.get('member_notifications.php', {action:'list'});
  if (!res.ok) {
    document.getElementById('memberNotificationStatus').textContent = 'Error';
    document.getElementById('memberNotificationList').innerHTML = `<p class="notice bad">${esc(res.message)}</p>`;
    return;
  }
  renderNotifications(res.data.notifications || [], Number(res.data.unread_count || 0));
}

async function markRead(id, reload = true) {
  const res = await Pyrk.post('member_notifications.php', {action:'mark_read', id});
  if (res.ok && reload) await loadMemberNotifications();
  return res;
}

async function markUnread(id, reload = true) {
  const res = await Pyrk.post('member_notifications.php', {action:'mark_unread', id});
  if (res.ok && reload) await loadMemberNotifications();
  return res;
}

async function markAllRead() {
  const res = await Pyrk.post('member_notifications.php', {action:'mark_all_read'});
  if (res.ok) await loadMemberNotifications();
}

async function markAllUnread() {
  const res = await Pyrk.post('member_notifications.php', {action:'mark_all_unread'});
  if (res.ok) await loadMemberNotifications();
}

function decrementUnreadCount() {
  const counter = document.getElementById('memberUnreadCount');
  const current = Math.max(0, Number(counter?.textContent || 0) - 1);
  if (counter) counter.textContent = String(current);
  updateNavNotificationBadge(current);
}

function updateMobileCardRead(card) {
  if (!card || !card.classList.contains('is-unread')) return;
  card.classList.remove('is-unread');
  const icon = card.querySelector('.notification-icon');
  const state = card.querySelector('.mobile-notification-state');
  const unreadButton = card.querySelector('[data-notification-unread]');
  if (icon) icon.textContent = '✓';
  if (state) state.textContent = 'Read';
  if (unreadButton) unreadButton.textContent = 'Mark unread';
  decrementUnreadCount();
}

async function toggleMobileNotification(button) {
  const card = button.closest('[data-notification-card]');
  const detail = card?.querySelector('.mobile-notification-detail');
  if (!card || !detail) return;
  const opening = detail.hidden;
  detail.hidden = !opening;
  button.setAttribute('aria-expanded', opening ? 'true' : 'false');
  card.classList.toggle('is-open', opening);
  if (opening && card.classList.contains('is-unread')) {
    const id = Number(card.dataset.notificationCard || 0);
    const res = await markRead(id, false);
    if (res.ok) updateMobileCardRead(card);
  }
}

document.getElementById('memberNotificationList')?.addEventListener('click', async e => {
  if (memberNotificationsMobile) {
    const toggle = e.target.closest('[data-notification-toggle]');
    if (toggle) {
      e.preventDefault();
      await toggleMobileNotification(toggle);
      return;
    }
    const unreadButton = e.target.closest('[data-notification-unread]');
    if (unreadButton) {
      e.preventDefault();
      const id = Number(unreadButton.dataset.notificationUnread || 0);
      await markUnread(id, true);
    }
    return;
  }

  const readBtn = e.target.closest('[data-read-id]');
  const unreadBtn = e.target.closest('[data-unread-id]');
  if (unreadBtn) {
    e.preventDefault();
    e.stopPropagation();
    markUnread(Number(unreadBtn.dataset.unreadId || 0));
    return;
  }
  if (readBtn) {
    e.preventDefault();
    e.stopPropagation();
    markRead(Number(readBtn.dataset.readId || 0));
    return;
  }
  const card = e.target.closest('[data-notification-card]');
  const id = Number(card?.dataset.notificationCard || 0);
  if (!id || !card.classList.contains('is-unread')) return;
  markRead(id);
});

document.getElementById('memberNotificationList')?.addEventListener('keydown', e => {
  if (memberNotificationsMobile || (e.key !== 'Enter' && e.key !== ' ')) return;
  const card = e.target.closest('[data-notification-card]');
  if (!card || !card.classList.contains('is-unread')) return;
  e.preventDefault();
  markRead(Number(card.dataset.notificationCard || 0));
});

document.getElementById('markAllNotificationsReadBtn')?.addEventListener('click', markAllRead);
document.getElementById('markAllNotificationsUnreadBtn')?.addEventListener('click', markAllUnread);

loadMemberNotifications();
