<?php
/**
 * FILE: public_html/reviewer-profile.php
 * Reviewer Detail / Profile Page — CommuneGlobal
 * DYNAMIC VERSION — pulls all data from DB
 */
ini_set('display_errors', 0);
if (session_status() === PHP_SESSION_NONE) session_start();
include_once __DIR__ . '/config/db_new.php';

/* ── Fetch reviewer from DB by slug ── */
$slug = trim($_GET['slug'] ?? '');
$reviewer      = null;
$reviewerRow   = null;  // reviewer_public_profile row
$userData      = null;  // users row
$affiliRow     = null;  // affiliations row
$reviewerMeta  = null;  // reviewers row

if ($slug && $pdo) {
    try {
        /* Join reviewer_public_profile → reviewers → users → affiliations */
        $stmt = $pdo->prepare("
            SELECT
                rpp.*,
                r.total_reviews_completed,
                r.is_available,
                r.avg_days_to_complete,
                r.reviewer_rating,
                u.first_name, u.last_name, u.email AS user_email,
                u.title AS user_title, u.country AS user_country,
                u.username, u.created_at AS member_since,
                a.name AS affil_name, a.city AS affil_city,
                a.country AS affil_country, a.department AS affil_dept
            FROM reviewer_public_profile rpp
            JOIN reviewers r          ON r.id       = rpp.reviewer_id
            JOIN users u              ON u.user_id  = rpp.user_id
            LEFT JOIN affiliations a  ON a.affiliation_id = rpp.profile_affiliation_id
            WHERE rpp.slug = ? AND rpp.is_published = 1
            LIMIT 1
        ");
        $stmt->execute([$slug]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $reviewerRow = $row;

            /* Build reviewer array for the template */
            $name       = trim($row['first_name'] . ' ' . $row['last_name']);
            $initials   = strtoupper(
                substr($row['first_name'], 0, 1) . substr($row['last_name'], 0, 1)
            );

            /* JSON fields */
            $areas       = [];  // We'll build from reviewing_interests if areas not in profile
            $publications = json_decode($row['publications'] ?? '[]', true) ?: [];
            $education   = json_decode($row['education']    ?? '[]', true) ?: [];
            $societies   = json_decode($row['societies']    ?? '[]', true) ?: [];
            $badges      = json_decode($row['badges']       ?? '[]', true) ?: [];

            /* Pull reviewing_interests from reviewers table for area chips */
            $rstmt = $pdo->prepare("SELECT reviewing_interests FROM reviewers WHERE id = ? LIMIT 1");
            $rstmt->execute([$row['reviewer_id']]);
            $rdata = $rstmt->fetch(PDO::FETCH_ASSOC);
            $interestsRaw = json_decode($rdata['reviewing_interests'] ?? '[]', true) ?: [];
            foreach ($interestsRaw as $i => $interest) {
                $areas[] = ['name' => $interest, 'pct' => max(5, 30 - ($i * 4))];
            }

            /* Average turnaround */
            $avgDays = $row['avg_days_to_complete'] > 0
                ? number_format($row['avg_days_to_complete'], 1) . ' days'
                : 'N/A';

            /* Member since */
            $memberSince = $row['member_since']
                ? date('F Y', strtotime($row['member_since']))
                : 'N/A';

            /* Location */
            $location = trim(implode(', ', array_filter([
                $row['affil_city'] ?? $row['user_country'] ?? '',
                $row['affil_country'] ?? ''
            ]))) ?: ($row['user_country'] ?? 'N/A');

            /* Affiliation URL fallback */
            $affilUrl = $row['website_url'] ?? '#';

            /* Profile level label */
            $levelLabel = ucfirst($row['profile_level'] ?? 'Standard');

            /* Track profile view */
            try {
                $pdo->prepare("UPDATE reviewer_public_profile SET profile_views = profile_views + 1 WHERE id = ?")
                    ->execute([$row['id']]);
            } catch (Exception $e) {}

            $reviewer = [
                'name'              => $name,
                'initials'          => $initials,
                'verified'          => (bool)$row['is_verified'],
                'role'              => $row['current_position'] ?? 'Researcher',
                'institution'       => $row['affil_name'] ?? 'N/A',
                'country'           => $row['user_country'] ?? '',
                'flag'              => '',
                'location'          => $location,
                'experience_years'  => ($row['total_experience_yrs'] ?? '?') . '+',
                'total_reviews'     => (int)$row['total_reviews_completed'],
                'acceptance_rate'   => 98, // computed below
                'journals_reviewed' => 0,  // computed below
                'profile_views'     => (int)$row['profile_views'] + 1,
                'avg_turnaround'    => $avgDays,
                'member_since'      => $memberSince,
                'h_index'           => (int)($row['h_index'] ?? 0),
                'total_citations'   => (int)($row['total_citations'] ?? 0),
                'availability'      => (bool)$row['is_available'],
                'bio'               => $row['bio'] ?? '',
                'areas'             => $areas,
                'publications'      => $publications,
                'journals'          => [],
                'societies'         => $societies,
                'education'         => $education,
                'affil_name'        => $row['affil_name'] ?? '',
                'affil_loc'         => trim(implode(', ', array_filter([$row['affil_city'] ?? '', $row['affil_country'] ?? '']))),
                'affil_url'         => $affilUrl,
                'badges'            => $badges,
                'contact_web'       => $row['website_url'] ?? '',
                'orcid'             => $row['orcid_id'] ?? '',
                'color'             => '#1a3a8f',
                'level'             => $levelLabel,
                'user_id'           => (int)$row['user_id'],
                'reviewer_id'       => (int)$row['reviewer_id'],
            ];

            /* ── Compute acceptance rate from review_assignments ── */
            try {
                $astmt = $pdo->prepare("
                    SELECT
                        COUNT(*) AS total,
                        SUM(CASE WHEN assignment_status = 'review_submitted' THEN 1 ELSE 0 END) AS completed
                    FROM review_assignments WHERE reviewer_id = ?
                ");
                $astmt->execute([$row['reviewer_id']]);
                $arow = $astmt->fetch(PDO::FETCH_ASSOC);
                if ($arow['total'] > 0) {
                    $reviewer['acceptance_rate'] = round(($arow['completed'] / $arow['total']) * 100);
                }
            } catch (Exception $e) {}

            /* ── Count distinct journals reviewed ── */
            try {
                $jstmt = $pdo->prepare("
                    SELECT COUNT(DISTINCT s.journal_id) AS cnt
                    FROM review_assignments ra
                    JOIN submissions s ON s.submission_id = ra.submission_id
                    WHERE ra.reviewer_id = ? AND s.journal_id IS NOT NULL
                ");
                $jstmt->execute([$row['reviewer_id']]);
                $jrow = $jstmt->fetch(PDO::FETCH_ASSOC);
                $reviewer['journals_reviewed'] = (int)$jrow['cnt'];
            } catch (Exception $e) {}

            /* ── Journals reviewed (names) ── */
            try {
                $jnstmt = $pdo->prepare("
                    SELECT DISTINCT j.name AS journal_name, j.slug AS journal_slug
                    FROM review_assignments ra
                    JOIN submissions s ON s.submission_id = ra.submission_id
                    JOIN journals j ON j.journal_id = s.journal_id
                    WHERE ra.reviewer_id = ? AND s.journal_id IS NOT NULL
                    LIMIT 10
                ");
                $jnstmt->execute([$row['reviewer_id']]);
                $jnames = $jnstmt->fetchAll(PDO::FETCH_ASSOC);
                foreach ($jnames as $jn) {
                    $words = explode(' ', $jn['journal_name']);
                    $short = implode('', array_map(fn($w) => strtoupper(substr($w, 0, 1)), array_slice($words, 0, 4)));
                    $reviewer['journals'][] = [
                        'name'  => $jn['journal_name'],
                        'short' => $short ?: 'J'
                    ];
                }
            } catch (Exception $e) {}
        }
    } catch (PDOException $e) {}
}

/* ── If no reviewer found, redirect or 404 ── */
if (!$reviewer) {
    http_response_code(404);
    die('<h1>Reviewer profile not found</h1>');
}

/* ═══════════════════════════════════════
   FETCH PUBLISHED ARTICLES
   Articles where this reviewer's user_id is an author
═══════════════════════════════════════ */
$publishedArticles = [];
$userId = $reviewer['user_id'];

if ($pdo && $userId) {
    try {
        $pasql = $pdo->prepare("
            SELECT
                s.submission_id,
                mi.article_title,
                mi.abstract,
                sf.doi,
                sf.page_no,
                sf.publication_date,
                sf.article_slug,
                sf.published_pdf_path,
                sf.volume_id,
                jv.volume  AS vol_num,
                jv.issue   AS vol_iss,
                jv.year    AS vol_year,
                j.name     AS journal_name,
                j.slug     AS journal_slug,
                sa.is_corresponding,
                sa.author_order,
                (
                    SELECT COUNT(*) FROM article_siq_ratings asr
                    WHERE asr.submission_id = s.submission_id AND asr.status = 1
                ) AS siq_count,
                (
                    SELECT AVG(asr.siq_score) FROM article_siq_ratings asr
                    WHERE asr.submission_id = s.submission_id AND asr.status = 1
                ) AS siq_avg,
                (
                    SELECT COUNT(*) FROM article_comments ac
                    WHERE ac.submission_id = s.submission_id AND ac.status = 1
                ) AS comment_count
            FROM submission_authors sa
            JOIN submissions s          ON s.submission_id  = sa.submission_id
            LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
            LEFT JOIN submission_files sf ON sf.submission_id = s.submission_id
                AND sf.publication_date IS NOT NULL
            LEFT JOIN journal_volumes jv ON jv.id = sf.volume_id
            LEFT JOIN journals j         ON j.journal_id = s.journal_id
            WHERE sa.user_id = ?
            GROUP BY s.submission_id
            ORDER BY sf.publication_date DESC, s.submission_id DESC
        ");
        $pasql->execute([$userId]);
        $publishedArticles = $pasql->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {}
}

/* ═══════════════════════════════════════
   FETCH REVIEWED ARTICLES
═══════════════════════════════════════ */
$reviewedArticles = [];
$reviewerId = $reviewer['reviewer_id'];

if ($pdo && $reviewerId) {
    try {
        $rasql = $pdo->prepare("
            SELECT
                s.submission_id,
                mi.article_title,
                sf.publication_date,
                sf.article_slug,
                j.name  AS journal_name,
                j.slug  AS journal_slug,
                jv.volume AS vol_num, jv.issue AS vol_iss, jv.year AS vol_year,
                ra.assignment_status AS decision,
                ra.request_sent_date AS reviewed_at,
                (
                    SELECT COUNT(*) FROM article_siq_ratings asr
                    WHERE asr.submission_id = s.submission_id AND asr.status=1
                ) AS siq_count,
                (
                    SELECT AVG(asr.siq_score) FROM article_siq_ratings asr
                    WHERE asr.submission_id = s.submission_id AND asr.status=1
                ) AS siq_avg
            FROM review_assignments ra
            JOIN submissions s          ON s.submission_id = ra.submission_id
            LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
            LEFT JOIN submission_files sf ON sf.submission_id = s.submission_id
                AND sf.publication_date IS NOT NULL
            LEFT JOIN journal_volumes jv ON jv.id = sf.volume_id
            LEFT JOIN journals j         ON j.journal_id = s.journal_id
            WHERE ra.reviewer_id = ?
            GROUP BY s.submission_id
            ORDER BY ra.request_sent_date DESC
        ");
        $rasql->execute([$reviewerId]);
        $reviewedArticles = $rasql->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {}
}

/* Exclude overlap */
$publishedIds = array_column($publishedArticles, 'submission_id');
$reviewedArticles = array_filter($reviewedArticles, fn($r) => !in_array($r['submission_id'], $publishedIds));

/* ── Helpers ── */
$siteUrl = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];

function hx($v): string { return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

function articleUrl($row, $siteUrl): string {
    $slug  = $row['article_slug']  ?? '';
    $jSlug = $row['journal_slug']  ?? 'journal';
    if ($slug) return $siteUrl . '/journals/' . $jSlug . '/article/' . urlencode($slug);
    return $siteUrl . '/journals/article.php?id=' . (int)$row['submission_id'];
}

function pdfLink($path, $siteUrl): string {
    $p = trim((string)$path);
    if (!$p || $p === '0') return '';
    if (str_starts_with($p, 'http')) return $p;
    return $siteUrl . '/' . ltrim($p, '/');
}

function volLabel($row): string {
    if (!($row['vol_num'] ?? '')) return '';
    return 'Vol.' . $row['vol_num'] . ', Issue ' . $row['vol_iss'] . ($row['vol_year'] ? ' (' . $row['vol_year'] . ')' : '');
}

function siqBadge(int $count, float $avg): string {
    if (!$count) return '<span class="siq-zero">No SIQ ratings yet</span>';
    $score = $count >= 2 ? number_format($avg, 1) : '—';
    return '<span class="siq-badge-inline">
        <svg viewBox="0 0 44 50" width="22" height="25" style="flex-shrink:0">
            <path d="M22 1.5L41 9V27C41 38.5 22 48.5 22 48.5S3 38.5 3 27V9Z" fill="#2196a0"/>
            <text x="50%" y="43%" text-anchor="middle" fill="#fff" font-size="9.5" font-weight="700" font-family="Georgia,serif" dy=".1em">SIQ</text>
            <text x="50%" y="70%" text-anchor="middle" fill="rgba(255,255,255,.9)" font-size="8.5" font-family="Georgia,serif" dy=".1em">' . hx($score) . '</text>
        </svg>
        <span class="siq-badge-text"><strong>' . $count . '</strong> rating' . ($count > 1 ? 's' : '') . ($count >= 2 ? ' &bull; avg ' . number_format($avg, 1) : '') . '</span>
    </span>';
}

$pageTitle = hx($reviewer['name']) . ' — Reviewer Profile — 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><?= $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=Playfair+Display:wght@600;700&family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;0,9..40,600;1,9..40,400&display=swap" rel="stylesheet">

<style>
/* ═══════════════════════════════════════
   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;
  --teal:     #2196a0;
  --muted:    #64748b;
  --border:   #e2e8f0;
  --surface:  #f8fafc;
  --white:    #ffffff;
  --text:     #1e293b;
  --text-sm:  #475569;
  --radius:   12px;
  --shadow-sm: 0 1px 3px rgba(0,0,0,.06), 0 1px 2px rgba(0,0,0,.04);
  --shadow:    0 4px 16px rgba(12,31,63,.08);
  --shadow-lg: 0 12px 40px rgba(12,31,63,.14);
}

*, *::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;
}
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: 'Playfair Display', 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; }
.top-banner-actions .btn {
  font-size: .75rem; border-radius: 6px;
  border-color: rgba(255,255,255,.25); color: rgba(255,255,255,.8);
  padding: 4px 10px;
}
.top-banner-actions .btn:hover { background: rgba(255,255,255,.1); color: #fff; }

/* ── PROFILE HEADER CARD ── */
.profile-header-card {
  background: var(--white);
  border: 1px solid var(--border);
  border-top: none;
  border-radius: 0 0 var(--radius) var(--radius);
  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: 'Playfair Display', 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: 'Playfair Display', 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;
}
@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-inst i { font-size: .75rem; }
.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 */
.profile-cta { display: flex; flex-direction: column; gap: 8px; min-width: 160px; }
.btn-request {
  background: var(--sky); color: #fff; border: none; border-radius: 8px;
  font-size: .85rem; font-weight: 600; padding: 10px 16px; cursor: pointer;
  display: flex; align-items: center; justify-content: center; gap: 7px;
  transition: background .15s, transform .1s, box-shadow .15s;
  box-shadow: 0 2px 8px rgba(37,99,235,.3);
}
.btn-request:hover { background: #1d4ed8; transform: translateY(-1px); box-shadow: 0 4px 14px rgba(37,99,235,.4); }
.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, border-color .15s;
}
.btn-secondary:hover { background: var(--surface); border-color: #94a3b8; color: var(--text); }
.avail-row {
  display: flex; align-items: center; gap: 6px;
  font-size: .73rem; color: var(--green); font-weight: 500;
  justify-content: center;
}

/* ── CONTRIBUTION STATS ROW ── */
.contrib-row {
  display: grid;
  grid-template-columns: repeat(5, 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);
  position: relative;
}
.contrib-cell:last-child { border-right: none; }
.contrib-num {
  font-family: 'Playfair Display', 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-lbl {
  font-size: .68rem; 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 CARD ── */
.sec {
  background: var(--white);
  border: 1px solid var(--border);
  border-radius: var(--radius);
  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-link { font-size: .78rem; color: var(--sky); font-weight: 500; }
.sec-body { padding: 20px; }

/* ── BIO ── */
.bio-text {
  font-size: .88rem; color: var(--text-sm); line-height: 1.85;
  display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical;
  overflow: hidden;
}
.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;
}

/* ── 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;
}

/* ── ARTICLES ── */
.art-card {
  background: var(--white);
  border: 1px solid var(--border);
  border-radius: 10px;
  padding: 16px 18px;
  margin-bottom: 12px;
  transition: border-color .15s, box-shadow .15s;
}
.art-card:hover { border-color: #b6d4f0; box-shadow: 0 2px 12px rgba(26,86,219,.06); }
.art-card-num {
  width: 30px; height: 30px; border-radius: 7px; flex-shrink: 0;
  background: var(--sky-lt); border: 1.5px solid #bfdbfe;
  display: flex; align-items: center; justify-content: center;
  font-size: .72rem; font-weight: 700; color: var(--sky);
}
.art-card-title {
  font-size: .9rem; font-weight: 700; color: var(--navy);
  line-height: 1.4; margin-bottom: 7px; text-decoration: none; display: block;
}
.art-card-title:hover { color: var(--sky); }
.art-meta-chip {
  display: inline-flex; align-items: center; gap: 4px;
  font-size: .72rem; font-weight: 600; padding: 3px 9px; border-radius: 5px;
  margin-right: 4px; margin-bottom: 4px;
}
.amc-journal { background: #eff6ff; color: #1a56db; }
.amc-vol     { background: #f0f9ff; color: #0369a1; }
.amc-date    { background: #f1f5f9; color: #374151; }
.amc-doi     { background: #f5f3ff; color: #6d28d9; }
.amc-corr    { background: #fef3e8; color: #c2560c; }
.art-abstract {
  font-size: .79rem; color: var(--muted); line-height: 1.6;
  display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;
  overflow: hidden; margin-bottom: 10px;
}
.art-footer {
  display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
  padding-top: 10px; border-top: 1px solid var(--surface);
}
.art-action {
  display: inline-flex; align-items: center; gap: 5px;
  font-size: .75rem; font-weight: 600; color: var(--sky);
  padding: 4px 10px; background: #eff6ff; border-radius: 5px;
  text-decoration: none; transition: all .15s;
}
.art-action:hover { background: #dbeafe; color: #1648c2; text-decoration: none; }
.art-action.red { color: #dc2626; background: #fee2e2; }
.art-action.red:hover { background: #fca5a5; }
.siq-badge-inline { display: inline-flex; align-items: center; gap: 6px; }
.siq-badge-text { font-size: .75rem; color: var(--teal); font-weight: 600; }
.siq-badge-text strong { color: var(--navy); }
.siq-zero { font-size: .75rem; color: var(--muted); font-style: italic; }
.empty-state {
  text-align: center; padding: 40px 20px; color: var(--muted);
}
.empty-state i { font-size: 36px; display: block; margin-bottom: 10px; color: #cbd5e1; }

/* ── PUBLICATIONS ── */
.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-text {
  font-size: .88rem; font-weight: 600; color: var(--navy);
  line-height: 1.45; margin-bottom: 5px;
}
.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); }

/* ── 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: .65rem; 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 ── */
.side-card {
  background: var(--white);
  border: 1px solid var(--border);
  border-radius: var(--radius);
  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; }

/* Contact 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; }
.info-row a { color: var(--sky); }

/* Affiliation */
.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; }
.affil-link { font-size: .73rem; color: var(--sky); margin-top: 4px; display: inline-flex; align-items: center; gap: 4px; }

/* Rating */
.rating-wrap { text-align: center; padding: 6px 0 10px; }
.rating-dial-svg { display: block; margin: 0 auto 8px; }
.rating-score { font-family: 'Playfair Display', 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; }

/* Societies */
.society-item {
  display: flex; align-items: flex-start; gap: 8px;
  font-size: .8rem; color: var(--text-sm);
  padding: 7px 0; border-bottom: 1px solid var(--border); line-height: 1.4;
}
.society-item:last-child { border-bottom: none; padding-bottom: 0; }
.society-item:first-child { padding-top: 0; }
.society-item i { color: var(--sky-mid); font-size: .72rem; margin-top: 3px; flex-shrink: 0; }

/* 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: .6rem; 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: 640px) {
  .contrib-row { grid-template-columns: repeat(3, 1fr); }
  .contrib-cell:nth-child(3) { border-right: none; }
  .contrib-cell:nth-child(4) { border-top: 1px solid var(--border); }
  .profile-header-body { padding: 20px 18px 18px; }
  .profile-name { font-size: 1.3rem; }
  .profile-cta { min-width: unset; width: 100%; }
}
@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); }
}
</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><?= hx($reviewer['name']) ?></span>
    </nav>
    <div class="top-banner-actions">
      <button class="btn btn-outline-light btn-sm" onclick="navigator.clipboard.writeText(window.location.href);this.innerHTML='<i class=\'fas fa-check me-1\'></i>Copied!'">
        <i class="fas fa-share-nodes me-1"></i>Share
      </button>
      <button class="btn btn-outline-light btn-sm"><i class="fas fa-bookmark me-1"></i>Save</button>
    </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">
        <?= hx($reviewer['initials']) ?>
        <?php if ($reviewer['level']): ?>
        <div class="avatar-level-badge"><?= hx($reviewer['level']) ?></div>
        <?php endif; ?>
      </div>

      <!-- Identity -->
      <div class="profile-identity">
        <div class="profile-name-row">
          <span class="profile-name"><?= hx($reviewer['name']) ?></span>
          <?php if ($reviewer['verified']): ?>
          <span class="verified-pill">
            <i class="fas fa-circle-check" style="font-size:.75rem;"></i> Verified Reviewer
          </span>
          <?php endif; ?>
        </div>
        <div class="profile-role"><?= hx($reviewer['role']) ?></div>
        <div class="profile-inst">
          <i class="fas fa-building-columns"></i>
          <?= hx($reviewer['institution']) ?>
          <?php if ($reviewer['country']): ?>&nbsp;<?= hx($reviewer['country']) ?><?php endif; ?>
        </div>
        <div class="profile-tags">
          <?php if ($reviewer['location']): ?>
          <span class="p-tag"><i class="fas fa-location-dot"></i><?= hx($reviewer['location']) ?></span>
          <?php endif; ?>
          <span class="p-tag"><i class="fas fa-calendar-days"></i>Member since <?= hx($reviewer['member_since']) ?></span>
          <?php if ($reviewer['avg_turnaround'] !== 'N/A'): ?>
          <span class="p-tag"><i class="fas fa-gauge-high"></i><?= hx($reviewer['avg_turnaround']) ?> avg. turnaround</span>
          <?php endif; ?>
          <span class="p-tag"><i class="fas fa-clock-rotate-left"></i><?= hx($reviewer['experience_years']) ?> yrs experience</span>
          <?php if ($reviewer['orcid']): ?>
          <span class="p-tag"><i class="fab fa-orcid" style="color:#a6ce39;"></i><?= hx($reviewer['orcid']) ?></span>
          <?php endif; ?>
        </div>
      </div>

      <!-- CTA -->
      <div class="profile-cta">
        <?php if ($reviewer['availability']): ?>
        <div class="avail-row">
          <div class="availability-dot"></div>
          <span>Available for review</span>
        </div>
        <?php endif; ?>
        <button class="btn-request">
          <i class="fas fa-paper-plane"></i> Request to Review
        </button>
        <button class="btn-secondary">
          <i class="fas fa-envelope"></i> Send Message
        </button>
        <button class="btn-secondary">
          <i class="fas fa-ellipsis"></i> More Options
        </button>
      </div>

    </div>

    <!-- Contribution stats row -->
    <div class="contrib-row">
      <div class="contrib-cell">
        <span class="contrib-num blue"><?= $reviewer['total_reviews'] ?></span>
        <span class="contrib-lbl">Reviews<br>Completed</span>
      </div>
      <div class="contrib-cell">
        <span class="contrib-num"><?= count($publishedArticles) ?></span>
        <span class="contrib-lbl">Publications</span>
      </div>
      <div class="contrib-cell">
        <span class="contrib-num green"><?= $reviewer['acceptance_rate'] ?>%</span>
        <span class="contrib-lbl">Acceptance<br>Rate</span>
      </div>
      <div class="contrib-cell">
        <span class="contrib-num"><?= number_format($reviewer['profile_views']) ?></span>
        <span class="contrib-lbl">Profile<br>Views</span>
      </div>
      <div class="contrib-cell">
        <span class="contrib-num gold"><?= $reviewer['h_index'] ?: '—' ?></span>
        <span class="contrib-lbl">h-Index</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($reviewer['areas'])): ?>
    <span class="snav-link" data-target="sec-areas">Research Areas</span>
    <?php endif; ?>
    <span class="snav-link" data-target="sec-articles">Published Articles <span style="background:#e0f2fe;color:#0369a1;border-radius:10px;padding:1px 7px;font-size:.7rem;font-weight:700;"><?= count($publishedArticles) ?></span></span>
    <?php if (!empty($reviewer['publications'])): ?>
    <span class="snav-link" data-target="sec-pubs">Publications</span>
    <?php endif; ?>
    <?php if (!empty($reviewer['journals'])): ?>
    <span class="snav-link" data-target="sec-journals">Journals</span>
    <?php endif; ?>
    <?php if (!empty($reviewer['education'])): ?>
    <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 ($reviewer['bio']): ?>
        <p class="bio-text" id="bioText"><?= hx($reviewer['bio']) ?></p>
        <button class="bio-toggle" onclick="toggleBio()" id="bioToggle">
          <span id="bioToggleTxt">Read more</span>
          <i class="fas fa-chevron-down" id="bioChevron"></i>
        </button>
        <?php else: ?>
        <p style="color:var(--muted);font-size:.88rem;">No bio available yet.</p>
        <?php endif; ?>
      </div>
    </div>

    <!-- Research Areas -->
    <?php if (!empty($reviewer['areas'])): ?>
    <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($reviewer['areas']) ?> areas</span>
      </div>
      <div class="sec-body">
        <div class="area-chips">
          <?php foreach ($reviewer['areas'] as $a): ?>
          <span class="area-chip"><?= hx($a['name']) ?></span>
          <?php endforeach; ?>
        </div>
        <div>
          <?php foreach ($reviewer['areas'] as $a): ?>
          <div class="area-bar-row">
            <div class="area-bar-label">
              <span><?= hx($a['name']) ?></span>
              <span><?= $a['pct'] ?>%</span>
            </div>
            <div class="area-track">
              <div class="area-fill" style="width:<?= $a['pct'] ?>%"></div>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <!-- Published Articles -->
    <div class="sec" id="sec-articles">
      <div class="sec-head">
        <span class="sec-title"><i class="fas fa-newspaper"></i>Published Articles</span>
        <span style="font-size:.75rem;color:var(--muted);"><?= count($publishedArticles) ?> article<?= count($publishedArticles) !== 1 ? 's' : '' ?></span>
      </div>
      <div class="sec-body" style="padding: 16px 20px;">
        <?php if (empty($publishedArticles)): ?>
        <div class="empty-state">
          <i class="fas fa-file-alt"></i>
          <p style="font-size:.85rem;">No published articles found for this reviewer.</p>
        </div>
        <?php else: ?>
        <?php foreach ($publishedArticles as $i => $art): ?>
        <?php
          $aUrl    = articleUrl($art, $siteUrl);
          $pdf     = pdfLink($art['published_pdf_path'] ?? '', $siteUrl);
          $vl      = volLabel($art);
          $siqHtml = siqBadge((int)($art['siq_count'] ?? 0), (float)($art['siq_avg'] ?? 0));
        ?>
        <div class="art-card">
          <div style="display:flex;align-items:flex-start;gap:12px;">
            <div class="art-card-num"><?= $i + 1 ?></div>
            <div style="flex:1;min-width:0;">
              <a href="<?= hx($aUrl) ?>" class="art-card-title" target="_blank">
                <?= hx($art['article_title'] ?? 'Untitled Article') ?>
              </a>

              <!-- Meta chips -->
              <div style="margin-bottom:8px;">
                <?php if ($art['journal_name'] ?? ''): ?>
                <span class="art-meta-chip amc-journal"><i class="fas fa-graduation-cap"></i> <?= hx($art['journal_name']) ?></span>
                <?php endif; ?>
                <?php if ($vl): ?>
                <span class="art-meta-chip amc-vol"><i class="fas fa-book-open"></i> <?= hx($vl) ?></span>
                <?php endif; ?>
                <?php if ($art['publication_date'] ?? ''): ?>
                <span class="art-meta-chip amc-date"><i class="fas fa-calendar-check"></i> <?= hx(date('d M Y', strtotime($art['publication_date']))) ?></span>
                <?php endif; ?>
                <?php if ($art['doi'] ?? ''): ?>
                <span class="art-meta-chip amc-doi"><i class="fas fa-fingerprint"></i> <?= hx($art['doi']) ?></span>
                <?php endif; ?>
                <?php if ($art['is_corresponding'] ?? false): ?>
                <span class="art-meta-chip amc-corr"><i class="fas fa-envelope"></i> Corresponding Author</span>
                <?php endif; ?>
                <?php if ($art['page_no'] ?? ''): ?>
                <span class="art-meta-chip" style="background:#f0fdf4;color:#166534;"><i class="fas fa-file-lines"></i> pp. <?= hx($art['page_no']) ?></span>
                <?php endif; ?>
              </div>

              <!-- Abstract -->
              <?php if ($art['abstract'] ?? ''): ?>
              <div class="art-abstract"><?= hx(mb_strimwidth(strip_tags($art['abstract']), 0, 220, '…')) ?></div>
              <?php endif; ?>

              <!-- Footer: SIQ + actions -->
              <div class="art-footer">
                <?= $siqHtml ?>
                <?php if ((int)($art['comment_count'] ?? 0) > 0): ?>
                <span style="font-size:.75rem;color:var(--muted);">
                  <i class="fas fa-comments" style="color:#94a3b8;margin-right:3px;"></i>
                  <?= (int)$art['comment_count'] ?> comment<?= $art['comment_count'] > 1 ? 's' : '' ?>
                </span>
                <?php endif; ?>
                <a href="<?= hx($aUrl) ?>" class="art-action" target="_blank">
                  <i class="fas fa-external-link-alt"></i> View
                </a>
                <?php if ($pdf): ?>
                <a href="<?= hx($pdf) ?>" class="art-action red" target="_blank">
                  <i class="fas fa-file-pdf"></i> PDF
                </a>
                <?php endif; ?>
              </div>
            </div>
          </div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>

    <!-- Selected Publications (from profile JSON) -->
    <?php if (!empty($reviewer['publications'])): ?>
    <div class="sec" id="sec-pubs">
      <div class="sec-head">
        <span class="sec-title"><i class="fas fa-book-open"></i>Selected Publications</span>
      </div>
      <div class="sec-body">
        <?php foreach ($reviewer['publications'] as $pub): ?>
        <div class="pub-item">
          <div class="pub-title-text"><?= hx($pub['title'] ?? 'Untitled') ?></div>
          <div class="pub-meta-row">
            <?php if ($pub['journal'] ?? ''): ?>
            <span class="pub-journal"><?= hx($pub['journal']) ?></span>
            <?php endif; ?>
            <?php if ($pub['year'] ?? ''): ?>
            <span class="pub-badge year"><?= hx($pub['year']) ?></span>
            <?php endif; ?>
            <?php if ($pub['cites'] ?? ''): ?>
            <span class="pub-badge cite"><i class="fas fa-quote-right" style="font-size:.6rem;"></i><?= hx($pub['cites']) ?> citations</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-file-pen"></i>Reviewer for Journals</span>
      </div>
      <div class="sec-body">
        <?php foreach ($reviewer['journals'] as $j): ?>
        <div class="journal-row">
          <div class="journal-icon"><?= hx($j['short']) ?></div>
          <span class="journal-name"><?= hx($j['name']) ?></span>
          <i class="fas fa-circle-check journal-check"></i>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Education -->
    <?php if (!empty($reviewer['education'])): ?>
    <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 ($reviewer['education'] as $edu): ?>
        <div class="edu-item">
          <div class="edu-dot">🎓</div>
          <div>
            <div class="edu-degree"><?= hx($edu['degree'] ?? '') ?></div>
            <div class="edu-inst"><?= hx($edu['institution'] ?? '') ?></div>
            <?php if ($edu['year'] ?? ''): ?>
            <span class="edu-year"><?= hx($edu['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">
        <?php
          $ratingVal = number_format((float)($reviewerRow['reviewer_rating'] ?? 0), 1);
          $fullStars = (int)floor($ratingVal);
          $halfStar  = ($ratingVal - $fullStars) >= 0.5;
          $emptyStars= 5 - $fullStars - ($halfStar ? 1 : 0);
          /* Arc = 126 total; filled portion */
          $arcFill = $ratingVal > 0 ? round(126 * ($ratingVal / 5)) : 0;
          $arcOffset = 126 - $arcFill;
        ?>
        <div class="rating-wrap">
          <svg class="rating-dial-svg" 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="<?= $arcOffset ?>" opacity=".9"/>
          </svg>
          <div class="rating-score"><?= $ratingVal ?></div>
          <div class="rating-stars">
            <?php for ($s = 0; $s < $fullStars; $s++): ?><i class="fas fa-star"></i><?php endfor; ?>
            <?php if ($halfStar): ?><i class="fas fa-star-half-stroke"></i><?php endif; ?>
            <?php for ($s = 0; $s < $emptyStars; $s++): ?><i class="far fa-star"></i><?php endfor; ?>
          </div>
          <div class="rating-count">Based on <?= (int)$reviewer['total_reviews'] ?> reviews</div>
        </div>
      </div>
    </div>

    <!-- Affiliation -->
    <?php if ($reviewer['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"><?= hx($reviewer['affil_name']) ?></div>
            <?php if ($reviewer['affil_loc']): ?>
            <div class="affil-loc">
              <i class="fas fa-location-dot" style="font-size:.7rem;margin-right:3px;color:var(--muted);"></i>
              <?= hx($reviewer['affil_loc']) ?>
            </div>
            <?php endif; ?>
            <?php if ($reviewer['affil_url'] && $reviewer['affil_url'] !== '#'): ?>
            <a href="<?= hx($reviewer['affil_url']) ?>" target="_blank" class="affil-link">
              Visit website <i class="fas fa-arrow-up-right-from-square" style="font-size:.6rem;"></i>
            </a>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <!-- Contact -->
    <div class="side-card">
      <div class="side-head"><i class="fas fa-address-card"></i>Contact & Details</div>
      <div class="side-body">
        <?php if ($reviewer['contact_web']): ?>
        <div class="info-row">
          <i class="fas fa-globe"></i>
          <a href="<?= hx($reviewer['contact_web']) ?>" target="_blank"><?= hx($reviewer['contact_web']) ?></a>
        </div>
        <?php endif; ?>
        <?php if ($reviewer['orcid']): ?>
        <div class="info-row">
          <i class="fab fa-orcid" style="color:#a6ce39;"></i>
          <a href="https://orcid.org/<?= hx($reviewer['orcid']) ?>" target="_blank"><?= hx($reviewer['orcid']) ?></a>
        </div>
        <?php endif; ?>
        <?php if ($reviewer['location']): ?>
        <div class="info-row">
          <i class="fas fa-location-dot"></i>
          <span><?= hx($reviewer['location']) ?></span>
        </div>
        <?php endif; ?>
        <div class="info-row">
          <i class="fas fa-calendar"></i>
          <span>Member since <?= hx($reviewer['member_since']) ?></span>
        </div>
        <?php if ($reviewer['total_citations']): ?>
        <div class="info-row">
          <i class="fas fa-quote-left"></i>
          <span><?= number_format($reviewer['total_citations']) ?> total citations</span>
        </div>
        <?php endif; ?>
        <?php if ($reviewer['journals_reviewed']): ?>
        <div class="info-row">
          <i class="fas fa-file-pen"></i>
          <span>Reviewed for <?= $reviewer['journals_reviewed'] ?> journal<?= $reviewer['journals_reviewed'] > 1 ? 's' : '' ?></span>
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Badges -->
    <?php if (!empty($reviewer['badges'])): ?>
    <div class="side-card">
      <div class="side-head"><i class="fas fa-trophy"></i>Badges &amp; Honours</div>
      <div class="side-body">
        <?php
        $bConfig = [
          ['bg'=>'#fef9c3','color'=>'#854d0e','icon'=>'fa-star'],
          ['bg'=>'#fce7f3','color'=>'#9d174d','icon'=>'fa-medal'],
          ['bg'=>'#e0f2fe','color'=>'#075985','icon'=>'fa-shield-halved'],
        ];
        foreach ($reviewer['badges'] as $bi => $b):
          $bc = $bConfig[$bi % count($bConfig)];
        ?>
        <div class="badge-cell" style="display:inline-block;margin:4px;min-width:80px;vertical-align:top;">
          <div class="badge-ico" style="background:<?= $bc['bg'] ?>;color:<?= $bc['color'] ?>;">
            <i class="fas <?= $bc['icon'] ?>"></i>
          </div>
          <div class="badge-name"><?= hx($b) ?></div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Professional Societies -->
    <?php if (!empty($reviewer['societies'])): ?>
    <div class="side-card">
      <div class="side-head"><i class="fas fa-users"></i>Professional Societies</div>
      <div class="side-body">
        <?php foreach ($reviewer['societies'] as $s): ?>
        <div class="society-item">
          <i class="fas fa-circle-dot"></i>
          <span><?= hx($s) ?></span>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Reviewed Articles (summary) -->
    <?php $revCount = count($reviewedArticles); ?>
    <?php if ($revCount > 0): ?>
    <div class="side-card">
      <div class="side-head"><i class="fas fa-search"></i>Articles Reviewed</div>
      <div class="side-body">
        <div style="text-align:center;padding:8px 0;">
          <div style="font-family:'Playfair Display',serif;font-size:2rem;font-weight:700;color:var(--navy);"><?= $revCount ?></div>
          <div style="font-size:.75rem;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;">Peer Reviews Contributed</div>
        </div>
      </div>
    </div>
    <?php endif; ?>

  </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>
/* Bio toggle */
let bioOpen = false;
function toggleBio() {
  bioOpen = !bioOpen;
  const bt = document.getElementById('bioText');
  const tl = document.getElementById('bioToggleTxt');
  const bc = document.getElementById('bioChevron');
  if (bt) bt.classList.toggle('expanded', bioOpen);
  if (tl) tl.textContent = bioOpen ? 'Show less' : 'Read more';
  if (bc) bc.style.transform = bioOpen ? 'rotate(180deg)' : '';
}

/* 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 sH = document.getElementById('stickyNav')?.offsetHeight || 56;
  let cur = sections[0]?.id;
  sections.forEach(s => { if (window.scrollY >= s.offsetTop - sH - 20) cur = s.id; });
  navLinks.forEach(l => l.classList.toggle('active', l.dataset.target === cur));
}
window.addEventListener('scroll', updateNav, { passive: true });
updateNav();

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

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

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