<?php $pageTitle = 'EL3AB - الاصدقاء'; ?>
<?php require __DIR__ . '/../includes/header.php'; ?>

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

  <div class="text-center">
    <h2 style="font-size:22px;font-weight:700;">الاصدقاء</h2>
  </div>

  <!-- Search -->
  <div class="input-group">
    <svg class="icon input-icon"><use href="/public/icons/sprite.svg#icon-search"></use></svg>
    <input type="text" class="input" id="friend-search" placeholder="ابحث عن لاعب...">
  </div>

  <!-- Tabs -->
  <div class="tab-group" id="friends-tabs">
    <button class="tab active" data-tab="friends">اصدقائي</button>
    <button class="tab" data-tab="requests">طلبات</button>
    <button class="tab" data-tab="search">بحث</button>
  </div>

  <!-- Friends List -->
  <div id="tab-friends" class="space-y-2">
    <div class="card" id="friends-list">
      <div class="empty-state">
        <svg class="icon-lg" style="color:var(--text-3);margin-bottom:8px;"><use href="/public/icons/sprite.svg#icon-friends"></use></svg>
        <p>لا يوجد اصدقاء بعد</p>
        <p class="text-muted text-xs">ابحث عن لاعبين واضفهم</p>
      </div>
    </div>
  </div>

  <!-- Requests -->
  <div id="tab-requests" class="space-y-2" style="display:none;">
    <div class="card" id="requests-list">
      <div class="empty-state">
        <p>لا يوجد طلبات صداقة</p>
      </div>
    </div>
  </div>

  <!-- Search Results -->
  <div id="tab-search" class="space-y-2" style="display:none;">
    <div class="card" id="search-results">
      <div class="empty-state">
        <p>اكتب اسم اللاعب للبحث</p>
      </div>
    </div>
  </div>

</div>

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

  const tabs = document.querySelectorAll('#friends-tabs .tab');
  tabs.forEach(tab => {
    tab.addEventListener('click', () => {
      tabs.forEach(t => t.classList.remove('active'));
      tab.classList.add('active');
      document.querySelectorAll('[id^="tab-"]').forEach(p => p.style.display = 'none');
      document.getElementById('tab-' + tab.dataset.tab).style.display = 'block';
    });
  });

  loadFriends();

  let searchTimeout;
  document.getElementById('friend-search').addEventListener('input', (e) => {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => searchPlayers(e.target.value), 500);
  });
});

async function loadFriends() {
  const data = await App.fetch('/api/friends?action=list');
  if (data && data.friends && data.friends.length > 0) {
    const list = document.getElementById('friends-list');
    list.innerHTML = data.friends.map(f => `
      <div class="card-body" style="display:flex;align-items:center;gap:12px;padding:12px;border-bottom:1px solid var(--border);">
        <div class="avatar avatar-sm">
          <svg class="icon"><use href="/public/icons/sprite.svg#icon-profile"></use></svg>
        </div>
        <div style="flex:1;">
          <p style="font-size:14px;font-weight:600;">${f.display_name || f.username}</p>
          <p class="text-muted text-xs">${f.elo_blitz || 1200} ELO</p>
        </div>
        <span class="badge ${f.online ? 'badge-success' : ''}">${f.online ? 'متصل' : 'غير متصل'}</span>
      </div>
    `).join('');
  }

  const reqData = await App.fetch('/api/friends?action=requests');
  if (reqData && reqData.requests && reqData.requests.length > 0) {
    const reqList = document.getElementById('requests-list');
    reqList.innerHTML = reqData.requests.map(r => `
      <div class="card-body" style="display:flex;align-items:center;gap:12px;padding:12px;border-bottom:1px solid var(--border);">
        <div class="avatar avatar-sm">
          <svg class="icon"><use href="/public/icons/sprite.svg#icon-profile"></use></svg>
        </div>
        <div style="flex:1;">
          <p style="font-size:14px;font-weight:600;">${r.display_name || r.username}</p>
        </div>
        <button class="btn btn-cyan btn-xs" onclick="acceptFriend('${r.id}')">قبول</button>
        <button class="btn btn-ghost btn-xs" onclick="rejectFriend('${r.id}')">رفض</button>
      </div>
    `).join('');
  }
}

async function searchPlayers(query) {
  if (!query || query.length < 2) return;
  const data = await App.fetch('/api/friends?action=search&q=' + encodeURIComponent(query));
  const results = document.getElementById('search-results');
  if (data && data.players && data.players.length > 0) {
    results.innerHTML = data.players.map(p => `
      <div class="card-body" style="display:flex;align-items:center;gap:12px;padding:12px;border-bottom:1px solid var(--border);">
        <div class="avatar avatar-sm">
          <svg class="icon"><use href="/public/icons/sprite.svg#icon-profile"></use></svg>
        </div>
        <div style="flex:1;">
          <p style="font-size:14px;font-weight:600;">${p.display_name || p.username}</p>
          <p class="text-muted text-xs">${p.elo_blitz || 1200} ELO</p>
        </div>
        <button class="btn btn-cyan btn-xs" onclick="addFriend('${p.id}')">اضافة</button>
      </div>
    `).join('');
  } else {
    results.innerHTML = '<div class="empty-state"><p>لا توجد نتائج</p></div>';
  }
}

async function addFriend(userId) {
  await App.fetch('/api/friends', {
    method: 'POST',
    body: JSON.stringify({ action: 'add', user_id: userId })
  });
  App.toast('تم ارسال طلب الصداقة', 'success');
}

async function acceptFriend(requestId) {
  await App.fetch('/api/friends', {
    method: 'POST',
    body: JSON.stringify({ action: 'accept', request_id: requestId })
  });
  App.toast('تم قبول الصداقة', 'success');
  loadFriends();
}

async function rejectFriend(requestId) {
  await App.fetch('/api/friends', {
    method: 'POST',
    body: JSON.stringify({ action: 'reject', request_id: requestId })
  });
  loadFriends();
}
</script>

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