<?php $pageTitle = 'EL3AB - الاشعارات'; ?>
<?php require __DIR__ . '/../includes/header.php'; ?>

<div class="space-y-6">

  <div style="display:flex;align-items:center;justify-content:space-between;">
    <h2 style="font-size:22px;font-weight:700;">الاشعارات</h2>
    <button class="btn btn-ghost btn-xs" id="mark-all-read">قراءة الكل</button>
  </div>

  <div id="notifications-list" class="space-y-2">
    <div class="card">
      <div class="empty-state">
        <svg class="icon-lg" style="color:var(--text-3);margin-bottom:8px;"><use href="/public/icons/sprite.svg#icon-bell"></use></svg>
        <p>لا يوجد اشعارات</p>
      </div>
    </div>
  </div>

</div>

<script>
document.addEventListener('DOMContentLoaded', async () => {
  if (!App.isLoggedIn()) {
    window.location.href = '/login';
    return;
  }

  const data = await App.fetch('/api/notifications');
  if (data && data.notifications && data.notifications.length > 0) {
    const list = document.getElementById('notifications-list');
    list.innerHTML = data.notifications.map(n => {
      const icons = {
        friend_request: 'friends', game_invite: 'sword', achievement: 'star',
        reward: 'coin', tournament: 'trophy', system: 'bell'
      };
      const icon = icons[n.type] || 'bell';
      const unread = !n.read_at ? 'border-right:3px solid var(--cyan);' : '';
      return `
        <div class="card" style="${unread}">
          <div class="card-body" style="display:flex;align-items:center;gap:12px;">
            <svg class="icon" style="color:var(--cyan);flex-shrink:0;"><use href="/public/icons/sprite.svg#icon-${icon}"></use></svg>
            <div style="flex:1;">
              <p style="font-size:14px;">${n.message}</p>
              <p class="text-muted text-xs">${timeAgo(n.created_at)}</p>
            </div>
          </div>
        </div>
      `;
    }).join('');
  }

  document.getElementById('mark-all-read').addEventListener('click', async () => {
    await App.fetch('/api/notifications', {
      method: 'POST',
      body: JSON.stringify({ action: 'read_all' })
    });
    document.querySelectorAll('#notifications-list .card').forEach(c => {
      c.style.borderRight = '';
    });
    App.toast('تم تحديد الكل كمقروء');
  });
});

function timeAgo(dateStr) {
  const diff = Date.now() - new Date(dateStr).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 + ' يوم';
}
</script>

<?php require __DIR__ . '/../includes/footer.php'; ?>
