<?php
require_once 'includes/config.php';
require_once 'includes/mailer.php';
requireLogin();
$uid = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    if ($action === 'send_request') {
        // Support both direct user_id and email
        $targetId = (int)($_POST['user_id'] ?? 0);
        if ($targetId) {
            $targetStmt = $pdo->prepare("SELECT id, name, email FROM users WHERE id=? AND is_verified=1");
            $targetStmt->execute([$targetId]);
            $target = $targetStmt->fetch();
        } else {
            $email = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
            if (!$email) jsonResponse(['success'=>false,'message'=>'Please enter an email.']);
            $targetStmt = $pdo->prepare("SELECT id, name, email FROM users WHERE email=? AND is_verified=1");
            $targetStmt->execute([$email]);
            $target = $targetStmt->fetch();
        }
        if (!$target)               jsonResponse(['success'=>false,'message'=>'No verified user found.']);
        if ($target['id'] === $uid) jsonResponse(['success'=>false,'message'=>'You cannot add yourself!']);
        $exists = $pdo->prepare("SELECT id FROM friend_requests WHERE (sender_id=? AND receiver_id=?) OR (sender_id=? AND receiver_id=?)");
        $exists->execute([$uid,$target['id'],$target['id'],$uid]);
        if ($exists->fetch()) jsonResponse(['success'=>false,'message'=>'Friend request already sent or you are already friends.']);
        $pdo->prepare("INSERT INTO friend_requests (sender_id,receiver_id) VALUES (?,?)")->execute([$uid,$target['id']]);
        $senderName = $_SESSION['user_name'] ?? 'Someone';
        if (!empty($target['email'])) {
            sendFriendRequest($target['email'], $target['name'], $senderName, SITE_URL . '/leaderboard');
        }
        $pdo->prepare("INSERT INTO notifications (user_id, title, message, type, link_url) VALUES (?, ?, ?, 'info', ?)")
            ->execute([
                $target['id'],
                '👥 New Friend Request',
                htmlspecialchars($senderName) . ' sent you a friend request. Visit the Leaderboard to accept or decline.',
                SITE_URL . '/leaderboard'
            ]);
        jsonResponse(['success'=>true,'message'=>"Friend request sent to {$target['name']}!"]);
    }

    if ($action === 'accept') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("UPDATE friend_requests SET status='accepted' WHERE id=? AND receiver_id=?")->execute([$id,$uid]);
        $frRow = $pdo->prepare("SELECT sender_id FROM friend_requests WHERE id=?");
        $frRow->execute([$id]); $frSenderId = (int)($frRow->fetchColumn() ?: 0);
        if ($frSenderId) {
            $acceptorName = $_SESSION['user_name'] ?? 'Someone';
            $pdo->prepare("INSERT INTO notifications (user_id, title, message, type, link_url) VALUES (?, ?, ?, 'success', ?)")
                ->execute([
                    $frSenderId,
                    '🎉 Friend Request Accepted!',
                    htmlspecialchars($acceptorName) . ' accepted your friend request. You can now see each other on the leaderboard!',
                    SITE_URL . '/leaderboard'
                ]);
        }
        jsonResponse(['success'=>true,'message'=>'Friend added!']);
    }

    if ($action === 'reject') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("UPDATE friend_requests SET status='rejected' WHERE id=? AND receiver_id=?")->execute([$id,$uid]);
        jsonResponse(['success'=>true]);
    }

    if ($action === 'remove') {
        $friendId = (int)($_POST['friend_id'] ?? 0);
        $pdo->prepare("DELETE FROM friend_requests WHERE ((sender_id=? AND receiver_id=?) OR (sender_id=? AND receiver_id=?)) AND status='accepted'")->execute([$uid,$friendId,$friendId,$uid]);
        jsonResponse(['success'=>true]);
    }

    if ($action === 'cancel') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("DELETE FROM friend_requests WHERE id=? AND sender_id=? AND status='pending'")->execute([$id,$uid]);
        jsonResponse(['success'=>true]);
    }
}

// Pending requests (to me)
$pending = $pdo->prepare("SELECT fr.*, u.name as sender_name FROM friend_requests fr JOIN users u ON fr.sender_id=u.id WHERE fr.receiver_id=? AND fr.status='pending'");
$pending->execute([$uid]); $pending = $pending->fetchAll();

// Pending requests (sent by me)
$sentPending = $pdo->prepare("SELECT fr.*, u.name as receiver_name FROM friend_requests fr JOIN users u ON fr.receiver_id=u.id WHERE fr.sender_id=? AND fr.status='pending'");
$sentPending->execute([$uid]); $sentPending = $sentPending->fetchAll();

// All users (excluding self) with their status and total study hours
$allUsers = $pdo->prepare("
    SELECT u.id, u.name, u.avatar,
           COALESCE(u.xp_points, 0) as xp,
           COALESCE((SELECT SUM(duration_minutes) FROM study_sessions WHERE user_id=u.id), 0) as total_mins,
           COALESCE((SELECT SUM(duration_minutes) FROM study_sessions WHERE user_id=u.id AND date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)), 0) as week_mins,
           (
             SELECT status FROM friend_requests
             WHERE (sender_id=? AND receiver_id=u.id) OR (receiver_id=? AND sender_id=u.id)
             ORDER BY created_at DESC LIMIT 1
           ) as fr_status,
           (
             SELECT id FROM friend_requests
             WHERE (sender_id=? AND receiver_id=u.id) OR (receiver_id=? AND sender_id=u.id)
             ORDER BY created_at DESC LIMIT 1
           ) as fr_id,
           (
             SELECT sender_id FROM friend_requests
             WHERE (sender_id=? AND receiver_id=u.id) OR (receiver_id=? AND sender_id=u.id)
             ORDER BY created_at DESC LIMIT 1
           ) as fr_sender_id
    FROM users u
    WHERE u.id != ? AND u.is_verified=1
    ORDER BY total_mins DESC
");
$allUsers->execute([$uid,$uid,$uid,$uid,$uid,$uid,$uid]);
$allUsers = $allUsers->fetchAll();

// --- Helper: fetch stats for a period ---
function getBoardForPeriod($pdo, $uid, $period) {
    if ($period === 'daily') {
        $whereDate = "AND date = CURDATE()";
    } elseif ($period === 'monthly') {
        $whereDate = "AND date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
    } else {
        $whereDate = "AND date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
    }

    $friends = $pdo->prepare("
        SELECT u.id, u.name, COALESCE(u.xp_points,0) as xp,
               (SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=u.id $whereDate) as period_mins,
               (SELECT COUNT(*) FROM study_sessions WHERE user_id=u.id) as total_sessions,
               (SELECT COUNT(*) FROM user_achievements WHERE user_id=u.id) as badges
        FROM users u
        JOIN friend_requests fr ON (fr.sender_id=u.id OR fr.receiver_id=u.id)
        WHERE fr.status='accepted' AND ((fr.sender_id=? AND fr.receiver_id=u.id) OR (fr.receiver_id=? AND fr.sender_id=u.id))
    ");
    $friends->execute([$uid, $uid]);
    $friends = $friends->fetchAll();

    $myStats = $pdo->prepare("
        SELECT COALESCE(xp_points,0) as xp,
               (SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=? $whereDate) as period_mins,
               (SELECT COUNT(*) FROM study_sessions WHERE user_id=?) as total_sessions,
               (SELECT COUNT(*) FROM user_achievements WHERE user_id=?) as badges
        FROM users WHERE id=?
    ");
    $myStats->execute([$uid,$uid,$uid,$uid]);
    $myStats = $myStats->fetch();

    $board = [['id'=>$uid,'name'=>$_SESSION['user_name'].' (You)','xp'=>$myStats['xp'],'period_mins'=>$myStats['period_mins'],'total_sessions'=>$myStats['total_sessions'],'badges'=>$myStats['badges'],'is_me'=>true]];
    foreach ($friends as $f) { $f['is_me'] = false; $board[] = $f; }
    usort($board, fn($a,$b)=>$b['period_mins']-$a['period_mins']);
    return $board;
}

$boardDaily   = getBoardForPeriod($pdo, $uid, 'daily');
$boardWeekly  = getBoardForPeriod($pdo, $uid, 'weekly');
$boardMonthly = getBoardForPeriod($pdo, $uid, 'monthly');

require_once 'includes/header.php';
renderHeader('Leaderboard', 'leaderboard');
?>

<style>
/* ── Filter Tabs ── */
.lb-filter-bar {
  display: flex;
  align-items: center;
  gap: 6px;
  background: var(--bg-secondary, rgba(255,255,255,.04));
  border: 1px solid var(--border);
  border-radius: 14px;
  padding: 5px;
}
.lb-tab {
  flex: 1;
  padding: 8px 18px;
  border-radius: 10px;
  border: none;
  background: transparent;
  color: var(--text-muted);
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: background .22s, color .22s, box-shadow .22s;
  white-space: nowrap;
}
.lb-tab.active {
  background: var(--card, rgba(255,255,255,.07));
  color: var(--text-primary);
  box-shadow: 0 2px 8px rgba(0,0,0,.18);
}
.lb-tab:hover:not(.active) { color: var(--text-primary); background: rgba(255,255,255,.04); }

/* ── Board panels ── */
.lb-panel { display: none; }
.lb-panel.active { display: flex; flex-direction: column; gap: 10px; }

/* ── Rank row ── */
.lb-row {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 14px;
  border-radius: 12px;
  border: 1px solid var(--border);
  background: var(--bg-secondary);
  transition: transform .18s, box-shadow .18s;
}
.lb-row:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0,0,0,.15); }
.lb-row.me {
  background: rgba(56,189,248,.08);
  border-color: rgba(56,189,248,.25);
}
.lb-row.rank-1 { background: rgba(251,191,36,.07); border-color: rgba(251,191,36,.3); }
.lb-row.rank-2 { background: rgba(148,163,184,.06); border-color: rgba(148,163,184,.25); }
.lb-row.rank-3 { background: rgba(251,146,60,.07); border-color: rgba(251,146,60,.25); }

.lb-rank-icon { font-size: 24px; font-weight: 800; width: 36px; text-align: center; flex-shrink: 0; }
.lb-rank-num  { font-size: 15px; font-weight: 800; width: 36px; text-align: center; color: var(--text-muted); flex-shrink: 0; }

.lb-avatar {
  width: 40px; height: 40px; border-radius: 10px; flex-shrink: 0;
  background: linear-gradient(135deg, #38bdf8, #818cf8);
  display: flex; align-items: center; justify-content: center;
  font-size: 16px; font-weight: 800; color: #fff;
}
.lb-name  { font-weight: 700; color: var(--text-primary); font-size: 14px; }
.lb-meta  { font-size: 12px; color: var(--text-muted); margin-top: 2px; }
.lb-time  { font-family: 'Sora', sans-serif; font-size: 19px; font-weight: 800; color: var(--teal, #38bdf8); text-align: right; }
.lb-time-label { font-size: 11px; color: var(--text-muted); text-align: right; }

.lb-empty {
  text-align: center; padding: 48px 24px; color: var(--text-muted);
}
.lb-empty .lb-empty-icon { font-size: 44px; margin-bottom: 12px; }
.lb-empty h3 { font-size: 16px; font-weight: 700; color: var(--text-primary); margin-bottom: 6px; }
.lb-empty p { font-size: 13px; }

@media (max-width: 500px) {
  .lb-filter-bar { gap: 3px; padding: 4px; }
  .lb-tab { padding: 7px 10px; font-size: 12px; }
}

/* ── Back ── */
.bm-back {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  color: var(--text-muted);
  font-size: 13px;
  font-weight: 600;
  text-decoration: none;
  margin-bottom: 26px;
  transition: color .18s;
}
.bm-back:hover { color: var(--text-primary); }

/* ── User Browse Modal ── */
.user-search-box {
  position: relative;
  margin-bottom: 14px;
}
.user-search-box input {
  width: 100%;
  padding: 10px 14px 10px 38px;
  border-radius: 10px;
  border: 1px solid var(--border);
  background: var(--bg-secondary);
  color: var(--text-primary);
  font-size: 14px;
  outline: none;
  box-sizing: border-box;
  transition: border-color .2s;
}
.user-search-box input:focus { border-color: rgba(56,189,248,.5); }
.user-search-box .search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-muted);
  font-size: 15px;
  pointer-events: none;
}

.user-list {
  max-height: 420px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding-right: 4px;
}
.user-list::-webkit-scrollbar { width: 4px; }
.user-list::-webkit-scrollbar-thumb { background: rgba(255,255,255,.12); border-radius: 4px; }

.user-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 11px 12px;
  border-radius: 10px;
  border: 1px solid var(--border);
  background: var(--bg-secondary);
  transition: border-color .18s, background .18s;
}
.user-card:hover { border-color: rgba(56,189,248,.3); background: rgba(56,189,248,.04); }

.user-card-avatar {
  width: 38px; height: 38px; border-radius: 9px; flex-shrink: 0;
  background: linear-gradient(135deg, #38bdf8, #818cf8);
  display: flex; align-items: center; justify-content: center;
  font-size: 15px; font-weight: 800; color: #fff;
  overflow: hidden;
}
.user-card-avatar img { width: 100%; height: 100%; object-fit: cover; }

.user-card-info { flex: 1; min-width: 0; }
.user-card-name { font-weight: 700; font-size: 13px; color: var(--text-primary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.user-card-hours { font-size: 11px; color: var(--text-muted); margin-top: 2px; }
.user-card-hours span.hrs-highlight { color: var(--teal, #38bdf8); font-weight: 700; }

.add-btn {
  flex-shrink: 0;
  padding: 5px 12px;
  border-radius: 8px;
  border: none;
  font-size: 12px;
  font-weight: 700;
  cursor: pointer;
  transition: opacity .18s, background .18s;
  white-space: nowrap;
}
.add-btn.btn-add      { background: rgba(56,189,248,.15); color: #38bdf8; border: 1px solid rgba(56,189,248,.3); }
.add-btn.btn-add:hover { background: rgba(56,189,248,.28); }
.add-btn.btn-pending  { background: rgba(251,191,36,.1); color: #f59e0b; border: 1px solid rgba(251,191,36,.25); cursor: default; }
.add-btn.btn-friends  { background: rgba(52,211,153,.1); color: #34d399; border: 1px solid rgba(52,211,153,.25); cursor: default; }
.add-btn.btn-incoming { background: rgba(129,140,248,.12); color: #818cf8; border: 1px solid rgba(129,140,248,.3); }
.add-btn.btn-incoming:hover { background: rgba(129,140,248,.25); }

.modal-users-count {
  font-size: 12px;
  color: var(--text-muted);
  margin-bottom: 10px;
}
</style>

  <!-- Back -->
  <a href="javascript:history.back()" class="bm-back">
    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
      <path d="M19 12H5M12 5l-7 7 7 7"/>
    </svg>
    Back
  </a>

<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:22px;flex-wrap:wrap">
  <div>
    <div style="font-size:22px;font-weight:800;font-family:'Sora',sans-serif">👥 Friend Leaderboard</div>
    <div style="font-size:13px;color:var(--text-muted);margin-top:3px">Compare your study hours with friends</div>
  </div>
  <button class="btn btn-primary" style="flex-shrink:0" onclick="document.getElementById('addFriendModal').classList.add('active')">＋ Add Friend</button>
</div>

<!-- Pending requests (incoming) -->
<?php if ($pending): ?>
<div class="card" style="margin-bottom:16px;border-color:rgba(251,191,36,0.3)">
  <div class="card-header"><div class="card-title">🔔 Pending Friend Requests</div></div>
  <div style="display:flex;flex-direction:column;gap:10px">
    <?php foreach ($pending as $p): ?>
    <div style="display:flex;align-items:center;justify-content:space-between;padding:10px 0;border-bottom:1px solid var(--border)">
      <div>
        <div style="font-weight:600;color:var(--text-primary)"><?= htmlspecialchars($p['sender_name']) ?></div>
      </div>
      <div style="display:flex;gap:8px">
        <button class="btn btn-success btn-sm" onclick="respond(<?=$p['id']?>,'accept')">✓ Accept</button>
        <button class="btn btn-danger btn-sm" onclick="respond(<?=$p['id']?>,'reject')">✕</button>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

<!-- Sent pending requests (outgoing) -->
<?php if ($sentPending): ?>
<div class="card" style="margin-bottom:16px;border-color:rgba(56,189,248,0.3)">
  <div class="card-header"><div class="card-title">📤 Sent Friend Requests</div></div>
  <div style="display:flex;flex-direction:column;gap:10px">
    <?php foreach ($sentPending as $s): ?>
    <div style="display:flex;align-items:center;justify-content:space-between;padding:10px 0;border-bottom:1px solid var(--border)">
      <div>
        <div style="font-weight:600;color:var(--text-primary)"><?= htmlspecialchars($s['receiver_name']) ?></div>
      </div>
      <div style="display:flex;align-items:center;gap:10px">
        <span style="font-size:12px;color:var(--text-muted);background:rgba(56,189,248,0.1);border:1px solid rgba(56,189,248,0.25);padding:3px 10px;border-radius:99px">⏳ Pending</span>
        <button class="btn btn-danger btn-sm" onclick="cancelRequest(<?=$s['id']?>)" title="Cancel request">✕ Cancel</button>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

<!-- Leaderboard Card -->
<div class="card">
  <div class="card-header" style="flex-wrap:wrap;gap:12px">
    <div class="card-title">🏆 Rankings</div>
    <!-- Filter Tabs -->
    <div class="lb-filter-bar" role="tablist">
      <button class="lb-tab active" data-period="daily"   onclick="switchPeriod('daily')"  >📅 Daily</button>
      <button class="lb-tab"        data-period="weekly"  onclick="switchPeriod('weekly')" >📆 Weekly</button>
      <button class="lb-tab"        data-period="monthly" onclick="switchPeriod('monthly')">🗓️ Monthly</button>
    </div>
  </div>

  <?php
  function renderBoard($board, $period) {
      $labels = ['daily'=>'today','weekly'=>'this week','monthly'=>'this month'];
      $label  = $labels[$period];
      if (count($board) <= 1 && !$board[0]['period_mins']) {
          echo "<div class='lb-empty'><div class='lb-empty-icon'>📚</div><h3>No data yet</h3><p>Study sessions logged $label will appear here.</p></div>";
          return;
      }
      foreach ($board as $i => $u):
          $rank   = $i + 1;
          $hrs    = floor($u['period_mins'] / 60);
          $mins   = $u['period_mins'] % 60;
          $classes = 'lb-row';
          if ($u['is_me'])  $classes .= ' me';
          if ($rank === 1)  $classes .= ' rank-1';
          if ($rank === 2)  $classes .= ' rank-2';
          if ($rank === 3)  $classes .= ' rank-3';
          $rankIcon = match($rank) { 1=>'🥇', 2=>'🥈', 3=>'🥉', default=>null };
          echo "<div class='$classes'>";
          if ($rankIcon) echo "<div class='lb-rank-icon'>$rankIcon</div>";
          else           echo "<div class='lb-rank-num'>#$rank</div>";
          echo "<div class='lb-avatar'>".strtoupper($u['name'][0])."</div>";
          echo "<div style='flex:1;min-width:0'>";
          echo "<div class='lb-name'>".htmlspecialchars($u['name'])."</div>";
          echo "<div class='lb-meta'>{$u['total_sessions']} sessions &middot; {$u['badges']} badges &middot; {$u['xp']} XP</div>";
          echo "</div>";
          echo "<div><div class='lb-time'>{$hrs}h {$mins}m</div><div class='lb-time-label'>$label</div></div>";
          if (!$u['is_me']) echo "<button onclick='removeFriend({$u['id']})' style='background:none;border:none;color:var(--text-muted);cursor:pointer;font-size:14px;padding:4px 6px;border-radius:6px' title='Remove friend'>✕</button>";
          echo "</div>";
      endforeach;
  }
  ?>

  <div id="panel-daily" class="lb-panel active">
    <?php renderBoard($boardDaily, 'daily'); ?>
  </div>
  <div id="panel-weekly" class="lb-panel">
    <?php renderBoard($boardWeekly, 'weekly'); ?>
  </div>
  <div id="panel-monthly" class="lb-panel">
    <?php renderBoard($boardMonthly, 'monthly'); ?>
  </div>
</div>

<!-- Add Friend Modal — User Browse -->
<div class="modal-overlay" id="addFriendModal">
  <div class="modal" style="max-width:480px;width:100%">
    <div class="modal-header">
      <span class="modal-title">👥 Add Friend</span>
      <button class="modal-close" onclick="document.getElementById('addFriendModal').classList.remove('active')">✕</button>
    </div>

    <div id="friendMsg" class="alert" style="display:none"></div>

    <!-- Search box -->
    <div class="user-search-box">
      <span class="search-icon">🔍</span>
      <input type="text" id="userSearchInput" placeholder="Search by name…" oninput="filterUsers(this.value)">
    </div>

    <div class="modal-users-count" id="usersCount"></div>

    <!-- User list -->
    <div class="user-list" id="userList">
      <?php foreach ($allUsers as $u):
        $totalHrs  = floor($u['total_mins'] / 60);
        $totalMins = $u['total_mins'] % 60;
        $weekHrs   = floor($u['week_mins'] / 60);
        $weekMins  = $u['week_mins'] % 60;
        $initials  = strtoupper(mb_substr($u['name'], 0, 1));

        // Determine button state
        $btnHtml = '';
        if ($u['fr_status'] === 'accepted') {
            $btnHtml = "<button class='add-btn btn-friends' disabled>✓ Friends</button>";
        } elseif ($u['fr_status'] === 'pending' && (int)$u['fr_sender_id'] === $uid) {
            $btnHtml = "<button class='add-btn btn-pending' disabled>⏳ Pending</button>";
        } elseif ($u['fr_status'] === 'pending' && (int)$u['fr_sender_id'] !== $uid) {
            // They sent us a request — we can accept from here
            $btnHtml = "<button class='add-btn btn-incoming' onclick=\"respond({$u['fr_id']},'accept')\">✓ Accept</button>";
        } else {
            $btnHtml = "<button class='add-btn btn-add' onclick=\"sendRequestById({$u['id']}, this)\">＋ Add</button>";
        }
      ?>
      <div class="user-card" data-name="<?= htmlspecialchars(strtolower($u['name'])) ?>">
        <div class="user-card-avatar">
          <?php if ($u['avatar']): ?>
            <img src="assets/uploads/avatars/<?= htmlspecialchars($u['avatar']) ?>" alt="">
          <?php else: ?>
            <?= $initials ?>
          <?php endif; ?>
        </div>
        <div class="user-card-info">
          <div class="user-card-name"><?= htmlspecialchars($u['name']) ?></div>
          <div class="user-card-hours">
            Total: <span class="hrs-highlight"><?= $totalHrs ?>h <?= $totalMins ?>m</span>
            &nbsp;·&nbsp; This week: <span class="hrs-highlight"><?= $weekHrs ?>h <?= $weekMins ?>m</span>
          </div>
        </div>
        <?= $btnHtml ?>
      </div>
      <?php endforeach; ?>

      <?php if (empty($allUsers)): ?>
        <div style="text-align:center;padding:32px;color:var(--text-muted)">
          <div style="font-size:36px;margin-bottom:8px">👤</div>
          <div style="font-size:13px">No other verified users found.</div>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<?php require_once 'includes/footer.php'; renderFooter(); ?>
<script>
/* ── Period Filter ── */
function switchPeriod(period) {
  document.querySelectorAll('.lb-tab').forEach(t => t.classList.remove('active'));
  document.querySelectorAll('.lb-panel').forEach(p => p.classList.remove('active'));
  document.querySelector('[data-period="'+period+'"]').classList.add('active');
  document.getElementById('panel-'+period).classList.add('active');
  localStorage.setItem('lb_period', period);
}

(function(){
  var saved = localStorage.getItem('lb_period');
  if (saved && ['daily','weekly','monthly'].includes(saved)) {
    switchPeriod(saved);
  }
})();

/* Update count on modal open */
document.getElementById('addFriendModal').addEventListener('transitionend', updateCount);
document.querySelector('[onclick*="addFriendModal"]') && document.querySelectorAll('[onclick*="addFriendModal"]').forEach(btn => {
  btn.addEventListener('click', () => setTimeout(updateCount, 50));
});

function updateCount() {
  var visible = document.querySelectorAll('#userList .user-card:not([style*="display: none"])').length;
  var total   = document.querySelectorAll('#userList .user-card').length;
  var el = document.getElementById('usersCount');
  if (el) el.textContent = visible + ' of ' + total + ' users';
}

/* ── User search filter ── */
function filterUsers(query) {
  query = query.toLowerCase().trim();
  document.querySelectorAll('#userList .user-card').forEach(function(card) {
    var name = card.getAttribute('data-name') || '';
    card.style.display = (!query || name.includes(query)) ? '' : 'none';
  });
  updateCount();
}

/* ── Friend actions ── */
async function post(data) {
  const fd = new FormData();
  Object.entries(data).forEach(([k,v])=>fd.append(k,v));
  const r = await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
  return r.json();
}

/* Send by user_id (from browse modal) */
async function sendRequestById(userId, btn) {
  btn.disabled = true;
  btn.textContent = '…';
  const data = await post({action:'send_request', user_id: userId});
  const msg = document.getElementById('friendMsg');
  msg.style.display = 'flex';
  msg.className = 'alert ' + (data.success ? 'alert-success' : 'alert-error');
  msg.textContent = data.message;
  if (data.success) {
    btn.className = 'add-btn btn-pending';
    btn.textContent = '⏳ Pending';
  } else {
    btn.disabled = false;
    btn.textContent = '＋ Add';
  }
}

/* Send by email (legacy, kept for compatibility) */
async function sendRequest() {
  const email = document.getElementById('friendEmail') ? document.getElementById('friendEmail').value : '';
  const data = await post({action:'send_request', email});
  const msg = document.getElementById('friendMsg');
  msg.style.display='flex'; msg.className='alert '+(data.success?'alert-success':'alert-error');
  msg.textContent = data.message;
  if (data.success) setTimeout(()=>location.reload(),1200);
}

async function respond(id, action) {
  await post({action, id});
  location.reload();
}

async function removeFriend(friendId) {
  if (!(await stConfirm('Remove this friend?'))) return;
  await post({action:'remove',friend_id:friendId});
  location.reload();
}

async function cancelRequest(id) {
  if (!(await stConfirm('Cancel this friend request?'))) return;
  await post({action:'cancel', id});
  location.reload();
}

// Initial count
updateCount();
</script>