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);
    store.set('notifications.unreadCount', 0);
  } 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;
  }

  list.innerHTML = notifications.map(n => `
    <div class="card" style="padding:var(--s-3);margin-bottom:var(--s-2);opacity:${n.is_read ? '0.7' : '1'};">
      <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('');
}

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} يوم`;
}
