import * as net from '../../../core/net.js';
import * as store from '../../../core/store.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:#94a3b8;font-size:12px;padding:6px 14px;border-radius:8px;cursor:pointer;font-family:inherit;">تعليم الكل كمقروء</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);
  });
}

function timeAgo(date) {
  if (!date) return '';
  const diff = Date.now() - new Date(date).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'الآن';
  if (mins < 60) return `منذ ${mins} دقيقة`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `منذ ${hours} ساعة`;
  const days = Math.floor(hours / 24);
  return `منذ ${days} يوم`;
}
