<?php
/**
 * FILE: public_html/reviewers.php
 * Dynamic Reviewer Listing Page — CommuneGlobal
 *
 * Shows ONLY: rpp.is_published = 1 AND rpp.approval_status = 'approved'
 *
 * Filters:
 *   q        — full-text search
 *   country  — filter by country (from affiliations or users table)
 *   area     — filter by research topic ID
 *   sort     — reviews | rate | newest | name
 *   page     — pagination
 */
ini_set('display_errors', 0);
if (session_status() === PHP_SESSION_NONE) session_start();
include_once __DIR__ . '/config/db_new.php';

/* ── GET params ─────────────────────────────────────────────── */
$search   = trim($_GET['q']       ?? '');
$country  = trim($_GET['country'] ?? '');
$area_id  = (int)($_GET['area']   ?? 0);
$sort     = trim($_GET['sort']    ?? 'reviews');
$page     = max(1, (int)($_GET['page'] ?? 1));
$per_page = 12;
$offset   = ($page - 1) * $per_page;

$valid_sorts = ['reviews','rate','newest','name'];
if (!in_array($sort, $valid_sorts)) $sort = 'reviews';

/* ── Base WHERE (only approved + published) ─────────────────── */
$where  = ["rpp.is_published = 1", "rpp.approval_status = 'approved'"];
$params = [];

if ($search !== '') {
    $where[] = "(CONCAT(u.first_name,' ',u.last_name) LIKE ?
        OR u.first_name LIKE ? OR u.last_name LIKE ?
        OR rpp.bio LIKE ? OR rpp.current_position LIKE ?
        OR ri_search.interests LIKE ?)";
    $s = "%{$search}%";
    $params = array_merge($params, [$s,$s,$s,$s,$s,$s]);
}
if ($country !== '' && $country !== 'all') {
    $where[] = "(u.country = ? OR a.country = ?)";
    $params[] = $country; $params[] = $country;
}
if ($area_id > 0) {
    $where[] = "uri_filter.user_id IS NOT NULL";
}

$where_sql = 'WHERE ' . implode(' AND ', $where);

/* ── Rebuild where_sql without uri_filter if no area ──────── */
if ($area_id <= 0) {
    $w2 = array_filter($where, fn($w) => strpos($w,'uri_filter') === false);
    $where_sql = 'WHERE ' . implode(' AND ', $w2);
}

/* ── Sort ───────────────────────────────────────────────────── */
$sort_map = [
    'reviews' => 'r.total_reviews_completed DESC',
    'rate'    => 'acceptance_rate DESC',
    'newest'  => 'rpp.created_at DESC',
    'name'    => 'u.first_name ASC, u.last_name ASC',
];
$order_sql = $sort_map[$sort];

/* ── Area filter JOIN ───────────────────────────────────────── */
$area_join = $area_id > 0
    ? "LEFT JOIN user_research_interests uri_filter
           ON uri_filter.user_id = u.user_id AND uri_filter.topic_id = {$area_id}"
    : '';

/* ── Interests search subquery ──────────────────────────────── */
$interests_subq = "LEFT JOIN (
    SELECT uri2.user_id, GROUP_CONCAT(rt2.title SEPARATOR ' ') AS interests
    FROM user_research_interests uri2
    JOIN research_topics rt2 ON rt2.topic_id = uri2.topic_id
    GROUP BY uri2.user_id
) ri_search ON ri_search.user_id = u.user_id";

/* ── Main SELECT ────────────────────────────────────────────── */
$main_select = "
SELECT
    rpp.id AS profile_id, rpp.slug, rpp.bio, rpp.current_position,
    rpp.total_experience_yrs, rpp.h_index, rpp.total_citations,
    rpp.is_verified, rpp.profile_views,
    u.user_id, u.first_name, u.last_name, u.title AS user_title,
    u.country AS user_country, u.created_at AS member_since,
    r.id AS reviewer_id, r.reviewer_rating, r.total_reviews_completed,
    r.is_available, r.reviewing_interests,
    a.name AS affil_name, a.city AS affil_city, a.country AS affil_country,
    COALESCE(ra_stats.total_assigned,0) AS total_assigned,
    COALESCE(ra_stats.total_completed, r.total_reviews_completed, 0) AS completed,
    CASE
        WHEN COALESCE(ra_stats.total_assigned,0) > 0
        THEN ROUND(COALESCE(ra_stats.total_completed,0) / ra_stats.total_assigned * 100)
        ELSE 0
    END AS acceptance_rate,
    COALESCE(interests_agg.top_interests,'') AS top_interests
FROM reviewer_public_profile rpp
JOIN  users u ON u.user_id = rpp.user_id
JOIN  reviewers r ON r.id = rpp.reviewer_id
LEFT JOIN affiliations a ON a.affiliation_id = COALESCE(rpp.profile_affiliation_id, u.affiliation_id)
LEFT JOIN (
    SELECT reviewer_id,
           COUNT(*) AS total_assigned,
           SUM(assignment_status = 'review_submitted') AS total_completed
    FROM review_assignments GROUP BY reviewer_id
) ra_stats ON ra_stats.reviewer_id = r.id
LEFT JOIN (
    SELECT uri.user_id,
           GROUP_CONCAT(rt.title ORDER BY rt.title SEPARATOR '||' LIMIT 5) AS top_interests
    FROM user_research_interests uri
    JOIN research_topics rt ON rt.topic_id = uri.topic_id
    WHERE uri.source IN ('manual','auto_suggested')
    GROUP BY uri.user_id
) interests_agg ON interests_agg.user_id = u.user_id
{$interests_subq}
{$area_join}";

/* ── Count query ────────────────────────────────────────────── */
$count_sql = "SELECT COUNT(DISTINCT rpp.id)
FROM reviewer_public_profile rpp
JOIN users u ON u.user_id = rpp.user_id
JOIN reviewers r ON r.id = rpp.reviewer_id
LEFT JOIN affiliations a ON a.affiliation_id = COALESCE(rpp.profile_affiliation_id, u.affiliation_id)
LEFT JOIN (SELECT uri2.user_id, GROUP_CONCAT(rt2.title SEPARATOR ' ') AS interests
    FROM user_research_interests uri2 JOIN research_topics rt2 ON rt2.topic_id = uri2.topic_id GROUP BY uri2.user_id
) ri_search ON ri_search.user_id = u.user_id
{$area_join}
{$where_sql}";

$total_count = 0; $reviewers = [];
try {
    $cs = $pdo->prepare($count_sql); $cs->execute($params);
    $total_count = (int)$cs->fetchColumn();

    $data_sql = $main_select . " {$where_sql} GROUP BY rpp.id ORDER BY {$order_sql} LIMIT {$per_page} OFFSET {$offset}";
    $ds = $pdo->prepare($data_sql); $ds->execute($params);
    $reviewers = $ds->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { error_log('reviewers.php: '.$e->getMessage()); }

$total_pages = max(1, ceil($total_count / $per_page));

/* ── ALL Countries — from all reviewers, ordered by reviewer count DESC ── */
// Shows every country that has at least one reviewer profile (any status),
// so the sidebar/pills always have useful options even with few approved profiles.
$all_countries = [];
try {
    $cq = $pdo->query("
        SELECT COALESCE(a.country, u.country) AS cname,
               COUNT(DISTINCT r.id) AS cnt
        FROM reviewers r
        JOIN users u ON u.user_id = r.user_id
        LEFT JOIN reviewer_public_profile rpp ON rpp.reviewer_id = r.id
        LEFT JOIN affiliations a ON a.affiliation_id = COALESCE(rpp.profile_affiliation_id, u.affiliation_id)
        WHERE COALESCE(a.country, u.country) IS NOT NULL
          AND COALESCE(a.country, u.country) != ''
        GROUP BY cname
        ORDER BY cnt DESC, cname ASC
    ");
    $all_countries = $cq->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {}

/* ── ALL Research Areas — from all reviewers, ordered by reviewer count DESC ── */
// Pulls every research topic linked to any reviewer (any status), so filters
// are always populated and useful even with few approved profiles.
$all_areas = [];
try {
    $raq = $pdo->query("
        SELECT rt.topic_id, rt.title,
               COUNT(DISTINCT uri.user_id) AS cnt
        FROM research_topics rt
        JOIN user_research_interests uri ON uri.topic_id = rt.topic_id
        JOIN reviewers r ON r.user_id = uri.user_id
        GROUP BY rt.topic_id, rt.title
        ORDER BY cnt DESC, rt.title ASC
    ");
    $all_areas = $raq->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {}

/* ── Top countries for pills (top 8 by count, already sorted DESC) ────── */
$top_countries = array_slice($all_countries, 0, 8);
// Keep all_countries in count-DESC order for the dropdown (most reviewers first)

/* ── Currently selected area name ───────────────────────────── */
$selected_area_name = '';
foreach ($all_areas as $ar) {
    if ($ar['topic_id'] == $area_id) { $selected_area_name = $ar['title']; break; }
}

/* ── Flags map ──────────────────────────────────────────────── */
$flags = [
    'India'=>'🇮🇳','United States'=>'🇺🇸','USA'=>'🇺🇸','UK'=>'🇬🇧','United Kingdom'=>'🇬🇧',
    'Germany'=>'🇩🇪','Japan'=>'🇯🇵','China'=>'🇨🇳','Nigeria'=>'🇳🇬','Australia'=>'🇦🇺',
    'Canada'=>'🇨🇦','France'=>'🇫🇷','Brazil'=>'🇧🇷','South Africa'=>'🇿🇦','Pakistan'=>'🇵🇰',
    'Bangladesh'=>'🇧🇩','Egypt'=>'🇪🇬','Iran'=>'🇮🇷','Turkey'=>'🇹🇷','Spain'=>'🇪🇸',
    'Italy'=>'🇮🇹','Netherlands'=>'🇳🇱','Sweden'=>'🇸🇪','Norway'=>'🇳🇴','Ghana'=>'🇬🇭',
    'Kenya'=>'🇰🇪','Ethiopia'=>'🇪🇹','Malaysia'=>'🇲🇾','Indonesia'=>'🇮🇩','Philippines'=>'🇵🇭',
    'South Korea'=>'🇰🇷','Mexico'=>'🇲🇽','Argentina'=>'🇦🇷','Colombia'=>'🇨🇴',
];
$avatar_colors = ['#1a3a8f','#0d6efd','#059669','#7c3aed','#dc2626','#b45309','#0891b2','#065f46'];

/* ── Helpers ────────────────────────────────────────────────── */
function getInitials(string $f, string $l): string { return strtoupper(substr($f,0,1).substr($l,0,1)); }
function buildUrl(array $p): string {
    $e = $_GET;
    foreach ($p as $k=>$v) { if ($v===null||$v==='') unset($e[$k]); else $e[$k]=$v; }
    $q = http_build_query($e);
    return '?'.($q?:'');
}
function starRating(float $r): string {
    $full=floor($r); $half=(($r-$full)>=.5)?1:0; $empty=5-$full-$half;
    $h=''; for($i=0;$i<$full;$i++) $h.='<i class="fas fa-star"></i>';
    if($half) $h.='<i class="fas fa-star-half-stroke"></i>';
    for($i=0;$i<$empty;$i++) $h.='<i class="far fa-star"></i>';
    return $h;
}
function esc($v){ return htmlspecialchars($v??'',ENT_QUOTES,'UTF-8'); }

$sortOptions = ['reviews'=>'Most Reviews','rate'=>'Acceptance Rate','newest'=>'Newest','name'=>'Name A–Z'];
$pageTitle = 'Expert Reviewers — CommuneGlobal';
include __DIR__ . '/include/header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= esc($pageTitle) ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=DM+Serif+Display&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
<style>
:root {
  --navy:#0d2137; --cobalt:#1a3a8f; --sky:#2563eb; --sky-lt:#eff6ff;
  --gold:#e8a842; --muted:#64748b; --border:#e2e8f0;
}
body { font-family:'DM Sans',sans-serif; background:#f8fafc; }

/* Hero */
.rev-hero {
  background:linear-gradient(135deg,var(--navy) 0%,#1a3a6e 55%,var(--cobalt) 100%);
  padding:48px 0 40px; position:relative; overflow:hidden;
}
.rev-hero::after {
  content:''; position:absolute; inset:0; pointer-events:none;
  background-image:radial-gradient(circle at 75% 40%,rgba(59,125,216,.22) 0%,transparent 55%),
                   radial-gradient(circle at 20% 80%,rgba(232,168,66,.1) 0%,transparent 50%);
}
.rev-hero h1 { font-family:'DM Serif Display',serif; font-size:clamp(1.7rem,3vw,2.4rem); color:#fff; }
.rev-hero p  { color:rgba(255,255,255,.72); font-size:.93rem; }
.hero-search .form-control { border-radius:50px 0 0 50px!important; border:none; height:46px; padding-left:20px; }
.hero-search .btn { border-radius:0 50px 50px 0!important; background:var(--gold); border:none; color:var(--navy); font-weight:600; padding:0 22px; }
.hero-stat { color:rgba(255,255,255,.75); font-size:.8rem; }
.hero-stat strong { font-family:'DM Serif Display',serif; font-size:1.25rem; color:#fff; display:block; }

/* Quick filter pills row */
.pill-row { background:#fff; border-bottom:1px solid var(--border); padding:12px 0; }
.pill-row .overflow-scroll { display:flex; gap:6px; overflow-x:auto; scrollbar-width:none; padding-bottom:2px; }
.pill-row .overflow-scroll::-webkit-scrollbar { display:none; }
.fpill {
  display:inline-flex; align-items:center; gap:5px; padding:6px 14px;
  font-size:.8rem; font-weight:500; border:1px solid var(--border);
  border-radius:50px; background:#fff; color:var(--muted);
  white-space:nowrap; text-decoration:none; cursor:pointer; transition:all .15s;
  flex-shrink:0;
}
.fpill:hover { background:var(--sky-lt); border-color:var(--sky); color:var(--sky); }
.fpill.active { background:var(--sky-lt); border-color:var(--sky); color:var(--sky); font-weight:600; }
.fpill .badge { background:var(--sky-lt); color:var(--sky); font-size:.68rem; border-radius:10px; padding:1px 6px; }
.fpill.active .badge { background:#dbeafe; }

/* Filter sidebar card */
.filter-card { background:#fff; border:1px solid var(--border); border-radius:12px; }
.fc-header { padding:12px 16px; border-bottom:1px solid var(--border); display:flex; align-items:center; justify-content:space-between; }
.fc-header .title { font-weight:600; font-size:.88rem; color:var(--navy); display:flex; align-items:center; gap:7px; }
.fc-body { padding:14px 16px; }
.fc-section-title { font-size:.7rem; font-weight:700; text-transform:uppercase; letter-spacing:.07em; color:var(--muted); margin:10px 0 6px; }

/* Scrollable area list */
.area-list { max-height:280px; overflow-y:auto; scrollbar-width:thin; scrollbar-color:#e2e8f0 transparent; }
.area-list::-webkit-scrollbar { width:4px; }
.area-list::-webkit-scrollbar-thumb { background:#e2e8f0; border-radius:4px; }
.area-item {
  display:flex; align-items:center; justify-content:space-between;
  padding:5px 8px; border-radius:7px; cursor:pointer;
  font-size:.83rem; color:#374151; text-decoration:none; transition:background .1s;
}
.area-item:hover { background:#f1f5f9; }
.area-item.active { background:var(--sky-lt); color:var(--sky); font-weight:600; }
.area-cnt { font-size:.72rem; color:var(--muted); background:#f1f5f9; padding:1px 6px; border-radius:8px; flex-shrink:0; }
.area-item.active .area-cnt { background:#dbeafe; color:var(--sky); }
.area-search { width:100%; border:1px solid var(--border); border-radius:8px; padding:6px 10px; font-size:.82rem; outline:none; color:#374151; margin-bottom:8px; }
.area-search:focus { border-color:var(--sky); }

/* Country select */
.country-select { width:100%; border:1px solid var(--border); border-radius:8px; padding:7px 10px; font-size:.83rem; color:#374151; outline:none; background:#fff; }
.country-select:focus { border-color:var(--sky); }

/* Sort links */
.sort-item { display:block; padding:4px 8px; font-size:.83rem; border-radius:6px; text-decoration:none; color:#374151; }
.sort-item:hover { background:#f1f5f9; }
.sort-item.active { color:var(--sky); font-weight:600; background:var(--sky-lt); }

/* Active filter tags */
.active-tag {
  display:inline-flex; align-items:center; gap:5px;
  background:var(--sky-lt); color:var(--sky); border:1px solid #bfdbfe;
  border-radius:20px; padding:3px 10px; font-size:.77rem; font-weight:500;
}
.active-tag a { color:var(--sky); line-height:1; text-decoration:none; font-weight:700; }

/* Reviewer cards */
.rev-card {
  background:#fff; border:1px solid var(--border); border-radius:12px;
  padding:18px; transition:box-shadow .18s,transform .18s;
  display:flex; gap:14px; align-items:flex-start;
  text-decoration:none; color:inherit; position:relative;
}
.rev-card:hover { box-shadow:0 6px 24px rgba(13,33,55,.09); transform:translateY(-2px); color:inherit; }
.rev-avatar { width:58px; height:58px; border-radius:10px; flex-shrink:0; display:flex; align-items:center; justify-content:center; font-size:1.15rem; font-weight:700; color:#fff; }
.rev-name { font-size:.95rem; font-weight:600; color:var(--navy); }
.rev-verified { color:#10b981; font-size:.82rem; margin-left:3px; }
.rev-pos  { font-size:.8rem; color:var(--muted); }
.rev-inst { font-size:.8rem; color:var(--muted); }
.rev-loc  { font-size:.76rem; color:var(--muted); display:flex; align-items:center; gap:4px; }
.rev-tags .badge { background:var(--sky-lt); color:var(--sky); font-weight:500; font-size:.7rem; border-radius:50px; padding:3px 9px; }
.rev-stars { color:var(--gold); font-size:.7rem; }
.rev-stat-num { font-size:1.2rem; font-weight:700; color:var(--navy); line-height:1; }
.rev-stat-pct { font-size:1rem; font-weight:700; color:var(--sky); line-height:1; }
.rev-stat-lbl { font-size:.7rem; color:var(--muted); }
.avail-dot { width:7px; height:7px; background:#10b981; border-radius:50%; display:inline-block; }
.results-bar { font-size:.85rem; color:var(--muted); }
.results-bar strong { color:var(--navy); }
.empty-state { text-align:center; padding:56px 20px; }
.empty-state i { font-size:3rem; opacity:.2; margin-bottom:14px; display:block; }

/* Pagination */
.page-link { color:var(--sky); border-color:var(--border); font-size:.85rem; }
.page-item.active .page-link { background:var(--sky); border-color:var(--sky); }
</style>
</head>
<body>

<!-- ══ HERO ══════════════════════════════════════════════════ -->
<section class="rev-hero">
  <div class="container position-relative" style="z-index:1;">
    <div class="row align-items-center">
      <div class="col-lg-8">
        <h1 class="mb-2">Discover Expert Reviewers Worldwide</h1>
        <p class="mb-4">Connect with leading researchers across <?= count($all_countries) ?>+ countries and <?= count($all_areas) ?>+ research areas.</p>
        <form method="GET" class="hero-search">
          <?php if ($country && $country!=='all'): ?><input type="hidden" name="country" value="<?= esc($country) ?>"><?php endif; ?>
          <?php if ($area_id): ?><input type="hidden" name="area" value="<?= $area_id ?>"><?php endif; ?>
          <input type="hidden" name="sort" value="<?= esc($sort) ?>">
          <div class="input-group">
            <input type="text" name="q" class="form-control" placeholder="Search by name, expertise or keyword…" value="<?= esc($search) ?>">
            <button class="btn" type="submit"><i class="fas fa-search"></i></button>
          </div>
        </form>
        <div class="d-flex gap-4 mt-3">
          <div class="hero-stat"><strong><?= number_format($total_count) ?></strong>Expert Reviewers</div>
          <div class="hero-stat"><strong><?= count($all_countries) ?>+</strong>Countries</div>
          <div class="hero-stat"><strong><?= count($all_areas) ?>+</strong>Research Areas</div>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- ══ QUICK COUNTRY PILLS ═══════════════════════════════════ -->
<div class="pill-row">
  <div class="container">
    <div class="overflow-scroll">
      <a href="<?= buildUrl(['country'=>null,'page'=>1]) ?>"
         class="fpill <?= (!$country||$country==='all')?'active':'' ?>">
        <i class="fas fa-globe" style="font-size:.75rem;"></i> All Countries
      </a>
      <?php foreach ($top_countries as $c):
        $flag = $flags[$c['cname']] ?? '🌍';
      ?>
      <a href="<?= buildUrl(['country'=>$c['cname'],'page'=>1]) ?>"
         class="fpill <?= ($country===$c['cname'])?'active':'' ?>">
        <?= $flag ?> <?= esc($c['cname']) ?>
        <span class="badge"><?= number_format($c['cnt']) ?></span>
      </a>
      <?php endforeach; ?>
      <?php if (count($all_countries) > 8): ?>
      <a href="#countryDropdown" onclick="document.getElementById('country_select').focus();return false;"
         class="fpill" style="border-style:dashed;">
        <i class="fas fa-plus" style="font-size:.7rem;"></i> More Countries
      </a>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- ══ MAIN CONTENT ═══════════════════════════════════════════ -->
<div class="container py-4">
  <div class="row g-4">

    <!-- ── LEFT FILTER SIDEBAR ────────────────────────────── -->
    <div class="col-lg-3">

      <!-- Country Filter -->
      <div class="filter-card mb-3">
        <div class="fc-header">
          <span class="title"><i class="fas fa-globe-americas text-primary"></i>Country</span>
          <?php if ($country && $country!=='all'): ?>
          <a href="<?= buildUrl(['country'=>null,'page'=>1]) ?>" style="font-size:.75rem;color:#ef4444;text-decoration:none;">Clear</a>
          <?php endif; ?>
        </div>
        <div class="fc-body">
          <select id="country_select" class="country-select"
                  onchange="window.location=this.value" name="countryDropdown">
            <option value="<?= buildUrl(['country'=>null,'page'=>1]) ?>" <?= (!$country||$country==='all')?'selected':'' ?>>
              🌍 All Countries
            </option>
            <?php foreach ($all_countries as $c):
              $flag = $flags[$c['cname']] ?? '🌍';
            ?>
            <option value="<?= esc(buildUrl(['country'=>$c['cname'],'page'=>1])) ?>"
                    <?= ($country===$c['cname'])?'selected':'' ?>>
              <?= $flag ?> <?= esc($c['cname']) ?> (<?= number_format($c['cnt']) ?>)
            </option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <!-- Research Area Filter -->
      <div class="filter-card mb-3">
        <div class="fc-header">
          <span class="title"><i class="fas fa-flask text-primary"></i>Research Area</span>
          <?php if ($area_id): ?>
          <a href="<?= buildUrl(['area'=>null,'page'=>1]) ?>" style="font-size:.75rem;color:#ef4444;text-decoration:none;">Clear</a>
          <?php endif; ?>
        </div>
        <div class="fc-body">
          <input type="text" class="area-search" id="areaSearch"
                 placeholder="Search areas…"
                 oninput="filterAreas(this.value)"
                 autocomplete="off">
          <div class="area-list" id="areaList">
            <a href="<?= buildUrl(['area'=>null,'page'=>1]) ?>"
               class="area-item <?= !$area_id?'active':'' ?>">
              <span>All Research Areas</span>
              <span class="area-cnt"><?= number_format($total_count) ?></span>
            </a>
            <?php foreach ($all_areas as $ra): ?>
            <a href="<?= buildUrl(['area'=>$ra['topic_id'],'page'=>1]) ?>"
               class="area-item <?= ($area_id==$ra['topic_id'])?'active':'' ?>"
               data-title="<?= esc(strtolower($ra['title'])) ?>">
              <span class="area-label"><?= esc($ra['title']) ?></span>
              <span class="area-cnt"><?= $ra['cnt'] ?></span>
            </a>
            <?php endforeach; ?>
          </div>
          <?php if (empty($all_areas)): ?>
          <p style="font-size:.78rem;color:var(--muted);margin:0;font-style:italic;">No research areas found.</p>
          <?php endif; ?>
        </div>
      </div>

      <!-- Availability -->
      <div class="filter-card mb-3">
        <div class="fc-header">
          <span class="title"><i class="fas fa-circle-check text-primary"></i>Availability</span>
        </div>
        <div class="fc-body" style="padding-top:10px;padding-bottom:10px;">
          <a href="<?= buildUrl(['available'=>null,'page'=>1]) ?>"
             class="area-item <?= !isset($_GET['available'])?'active':'' ?>">
            <span>All Reviewers</span>
          </a>
          <a href="<?= buildUrl(['available'=>1,'page'=>1]) ?>"
             class="area-item <?= isset($_GET['available'])?'active':'' ?>">
            <span>Available Now <span class="avail-dot ms-1"></span></span>
          </a>
        </div>
      </div>

      <!-- Sort By -->
      <div class="filter-card mb-3">
        <div class="fc-header">
          <span class="title"><i class="fas fa-arrow-up-wide-short text-primary"></i>Sort By</span>
        </div>
        <div class="fc-body" style="padding-top:8px;padding-bottom:8px;">
          <?php foreach ($sortOptions as $sv => $sl): ?>
          <a href="<?= buildUrl(['sort'=>$sv,'page'=>1]) ?>"
             class="sort-item <?= ($sort===$sv)?'active':'' ?>">
            <?php if ($sort===$sv): ?><i class="fas fa-check me-1" style="font-size:.7rem;"></i><?php endif; ?>
            <?= esc($sl) ?>
          </a>
          <?php endforeach; ?>
        </div>
      </div>

    </div>

    <!-- ── REVIEWER LIST ──────────────────────────────────── -->
    <div class="col-lg-9">

      <!-- Active filter tags -->
      <?php if ($search || ($country && $country!=='all') || $area_id): ?>
      <div class="d-flex flex-wrap gap-2 mb-3">
        <?php if ($search): ?>
        <span class="active-tag">
          <i class="fas fa-search" style="font-size:.62rem;"></i>
          "<?= esc($search) ?>"
          <a href="<?= buildUrl(['q'=>null,'page'=>1]) ?>">×</a>
        </span>
        <?php endif; ?>
        <?php if ($country && $country!=='all'): ?>
        <span class="active-tag">
          <?= $flags[$country] ?? '🌍' ?> <?= esc($country) ?>
          <a href="<?= buildUrl(['country'=>null,'page'=>1]) ?>">×</a>
        </span>
        <?php endif; ?>
        <?php if ($area_id): ?>
        <span class="active-tag">
          <i class="fas fa-flask" style="font-size:.62rem;"></i>
          <?= esc($selected_area_name ?: 'Area #'.$area_id) ?>
          <a href="<?= buildUrl(['area'=>null,'page'=>1]) ?>">×</a>
        </span>
        <?php endif; ?>
        <a href="reviewers.php" class="active-tag" style="background:#fef2f2;color:#dc2626;border-color:#fecaca;">
          <i class="fas fa-times" style="font-size:.62rem;"></i> Clear all
        </a>
      </div>
      <?php endif; ?>

      <!-- Results bar -->
      <div class="d-flex justify-content-between align-items-center mb-3 results-bar flex-wrap gap-2">
        <span>
          <strong><?= number_format($total_count) ?> Reviewer<?= $total_count!==1?'s':'' ?></strong>
          <?php if ($country && $country!=='all'): ?> in <?= esc($country) ?><?php endif; ?>
          <?php if ($selected_area_name): ?> · <?= esc($selected_area_name) ?><?php endif; ?>
          <?php if ($search): ?> matching "<?= esc($search) ?>"<?php endif; ?>
          <?php if ($total_pages > 1): ?> · Page <?= $page ?>/<?= $total_pages ?><?php endif; ?>
        </span>
        <div class="d-flex align-items-center gap-2">
          <span>Sort:</span>
          <select class="form-select form-select-sm" style="width:auto;border-radius:8px;"
                  onchange="window.location=this.value">
            <?php foreach ($sortOptions as $sv=>$sl): ?>
            <option value="<?= buildUrl(['sort'=>$sv,'page'=>1]) ?>" <?= ($sort===$sv)?'selected':'' ?>>
              <?= esc($sl) ?>
            </option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <!-- Cards -->
      <?php if (empty($reviewers)): ?>
      <div class="empty-state bg-white rounded-3 border">
        <i class="fas fa-user-slash text-muted"></i>
        <h5 class="fw-semibold mb-2">No reviewers found</h5>
        <p class="text-muted" style="font-size:.88rem;">
          <?php if ($search || $country || $area_id): ?>
            Try adjusting your filters or search terms.
          <?php else: ?>
            No approved reviewer profiles yet. Profiles appear here once approved by an admin.
          <?php endif; ?>
        </p>
        <?php if ($search||$country||$area_id): ?>
        <a href="reviewers.php" class="btn btn-sm btn-outline-primary mt-2">Clear all filters</a>
        <?php endif; ?>
      </div>
      <?php else: ?>
      <div class="d-flex flex-column gap-3">
        <?php foreach ($reviewers as $idx => $r):
          $title_prefix = $r['user_title'] ? $r['user_title'].'. ' : '';
          $full_name    = $title_prefix.trim($r['first_name'].' '.$r['last_name']);
          $initials     = getInitials($r['first_name'], $r['last_name']);
          $color        = $avatar_colors[$idx % count($avatar_colors)];
          $affil        = $r['affil_name'] ?? '';
          $loc          = trim(($r['affil_city']??'').($r['affil_country']?', '.$r['affil_country']:''));
          if (!$loc) $loc = $r['user_country'] ?? '';
          $tags = ($r['top_interests']!=='') ? array_slice(explode('||',$r['top_interests']),0,3) : [];
          if (empty($tags) && !empty($r['reviewing_interests'])) {
              $d = json_decode($r['reviewing_interests'],true);
              if (is_array($d)) $tags = array_slice($d,0,3);
          }
          $total_tags   = $r['top_interests'] ? count(explode('||',$r['top_interests'])) : 0;
          $reviews_done = (int)$r['completed'];
          $rate         = (int)$r['acceptance_rate'];
          $rating       = number_format((float)$r['reviewer_rating'],1);
        ?>
        <a href="/reviewer-profile3.php?slug=<?= urlencode($r['slug']??'') ?>" class="rev-card">
          <div class="rev-avatar" style="background:linear-gradient(135deg,<?= $color ?>,<?= $color ?>cc);">
            <?= esc($initials) ?>
          </div>
          <div class="flex-grow-1 min-width-0">
            <div class="d-flex align-items-start justify-content-between mb-1">
              <div>
                <div class="rev-name">
                  <?= esc($full_name) ?>
                  <?php if ($r['is_verified']): ?>
                  <i class="fas fa-circle-check rev-verified" title="Verified"></i>
                  <?php endif; ?>
                </div>
                <?php if ($r['current_position']): ?><div class="rev-pos"><?= esc($r['current_position']) ?></div><?php endif; ?>
                <?php if ($affil): ?><div class="rev-inst"><?= esc($affil) ?></div><?php endif; ?>
              </div>
              <button class="btn btn-sm text-muted ms-2 p-0"
                      onclick="event.preventDefault();this.classList.toggle('text-primary');"
                      title="Bookmark" style="font-size:.95rem;background:none;border:none;">
                <i class="fas fa-bookmark"></i>
              </button>
            </div>
            <?php if ($loc): ?>
            <div class="rev-loc mb-2">
              <i class="fas fa-location-dot" style="font-size:.72rem;"></i> <?= esc($loc) ?>
              <?php if ($r['is_available']): ?>
              <span class="ms-2" style="font-size:.7rem;color:#10b981;font-weight:600;">
                <span class="avail-dot"></span> Available
              </span>
              <?php endif; ?>
            </div>
            <?php endif; ?>
            <?php if (!empty($tags)): ?>
            <div class="rev-tags d-flex flex-wrap gap-1 mb-2">
              <?php foreach ($tags as $tag): ?>
              <span class="badge"><?= esc($tag) ?></span>
              <?php endforeach; ?>
              <?php if ($total_tags > 3): ?>
              <span class="badge" style="background:#f1f5f9;color:#64748b;">+<?= $total_tags-3 ?></span>
              <?php endif; ?>
            </div>
            <?php endif; ?>
            <?php if ((float)$r['reviewer_rating']>0): ?>
            <div class="rev-stars"><?= starRating((float)$r['reviewer_rating']) ?> <span style="color:var(--muted);font-size:.7rem;margin-left:3px;"><?= $rating ?></span></div>
            <?php endif; ?>
          </div>
          <div class="d-none d-md-flex gap-3 align-items-start ms-2 flex-shrink-0">
            <div class="text-center">
              <div class="rev-stat-num"><?= $reviews_done ?></div>
              <div class="rev-stat-lbl">Reviews</div>
            </div>
            <?php if ($rate>0): ?>
            <div class="text-center">
              <div class="rev-stat-pct"><?= $rate ?>%</div>
              <div class="rev-stat-lbl">Acceptance</div>
            </div>
            <?php endif; ?>
          </div>
        </a>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <!-- Pagination -->
      <?php if ($total_pages > 1): ?>
      <nav class="mt-4">
        <ul class="pagination justify-content-center flex-wrap">
          <li class="page-item <?= ($page<=1)?'disabled':'' ?>">
            <a class="page-link" href="<?= buildUrl(['page'=>$page-1]) ?>">&laquo;</a>
          </li>
          <?php
          $start = max(1,$page-2); $end = min($total_pages,$page+2);
          if ($start>1) echo '<li class="page-item"><a class="page-link" href="'.buildUrl(['page'=>1]).'">1</a></li>';
          if ($start>2) echo '<li class="page-item disabled"><span class="page-link">…</span></li>';
          for ($pg=$start;$pg<=$end;$pg++): ?>
          <li class="page-item <?= ($pg==$page)?'active':'' ?>">
            <a class="page-link" href="<?= buildUrl(['page'=>$pg]) ?>"><?= $pg ?></a>
          </li>
          <?php endfor;
          if ($end<$total_pages-1) echo '<li class="page-item disabled"><span class="page-link">…</span></li>';
          if ($end<$total_pages) echo '<li class="page-item"><a class="page-link" href="'.buildUrl(['page'=>$total_pages]).'">'.$total_pages.'</a></li>';
          ?>
          <li class="page-item <?= ($page>=$total_pages)?'disabled':'' ?>">
            <a class="page-link" href="<?= buildUrl(['page'=>$page+1]) ?>">&raquo;</a>
          </li>
        </ul>
      </nav>
      <?php endif; ?>
    </div>

  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
/* ── Research area live search ───────────────────────── */
function filterAreas(q) {
    q = q.trim().toLowerCase();
    document.querySelectorAll('#areaList .area-item[data-title]').forEach(el => {
        el.style.display = (!q || el.dataset.title.includes(q)) ? '' : 'none';
    });
}

/* ── Sort dropdown ───────────────────────────────────── */
document.querySelectorAll('.form-select').forEach(sel => {
    sel.addEventListener('change', function(){ window.location.href = this.value; });
});
</script>

<?php include __DIR__ . '/include/footer.php'; ?>
</body>
</html>