<?php
/**
 * FILE: public_html/reviewer-profile.php
 * Fully Dynamic Public Reviewer Profile — CommuneGlobal
 * Reads from: reviewer_public_profile, reviewers, users, affiliations,
 *             user_research_interests, research_topics, review_assignments,
 *             submissions, journals, submission_files, manuscript_info, reviews
 */
ini_set('display_errors', 0);
if (session_status() === PHP_SESSION_NONE) session_start();
include_once __DIR__ . '/config/db_new.php';

// ── Fetch reviewer by slug ────────────────────────────────────
$slug     = trim($_GET['slug'] ?? '');
$reviewer_data = null;

if ($slug && $pdo) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                rpp.*,
                u.user_id,
                u.first_name, u.middle_name, u.last_name, u.title AS user_title,
                u.email, u.institutional_email, u.country AS user_country,
                u.created_at AS member_since,
                u.affiliation_id AS user_affil_id,
                r.id            AS reviewer_id,
                r.reviewer_rating,
                r.total_reviews_completed,
                r.total_reviews_declined,
                r.total_reviews_cancelled,
                r.avg_days_to_complete,
                r.max_reviews_per_period,
                r.preferred_review_duration_days,
                r.is_available,
                r.reviewing_interests,
                a.name          AS affil_name,
                a.department    AS affil_dept,
                a.city          AS affil_city,
                a.country       AS affil_country
            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)
            WHERE rpp.slug = ?
              AND rpp.is_published = 1
            LIMIT 1
        ");
        $stmt->execute([$slug]);
        $reviewer_data = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {}
}

// ── 404 if not found ─────────────────────────────────────────
if (!$reviewer_data) {
    http_response_code(404);
    include __DIR__ . '/include/header.php';
    echo '<div style="text-align:center;padding:80px 20px;font-family:sans-serif;">
        <h2 style="color:#0c1f3f;font-size:1.5rem;margin-bottom:8px;">Reviewer profile not found</h2>
        <p style="color:#64748b;">This profile may not exist or is not yet published.</p>
        <a href="/reviewers" style="color:#2563eb;font-weight:600;margin-top:16px;display:inline-block;">← Browse Reviewers</a>
    </div>';
    include __DIR__ . '/include/footer.php';
    exit;
}

$r = $reviewer_data;

// ── Display name ──────────────────────────────────────────────
$title_prefix  = $r['user_title'] ? $r['user_title'].'. ' : '';
$full_name     = $title_prefix.trim(($r['first_name']??'').($r['middle_name']?' '.$r['middle_name']:'').' '.($r['last_name']??''));
$initials      = strtoupper(substr($r['first_name']??'R',0,1).substr($r['last_name']??'',0,1));
$member_since  = !empty($r['member_since']) ? date('F Y', strtotime($r['member_since'])) : '';
$rating        = number_format($r['reviewer_rating'] ?? 0, 1);
$avg_turnaround= number_format($r['avg_days_to_complete'] ?? 0, 1);

// ── Parse JSON fields ─────────────────────────────────────────
$edu         = json_decode($r['education']    ?? '[]', true) ?: [];
$pubs        = json_decode($r['publications'] ?? '[]', true) ?: [];
$badges      = json_decode($r['badges']       ?? '[]', true) ?: [];
// societies removed — block removed per request

// ── Research interests ────────────────────────────────────────
$interests = [];
try {
    $iq = $pdo->prepare("
        SELECT rt.title, rt.topic_id
        FROM user_research_interests uri
        JOIN research_topics rt ON uri.topic_id = rt.topic_id
        WHERE uri.user_id = ? AND uri.source IN ('manual','auto_suggested')
        ORDER BY uri.created_at
        LIMIT 12
    ");
    $iq->execute([$r['user_id']]);
    $interests = $iq->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {}

// Fallback to reviewing_interests JSON
if (empty($interests) && !empty($r['reviewing_interests'])) {
    $d = json_decode($r['reviewing_interests'], true);
    if (is_array($d)) {
        foreach ($d as $tag) $interests[] = ['title'=>$tag, 'topic_id'=>0];
    }
}

// ── Review assignment stats ───────────────────────────────────
$total_completed  = (int)($r['total_reviews_completed']  ?? 0);
$total_declined   = (int)($r['total_reviews_declined']   ?? 0);
$total_cancelled  = (int)($r['total_reviews_cancelled']  ?? 0);

$total_assigned = 0;
try {
    $aq = $pdo->prepare("SELECT COUNT(*) FROM review_assignments WHERE reviewer_id = ?");
    $aq->execute([$r['reviewer_id']]);
    $total_assigned = (int)$aq->fetchColumn();
} catch (PDOException $e) {}
$acceptance_rate = $total_assigned > 0 ? round($total_completed / $total_assigned * 100) : 0;

// ── Journals this reviewer has reviewed for ───────────────────
$reviewer_journals = [];
try {
    $jq = $pdo->prepare("
        SELECT DISTINCT j.journal_id, j.name AS journal_name, j.slug AS journal_slug
        FROM review_assignments ra
        JOIN submissions s ON ra.submission_id = s.submission_id
        JOIN journals j    ON s.journal_id     = j.journal_id
        WHERE ra.reviewer_id       = ?
          AND ra.assignment_status = 'review_submitted'
        ORDER BY j.name
        LIMIT 10
    ");
    $jq->execute([$r['reviewer_id']]);
    $reviewer_journals = $jq->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {}

// ── Published articles: saved pubs + auto-detected from submissions ───────
$published_articles = [];
try {
    $paq = $pdo->prepare("
        SELECT DISTINCT
            mi.article_title       AS title,
            j.name                 AS journal_name,
            sf.publication_date,
            sf.doi,
            sf.page_no,
            YEAR(sf.publication_date) AS pub_year,
            0 AS citations
        FROM review_assignments ra
        JOIN submissions s          ON ra.submission_id  = s.submission_id
        JOIN submission_files sf    ON sf.submission_id  = s.submission_id
        LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
        LEFT JOIN journals j         ON j.journal_id     = s.journal_id
        WHERE ra.reviewer_id       = ?
          AND ra.assignment_status = 'review_submitted'
          AND sf.publication_date  IS NOT NULL
          AND sf.doi               IS NOT NULL AND sf.doi != ''
        ORDER BY sf.publication_date DESC
        LIMIT 20
    ");
    $paq->execute([$r['reviewer_id']]);
    $published_articles = $paq->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {}

// Merge: saved pubs first, then auto-detected (no DOI duplicates)
$display_pubs = $pubs;
foreach ($published_articles as $pa) {
    $already = false;
    foreach ($display_pubs as $dp) {
        if (!empty($dp['doi']) && $dp['doi'] === $pa['doi']) { $already = true; break; }
    }
    if (!$already) $display_pubs[] = [
        'title'   => $pa['title']       ?? '',
        'journal' => $pa['journal_name'] ?? '',
        'year'    => $pa['pub_year']     ?? 0,
        'citations'=> 0,
        'doi'     => $pa['doi']          ?? '',
    ];
}

// ── REVIEWED PAPERS — every paper this reviewer submitted a review on ────
// Shown regardless of whether the article is published or not
$reviewed_papers = [];
try {
    $rpq = $pdo->prepare("
        SELECT DISTINCT
            mi.article_title                    AS title,
            j.name                              AS journal_name,
            s.tracking_code,
            s.submission_status,
            ra.submitted_date                   AS review_submitted_at,
            sf.doi,
            sf.publication_date,
            YEAR(sf.publication_date)           AS pub_year,
            rev.recommendation
        FROM review_assignments ra
        JOIN submissions s          ON ra.submission_id  = s.submission_id
        LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
        LEFT JOIN journals j         ON j.journal_id     = s.journal_id
        LEFT JOIN submission_files sf ON sf.submission_id = s.submission_id
              AND sf.doi IS NOT NULL AND sf.doi != ''
        LEFT JOIN reviews rev        ON rev.submission_id = s.submission_id
                                    AND rev.reviewer_id   = ra.reviewer_id
        WHERE ra.reviewer_id       = ?
          AND ra.assignment_status = 'review_submitted'
        ORDER BY ra.submitted_date DESC
        LIMIT 30
    ");
    $rpq->execute([$r['reviewer_id']]);
    $reviewed_papers = $rpq->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {}

// ── Profile views counter ─────────────────────────────────────
try {
    $pdo->prepare("UPDATE reviewer_public_profile SET profile_views = profile_views + 1 WHERE reviewer_id = ?")
        ->execute([$r['reviewer_id']]);
} catch (PDOException $e) {}
$profile_views = ($r['profile_views'] ?? 0) + 1;

// ── Affiliation display ───────────────────────────────────────
$affil_name    = $r['affil_name']    ?? '';
$affil_dept    = $r['affil_dept']    ?? '';
$affil_city    = $r['affil_city']    ?? '';
$affil_country = $r['affil_country'] ?? '';
$affil_loc     = trim($affil_city.($affil_country?', '.$affil_country:''));

// ── Badges: auto-generate if none saved ──────────────────────
if (empty($badges)) {
    if ($total_completed >= 1)    $badges[] = 'Top Reviewer '.date('Y');
    if ($total_completed >= 5)    $badges[] = 'Outstanding Reviewer';
    if ($total_completed >= 10)   $badges[] = 'Expert Reviewer';
    if ($r['is_available']??false) $badges[] = 'Available';
    if ($r['is_verified']??false)  $badges[] = 'Verified Expert';
}

// ── Citations ─────────────────────────────────────────────────
$total_citations = (int)($r['total_citations'] ?? 0);

// ── Current page URL for share popup ─────────────────────────
$current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')
    . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

// ── Meta ──────────────────────────────────────────────────────
$pageTitle = htmlspecialchars($full_name) . ' — Reviewer Profile — CommuneGlobal';
$meta_desc = htmlspecialchars(mb_substr(strip_tags($r['bio']??''), 0, 160));
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><?= $pageTitle ?></title>
<meta name="description" content="<?= $meta_desc ?>">
<!-- Open Graph -->
<meta property="og:title"       content="<?= htmlspecialchars($full_name) ?> — Reviewer Profile">
<meta property="og:description" content="<?= $meta_desc ?>">
<meta property="og:type"        content="profile">
<meta property="og:url"         content="<?= htmlspecialchars($current_url) ?>">
<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=Instrument+Serif:ital@0;1&family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700;1,9..40,400&display=swap" rel="stylesheet">
<style>
/* ═══════════════════════════════════════
   CSS TOKENS
═══════════════════════════════════════ */
:root {
  --navy:     #0c1f3f;
  --cobalt:   #1a3a8f;
  --sky:      #2563eb;
  --sky-mid:  #3b82f6;
  --sky-lt:   #eff6ff;
  --sky-pale: #f0f7ff;
  --gold:     #d4a017;
  --gold-lt:  #fef9ec;
  --green:    #059669;
  --green-lt: #ecfdf5;
  --purple:   #7c3aed;
  --muted:    #64748b;
  --border:   #e2e8f0;
  --surface:  #f8fafc;
  --white:    #ffffff;
  --text:     #1e293b;
  --text-sm:  #475569;
  --r:        12px;
  --shadow-sm:0 1px 3px rgba(0,0,0,.06);
  --shadow:   0 4px 16px rgba(12,31,63,.08);
  --shadow-lg:0 12px 40px rgba(12,31,63,.14);
}

/* ═══════════════════════════════════════
   BASE
═══════════════════════════════════════ */
*, *::before, *::after { box-sizing: border-box; }
body {
  font-family: 'DM Sans', sans-serif;
  background: var(--surface);
  color: var(--text);
  font-size: 15px;
  line-height: 1.6;
}
.serif { font-family: 'Instrument Serif', serif; }
a { color: var(--sky); text-decoration: none; }
a:hover { text-decoration: underline; }

/* ═══════════════════════════════════════
   LAYOUT
═══════════════════════════════════════ */
.profile-wrap { max-width: 1120px; margin: 0 auto; padding: 0 20px 60px; }

/* ═══════════════════════════════════════
   TOP BANNER
═══════════════════════════════════════ */
.top-banner {
  background: var(--navy);
  padding: 10px 0;
  border-bottom: 3px solid var(--sky);
}
.top-banner .container-fluid {
  display: flex; align-items: center; justify-content: space-between;
  padding: 0 24px; gap: 12px;
}
.top-banner-brand {
  font-family: 'Instrument Serif', serif;
  font-size: 1.15rem; color: #fff; letter-spacing: .01em;
}
.top-banner-brand span { color: #93c5fd; }
.top-banner-breadcrumb {
  font-size: .78rem; color: rgba(255,255,255,.55);
  display: flex; align-items: center; gap: 6px;
}
.top-banner-breadcrumb a { color: rgba(255,255,255,.7); }
.top-banner-breadcrumb .sep { opacity: .35; }
.top-banner-actions { display: flex; gap: 8px; }

/* ── Share button & popup ── */
.share-wrap { position: relative; }
.btn-share {
  font-size: .75rem; border-radius: 6px;
  border: 1px solid rgba(255,255,255,.25);
  color: rgba(255,255,255,.85); padding: 5px 13px;
  background: transparent; cursor: pointer;
  display: flex; align-items: center; gap: 6px;
  transition: background .15s;
  font-family: 'DM Sans', sans-serif;
}
.btn-share:hover { background: rgba(255,255,255,.12); color: #fff; }

.share-popup {
  display: none;
  position: absolute; top: calc(100% + 10px); right: 0;
  background: #fff; border: 1px solid var(--border);
  border-radius: 14px; box-shadow: 0 8px 32px rgba(0,0,0,.14);
  padding: 18px; z-index: 1000; width: 268px;
}
.share-popup.open { display: block; }
.share-popup-title {
  font-size: .7rem; font-weight: 700; text-transform: uppercase;
  letter-spacing: .08em; color: var(--muted); margin-bottom: 14px;
}
.share-grid {
  display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin-bottom: 14px;
}
.share-btn {
  display: flex; flex-direction: column; align-items: center; gap: 5px;
  padding: 10px 4px; border-radius: 10px; border: 1px solid var(--border);
  background: var(--surface); cursor: pointer; text-decoration: none;
  transition: background .12s, border-color .12s;
}
.share-btn:hover { background: var(--sky-lt); border-color: var(--sky); text-decoration: none; }
.share-btn-icon {
  width: 36px; height: 36px; border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  font-size: .95rem; color: #fff;
}
.share-btn-label { font-size: .63rem; color: var(--text-sm); font-weight: 500; text-align: center; }
.share-copy-row { display: flex; gap: 6px; }
.share-copy-input {
  flex: 1; border: 1px solid var(--border); border-radius: 7px;
  padding: 7px 10px; font-size: .72rem; color: var(--muted);
  background: var(--surface); outline: none;
  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.share-copy-btn {
  background: var(--sky); color: #fff; border: none; border-radius: 7px;
  padding: 7px 13px; font-size: .72rem; font-weight: 600; cursor: pointer; white-space: nowrap;
  font-family: 'DM Sans', sans-serif;
}
.share-copy-btn:hover { background: #1d4ed8; }
.share-copy-btn.copied { background: var(--green); }

/* ═══════════════════════════════════════
   PROFILE HEADER CARD
═══════════════════════════════════════ */
.profile-header-card {
  background: var(--white);
  border: 1px solid var(--border);
  border-top: none;
  border-radius: 0 0 var(--r) var(--r);
  box-shadow: var(--shadow);
  margin-bottom: 28px;
  overflow: hidden;
}
.profile-header-stripe {
  height: 6px;
  background: linear-gradient(90deg, var(--cobalt) 0%, var(--sky-mid) 60%, #60a5fa 100%);
}
.profile-header-body {
  padding: 28px 32px 24px;
  display: flex; gap: 24px; align-items: flex-start; flex-wrap: wrap;
}

/* Avatar */
.profile-avatar {
  width: 96px; height: 96px; border-radius: 14px; flex-shrink: 0;
  background: linear-gradient(145deg, var(--cobalt), var(--sky-mid));
  display: flex; align-items: center; justify-content: center;
  font-family: 'Instrument Serif', serif;
  font-size: 2.2rem; font-weight: 700; color: #fff;
  box-shadow: 0 4px 16px rgba(37,99,235,.3);
  position: relative;
}
.avatar-level-badge {
  position: absolute; bottom: -8px; left: 50%; transform: translateX(-50%);
  background: var(--gold); color: #fff; font-size: .6rem; font-weight: 700;
  padding: 2px 8px; border-radius: 20px; white-space: nowrap;
  text-transform: uppercase; letter-spacing: .06em;
  box-shadow: 0 2px 6px rgba(212,160,23,.4);
}

/* Identity */
.profile-identity { flex: 1; min-width: 240px; }
.profile-name-row {
  display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 2px;
}
.profile-name {
  font-family: 'Instrument Serif', serif;
  font-size: 1.6rem; font-weight: 700; color: var(--navy); line-height: 1.2;
}
.verified-pill {
  display: inline-flex; align-items: center; gap: 4px;
  background: var(--green-lt); color: var(--green);
  border: 1px solid #a7f3d0; border-radius: 20px;
  font-size: .7rem; font-weight: 600; padding: 2px 9px;
}
.availability-dot {
  width: 8px; height: 8px; border-radius: 50%;
  background: var(--green); box-shadow: 0 0 0 2px rgba(5,150,105,.2);
  animation: pulse-dot 2s infinite; flex-shrink: 0;
}
@keyframes pulse-dot {
  0%,100% { box-shadow: 0 0 0 2px rgba(5,150,105,.2); }
  50%      { box-shadow: 0 0 0 5px rgba(5,150,105,.08); }
}
.profile-role { font-size: .95rem; color: var(--text-sm); font-weight: 500; margin-bottom: 4px; }
.profile-inst {
  font-size: .85rem; color: var(--muted); margin-bottom: 14px;
  display: flex; align-items: center; gap: 6px;
}
.profile-tags { display: flex; flex-wrap: wrap; gap: 7px; }
.p-tag {
  display: inline-flex; align-items: center; gap: 5px;
  font-size: .75rem; color: var(--text-sm); font-weight: 500;
  background: var(--surface); border: 1px solid var(--border);
  border-radius: 6px; padding: 4px 10px;
}
.p-tag i { color: var(--sky); font-size: .72rem; }

/* CTA — only availability dot + website (Apply & View Profile removed) */
.profile-cta { display: flex; flex-direction: column; gap: 8px; min-width: 140px; }
.avail-row {
  display: flex; align-items: center; gap: 6px;
  font-size: .73rem; color: var(--green); font-weight: 500; justify-content: center;
}
.btn-secondary {
  background: transparent; color: var(--text-sm); border: 1px solid var(--border);
  border-radius: 8px; font-size: .8rem; padding: 7px 14px; cursor: pointer;
  display: flex; align-items: center; justify-content: center; gap: 6px;
  transition: background .15s; text-decoration: none;
}
.btn-secondary:hover { background: var(--surface); border-color: #94a3b8; color: var(--text); text-decoration: none; }

/* ═══════════════════════════════════════
   CONTRIBUTION STATS ROW — 6 columns
═══════════════════════════════════════ */
.contrib-row {
  display: grid; grid-template-columns: repeat(6, 1fr);
  border-top: 1px solid var(--border); background: var(--sky-pale);
}
.contrib-cell {
  text-align: center; padding: 16px 8px;
  border-right: 1px solid var(--border);
}
.contrib-cell:last-child { border-right: none; }
.contrib-num {
  font-family: 'Instrument Serif', serif;
  font-size: 1.5rem; font-weight: 700; color: var(--navy); line-height: 1; display: block;
}
.contrib-num.blue   { color: var(--sky); }
.contrib-num.green  { color: var(--green); }
.contrib-num.gold   { color: var(--gold); }
.contrib-num.purple { color: var(--purple); }
.contrib-lbl {
  font-size: .65rem; color: var(--muted); text-transform: uppercase;
  letter-spacing: .06em; margin-top: 4px; display: block; line-height: 1.3;
}

/* ═══════════════════════════════════════
   BODY GRID
═══════════════════════════════════════ */
.body-grid { display: grid; grid-template-columns: 1fr 300px; gap: 24px; align-items: start; }
@media (max-width: 860px) { .body-grid { grid-template-columns: 1fr; } }

/* ═══════════════════════════════════════
   SECTION CARDS
═══════════════════════════════════════ */
.sec {
  background: var(--white); border: 1px solid var(--border);
  border-radius: var(--r); box-shadow: var(--shadow-sm); margin-bottom: 20px; overflow: hidden;
}
.sec-head {
  display: flex; align-items: center; justify-content: space-between;
  padding: 16px 20px; border-bottom: 1px solid var(--border);
}
.sec-title {
  font-size: .82rem; font-weight: 700; color: var(--navy);
  text-transform: uppercase; letter-spacing: .08em;
  display: flex; align-items: center; gap: 8px;
}
.sec-title i { color: var(--sky); font-size: .85rem; }
.sec-body { padding: 20px; }

/* ═══════════════════════════════════════
   BIO / ABOUT
═══════════════════════════════════════ */
.bio-text {
  font-size: .9rem; color: var(--text-sm); line-height: 1.85;
  display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden;
  transition: all .3s;
}
.bio-text.expanded { -webkit-line-clamp: unset; }
.bio-toggle {
  background: none; border: none; color: var(--sky); font-size: .8rem;
  font-weight: 500; padding: 8px 0 0; cursor: pointer;
  display: flex; align-items: center; gap: 5px;
}
.bio-chevron { transition: transform .25s; }
.bio-chevron.open { transform: rotate(180deg); }

/* ═══════════════════════════════════════
   RESEARCH AREAS
═══════════════════════════════════════ */
.area-chips { display: flex; flex-wrap: wrap; gap: 7px; margin-bottom: 20px; }
.area-chip {
  font-size: .78rem; font-weight: 500;
  background: var(--sky-lt); color: var(--sky);
  border: 1px solid #bfdbfe; border-radius: 20px; padding: 5px 13px;
}
.area-bar-row { margin-bottom: 10px; }
.area-bar-label {
  display: flex; justify-content: space-between; align-items: center;
  font-size: .8rem; color: var(--text-sm); margin-bottom: 5px;
}
.area-bar-label span:last-child { color: var(--muted); font-size: .75rem; }
.area-track { height: 5px; background: #e2e8f0; border-radius: 10px; overflow: hidden; }
.area-fill {
  height: 100%; background: linear-gradient(90deg, var(--sky) 0%, var(--sky-mid) 100%);
  border-radius: 10px; transition: width 1s ease;
}

/* ═══════════════════════════════════════
   PUBLICATIONS & REVIEWED PAPERS
═══════════════════════════════════════ */
.pub-item { padding: 14px 0; border-bottom: 1px solid var(--border); }
.pub-item:last-child { border-bottom: none; padding-bottom: 0; }
.pub-item:first-child { padding-top: 0; }
.pub-title { font-size: .88rem; font-weight: 600; color: var(--navy); line-height: 1.45; margin-bottom: 5px; }
.pub-title a { color: inherit; }
.pub-title a:hover { color: var(--sky); }
.pub-meta-row { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
.pub-journal  { font-size: .76rem; color: var(--muted); }
.pub-badge { font-size: .68rem; font-weight: 600; padding: 2px 8px; border-radius: 4px; display: inline-flex; align-items: center; gap: 4px; }
.pub-badge.year       { background: #e0e7ff; color: #3730a3; }
.pub-badge.cite       { background: var(--sky-lt); color: var(--sky); }
.pub-badge.published  { background: var(--green-lt); color: var(--green); }
.pub-badge.inreview   { background: var(--gold-lt);  color: #92400e; }
.pub-badge.tracking   { background: var(--surface);  color: var(--muted); border: 1px solid var(--border); }
.pub-doi-link { font-size: .68rem; color: var(--muted); font-family: monospace; }

/* verdict badges on reviewed papers */
.verdict { font-size: .68rem; font-weight: 700; padding: 2px 8px; border-radius: 20px; display: inline-flex; align-items: center; gap: 4px; }
.verdict.accepted { background: var(--green-lt); color: var(--green); }
.verdict.rejected { background: #fef2f2; color: #dc2626; }
.verdict.revision { background: var(--gold-lt);  color: #92400e; }
.pub-empty { font-size: .85rem; color: var(--muted); font-style: italic; text-align: center; padding: 20px 0; }

/* ═══════════════════════════════════════
   JOURNALS TABLE
═══════════════════════════════════════ */
.journal-row {
  display: flex; align-items: center; gap: 12px;
  padding: 10px 0; border-bottom: 1px solid var(--border); font-size: .83rem;
}
.journal-row:last-child { border-bottom: none; padding-bottom: 0; }
.journal-row:first-child { padding-top: 0; }
.journal-icon {
  width: 36px; height: 36px; border-radius: 8px; flex-shrink: 0;
  background: var(--sky-lt); border: 1px solid #bfdbfe;
  display: flex; align-items: center; justify-content: center;
  font-size: .62rem; font-weight: 800; color: var(--sky); line-height: 1.1; text-align: center;
}
.journal-name { color: var(--text-sm); flex: 1; line-height: 1.35; }
.journal-check { color: var(--green); font-size: .8rem; flex-shrink: 0; }

/* ═══════════════════════════════════════
   SIDEBAR CARDS
═══════════════════════════════════════ */
.side-card {
  background: var(--white); border: 1px solid var(--border);
  border-radius: var(--r); box-shadow: var(--shadow-sm); margin-bottom: 16px; overflow: hidden;
}
.side-head {
  font-size: .75rem; font-weight: 700; color: var(--navy);
  text-transform: uppercase; letter-spacing: .08em;
  padding: 13px 16px; border-bottom: 1px solid var(--border);
  display: flex; align-items: center; gap: 7px;
}
.side-head i { color: var(--sky); }
.side-body { padding: 14px 16px; }

/* Info rows */
.info-row { display: flex; align-items: flex-start; gap: 10px; font-size: .8rem; color: var(--text-sm); margin-bottom: 10px; }
.info-row:last-child { margin-bottom: 0; }
.info-row i { color: var(--sky); font-size: .8rem; margin-top: 2px; flex-shrink: 0; width: 14px; text-align: center; }

/* Affiliation block */
.affil-block { display: flex; gap: 12px; align-items: flex-start; }
.affil-icon {
  width: 42px; height: 42px; border-radius: 10px; flex-shrink: 0;
  background: var(--sky-lt); border: 1px solid #bfdbfe;
  display: flex; align-items: center; justify-content: center;
}
.affil-icon i { color: var(--sky); font-size: 1rem; }
.affil-name { font-size: .83rem; font-weight: 600; color: var(--navy); line-height: 1.3; }
.affil-loc  { font-size: .75rem; color: var(--muted); margin-top: 2px; }

/* Rating dial */
.rating-wrap { text-align: center; padding: 6px 0 10px; }
.rating-score { font-family: 'Instrument Serif', serif; font-size: 2rem; font-weight: 700; color: var(--navy); }
.rating-label { font-size: .72rem; color: var(--muted); text-transform: uppercase; letter-spacing: .06em; }
.rating-stars { color: var(--gold); font-size: .85rem; margin: 6px 0 2px; }
.rating-count { font-size: .73rem; color: var(--muted); }

/* Badges */
.badges-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
.badge-cell {
  text-align: center; padding: 12px 6px 10px;
  border: 1px solid var(--border); border-radius: 10px; background: var(--surface);
}
.badge-ico { width: 38px; height: 38px; border-radius: 50%; margin: 0 auto 6px; display: flex; align-items: center; justify-content: center; font-size: 1rem; }
.badge-name { font-size: .65rem; color: var(--muted); font-weight: 500; line-height: 1.3; }

/* Education timeline */
.edu-item { display: flex; gap: 12px; padding-bottom: 16px; position: relative; }
.edu-item:last-child { padding-bottom: 0; }
.edu-item::before { content: ''; position: absolute; left: 15px; top: 26px; bottom: 0; width: 1px; background: var(--border); }
.edu-item:last-child::before { display: none; }
.edu-dot {
  width: 30px; height: 30px; border-radius: 50%; flex-shrink: 0;
  background: var(--sky-lt); border: 2px solid var(--sky-mid);
  display: flex; align-items: center; justify-content: center;
  font-size: .62rem; font-weight: 700; color: var(--sky); z-index: 1;
}
.edu-degree { font-size: .83rem; font-weight: 600; color: var(--navy); }
.edu-inst   { font-size: .77rem; color: var(--muted); }
.edu-year   {
  font-size: .68rem; font-weight: 700; color: var(--sky);
  background: var(--sky-lt); border: 1px solid #bfdbfe;
  border-radius: 4px; padding: 1px 6px; margin-top: 3px; display: inline-block;
}

/* ═══════════════════════════════════════
   STICKY NAV
═══════════════════════════════════════ */
.sticky-nav {
  position: sticky; top: 0; z-index: 200;
  background: var(--white); border-bottom: 1px solid var(--border);
  box-shadow: 0 2px 8px rgba(0,0,0,.05);
}
.sticky-nav-inner {
  max-width: 1120px; margin: 0 auto; padding: 0 20px;
  display: flex; overflow-x: auto; gap: 0;
  -ms-overflow-style: none; scrollbar-width: none;
}
.sticky-nav-inner::-webkit-scrollbar { display: none; }
.snav-link {
  font-size: .8rem; font-weight: 500; color: var(--muted);
  padding: 13px 16px; white-space: nowrap; cursor: pointer;
  border-bottom: 2px solid transparent; transition: color .15s, border-color .15s;
}
.snav-link:hover { color: var(--sky); }
.snav-link.active { color: var(--sky); border-bottom-color: var(--sky); }

/* ═══════════════════════════════════════
   RESPONSIVE
═══════════════════════════════════════ */
@media (max-width: 768px) {
  .contrib-row { grid-template-columns: repeat(3, 1fr); }
  .contrib-cell:nth-child(3) { border-right: none; }
  .contrib-cell:nth-child(4),
  .contrib-cell:nth-child(5),
  .contrib-cell:nth-child(6) { border-top: 1px solid var(--border); }
  .profile-header-body { padding: 20px 18px 18px; }
  .profile-name { font-size: 1.3rem; }
}
@media (max-width: 479px) {
  .contrib-row { grid-template-columns: repeat(2, 1fr); }
  .contrib-cell:nth-child(2) { border-right: none; }
  .contrib-cell:nth-child(3) { border-top: 1px solid var(--border); }
  .contrib-cell:nth-child(4) { border-top: 1px solid var(--border); border-right: none; }
  .contrib-cell:nth-child(5) { border-top: 1px solid var(--border); }
  .contrib-cell:nth-child(6) { border-top: 1px solid var(--border); border-right: none; }
}
</style>
</head>
<body>

<!-- ═══════════════════════════════════
     TOP BANNER
═══════════════════════════════════ -->
<div class="top-banner">
  <div class="container-fluid">
    <div class="top-banner-brand">Commune<span>Global</span></div>
    <nav class="top-banner-breadcrumb d-none d-sm-flex">
      <a href="/">Home</a><span class="sep">/</span>
      <a href="/reviewers">Reviewers</a><span class="sep">/</span>
      <span><?= htmlspecialchars($full_name) ?></span>
    </nav>
    <div class="top-banner-actions">
      <!-- Share button + popup -->
      <div class="share-wrap">
        <button class="btn-share" id="shareBtn" onclick="toggleSharePopup(event)">
          <i class="fas fa-share-nodes"></i>Share Profile
        </button>
        <div class="share-popup" id="sharePopup">
          <div class="share-popup-title">Share this profile</div>
          <div class="share-grid">
            <a class="share-btn"
               href="https://wa.me/?text=<?= urlencode($full_name.' — Reviewer Profile '."\n".$current_url) ?>"
               target="_blank" rel="noopener">
              <div class="share-btn-icon" style="background:#25D366;"><i class="fab fa-whatsapp"></i></div>
              <span class="share-btn-label">WhatsApp</span>
            </a>
            <a class="share-btn"
               href="https://www.facebook.com/sharer/sharer.php?u=<?= urlencode($current_url) ?>"
               target="_blank" rel="noopener">
              <div class="share-btn-icon" style="background:#1877F2;"><i class="fab fa-facebook-f"></i></div>
              <span class="share-btn-label">Facebook</span>
            </a>
            <a class="share-btn"
               href="https://twitter.com/intent/tweet?text=<?= urlencode('Check out '.$full_name.'\'s reviewer profile on CommuneGlobal') ?>&url=<?= urlencode($current_url) ?>"
               target="_blank" rel="noopener">
              <div class="share-btn-icon" style="background:#000000;"><i class="fab fa-x-twitter"></i></div>
              <span class="share-btn-label">Twitter / X</span>
            </a>
            <a class="share-btn"
               href="https://www.linkedin.com/sharing/share-offsite/?url=<?= urlencode($current_url) ?>"
               target="_blank" rel="noopener">
              <div class="share-btn-icon" style="background:#0A66C2;"><i class="fab fa-linkedin-in"></i></div>
              <span class="share-btn-label">LinkedIn</span>
            </a>
          </div>
          <!-- Copy link row -->
          <div class="share-copy-row">
            <input class="share-copy-input" id="shareLinkInput" type="text"
                   value="<?= htmlspecialchars($current_url) ?>" readonly>
            <button class="share-copy-btn" id="copyLinkBtn" onclick="copyProfileLink()">Copy</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ═══════════════════════════════════
     PROFILE HEADER CARD
═══════════════════════════════════ -->
<div class="profile-wrap" style="padding-top:24px;">
  <div class="profile-header-card" id="top">
    <div class="profile-header-stripe"></div>
    <div class="profile-header-body">

      <!-- Avatar -->
      <div class="profile-avatar">
        <?= htmlspecialchars($initials) ?>
        <?php if ($total_completed >= 10): ?>
        <div class="avatar-level-badge">Laureate</div>
        <?php elseif ($total_completed >= 5): ?>
        <div class="avatar-level-badge">Senior</div>
        <?php endif; ?>
      </div>

      <!-- Identity -->
      <div class="profile-identity">
        <div class="profile-name-row">
          <span class="profile-name"><?= htmlspecialchars($full_name) ?></span>
          <?php if ($r['is_verified'] ?? false): ?>
          <span class="verified-pill">
            <i class="fas fa-circle-check" style="font-size:.75rem;"></i> Verified Reviewer
          </span>
          <?php endif; ?>
        </div>
        <?php if ($r['current_position']): ?>
        <div class="profile-role"><?= htmlspecialchars($r['current_position']) ?></div>
        <?php endif; ?>
        <div class="profile-inst">
          <?php if ($affil_name): ?>
          <i class="fas fa-building-columns"></i>
          <?= htmlspecialchars($affil_name) ?>
          <?php if ($affil_country): ?>&nbsp;— <?= htmlspecialchars($affil_country) ?><?php endif; ?>
          <?php else: ?>
          <i class="fas fa-user"></i><?= htmlspecialchars($r['user_country'] ?? '') ?>
          <?php endif; ?>
        </div>
        <div class="profile-tags">
          <?php if ($affil_loc): ?>
          <span class="p-tag"><i class="fas fa-location-dot"></i><?= htmlspecialchars($affil_loc) ?></span>
          <?php elseif ($r['user_country']): ?>
          <span class="p-tag"><i class="fas fa-location-dot"></i><?= htmlspecialchars($r['user_country']) ?></span>
          <?php endif; ?>
          <?php if ($member_since): ?>
          <span class="p-tag"><i class="fas fa-calendar-days"></i>Member since <?= htmlspecialchars($member_since) ?></span>
          <?php endif; ?>
          <?php if ($avg_turnaround > 0): ?>
          <span class="p-tag"><i class="fas fa-gauge-high"></i><?= $avg_turnaround ?> days avg. turnaround</span>
          <?php endif; ?>
          <?php if ($r['total_experience_yrs']): ?>
          <span class="p-tag"><i class="fas fa-clock-rotate-left"></i><?= (int)$r['total_experience_yrs'] ?>+ yrs experience</span>
          <?php endif; ?>
          <?php if ($r['orcid_id']): ?>
          <a class="p-tag" href="https://orcid.org/<?= htmlspecialchars($r['orcid_id']) ?>" target="_blank" style="color:inherit;">
            <i class="fas fa-fingerprint"></i>ORCID
          </a>
          <?php endif; ?>
        </div>
      </div>

      <!-- CTA: Apply for Review & View Profile REMOVED — only availability + website -->
      <div class="profile-cta">
        <?php if ($r['is_available'] ?? false): ?>
        <div class="avail-row">
          <div class="availability-dot"></div>
          <span>Available for review</span>
        </div>
        <?php endif; ?>
        <?php if ($r['website_url']): ?>
        <a href="<?= htmlspecialchars($r['website_url']) ?>" target="_blank" class="btn-secondary">
          <i class="fas fa-external-link-alt" style="font-size:.7rem;"></i>Visit Website
        </a>
        <?php endif; ?>
      </div>

    </div>

    <!-- ── Contribution Stats Strip — 6 columns ── -->
    <div class="contrib-row">
      <div class="contrib-cell">
        <span class="contrib-num blue"><?= $total_completed ?></span>
        <span class="contrib-lbl">Reviews<br>Completed</span>
      </div>
      <div class="contrib-cell">
        <span class="contrib-num"><?= count($display_pubs) ?>+</span>
        <span class="contrib-lbl">Publications</span>
      </div>
      <div class="contrib-cell">
        <span class="contrib-num green"><?= $acceptance_rate ?>%</span>
        <span class="contrib-lbl">Acceptance<br>Rate</span>
      </div>
      <div class="contrib-cell">
        <span class="contrib-num"><?= number_format($profile_views) ?></span>
        <span class="contrib-lbl">Profile<br>Views</span>
      </div>
      <div class="contrib-cell">
        <span class="contrib-num gold"><?= $r['h_index'] ?? '—' ?></span>
        <span class="contrib-lbl">h-Index</span>
      </div>
      <!-- Citations — dynamically from rpp.total_citations -->
      <div class="contrib-cell">
        <span class="contrib-num purple">
          <?= $total_citations > 0 ? number_format($total_citations) : '—' ?>
        </span>
        <span class="contrib-lbl">Total<br>Citations</span>
      </div>
    </div>

  </div>
</div>

<!-- ═══════════════════════════════════
     STICKY NAV
═══════════════════════════════════ -->
<div class="sticky-nav" id="stickyNav">
  <div class="sticky-nav-inner">
    <span class="snav-link active" data-target="sec-about">About</span>
    <?php if (!empty($interests)): ?>
    <span class="snav-link" data-target="sec-areas">Research Areas</span>
    <?php endif; ?>
    <span class="snav-link" data-target="sec-pubs">Publications</span>
    <?php if (!empty($reviewed_papers)): ?>
    <span class="snav-link" data-target="sec-reviewed">Reviewed Papers</span>
    <?php endif; ?>
    <?php if (!empty($reviewer_journals)): ?>
    <span class="snav-link" data-target="sec-journals">Journals</span>
    <?php endif; ?>
    <?php if (!empty($edu)): ?>
    <span class="snav-link" data-target="sec-edu">Education</span>
    <?php endif; ?>
  </div>
</div>

<!-- ═══════════════════════════════════
     BODY CONTENT
═══════════════════════════════════ -->
<div class="profile-wrap" style="padding-top:0;">
<div class="body-grid">

  <!-- ── MAIN COLUMN ── -->
  <div>

    <!-- About -->
    <div class="sec" id="sec-about">
      <div class="sec-head">
        <span class="sec-title"><i class="fas fa-user-pen"></i>About</span>
      </div>
      <div class="sec-body">
        <?php if ($r['bio']): ?>
        <p class="bio-text" id="bioText"><?= nl2br(htmlspecialchars($r['bio'])) ?></p>
        <button class="bio-toggle" onclick="toggleBio()" id="bioToggle">
          <span id="bioToggleTxt">Read more</span>
          <i class="fas fa-chevron-down bio-chevron" id="bioChevron"></i>
        </button>
        <?php else: ?>
        <p style="color:var(--muted);font-style:italic;font-size:.88rem;">No bio provided.</p>
        <?php endif; ?>
      </div>
    </div>

    <!-- Research Areas -->
    <?php if (!empty($interests)): ?>
    <div class="sec" id="sec-areas">
      <div class="sec-head">
        <span class="sec-title"><i class="fas fa-flask-vial"></i>Research Areas</span>
        <span style="font-size:.75rem;color:var(--muted);"><?= count($interests) ?> areas</span>
      </div>
      <div class="sec-body">
        <div class="area-chips">
          <?php foreach ($interests as $area): ?>
          <span class="area-chip"><?= htmlspecialchars($area['title']) ?></span>
          <?php endforeach; ?>
        </div>
        <div>
          <?php
          $max_pct = 35;
          $step    = max(1, intdiv($max_pct, count($interests)));
          foreach ($interests as $idx => $area):
            $pct = max(10, $max_pct - $idx * $step);
          ?>
          <div class="area-bar-row">
            <div class="area-bar-label">
              <span><?= htmlspecialchars($area['title']) ?></span>
              <span><?= $pct ?>%</span>
            </div>
            <div class="area-track">
              <div class="area-fill" style="width:0%" data-width="<?= $pct ?>%"></div>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <!-- Publications — saved profile pubs + auto-detected published articles -->
    <div class="sec" id="sec-pubs">
      <div class="sec-head">
        <span class="sec-title"><i class="fas fa-book-open"></i>Publications</span>
        <?php if (!empty($display_pubs)): ?>
        <span style="font-size:.75rem;color:var(--muted);"><?= count($display_pubs) ?> papers</span>
        <?php endif; ?>
      </div>
      <div class="sec-body">
        <?php if (!empty($display_pubs)): ?>
          <?php foreach ($display_pubs as $pub): ?>
          <div class="pub-item">
            <div class="pub-title">
              <?php if (!empty($pub['doi'])): ?>
              <a href="https://doi.org/<?= htmlspecialchars($pub['doi']) ?>" target="_blank">
                <?= htmlspecialchars($pub['title'] ?? 'Untitled') ?>
              </a>
              <?php else: ?>
              <?= htmlspecialchars($pub['title'] ?? 'Untitled') ?>
              <?php endif; ?>
            </div>
            <div class="pub-meta-row">
              <?php if (!empty($pub['journal'])): ?>
              <span class="pub-journal"><?= htmlspecialchars($pub['journal']) ?></span>
              <?php endif; ?>
              <?php if (!empty($pub['year'])): ?>
              <span class="pub-badge year"><?= (int)$pub['year'] ?></span>
              <?php endif; ?>
              <?php if (!empty($pub['citations']) && $pub['citations'] > 0): ?>
              <span class="pub-badge cite"><i class="fas fa-quote-right" style="font-size:.6rem;"></i><?= (int)$pub['citations'] ?> citations</span>
              <?php endif; ?>
              <?php if (!empty($pub['doi'])): ?>
              <a href="https://doi.org/<?= htmlspecialchars($pub['doi']) ?>" target="_blank" class="pub-doi-link">
                DOI: <?= htmlspecialchars($pub['doi']) ?>
              </a>
              <?php endif; ?>
            </div>
          </div>
          <?php endforeach; ?>
        <?php else: ?>
          <p class="pub-empty">No publications listed yet.</p>
        <?php endif; ?>
      </div>
    </div>

    <!-- Reviewed Papers — ALL papers this reviewer submitted a review on,
         published or not. Includes verdict, journal, tracking code, date. -->
    <?php if (!empty($reviewed_papers)): ?>
    <div class="sec" id="sec-reviewed">
      <div class="sec-head">
        <span class="sec-title"><i class="fas fa-file-pen"></i>Reviewed Papers</span>
        <span style="font-size:.75rem;color:var(--muted);"><?= count($reviewed_papers) ?> paper<?= count($reviewed_papers)!==1?'s':'' ?> reviewed</span>
      </div>
      <div class="sec-body">
        <?php foreach ($reviewed_papers as $rp):
          $is_published = !empty($rp['doi']) && !empty($rp['publication_date']);
          // Map recommendation → verdict badge
          $rec      = strtolower($rp['recommendation'] ?? '');
          $vrd_cls  = '';
          $vrd_lbl  = '';
          if (str_contains($rec, 'accept'))      { $vrd_cls = 'accepted'; $vrd_lbl = 'Accepted'; }
          elseif (str_contains($rec, 'reject'))  { $vrd_cls = 'rejected'; $vrd_lbl = 'Rejected'; }
          elseif ($rec !== '')                   { $vrd_cls = 'revision'; $vrd_lbl = 'Revision'; }
        ?>
        <div class="pub-item">
          <div class="pub-title" style="display:flex;align-items:flex-start;justify-content:space-between;gap:10px;">
            <span>
              <?php if ($is_published && !empty($rp['doi'])): ?>
              <a href="https://doi.org/<?= htmlspecialchars($rp['doi']) ?>" target="_blank">
                <?= htmlspecialchars($rp['title'] ?? 'Untitled Manuscript') ?>
              </a>
              <?php else: ?>
              <?= htmlspecialchars($rp['title'] ?? 'Untitled Manuscript') ?>
              <?php endif; ?>
            </span>
           
          </div>
          <div class="pub-meta-row" style="margin-top:5px;">
            <?php if (!empty($rp['journal_name'])): ?>
            <span class="pub-journal"><?= htmlspecialchars($rp['journal_name']) ?></span>
            <?php endif; ?>
            <?php if ($is_published && !empty($rp['pub_year'])): ?>
            <span class="pub-badge year"><?= (int)$rp['pub_year'] ?></span>
            <?php endif; ?>
            <?php if (!empty($rp['tracking_code'])): ?>
            <span class="pub-badge tracking"><?= htmlspecialchars($rp['tracking_code']) ?></span>
            <?php endif; ?>
            <?php if ($vrd_lbl): ?>
            <span class="verdict <?= $vrd_cls ?>">
              <i class="fas fa-gavel" style="font-size:.58rem;"></i><?= $vrd_lbl ?>
            </span>
            <?php endif; ?>
            <?php if (!empty($rp['review_submitted_at'])): ?>
            <span style="font-size:.7rem;color:var(--muted);">
              Reviewed <?= date('M Y', strtotime($rp['review_submitted_at'])) ?>
            </span>
            <?php endif; ?>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Reviewer for Journals -->
    <?php if (!empty($reviewer_journals)): ?>
    <div class="sec" id="sec-journals">
      <div class="sec-head">
        <span class="sec-title"><i class="fas fa-journal-whills"></i>Reviewer for Journals</span>
      </div>
      <div class="sec-body">
        <?php foreach ($reviewer_journals as $j): ?>
        <div class="journal-row">
          <div class="journal-icon">
            <?= htmlspecialchars(strtoupper(substr($j['journal_name'],0,4))) ?>
          </div>
          <span class="journal-name"><?= htmlspecialchars($j['journal_name']) ?></span>
          <i class="fas fa-circle-check journal-check"></i>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Education -->
    <?php if (!empty($edu)): ?>
    <div class="sec" id="sec-edu">
      <div class="sec-head">
        <span class="sec-title"><i class="fas fa-graduation-cap"></i>Education</span>
      </div>
      <div class="sec-body">
        <?php foreach ($edu as $e): ?>
        <div class="edu-item">
          <div class="edu-dot">🎓</div>
          <div>
            <div class="edu-degree"><?= htmlspecialchars($e['degree'] ?? '') ?></div>
            <div class="edu-inst"><?= htmlspecialchars($e['institution'] ?? '') ?></div>
            <?php if (!empty($e['year'])): ?>
            <span class="edu-year"><?= (int)$e['year'] ?></span>
            <?php endif; ?>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

  </div><!-- /main col -->

  <!-- ── SIDEBAR ── -->
  <div>

    <!-- Reviewer Rating -->
    <div class="side-card">
      <div class="side-head"><i class="fas fa-star-half-stroke"></i>Reviewer Rating</div>
      <div class="side-body">
        <div class="rating-wrap">
          <svg class="rating-dial-svg d-block mx-auto mb-2" width="100" height="60" viewBox="0 0 100 60">
            <path d="M10 55 A40 40 0 0 1 90 55" fill="none" stroke="#e2e8f0" stroke-width="8" stroke-linecap="round"/>
            <path d="M10 55 A40 40 0 0 1 90 55" fill="none" stroke="#2563eb" stroke-width="8" stroke-linecap="round"
                  stroke-dasharray="126" stroke-dashoffset="<?= max(5, 126 - (float)$rating/5*126) ?>" opacity=".9"/>
          </svg>
          <div class="rating-score"><?= $rating ?></div>
          <div class="rating-stars">
            <?php
            $full = floor((float)$rating);
            $half = ((float)$rating - $full) >= 0.5 ? 1 : 0;
            $empty= 5 - $full - $half;
            for($i=0;$i<$full;$i++) echo '<i class="fas fa-star"></i>';
            if($half) echo '<i class="fas fa-star-half-stroke"></i>';
            for($i=0;$i<$empty;$i++) echo '<i class="far fa-star"></i>';
            ?>
          </div>
          <div class="rating-count">Based on <?= $total_completed ?> completed reviews</div>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:10px;">
          <div style="text-align:center;background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:8px 4px;">
            <div class="serif" style="font-size:1.1rem;font-weight:700;color:var(--sky);"><?= $total_assigned ?></div>
            <div style="font-size:.62rem;color:var(--muted);">Assigned</div>
          </div>
          <div style="text-align:center;background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:8px 4px;">
            <div class="serif" style="font-size:1.1rem;font-weight:700;color:var(--green);"><?= $acceptance_rate ?>%</div>
            <div style="font-size:.62rem;color:var(--muted);">Acceptance</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Affiliation -->
    <?php if ($affil_name): ?>
    <div class="side-card">
      <div class="side-head"><i class="fas fa-building-columns"></i>Affiliation</div>
      <div class="side-body">
        <div class="affil-block">
          <div class="affil-icon"><i class="fas fa-university"></i></div>
          <div>
            <div class="affil-name"><?= htmlspecialchars($affil_name) ?></div>
            <?php if ($affil_dept): ?>
            <div class="affil-loc" style="font-size:.7rem;"><?= htmlspecialchars($affil_dept) ?></div>
            <?php endif; ?>
            <div class="affil-loc">
              <i class="fas fa-location-dot" style="font-size:.65rem;margin-right:3px;color:var(--muted);"></i>
              <?= htmlspecialchars($affil_loc ?: $affil_country) ?>
            </div>
          </div>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <!-- Contact & Academic IDs -->
    <div class="side-card">
      <div class="side-head"><i class="fas fa-address-card"></i>Contact &amp; IDs</div>
      <div class="side-body">
        <?php if (!empty($r['institutional_email'])): ?>
        <div class="info-row">
          <i class="fas fa-envelope"></i>
          <a href="mailto:<?= htmlspecialchars($r['institutional_email']) ?>"><?= htmlspecialchars($r['institutional_email']) ?></a>
        </div>
        <?php endif; ?>
        <?php if ($affil_city || $affil_country): ?>
        <div class="info-row">
          <i class="fas fa-location-dot"></i>
          <span><?= htmlspecialchars($affil_loc) ?></span>
        </div>
        <?php elseif ($r['user_country']): ?>
        <div class="info-row">
          <i class="fas fa-location-dot"></i>
          <span><?= htmlspecialchars($r['user_country']) ?></span>
        </div>
        <?php endif; ?>
        <?php if ($member_since): ?>
        <div class="info-row">
          <i class="fas fa-calendar"></i>
          <span>Member since <?= htmlspecialchars($member_since) ?></span>
        </div>
        <?php endif; ?>
        <?php if ($r['h_index']): ?>
        <div class="info-row">
          <i class="fas fa-chart-bar"></i>
          <span>h-Index: <strong><?= (int)$r['h_index'] ?></strong></span>
        </div>
        <?php endif; ?>
        <?php if ($total_citations > 0): ?>
        <div class="info-row">
          <i class="fas fa-quote-left"></i>
          <span><?= number_format($total_citations) ?> total citations</span>
        </div>
        <?php endif; ?>
        <?php if ($r['orcid_id']): ?>
        <div class="info-row">
          <i class="fas fa-fingerprint"></i>
          <a href="https://orcid.org/<?= htmlspecialchars($r['orcid_id']) ?>" target="_blank">
            ORCID: <?= htmlspecialchars($r['orcid_id']) ?>
          </a>
        </div>
        <?php endif; ?>
        <?php if ($r['website_url']): ?>
        <div class="info-row">
          <i class="fas fa-globe"></i>
          <a href="<?= htmlspecialchars($r['website_url']) ?>" target="_blank">
            <?= htmlspecialchars(preg_replace('#^https?://#','',rtrim($r['website_url'],'/') )) ?>
          </a>
        </div>
        <?php endif; ?>
        <?php if (!empty($r['max_reviews_per_period'])): ?>
        <div class="info-row">
          <i class="fas fa-clipboard-list"></i>
          <span>Max <?= (int)$r['max_reviews_per_period'] ?> reviews/period</span>
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Badges & Honours -->
    <?php if (!empty($badges)): ?>
    <div class="side-card">
      <div class="side-head"><i class="fas fa-trophy"></i>Badges &amp; Honours</div>
      <div class="side-body">
        <div class="badges-grid">
          <?php
          $bConfig = [
            ['bg'=>'#fef9c3','color'=>'#854d0e','icon'=>'fa-star'],
            ['bg'=>'#fce7f3','color'=>'#9d174d','icon'=>'fa-medal'],
            ['bg'=>'#e0f2fe','color'=>'#075985','icon'=>'fa-shield-halved'],
            ['bg'=>'#f0fdf4','color'=>'#166534','icon'=>'fa-circle-check'],
            ['bg'=>'#fef3c7','color'=>'#92400e','icon'=>'fa-award'],
            ['bg'=>'#ede9fe','color'=>'#5b21b6','icon'=>'fa-gem'],
          ];
          foreach ($badges as $bi => $b):
            $bc = $bConfig[$bi % count($bConfig)];
          ?>
          <div class="badge-cell">
            <div class="badge-ico" style="background:<?= $bc['bg'] ?>;color:<?= $bc['color'] ?>;">
              <i class="fas <?= $bc['icon'] ?>"></i>
            </div>
            <div class="badge-name"><?= htmlspecialchars($b) ?></div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <!-- Professional Societies block REMOVED -->

  </div><!-- /sidebar -->
</div>
</div><!-- /profile-wrap -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
/* ── Share popup ─────────────────────────────────────────────── */
function toggleSharePopup(e) {
  e.stopPropagation();
  document.getElementById('sharePopup').classList.toggle('open');
}
// Close when clicking anywhere outside the share popup
document.addEventListener('click', function(e) {
  const wrap = document.querySelector('.share-wrap');
  if (wrap && !wrap.contains(e.target)) {
    document.getElementById('sharePopup').classList.remove('open');
  }
});
function copyProfileLink() {
  const input = document.getElementById('shareLinkInput');
  const btn   = document.getElementById('copyLinkBtn');
  // Try modern clipboard API first, fallback to execCommand
  const doCopy = () => {
    btn.textContent = 'Copied!';
    btn.classList.add('copied');
    setTimeout(() => { btn.textContent = 'Copy'; btn.classList.remove('copied'); }, 2200);
  };
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(input.value).then(doCopy).catch(() => {
      input.select(); document.execCommand('copy'); doCopy();
    });
  } else {
    input.select(); document.execCommand('copy'); doCopy();
  }
}

/* ── Bio toggle ──────────────────────────────────────────────── */
let bioOpen = false;
function toggleBio() {
  bioOpen = !bioOpen;
  document.getElementById('bioText').classList.toggle('expanded', bioOpen);
  document.getElementById('bioToggleTxt').textContent = bioOpen ? 'Show less' : 'Read more';
  const ch = document.getElementById('bioChevron');
  if (ch) ch.classList.toggle('open', bioOpen);
}

/* ── Sticky nav active state ─────────────────────────────────── */
const navLinks = document.querySelectorAll('.snav-link');
const sections = Array.from(navLinks).map(l => document.getElementById(l.dataset.target)).filter(Boolean);

function updateNav() {
  const stickyH = document.getElementById('stickyNav')?.offsetHeight || 56;
  let current = sections[0]?.id;
  sections.forEach(s => {
    if (window.scrollY >= s.offsetTop - stickyH - 20) current = s.id;
  });
  navLinks.forEach(l => l.classList.toggle('active', l.dataset.target === current));
}
window.addEventListener('scroll', updateNav, { passive: true });
updateNav();

navLinks.forEach(l => {
  l.addEventListener('click', () => {
    const sec = document.getElementById(l.dataset.target);
    if (!sec) return;
    const stickyH = document.getElementById('stickyNav')?.offsetHeight || 56;
    window.scrollTo({ top: sec.offsetTop - stickyH - 8, behavior: 'smooth' });
  });
});

/* ── Animate area bars on load ───────────────────────────────── */
document.querySelectorAll('.area-fill').forEach(el => {
  const w = el.dataset.width || el.style.width;
  el.style.width = '0%';
  requestAnimationFrame(() => {
    setTimeout(() => { el.style.width = w; }, 300);
  });
});
</script>

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