import * as net from '../../../core/net.js';
import * as store from '../../../core/store.js';
import * as scene from '../../../core/scene.js';
import * as bus from '../../../core/bus.js';
import { t } from '../../../core/i18n.js';

export async function mountNotifications(el) {
  el.innerHTML = `
    <div style="padding:var(--s-4);display:flex;flex-direction:column;gap:var(--s-4);">
      <h2 style="font-size:20px;font-weight:700;">${t('social.notifications')}</h2>
      <div id="notif-list">
        <div class="skeleton" style="height:50px;margin-bottom:var(--s-2);"></div>
        <div class="skeleton" style="height:50px;margin-bottom:var(--s-2);"></div>
      </div>
    </div>
  `;

  try {
    const data = await net.get('notifications.php');
    const notifications = data.notifications || data || [];
    renderNotifications(el, notifications);
  } catch (e) {
    el.querySelector('#notif-list').innerHTML = `<p style="color:var(--text-secondary);text-align:center;">${t('common.empty')}</p>`;
  }
}

function renderNotifications(el, notifications) {
  const list = el.querySelector('#notif-list');
  if (notifications.length === 0) {
    list.innerHTML = `<p style="color:var(--text-secondary);text-align:center;padding:var(--s-8);">${t('common.empty')}</p>`;
    return;
  }

  const hasUnread = notifications.some(n => !n.is_read);
  list.innerHTML = (hasUnread ? `<button id="mark-all-read" style="margin-bottom:8px;background:none;border:1px solid rgba(255,255,255,0.1);color:var(--text-secondary);font-size:12px;padding:6px 14px;border-radius:8px;cursor:pointer;font-family:inherit;">${t('chat.mark_all_read')}</button>` : '') +
    notifications.map(n => `
    <div class="card notif-item" data-id="${n.id}" style="padding:var(--s-3);margin-bottom:var(--s-2);opacity:${n.is_read ? '0.7' : '1'};cursor:pointer;">
      <div style="font-size:14px;font-weight:${n.is_read ? '400' : '600'};">${n.title_ar || n.title || ''}</div>
      <div style="font-size:12px;color:var(--text-secondary);margin-top:2px;">${n.body_ar || n.body || ''}</div>
      <div style="font-size:10px;color:var(--text-muted);margin-top:4px;">${timeAgo(n.created_at)}</div>
    </div>
  `).join('');

  list.querySelector('#mark-all-read')?.addEventListener('click', async () => {
    await net.post('notifications.php', { action: 'mark-all-read' }).catch(() => {});
    store.set('notifications.unreadCount', 0);
    notifications.forEach(n => n.is_read = true);
    renderNotifications(el, notifications);
  });

  list.querySelectorAll('.notif-item').forEach(item => {
    item.addEventListener('click', () => {
      const id = item.dataset.id;
      const notif = notifications.find(n => n.id === id);
      if (!notif) return;
      const type = notif.type || notif.notification_type || '';
      if (type === 'friend_request' || type === 'friend_accept') {
        bus.emit('navigate', { world: 'social', scene: 'friends' });
      } else if (type === 'match_invite' || type === 'challenge') {
        bus.emit('navigate', { world: 'play' });
      } else if (type === 'tournament') {
        bus.emit('navigate', { world: 'tournaments' });
      } else if (type === 'achievement') {
        scene.push('achievements');
      }
    });
  });
}

function timeAgo(date) {
  if (!date) return '';
  const diff = Date.now() - new Date(date).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return t('common.now');
  if (mins < 60) return t('common.minutes_ago', { n: mins });
  const hours = Math.floor(mins / 60);
  if (hours < 24) return t('common.hours_ago', { n: hours });
  const days = Math.floor(hours / 24);
  return t('common.days_ago', { n: days });
}
