<?php
// reviewer/dashboard.php — Complete version with stat card filters

error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once __DIR__ . '/config/db.php';
startSession();

// ── Auth guard ──────────────────────────────────────────────
if (!isset($_SESSION['user_id'])) {
    header('Location: /reviewer/login.php?redirect=reviewer/dashboard.php');
    exit;
}

$user    = getCurrentUser();
$user_id = $user['user_id'];

// Dual-role switcher flag
$showAuthorLink = in_array($user['role'] ?? '', ['author', 'both']);

// ── Role guard ──────────────────────────────────────────────
if (!in_array($user['role'], ['reviewer', 'both', 'editor'])) {
    header('Location: /author/dashboard.php');
    exit;
}

// ── Fetch reviewer record FIRST before any checks ──────────
$stmt = db()->prepare("SELECT * FROM reviewers WHERE user_id = ? LIMIT 1");
$stmt->execute([$user_id]);
$reviewer = $stmt->fetch();

// ── NOW check if reviewer record exists ────────────────────
if (!$reviewer) {
    try {
        db()->prepare(
            "INSERT INTO reviewers 
             (user_id, reviewer_come_from, is_available, 
              max_reviews_per_period, preferred_review_duration_days,
              created_at) 
             VALUES (?, 'role_upgrade', 1, 5, 21, NOW())"
        )->execute([$user_id]);

        $stmt2 = db()->prepare("SELECT * FROM reviewers WHERE user_id = ? LIMIT 1");
        $stmt2->execute([$user_id]);
        $reviewer = $stmt2->fetch();
    } catch (PDOException $e) {
        error_log('reviewer auto-create error: ' . $e->getMessage());
        header('Location: /author/dashboard.php?msg=reviewer_not_setup');
        exit;
    }
}

$reviewer_id = $reviewer['id'];

$full_name    = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
$display_name = $full_name ?: ($user['username'] ?? 'Reviewer');
$user_initial = strtoupper(substr($user['first_name'] ?? 'R', 0, 1));

// ── Fetch reviewer record (second fetch for safety) ─────────
$stmt = db()->prepare("SELECT * FROM reviewers WHERE user_id = ? LIMIT 1");
$stmt->execute([$user_id]);
$reviewer = $stmt->fetch();

if (!$reviewer) {
    session_destroy();
    header('Location: /author/dashboard.php?msg=reviewer_not_setup');
    exit;
}
$reviewer_id = $reviewer['id'];

// ── Section routing ─────────────────────────────────────────
$active  = isset($_GET['section']) ? $_GET['section'] : 'dashboard';
$allowed = array('dashboard','profile','change_password','tickets','raise_ticket','view_ticket','certificate','reviewer_profiles');
if (!in_array($active, $allowed)) $active = 'dashboard';

$error   = null;
$success = null;

// ════════════════════════════════════════════════════════════
// POST: CHANGE PASSWORD
// ════════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $current = isset($_POST['current_password']) ? $_POST['current_password'] : '';
    $new     = isset($_POST['new_password'])     ? $_POST['new_password']     : '';
    $confirm = isset($_POST['confirm_password']) ? $_POST['confirm_password'] : '';

    if (strlen($new) < 8) {
        $error = 'New password must be at least 8 characters.';
    } elseif ($new !== $confirm) {
        $error = 'New passwords do not match.';
    } else {
        $q = db()->prepare("SELECT password_hash FROM users WHERE user_id = ?");
        $q->execute([$user_id]);
        $row = $q->fetch();
        if ($row && password_verify($current, $row['password_hash'])) {
            $hash = password_hash($new, PASSWORD_DEFAULT);
            db()->prepare("UPDATE users SET password_hash = ? WHERE user_id = ?")
               ->execute([$hash, $user_id]);
            $success = 'Password changed successfully!';
        } else {
            $error = 'Current password is incorrect.';
        }
    }
    $active = 'change_password';
}

// ════════════════════════════════════════════════════════════
// POST: PROFILE UPDATE
// ════════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $first     = trim(isset($_POST['first_name'])          ? $_POST['first_name']          : '');
    $last      = trim(isset($_POST['last_name'])           ? $_POST['last_name']           : '');
    $raw_title = isset($_POST['title'])                    ? $_POST['title']               : '';
    $phone_cc  = trim(isset($_POST['phone_country_code'])  ? $_POST['phone_country_code']  : '');
    $phone     = trim(isset($_POST['phone_number'])        ? $_POST['phone_number']        : '');
    $inst_em   = trim(isset($_POST['institutional_email']) ? $_POST['institutional_email'] : '');
    $interests = trim(isset($_POST['reviewing_interests']) ? $_POST['reviewing_interests'] : '');

    $valid_titles = array('Mr','Mrs','Ms','Dr','Prof');
    $title = in_array($raw_title, $valid_titles) ? $raw_title : null;

    if (!$first || !$last) {
        $error = 'First name and last name are required.';
    } else {
        db()->prepare("
            UPDATE users
            SET first_name=?, last_name=?, title=?,
                phone_country_code=?, phone_number=?, institutional_email=?,
                updated_at=NOW()
            WHERE user_id=?
        ")->execute([$first, $last, $title,
                     ($phone_cc ?: null), ($phone ?: null), ($inst_em ?: null),
                     $user_id]);

        $interests_json = $interests ? json_encode(array_map('trim', explode(',', $interests))) : null;
        db()->prepare("UPDATE reviewers SET reviewing_interests=? WHERE id=?")
           ->execute([$interests_json, $reviewer_id]);

        $success = 'Profile updated successfully!';
        $user = getCurrentUser();
        $full_name    = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
        $display_name = $full_name ?: ($user['username'] ?? 'Reviewer');
        $user_initial = strtoupper(substr($user['first_name'] ?? 'R', 0, 1));
    }
    $active = 'profile';
}

// ════════════════════════════════════════════════════════════
// POST: RAISE TICKET
// ════════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['raise_ticket'])) {
    $subject  = trim(isset($_POST['subject'])  ? $_POST['subject']  : '');
    $message  = trim(isset($_POST['message'])  ? $_POST['message']  : '');
    $raw_pri  = isset($_POST['priority'])      ? $_POST['priority'] : '';
    $priority = in_array($raw_pri, array('low','medium','high','urgent')) ? $raw_pri : 'medium';
    $sub_id   = filter_var(isset($_POST['submission_id']) ? $_POST['submission_id'] : 0, FILTER_VALIDATE_INT);
    $sub_id   = $sub_id ?: null;

    if (!$subject || !$message) {
        $error  = 'Subject and message are required.';
        $active = 'raise_ticket';
    } else {
        do {
            $tn  = 'TKT-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid(rand(), true)), 0, 6));
            $chk = db()->prepare("SELECT id FROM reviewer_tickets WHERE ticket_number = ?");
            $chk->execute([$tn]);
        } while ($chk->fetch());

        db()->prepare("
            INSERT INTO reviewer_tickets
                (ticket_number, reviewer_id, user_id, submission_id, subject, message, priority)
            VALUES (?,?,?,?,?,?,?)
        ")->execute([$tn, $reviewer_id, $user_id, $sub_id, $subject, $message, $priority]);

        try {
            if (function_exists('sendEmail') && defined('ADMIN_EMAIL')) {
                sendEmail(
                    ADMIN_EMAIL, 'Editorial Office',
                    "New Reviewer Ticket - {$tn}",
                    "<p><strong>Ticket:</strong> {$tn}</p>
                     <p><strong>Reviewer:</strong> " . htmlspecialchars($display_name) . "</p>
                     <p><strong>Subject:</strong> " . htmlspecialchars($subject) . "</p>
                     <p><strong>Message:</strong><br>" . nl2br(htmlspecialchars($message)) . "</p>"
                );
            }
        } catch (Exception $e) {
            error_log('Ticket email error: ' . $e->getMessage());
        }

        header("Location: ?section=tickets&created=" . urlencode($tn));
        exit;
    }
}

// ════════════════════════════════════════════════════════════
// POST: TICKET REPLY
// ════════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_ticket'])) {
    $ticket_id = filter_var(isset($_POST['ticket_id']) ? $_POST['ticket_id'] : 0, FILTER_VALIDATE_INT);
    $reply_msg = trim(isset($_POST['reply_message']) ? $_POST['reply_message'] : '');

    if (!$ticket_id || !$reply_msg) {
        $error  = 'Reply message cannot be empty.';
        $active = 'view_ticket';
    } else {
        $chk = db()->prepare("SELECT id FROM reviewer_tickets WHERE id = ? AND reviewer_id = ?");
        $chk->execute([$ticket_id, $reviewer_id]);

        if ($chk->fetch()) {
            try {
                db()->prepare("
                    INSERT INTO reviewer_ticket_replies (ticket_id, user_id, message, is_admin)
                    VALUES (?, ?, ?, 0)
                ")->execute([$ticket_id, $user_id, $reply_msg]);

                db()->prepare("UPDATE reviewer_tickets SET updated_at = NOW() WHERE id = ?")
                   ->execute([$ticket_id]);

                try {
                    if (function_exists('sendEmail') && defined('ADMIN_EMAIL')) {
                        $t = db()->prepare("SELECT ticket_number, subject FROM reviewer_tickets WHERE id=?");
                        $t->execute([$ticket_id]);
                        $td = $t->fetch();
                        sendEmail(
                            ADMIN_EMAIL, 'Editorial Office',
                            "Reviewer Reply on Ticket - " . ($td['ticket_number'] ?? ''),
                            "<p><strong>Ticket:</strong> " . htmlspecialchars($td['ticket_number'] ?? '') . "</p>
                             <p><strong>Reviewer:</strong> " . htmlspecialchars($display_name) . "</p>
                             <p><strong>Reply:</strong><br>" . nl2br(htmlspecialchars($reply_msg)) . "</p>"
                        );
                    }
                } catch (Exception $emailEx) {
                    error_log('Reply email error: ' . $emailEx->getMessage());
                }

                header("Location: ?section=view_ticket&id={$ticket_id}&reply=1");
                exit;

            } catch (PDOException $e) {
                $error  = 'Database error: ' . $e->getMessage();
                $active = 'view_ticket';
            }
        } else {
            $error  = 'Ticket not found or access denied.';
            $active = 'view_ticket';
        }
    }
}

// ════════════════════════════════════════════════════════════
// DATA LOADERS
// ════════════════════════════════════════════════════════════

$assignments = array();
$stats = array('total'=>0,'pending'=>0,'accepted'=>0,'submitted'=>0,'declined'=>0);

if ($active === 'dashboard') {
    try {
        $q = db()->prepare("
            SELECT
                ra.id,
                ra.submission_id,
                ra.reviewer_id,
                ra.assignment_status,
                ra.review_round,
                ra.reviewer_type,
                ra.access_key,
                ra.request_sent_date,
                ra.response_due_date,
                ra.review_due_date,
                ra.submitted_date,
                mi.article_title  AS title,
                mi.abstract,
                s.tracking_code,
                s.submitted_at,
                j.name            AS journal_name
            FROM review_assignments ra
            INNER JOIN submissions s      ON ra.submission_id = s.submission_id
            LEFT  JOIN manuscript_info mi ON s.submission_id  = mi.submission_id
            LEFT  JOIN journals j         ON s.journal_id     = j.journal_id
            WHERE ra.reviewer_id = ?
            ORDER BY ra.request_sent_date DESC
        ");
        $q->execute([$reviewer_id]);
        $assignments = $q->fetchAll();

        foreach ($assignments as $a) {
            $stats['total']++;
            switch ($a['assignment_status']) {
                case 'request_sent':     $stats['pending']++;   break;
                case 'accepted':         $stats['accepted']++;  break;
                case 'review_submitted': $stats['submitted']++; break;
                case 'declined':
                case 'cancelled':        $stats['declined']++;  break;
            }
        }
    } catch (PDOException $e) {
        $error = 'Could not load assignments.';
        error_log('dashboard error: ' . $e->getMessage());
    }
}

// Assigned submissions for ticket dropdown
$assigned_subs = array();
try {
    $q = db()->prepare("
        SELECT s.submission_id, s.tracking_code, mi.article_title
        FROM review_assignments ra
        INNER JOIN submissions s      ON ra.submission_id = s.submission_id
        LEFT  JOIN manuscript_info mi ON s.submission_id  = mi.submission_id
        WHERE ra.reviewer_id = ?
          AND ra.assignment_status NOT IN ('declined','cancelled')
        ORDER BY ra.request_sent_date DESC
    ");
    $q->execute([$reviewer_id]);
    $assigned_subs = $q->fetchAll();
} catch (PDOException $e) {}

// Tickets list
$tickets = array();
if ($active === 'tickets') {
    try {
        $q = db()->prepare("
            SELECT t.*,
                   s.tracking_code  AS sub_code,
                   mi.article_title AS sub_title
            FROM reviewer_tickets t
            LEFT JOIN submissions s      ON t.submission_id  = s.submission_id
            LEFT JOIN manuscript_info mi ON s.submission_id  = mi.submission_id
            WHERE t.reviewer_id = ?
            ORDER BY t.created_at DESC
        ");
        $q->execute([$reviewer_id]);
        $tickets = $q->fetchAll();
    } catch (PDOException $e) {
        $error = 'Could not load tickets.';
    }
}

// Single ticket + replies
$ticket         = null;
$ticket_replies = array();
if ($active === 'view_ticket') {
    $tid = filter_var(isset($_GET['id']) ? $_GET['id'] : 0, FILTER_VALIDATE_INT);
    if ($tid) {
        try {
            $q = db()->prepare("
                SELECT t.*,
                       s.tracking_code  AS sub_code,
                       mi.article_title AS sub_title
                FROM reviewer_tickets t
                LEFT JOIN submissions s      ON t.submission_id  = s.submission_id
                LEFT JOIN manuscript_info mi ON s.submission_id  = mi.submission_id
                WHERE t.id = ? AND t.reviewer_id = ?
            ");
            $q->execute([$tid, $reviewer_id]);
            $ticket = $q->fetch();

            if ($ticket) {
                $r = db()->prepare("
                    SELECT
                        tr.id,
                        tr.ticket_id,
                        tr.user_id,
                        tr.message,
                        tr.is_admin,
                        tr.created_at,
                        CASE
                            WHEN tr.is_admin = 1
                                THEN TRIM(CONCAT(COALESCE(au.first_name,''), ' ', COALESCE(au.last_name,'')))
                            ELSE TRIM(CONCAT(COALESCE(u.first_name,''), ' ', COALESCE(u.last_name,'')))
                        END AS sender_name,
                        CASE
                            WHEN tr.is_admin = 1 THEN 'admin'
                            ELSE COALESCE(u.role, 'reviewer')
                        END AS sender_role
                    FROM reviewer_ticket_replies tr
                    LEFT JOIN users u
                           ON tr.is_admin = 0
                          AND tr.user_id = u.user_id
                    LEFT JOIN admin_users au
                           ON tr.is_admin = 1
                          AND tr.user_id = au.id
                    WHERE tr.ticket_id = ?
                    ORDER BY tr.created_at ASC
                ");
                $r->execute([$tid]);
                $ticket_replies = $r->fetchAll();
            }
        } catch (PDOException $e) {
            $error = 'Could not load ticket: ' . $e->getMessage();
        }
    }
}

// Certificates
$completed_reviews = array();
if ($active === 'certificate') {
    try {
        $q = db()->prepare("
            SELECT
                ra.id            AS assignment_id,
                ra.submitted_date,
                mi.article_title AS title,
                s.tracking_code,
                j.name           AS journal_name
            FROM review_assignments ra
            INNER JOIN submissions s      ON ra.submission_id = s.submission_id
            LEFT  JOIN manuscript_info mi ON s.submission_id  = mi.submission_id
            LEFT  JOIN journals j         ON s.journal_id     = j.journal_id
            WHERE ra.reviewer_id = ?
              AND ra.assignment_status = 'review_submitted'
            ORDER BY ra.submitted_date DESC
        ");
        $q->execute([$reviewer_id]);
        $completed_reviews = $q->fetchAll();
    } catch (PDOException $e) {}
}

// ════════════════════════════════════════════════════════════
// HELPERS
// ════════════════════════════════════════════════════════════
function statusBadge($status) {
    $map = array(
        'request_sent'     => array('p-pending',  'Pending Response'),
        'accepted'         => array('p-accepted', 'Accepted'),
        'review_submitted' => array('p-submitted','Submitted'),
        'declined'         => array('p-declined', 'Declined'),
        'cancelled'        => array('p-declined', 'Cancelled'),
    );
    return isset($map[$status]) ? $map[$status] : array('p-closed', ucfirst($status));
}
function ticketStatusClass($status) {
    $map = array('open'=>'p-open','in_progress'=>'p-inprog','resolved'=>'p-resolved','closed'=>'p-closed');
    return isset($map[$status]) ? $map[$status] : 'p-closed';
}
function priorityClass($p) {
    $map = array('urgent'=>'p-urgent','high'=>'p-high','medium'=>'p-medium','low'=>'p-low');
    return isset($map[$p]) ? $map[$p] : 'p-low';
}
function isOverdue($date) {
    return $date && strtotime($date) < time();
}

$raw_interests       = isset($reviewer['reviewing_interests']) ? $reviewer['reviewing_interests'] : '';
$reviewing_interests = json_decode($raw_interests, true);
$interests_str       = is_array($reviewing_interests) ? implode(', ', $reviewing_interests) : $raw_interests;

$sectionTitles = array(
    'dashboard'         => 'My Reviews',
    'profile'           => 'My Profile',
    'change_password'   => 'Change Password',
    'tickets'           => 'My Tickets',
    'raise_ticket'      => 'Raise a Ticket',
    'view_ticket'       => 'Ticket Details',
    'certificate'       => 'Certificates',
    'reviewer_profiles' => 'Reviewer Profiles',
);
$page_title = isset($sectionTitles[$active]) ? $sectionTitles[$active] : 'Dashboard';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo htmlspecialchars($page_title); ?> — Communeglobal Reviewer</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Sora:wght@600;700&display=swap" rel="stylesheet">
<style>
body { font-family: 'Inter', sans-serif; background: #f8fafc; color: #1e293b; }
.font-display { font-family: 'Sora', sans-serif; }

/* ── Sidebar transitions ── */
#sidebar { transition: transform 0.25s ease, width 0.25s ease; }

/* Desktop collapsed state */
#sidebar.collapsed { width: 72px; }
#sidebar.collapsed .nav-label,
#sidebar.collapsed .sidebar-brand-text,
#sidebar.collapsed .sidebar-user-text { display: none; }
#sidebar.collapsed .nav-link { justify-content: center; padding-left: 0; padding-right: 0; }
#sidebar.collapsed .nav-icon { margin-right: 0; }

/* Main content offset */
#main-content { transition: margin-left 0.25s ease; }

/* Pills */
.pill { display: inline-flex; align-items: center; gap: 4px; padding: 3px 9px; border-radius: 20px;
        font-size: 11px; font-weight: 600; border: 1px solid; white-space: nowrap; }
.p-pending   { background:#fffbeb; color:#92400e; border-color:#fcd34d; }
.p-accepted  { background:#eff6ff; color:#1e40af; border-color:#bfdbfe; }
.p-submitted { background:#f0fdf4; color:#166534; border-color:#bbf7d0; }
.p-declined  { background:#fef2f2; color:#991b1b; border-color:#fecaca; }
.p-open      { background:#eff6ff; color:#1e40af; border-color:#bfdbfe; }
.p-inprog    { background:#fffbeb; color:#92400e; border-color:#fcd34d; }
.p-resolved  { background:#f0fdf4; color:#166534; border-color:#bbf7d0; }
.p-closed    { background:#f1f5f9; color:#475569; border-color:#e2e8f0; }
.p-low       { background:#f1f5f9; color:#475569; border-color:#e2e8f0; }
.p-medium    { background:#fffbeb; color:#92400e; border-color:#fcd34d; }
.p-high      { background:#fff7ed; color:#9a3412; border-color:#fed7aa; }
.p-urgent    { background:#fef2f2; color:#991b1b; border-color:#fecaca; }

.stat-card { transition: transform .15s, box-shadow .15s; cursor: pointer; user-select: none; }
.stat-card:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0,0,0,.08); }
.stat-card.active-filter { box-shadow: 0 0 0 2px #3b82f6, 0 4px 16px rgba(59,130,246,.15); }
.clamp-3 { display:-webkit-box; -webkit-line-clamp:3; -webkit-box-orient:vertical; overflow:hidden; }
.pw-bar  { height:3px; background:#e2e8f0; border-radius:2px; margin-top:4px; }
.pw-fill { height:100%; border-radius:2px; transition:width .3s,background .3s; }
.bubble-you   { background:#EFF6FF; border-left:3px solid #3B82F6; border-radius:0 10px 10px 10px; }
.bubble-admin { background:#F0FDF4; border-left:3px solid #10B981; border-radius:10px 0 10px 10px; }

/* ── Mobile sidebar behaviour ── */
@media (max-width: 768px) {
  /* Off-canvas by default */
  #sidebar {
    position: fixed;
    z-index: 50;
    transform: translateX(-100%);
    width: 256px !important; /* always full-width on mobile regardless of collapsed state */
  }
  /* Slide in when open */
  #sidebar.mobile-open { transform: translateX(0); }

  /* Main content always full-width on mobile */
  #main-content { margin-left: 0 !important; }

  /* Overlay hidden until sidebar opens */
  #mobile-overlay { display: none; }
  #mobile-overlay.active { display: block; }

  /* Always show all sidebar labels on mobile (even if JS collapsed it on desktop) */
  #sidebar .nav-label,
  #sidebar .sidebar-brand-text,
  #sidebar .sidebar-user-text { display: block !important; }
  #sidebar .nav-link { justify-content: flex-start !important; padding-left: 12px !important; padding-right: 12px !important; }
  #sidebar .nav-icon { margin-right: 0; }
}
</style>
</head>
<body class="bg-gray-50 min-h-screen">

<!-- Dim overlay — mobile only, shown when sidebar is open -->
<div id="mobile-overlay" class="fixed inset-0 bg-black opacity-40 z-40 md:hidden" onclick="closeSidebar()"></div>

<!-- ══ SIDEBAR ══════════════════════════════════════════════ -->
<aside id="sidebar" class="fixed top-0 left-0 h-full w-64 bg-white border-r border-gray-200 flex flex-col z-50 shadow-sm overflow-hidden">
  <div class="flex items-center gap-3 px-5 py-4 border-b border-gray-100">
    <div class="w-9 h-9 bg-blue-600 rounded-xl flex items-center justify-center flex-shrink-0">
      <span class="text-white font-display font-bold text-sm">C</span>
    </div>
    <div class="sidebar-brand-text min-w-0">
      <div class="font-display text-gray-800 text-sm font-bold truncate">Communeglobal</div>
      <div class="text-gray-400 text-xs">Reviewer Portal</div>
    </div>
  </div>

  <div class="sidebar-user px-4 py-4 border-b border-gray-100">
    <div class="flex items-center gap-3 bg-gray-50 rounded-xl px-3 py-2.5 mb-3">
      <div class="w-9 h-9 rounded-full bg-blue-600 flex items-center justify-center text-white font-bold text-sm flex-shrink-0">
        <?php echo htmlspecialchars($user_initial); ?>
      </div>
      <div class="sidebar-user-text min-w-0 flex-1">
        <div class="text-gray-800 text-sm font-semibold truncate"><?php echo htmlspecialchars($display_name); ?></div>
        <span class="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-700 mt-0.5">Reviewer</span>
      </div>
    </div>
    <div class="sidebar-user-text grid grid-cols-3 gap-1.5">
      <div class="bg-white border border-gray-200 rounded-lg py-2 px-1 text-center">
        <div class="text-gray-800 text-sm font-bold leading-none"><?php echo (int)($reviewer['total_reviews_completed'] ?? 0); ?></div>
        <div class="text-gray-400 text-xs mt-0.5">Done</div>
      </div>
      <div class="bg-white border border-gray-200 rounded-lg py-2 px-1 text-center">
        <div class="text-gray-800 text-sm font-bold leading-none"><?php echo number_format($reviewer['reviewer_rating'] ?? 0, 1); ?></div>
        <div class="text-gray-400 text-xs mt-0.5">Rating</div>
      </div>
      <div class="bg-white border border-gray-200 rounded-lg py-2 px-1 text-center">
        <?php $avail = isset($reviewer['is_available']) ? $reviewer['is_available'] : 0; ?>
        <div class="text-sm font-bold leading-none <?php echo $avail ? 'text-emerald-600' : 'text-red-500'; ?>">
          <?php echo $avail ? 'Yes' : 'No'; ?>
        </div>
        <div class="text-gray-400 text-xs mt-0.5">Avail</div>
      </div>
    </div>
  </div>

  <nav class="flex-1 px-3 py-4 overflow-y-auto space-y-0.5">
    <?php
    $navItems = array(
      array('section'=>'dashboard',         'icon'=>'fa-clipboard-list', 'label'=>'My Reviews'),
      array('section'=>'profile',           'icon'=>'fa-user-circle',    'label'=>'My Profile'),
      array('section'=>'change_password',   'icon'=>'fa-key',            'label'=>'Change Password'),
      array('section'=>'raise_ticket',      'icon'=>'fa-headset',        'label'=>'Raise a Ticket'),
      array('section'=>'tickets',           'icon'=>'fa-ticket-alt',     'label'=>'My Tickets'),
      array('section'=>'certificate',       'icon'=>'fa-certificate',    'label'=>'Certificates'),
      array('section'=>'reviewer_profiles', 'icon'=>'fa-id-badge',       'label'=>'Reviewer Profiles'),
    );
    foreach ($navItems as $nav):
      $isActive  = ($active === $nav['section']);
      $linkClass = $isActive
        ? 'bg-blue-50 text-blue-700 font-semibold border-l-4 border-blue-600'
        : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900 border-l-4 border-transparent';
    ?>
    <a href="?section=<?php echo $nav['section']; ?>"
       class="nav-link flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm transition-all <?php echo $linkClass; ?>"
       onclick="closeSidebar()">
      <i class="nav-icon fas <?php echo $nav['icon']; ?> w-4 text-center flex-shrink-0
         <?php echo $isActive ? 'text-blue-600' : 'text-gray-400'; ?>"></i>
      <span class="nav-label"><?php echo $nav['label']; ?></span>
    </a>
    <?php endforeach; ?>
  </nav>

  <div class="px-3 py-4 border-t border-gray-100">
    <a href="logout.php" class="nav-link flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm text-gray-500 hover:bg-red-50 hover:text-red-600 transition-all border-l-4 border-transparent">
      <i class="nav-icon fas fa-sign-out-alt w-4 text-center flex-shrink-0"></i>
      <span class="nav-label">Sign Out</span>
    </a>
  </div>
</aside>

<!-- ══ MAIN ══════════════════════════════════════════════════ -->
<div id="main-content" class="ml-64 min-h-screen flex flex-col">

  <!-- Single topbar with ONE hamburger button -->
  <header class="bg-white border-b border-gray-200 px-4 md:px-6 py-3.5 flex items-center justify-between sticky top-0 z-20 shadow-sm">
    <div class="flex items-center gap-3">
      <!--
        ONE hamburger for all screen sizes:
        - On mobile  (≤768px): opens/closes the off-canvas sidebar
        - On desktop (>768px): collapses/expands the sidebar width
      -->
      <button id="hamburger-btn"
              onclick="handleHamburger()"
              class="flex items-center justify-center w-8 h-8 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100 transition-colors"
              title="Toggle menu">
        <i class="fas fa-bars text-sm"></i>
      </button>
      <div>
        <h1 class="font-display text-base font-bold text-gray-800"><?php echo htmlspecialchars($page_title); ?></h1>
        <p class="text-xs text-gray-400 hidden sm:block"><?php echo date('l, d F Y'); ?></p>
      </div>
    </div>
    <div class="flex items-center gap-2 md:gap-3">
      <?php if ($showAuthorLink): ?>
      <a href="/author/auth_bridge.php" class="hidden sm:flex items-center gap-2 text-xs bg-blue-600 hover:bg-blue-700 text-white px-3.5 py-2 rounded-lg font-medium whitespace-nowrap">
       Switch to Author →
      </a>
      <?php endif; ?>
      <div class="flex items-center gap-2 border-l border-gray-200 pl-2 md:pl-3">
        <div class="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center text-white font-bold text-xs flex-shrink-0">
          <?php echo htmlspecialchars($user_initial); ?>
        </div>
        <div class="hidden md:block">
          <div class="text-xs font-semibold text-gray-700"><?php echo htmlspecialchars($display_name); ?></div>
          <div class="text-xs text-gray-400">Reviewer</div>
        </div>
      </div>
      <a href="logout.php" class="flex items-center gap-1.5 text-xs text-gray-500 hover:text-red-600 border border-gray-200 hover:border-red-200 px-2.5 md:px-3 py-2 rounded-lg transition-all whitespace-nowrap">
        <i class="fas fa-sign-out-alt"></i>
        <span class="hidden sm:inline">Logout</span>
      </a>
    </div>
  </header>

  <main class="flex-1 p-4 md:p-6">

    <?php if ($error): ?>
    <div class="mb-5 flex items-start gap-3 bg-red-50 border border-red-200 text-red-700 rounded-xl px-4 py-3 text-sm">
      <i class="fas fa-exclamation-circle flex-shrink-0 mt-0.5"></i>
      <span><?php echo htmlspecialchars($error); ?></span>
    </div>
    <?php endif; ?>

    <?php if ($success): ?>
    <div class="mb-5 flex items-start gap-3 bg-emerald-50 border border-emerald-200 text-emerald-700 rounded-xl px-4 py-3 text-sm">
      <i class="fas fa-check-circle flex-shrink-0 mt-0.5"></i>
      <span><?php echo htmlspecialchars($success); ?></span>
    </div>
    <?php endif; ?>

    <?php if (isset($_GET['created'])): ?>
    <div class="mb-5 flex items-start gap-3 bg-emerald-50 border border-emerald-200 text-emerald-700 rounded-xl px-4 py-3 text-sm">
      <i class="fas fa-check-circle flex-shrink-0 mt-0.5"></i>
      <span>Ticket <strong><?php echo htmlspecialchars($_GET['created']); ?></strong> raised successfully!</span>
    </div>
    <?php endif; ?>

    <?php if (isset($_GET['reply']) && $_GET['reply'] == 1): ?>
    <div class="mb-5 flex items-start gap-3 bg-emerald-50 border border-emerald-200 text-emerald-700 rounded-xl px-4 py-3 text-sm">
      <i class="fas fa-check-circle flex-shrink-0 mt-0.5"></i>
      <span>Reply sent successfully.</span>
    </div>
    <?php endif; ?>

    <?php if (isset($_GET['declined'])): ?>
    <div class="mb-5 flex items-start gap-3 bg-blue-50 border border-blue-200 text-blue-700 rounded-xl px-4 py-3 text-sm">
      <i class="fas fa-info-circle flex-shrink-0 mt-0.5"></i>
      <span>Review invitation declined.</span>
    </div>
    <?php endif; ?>

    <?php
    // ══════════════════════════════════════════════════════════
    // SECTION: DASHBOARD
    // ══════════════════════════════════════════════════════════
    if ($active === 'dashboard'):
    ?>

    <!-- ── STAT CARDS ─────────────────────────────────────── -->
    <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 md:gap-4 mb-6">
      <?php
      $statCards = array(
        array('label'=>'Total',     'value'=>$stats['total'],     'bg'=>'bg-gray-700',    'icon'=>'fa-layer-group',  'filter'=>'all'),
        array('label'=>'Pending',   'value'=>$stats['pending'],   'bg'=>'bg-amber-500',   'icon'=>'fa-clock',        'filter'=>'request_sent'),
        array('label'=>'Accepted',  'value'=>$stats['accepted'],  'bg'=>'bg-blue-600',    'icon'=>'fa-check',        'filter'=>'accepted'),
        array('label'=>'Submitted', 'value'=>$stats['submitted'], 'bg'=>'bg-emerald-500', 'icon'=>'fa-check-circle', 'filter'=>'review_submitted'),
        array('label'=>'Declined',  'value'=>$stats['declined'],  'bg'=>'bg-red-500',     'icon'=>'fa-times-circle', 'filter'=>'declined'),
      );
      foreach ($statCards as $card): ?>
      <div class="stat-card bg-white rounded-xl border border-slate-200 p-4 flex flex-col gap-2"
           data-filter="<?php echo $card['filter']; ?>"
           onclick="filterAssignments('<?php echo $card['filter']; ?>', this)"
           title="Click to filter by <?php echo $card['label']; ?>">
        <div class="w-8 h-8 <?php echo $card['bg']; ?> rounded-lg flex items-center justify-center">
          <i class="fas <?php echo $card['icon']; ?> text-white text-xs"></i>
        </div>
        <div class="text-2xl font-display font-bold text-slate-800"><?php echo $card['value']; ?></div>
        <div class="text-xs text-slate-500 font-medium"><?php echo $card['label']; ?></div>
      </div>
      <?php endforeach; ?>
    </div>

    <!-- ── ASSIGNED ARTICLES header ───────────────────────── -->
    <div class="flex items-center gap-2 mb-4 flex-wrap">
      <i class="fas fa-file-alt text-blue-500"></i>
      <h2 class="font-display font-bold text-slate-800 text-base">Assigned Articles</h2>
      <span class="bg-slate-200 text-slate-600 text-xs font-semibold px-2 py-0 rounded-full assignment-count"><?php echo count($assignments); ?></span>
      <span id="active-filter-label" class="hidden text-xs text-blue-600 bg-blue-50 border border-blue-200 px-2 py-0.5 rounded-full font-medium">Filtered</span>
      <button id="clear-filter-btn"
              onclick="filterAssignments('all', document.querySelector('[data-filter=all]'))"
              class="hidden text-xs text-slate-500 hover:text-blue-600 underline ml-1">
        Clear filter
      </button>
    </div>

    <?php if (empty($assignments)): ?>
    <div class="bg-white rounded-xl border border-slate-200 p-16 text-center">
      <i class="fas fa-inbox text-5xl text-slate-300 mb-4"></i>
      <h3 class="font-semibold text-slate-600 mb-1">No assignments yet</h3>
      <p class="text-slate-400 text-sm">Review invitations will appear here when assigned by the editor.</p>
    </div>
    <?php else: ?>
    <div class="space-y-4" id="assignments-list">
      <div id="filter-empty" style="display:none"
           class="bg-white rounded-xl border border-slate-200 p-10 text-center">
        <i class="fas fa-filter text-4xl text-slate-300 mb-3 block"></i>
        <p class="text-slate-500 text-sm font-medium">No assignments match this filter.</p>
        <button onclick="filterAssignments('all', document.querySelector('[data-filter=all]'))"
                class="mt-3 text-blue-600 hover:underline text-xs font-semibold">
          Show all assignments
        </button>
      </div>

      <?php foreach ($assignments as $item):
        $badge      = statusBadge($item['assignment_status']);
        $badgeClass = $badge[0];
        $badgeLabel = $badge[1];
        $isPending   = ($item['assignment_status'] === 'request_sent');
        $isSubmitted = ($item['assignment_status'] === 'review_submitted');
        $isAccepted  = ($item['assignment_status'] === 'accepted');
        $isDeclined  = ($item['assignment_status'] === 'declined' || $item['assignment_status'] === 'cancelled');
        $responseOD  = !$isSubmitted && isOverdue(isset($item['response_due_date']) ? $item['response_due_date'] : null);
        $reviewOD    = !$isSubmitted && isOverdue(isset($item['review_due_date'])   ? $item['review_due_date']   : null);
        $anyOverdue  = $responseOD || $reviewOD;
        $title = isset($item['title']) && $item['title'] ? $item['title'] : ('Submission #' . $item['submission_id']);
      ?>
      <div class="assignment-card bg-white rounded-xl border <?php echo $anyOverdue ? 'border-red-300' : 'border-slate-200'; ?> overflow-hidden"
           data-status="<?php echo htmlspecialchars($item['assignment_status']); ?>">
        <?php if ($anyOverdue): ?>
        <div class="bg-red-50 border-b border-red-200 px-4 py-2 flex items-center gap-2 text-red-700 text-xs font-semibold flex-wrap">
          <i class="fas fa-exclamation-triangle"></i> Overdue —
          <?php if ($responseOD): ?>Response was due <?php echo date('M d, Y', strtotime($item['response_due_date'])); ?><?php endif; ?>
          <?php if ($responseOD && $reviewOD): ?> · <?php endif; ?>
          <?php if ($reviewOD): ?>Review overdue since <?php echo date('M d, Y', strtotime($item['review_due_date'])); ?><?php endif; ?>
        </div>
        <?php endif; ?>
        <div class="p-4 md:p-5">
          <div class="flex items-start justify-between gap-3 mb-3">
            <h3 class="font-semibold text-slate-800 text-sm leading-snug flex-1"><?php echo htmlspecialchars($title); ?></h3>
            <span class="pill <?php echo $badgeClass; ?> flex-shrink-0"><?php echo $badgeLabel; ?></span>
          </div>
          <div class="flex flex-wrap gap-2 md:gap-3 text-xs text-slate-500 mb-4">
            <?php if (!empty($item['tracking_code'])): ?>
            <span class="font-mono bg-slate-100 px-2 py-0.5 rounded text-slate-600"><?php echo htmlspecialchars($item['tracking_code']); ?></span>
            <?php endif; ?>
            <?php if (!empty($item['journal_name'])): ?>
            <span><i class="fas fa-book-open text-slate-400 mr-1"></i><?php echo htmlspecialchars($item['journal_name']); ?></span>
            <?php endif; ?>
            <span><i class="fas fa-calendar text-slate-400 mr-1"></i>Assigned <?php echo date('M d, Y', strtotime($item['request_sent_date'])); ?></span>
          </div>
          <div class="grid grid-cols-2 gap-3 mb-4">
            <div class="bg-slate-50 rounded-lg p-3 text-xs">
              <div class="text-slate-500 mb-1">Response due</div>
              <div class="font-semibold <?php echo $responseOD ? 'text-red-600' : 'text-slate-700'; ?>">
                <?php echo !empty($item['response_due_date']) ? date('M d, Y', strtotime($item['response_due_date'])) : 'Not set'; ?>
                <?php if ($responseOD): ?><span class="text-red-500"> (Overdue)</span><?php endif; ?>
              </div>
            </div>
            <div class="bg-slate-50 rounded-lg p-3 text-xs">
              <div class="text-slate-500 mb-1">Review due</div>
              <div class="font-semibold <?php echo $reviewOD ? 'text-red-600' : 'text-slate-700'; ?>">
                <?php echo !empty($item['review_due_date']) ? date('M d, Y', strtotime($item['review_due_date'])) : 'Not set'; ?>
                <?php if ($reviewOD): ?><span class="text-red-500"> (Overdue)</span><?php endif; ?>
              </div>
            </div>
          </div>
          <?php if (!empty($item['abstract'])): ?>
          <div class="text-xs text-slate-600 mb-4 leading-relaxed clamp-3"><?php echo htmlspecialchars($item['abstract']); ?></div>
          <?php endif; ?>
          <div class="flex flex-wrap gap-2 pt-3 border-t border-slate-100">
            <?php if ($isPending):
              $due_str = !empty($item['review_due_date']) ? date('M d, Y', strtotime($item['review_due_date'])) : 'the due date'; ?>
              <button onclick="confirmAccept(<?php echo (int)$item['id']; ?>, '<?php echo htmlspecialchars($due_str); ?>')"
                      class="text-xs bg-emerald-600 hover:bg-emerald-700 text-white px-4 py-2 rounded-lg font-medium min-h-[36px]">
                <i class="fas fa-check mr-1"></i> Accept Review
              </button>
              <button onclick="confirmDecline(<?php echo (int)$item['id']; ?>)"
                      class="text-xs bg-red-50 hover:bg-red-100 text-red-700 border border-red-200 px-4 py-2 rounded-lg font-medium min-h-[36px]">
                <i class="fas fa-times mr-1"></i> Decline
              </button>
            <?php elseif ($isAccepted): ?>
              <a href="view_article.php?assignment_id=<?php echo (int)$item['id']; ?>"
                 class="text-xs bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg font-medium min-h-[36px] flex items-center">
                <i class="fas fa-edit mr-1"></i> Review Article
              </a>
            <?php elseif ($isSubmitted): ?>
              <a href="view_article.php?assignment_id=<?php echo (int)$item['id']; ?>"
                 class="text-xs bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 py-2 rounded-lg font-medium min-h-[36px] flex items-center">
                <i class="fas fa-eye mr-1"></i> View Article
              </a>
              <span class="pill p-submitted"><i class="fas fa-check-circle"></i> Review Submitted</span>
            <?php elseif ($isDeclined): ?>
              <span class="pill p-declined"><i class="fas fa-times-circle"></i> Declined</span>
            <?php endif; ?>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <?php
    // ══════════════════════════════════════════════════════════
    // SECTION: PROFILE
    // ══════════════════════════════════════════════════════════
    elseif ($active === 'profile'):
    ?>
    <div class="max-w-2xl">
      <div class="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div class="bg-gray-50 border-b border-gray-200 px-6 py-5 flex items-center gap-4">
          <div class="w-14 h-14 rounded-xl bg-blue-600 flex items-center justify-center text-white font-bold text-xl flex-shrink-0">
            <?php echo htmlspecialchars($user_initial); ?>
          </div>
          <div>
            <div class="text-gray-800 font-display font-bold"><?php echo htmlspecialchars($display_name); ?></div>
            <div class="text-gray-400 text-sm"><?php echo htmlspecialchars($user['email'] ?? ''); ?></div>
          </div>
        </div>
        <form method="POST" class="p-6 space-y-5">
          <input type="hidden" name="update_profile" value="1">
          <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label class="block text-xs font-semibold text-slate-600 mb-1">First Name <span class="text-red-500">*</span></label>
              <input type="text" name="first_name" required value="<?php echo htmlspecialchars($user['first_name'] ?? ''); ?>"
                     class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100">
            </div>
            <div>
              <label class="block text-xs font-semibold text-slate-600 mb-1">Last Name <span class="text-red-500">*</span></label>
              <input type="text" name="last_name" required value="<?php echo htmlspecialchars($user['last_name'] ?? ''); ?>"
                     class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100">
            </div>
          </div>
          <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label class="block text-xs font-semibold text-slate-600 mb-1">Title</label>
              <select name="title" class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400">
                <option value="">— Select —</option>
                <?php foreach (array('Mr','Mrs','Ms','Dr','Prof') as $t): ?>
                <option value="<?php echo $t; ?>" <?php echo (($user['title'] ?? '') === $t) ? 'selected' : ''; ?>><?php echo $t; ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div>
              <label class="block text-xs font-semibold text-slate-600 mb-1">Email (read-only)</label>
              <input type="email" value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>" disabled
                     class="w-full px-3 py-2 border border-slate-100 bg-slate-50 rounded-lg text-sm text-slate-400 cursor-not-allowed">
            </div>
          </div>
          <div class="grid grid-cols-3 gap-3">
            <div>
              <label class="block text-xs font-semibold text-slate-600 mb-1">Country Code</label>
              <input type="text" name="phone_country_code" placeholder="+91"
                     value="<?php echo htmlspecialchars($user['phone_country_code'] ?? ''); ?>"
                     class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400">
            </div>
            <div class="col-span-2">
              <label class="block text-xs font-semibold text-slate-600 mb-1">Phone Number</label>
              <input type="text" name="phone_number" value="<?php echo htmlspecialchars($user['phone_number'] ?? ''); ?>"
                     class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400">
            </div>
          </div>
          <div>
            <label class="block text-xs font-semibold text-slate-600 mb-1">Institutional Email</label>
            <input type="email" name="institutional_email" value="<?php echo htmlspecialchars($user['institutional_email'] ?? ''); ?>"
                   placeholder="your@institution.edu"
                   class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400">
          </div>
          <div>
            <label class="block text-xs font-semibold text-slate-600 mb-1">Reviewing Interests</label>
            <textarea name="reviewing_interests" rows="3" placeholder="e.g. Machine Learning, Climate Science"
                      class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400 resize-none"><?php echo htmlspecialchars($interests_str); ?></textarea>
            <p class="text-xs text-slate-400 mt-1">Comma-separated topics</p>
          </div>
          <div class="bg-slate-50 rounded-lg p-4 grid grid-cols-3 gap-4 text-center text-xs">
            <div>
              <div class="font-bold text-slate-800 text-lg"><?php echo (int)($reviewer['total_reviews_completed'] ?? 0); ?></div>
              <div class="text-slate-500">Completed</div>
            </div>
            <div>
              <div class="font-bold text-slate-800 text-lg"><?php echo number_format($reviewer['reviewer_rating'] ?? 0, 1); ?></div>
              <div class="text-slate-500">Rating</div>
            </div>
            <div>
              <div class="font-bold text-slate-800 text-lg"><?php echo number_format($reviewer['avg_days_to_complete'] ?? 0, 0); ?>d</div>
              <div class="text-slate-500">Avg time</div>
            </div>
          </div>
          <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-lg font-semibold text-sm">
            <i class="fas fa-save mr-2"></i> Save Profile
          </button>
        </form>
      </div>
    </div>

    <?php
    // ══════════════════════════════════════════════════════════
    // SECTION: CHANGE PASSWORD
    // ══════════════════════════════════════════════════════════
    elseif ($active === 'change_password'):
    ?>
    <div class="max-w-lg">
      <div class="bg-white rounded-xl border border-slate-200 p-6">
        <div class="flex items-center gap-3 mb-6">
          <div class="w-10 h-10 bg-amber-100 rounded-xl flex items-center justify-center">
            <i class="fas fa-key text-amber-600"></i>
          </div>
          <div>
            <h2 class="font-display font-bold text-slate-800">Change Password</h2>
            <p class="text-xs text-slate-500">Minimum 8 characters required</p>
          </div>
        </div>
        <form method="POST" class="space-y-4">
          <input type="hidden" name="change_password" value="1">
          <div>
            <label class="block text-xs font-semibold text-slate-600 mb-1">Current Password <span class="text-red-500">*</span></label>
            <input type="password" name="current_password" required placeholder="Enter current password"
                   class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400">
          </div>
          <div>
            <label class="block text-xs font-semibold text-slate-600 mb-1">New Password <span class="text-red-500">*</span></label>
            <input type="password" name="new_password" id="new_pw" required minlength="8"
                   placeholder="At least 8 characters" oninput="pwStrength(this.value)"
                   class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400">
            <div class="pw-bar mt-2"><div class="pw-fill" id="pw-fill" style="width:0%;background:#ef4444"></div></div>
            <p class="text-xs mt-1" id="pw-lbl" style="color:#ef4444"></p>
          </div>
          <div>
            <label class="block text-xs font-semibold text-slate-600 mb-1">Confirm New Password <span class="text-red-500">*</span></label>
            <input type="password" name="confirm_password" required minlength="8" placeholder="Repeat new password"
                   class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400">
          </div>
          <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-lg font-semibold text-sm">
            <i class="fas fa-lock mr-2"></i> Update Password
          </button>
        </form>
      </div>
    </div>

    <?php
    // ══════════════════════════════════════════════════════════
    // SECTION: RAISE TICKET
    // ══════════════════════════════════════════════════════════
    elseif ($active === 'raise_ticket'):
    ?>
    <div class="max-w-2xl">
      <div class="bg-white rounded-xl border border-slate-200 p-6">
        <div class="flex items-center gap-3 mb-6">
          <div class="w-10 h-10 bg-blue-100 rounded-xl flex items-center justify-center">
            <i class="fas fa-headset text-blue-600"></i>
          </div>
          <div>
            <h2 class="font-display font-bold text-slate-800">Raise a Support Ticket</h2>
            <p class="text-xs text-slate-500">The editorial team will respond within 1–2 business days.</p>
          </div>
        </div>
        <form method="POST" class="space-y-5">
          <input type="hidden" name="raise_ticket" value="1">
          <div>
            <label class="block text-xs font-semibold text-slate-600 mb-1">Related Submission <span class="text-slate-400">(optional)</span></label>
            <select name="submission_id" class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400">
              <option value="">— Not related to a specific manuscript —</option>
              <?php foreach ($assigned_subs as $sub):
                $sub_label = isset($sub['article_title']) && $sub['article_title'] ? $sub['article_title'] : 'Untitled';
                if (!empty($sub['tracking_code'])) $sub_label = '[' . $sub['tracking_code'] . '] ' . $sub_label;
                $sub_label = substr($sub_label, 0, 90) . (strlen($sub_label) > 90 ? '…' : '');
                $sel = (isset($_POST['submission_id']) && $_POST['submission_id'] == $sub['submission_id']) ? 'selected' : '';
              ?>
              <option value="<?php echo (int)$sub['submission_id']; ?>" <?php echo $sel; ?>><?php echo htmlspecialchars($sub_label); ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label class="block text-xs font-semibold text-slate-600 mb-1">Subject <span class="text-red-500">*</span></label>
            <input type="text" name="subject" required maxlength="255"
                   value="<?php echo htmlspecialchars(isset($_POST['subject']) ? $_POST['subject'] : ''); ?>"
                   placeholder="Brief description of your query"
                   class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400">
          </div>
          <div>
            <label class="block text-xs font-semibold text-slate-600 mb-1">Message <span class="text-red-500">*</span></label>
            <textarea name="message" required rows="6" placeholder="Describe your issue in detail..."
                      class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400 resize-none"><?php echo htmlspecialchars(isset($_POST['message']) ? $_POST['message'] : ''); ?></textarea>
          </div>
          <div>
            <label class="block text-xs font-semibold text-slate-600 mb-1">Priority</label>
            <select name="priority" class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400">
              <?php
              $priorities = array('low'=>'Low — General inquiry','medium'=>'Medium — Standard query','high'=>'High — Urgent matter','urgent'=>'Urgent — Critical issue');
              $cur_pri    = isset($_POST['priority']) ? $_POST['priority'] : 'medium';
              foreach ($priorities as $val => $label): ?>
              <option value="<?php echo $val; ?>" <?php echo $cur_pri === $val ? 'selected' : ''; ?>><?php echo $label; ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="flex flex-col sm:flex-row gap-3">
            <button type="submit" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-lg font-semibold text-sm">
              <i class="fas fa-paper-plane mr-2"></i> Submit Ticket
            </button>
            <a href="?section=tickets" class="px-5 py-3 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg font-semibold text-sm text-center">
              View Tickets
            </a>
          </div>
        </form>
      </div>
    </div>

    <?php
    // ══════════════════════════════════════════════════════════
    // SECTION: MY TICKETS
    // ══════════════════════════════════════════════════════════
    elseif ($active === 'tickets'):
    ?>
    <div class="flex items-center justify-between mb-5 gap-3 flex-wrap">
      <h2 class="font-display font-bold text-slate-800 flex items-center gap-2">
        <i class="fas fa-ticket-alt text-blue-500"></i> My Tickets
        <span class="bg-slate-200 text-slate-600 text-xs font-semibold px-2 py-0 rounded-full"><?php echo count($tickets); ?></span>
      </h2>
      <a href="?section=raise_ticket" class="text-xs bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg font-medium whitespace-nowrap">
        <i class="fas fa-plus mr-1"></i> New Ticket
      </a>
    </div>

    <?php if (empty($tickets)): ?>
    <div class="bg-white rounded-xl border border-slate-200 p-16 text-center">
      <i class="fas fa-inbox text-5xl text-slate-300 mb-4"></i>
      <h3 class="font-semibold text-slate-600 mb-1">No tickets yet</h3>
      <p class="text-slate-400 text-sm mb-4">Need help? Raise a ticket and our team will assist you.</p>
      <a href="?section=raise_ticket" class="inline-flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white text-sm px-5 py-2 rounded-lg font-medium">
        <i class="fas fa-plus"></i> Raise First Ticket
      </a>
    </div>
    <?php else: ?>
    <div class="space-y-3">
      <?php foreach ($tickets as $t): ?>
      <div class="bg-white rounded-xl border border-slate-200 p-4 md:p-5 hover:shadow-md transition-shadow">
        <div class="flex flex-col sm:flex-row sm:items-start justify-between gap-3 mb-3">
          <div class="flex-1 min-w-0">
            <h3 class="font-semibold text-slate-800 text-sm truncate"><?php echo htmlspecialchars($t['subject']); ?></h3>
            <div class="flex flex-wrap items-center gap-2 mt-1">
              <span class="font-mono text-xs bg-slate-100 px-2 py-0 rounded text-slate-600">#<?php echo htmlspecialchars($t['ticket_number']); ?></span>
              <?php if (!empty($t['sub_code'])): ?>
              <span class="text-xs text-slate-500"><i class="fas fa-file-alt mr-1 text-slate-400"></i><?php echo htmlspecialchars($t['sub_code']); ?></span>
              <?php endif; ?>
            </div>
          </div>
          <div class="flex items-center gap-2 flex-shrink-0 flex-wrap">
            <span class="pill <?php echo priorityClass($t['priority']); ?>"><?php echo ucfirst($t['priority']); ?></span>
            <span class="pill <?php echo ticketStatusClass($t['status']); ?>"><?php echo ucfirst(str_replace('_',' ',$t['status'])); ?></span>
          </div>
        </div>
        <p class="text-xs text-slate-500 mb-3">
          <?php echo htmlspecialchars(substr($t['message'],0,180)); ?><?php echo strlen($t['message'])>180?'…':''; ?>
        </p>
        <div class="flex items-center justify-between text-xs text-slate-400 pt-3 border-t border-slate-100 flex-wrap gap-2">
          <span><i class="fas fa-clock mr-1"></i><?php echo date('M d, Y g:i A', strtotime($t['created_at'])); ?></span>
          <a href="?section=view_ticket&id=<?php echo (int)$t['id']; ?>" class="flex items-center gap-1 text-blue-600 hover:text-blue-700 font-semibold">
            View <i class="fas fa-arrow-right text-xs"></i>
          </a>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <?php
    // ══════════════════════════════════════════════════════════
    // SECTION: VIEW TICKET
    // ══════════════════════════════════════════════════════════
    elseif ($active === 'view_ticket'):
    ?>
    <?php if (!$ticket): ?>
    <div class="bg-red-50 border border-red-200 text-red-700 rounded-xl p-4 text-sm">
      Ticket not found or you don't have permission to view it.
      <a href="?section=tickets" class="underline ml-2">Back to tickets</a>
    </div>
    <?php else: ?>
    <div class="max-w-3xl">
      <div class="flex items-center gap-3 mb-5 flex-wrap">
        <a href="?section=tickets" class="text-slate-400 hover:text-slate-700"><i class="fas fa-arrow-left"></i></a>
        <div class="flex-1 min-w-0">
          <h2 class="font-display font-bold text-slate-800">Ticket #<?php echo htmlspecialchars($ticket['ticket_number']); ?></h2>
          <p class="text-xs text-slate-500 truncate"><?php echo htmlspecialchars($ticket['subject']); ?></p>
        </div>
        <div class="flex gap-2 flex-wrap">
          <span class="pill <?php echo priorityClass($ticket['priority']); ?>"><?php echo ucfirst($ticket['priority']); ?></span>
          <span class="pill <?php echo ticketStatusClass($ticket['status']); ?>"><?php echo ucfirst(str_replace('_',' ',$ticket['status'])); ?></span>
        </div>
      </div>

      <div class="bg-white rounded-xl border border-slate-200 p-4 mb-4 grid grid-cols-2 sm:grid-cols-3 gap-4 text-xs">
        <div>
          <div class="text-slate-500 mb-0.5">Created</div>
          <div class="font-medium text-slate-700"><?php echo date('M d, Y g:i A',strtotime($ticket['created_at'])); ?></div>
        </div>
        <div>
          <div class="text-slate-500 mb-0.5">Last updated</div>
          <div class="font-medium text-slate-700"><?php echo date('M d, Y g:i A',strtotime($ticket['updated_at'])); ?></div>
        </div>
        <?php if (!empty($ticket['sub_code'])): ?>
        <div>
          <div class="text-slate-500 mb-0.5">Related submission</div>
          <div class="font-mono font-medium text-slate-700"><?php echo htmlspecialchars($ticket['sub_code']); ?></div>
        </div>
        <?php endif; ?>
      </div>

      <div class="bg-white rounded-xl border border-slate-200 mb-4 overflow-hidden">
        <div class="bg-blue-50 border-b border-blue-100 px-4 py-2 flex items-center gap-2 text-xs font-semibold text-blue-700 flex-wrap">
          <i class="fas fa-comment-dots"></i>
          Your Original Message
          <span class="ml-auto text-slate-400 font-normal"><?php echo date('M d, Y g:i A', strtotime($ticket['created_at'])); ?></span>
        </div>
        <div class="p-4 md:p-5 text-sm text-slate-700 leading-relaxed whitespace-pre-wrap"><?php echo htmlspecialchars($ticket['message']); ?></div>
      </div>

      <?php if (!empty($ticket_replies)): ?>
      <div class="space-y-3 mb-4">
        <?php foreach ($ticket_replies as $reply):
          $isAdmin     = (bool)(int)$reply['is_admin'];
          $rawName     = trim($reply['sender_name'] ?? '');
          $senderLabel = $isAdmin ? ($rawName ?: 'Editorial Support') : 'You';
          $initial     = strtoupper(substr($senderLabel, 0, 1));
        ?>
        <div class="<?php echo $isAdmin ? 'bubble-admin' : 'bubble-you'; ?> overflow-hidden rounded-xl">
          <div class="px-4 py-2.5 flex items-center justify-between border-b flex-wrap gap-2
               <?php echo $isAdmin ? 'border-emerald-100' : 'border-blue-100'; ?>">
            <div class="flex items-center gap-2">
              <div class="w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold
                   <?php echo $isAdmin ? 'bg-emerald-600 text-white' : 'bg-blue-600 text-white'; ?>">
                <?php echo $initial; ?>
              </div>
              <span class="font-semibold text-sm <?php echo $isAdmin ? 'text-emerald-800' : 'text-blue-800'; ?>">
                <?php echo htmlspecialchars($senderLabel); ?>
              </span>
              <?php if ($isAdmin): ?>
              <span class="text-xs bg-emerald-600 text-white px-2 py-0.5 rounded-full">Support</span>
              <?php endif; ?>
            </div>
            <span class="text-xs text-slate-400"><?php echo date('M d, Y g:i A', strtotime($reply['created_at'])); ?></span>
          </div>
          <div class="p-4 text-sm text-slate-700 leading-relaxed whitespace-pre-wrap">
            <?php echo htmlspecialchars($reply['message']); ?>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <?php if ($ticket['status'] !== 'closed'): ?>
      <div class="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div class="bg-slate-50 border-b border-slate-200 px-4 py-2 flex items-center gap-2 text-xs font-semibold text-slate-600">
          <i class="fas fa-reply text-slate-400"></i> Add a Reply
        </div>
        <form method="POST" class="p-4 md:p-5" id="replyForm">
          <input type="hidden" name="reply_ticket" value="1">
          <input type="hidden" name="ticket_id" value="<?php echo (int)$ticket['id']; ?>">
          <textarea name="reply_message" required rows="4" id="replyText"
                    placeholder="Type your reply..."
                    class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400 resize-none mb-3"></textarea>
          <div class="flex items-center justify-between flex-wrap gap-2">
            <span class="text-xs text-slate-400" id="charCount">0 chars</span>
            <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg text-sm font-semibold flex items-center gap-2">
              <i class="fas fa-paper-plane text-xs"></i> Send Reply
            </button>
          </div>
        </form>
      </div>
      <?php else: ?>
      <div class="bg-slate-50 border border-slate-200 rounded-xl p-5 text-center text-slate-500 text-sm">
        <i class="fas fa-lock text-2xl mb-2 block text-slate-300"></i>
        This ticket is closed.
        <a href="?section=raise_ticket" class="text-blue-600 hover:underline ml-1">Open a new ticket</a> if needed.
      </div>
      <?php endif; ?>
    </div>
    <?php endif; ?>

    <?php
    // ══════════════════════════════════════════════════════════
    // SECTION: CERTIFICATE
    // ══════════════════════════════════════════════════════════
    elseif ($active === 'certificate'):
    ?>
    <div class="max-w-3xl">
      <div class="bg-white rounded-xl border border-slate-200 overflow-hidden mb-6">
        <div class="bg-gray-50 border-b border-gray-200 px-6 py-5">
          <h2 class="font-display font-bold text-gray-800 flex items-center gap-2">
            <i class="fas fa-certificate text-amber-500"></i> Review Certificates
          </h2>
          <p class="text-gray-400 text-xs mt-1">Available for all submitted reviews.</p>
        </div>
        <?php if (empty($completed_reviews)): ?>
        <div class="p-16 text-center">
          <i class="fas fa-hourglass text-5xl text-slate-300 mb-4"></i>
          <h3 class="font-semibold text-slate-600 mb-1">No certificates yet</h3>
          <p class="text-slate-400 text-sm">Submit at least one review to unlock your certificate.</p>
        </div>
        <?php else: ?>
        <div class="divide-y divide-slate-100">
          <?php foreach ($completed_reviews as $rev): ?>
          <div class="flex items-center gap-4 px-4 md:px-6 py-4 hover:bg-slate-50 transition-colors">
            <div class="w-10 h-10 bg-amber-100 rounded-xl flex items-center justify-center flex-shrink-0">
              <i class="fas fa-file text-amber-600"></i>
            </div>
            <div class="flex-1 min-w-0">
              <div class="text-sm font-medium text-slate-800 truncate"><?php echo htmlspecialchars($rev['title'] ?? 'Untitled'); ?></div>
              <div class="text-xs text-slate-500 flex items-center gap-2 mt-0.5 flex-wrap">
                <span class="font-mono"><?php echo htmlspecialchars($rev['tracking_code'] ?? ''); ?></span>
                <?php if (!empty($rev['journal_name'])): ?><span class="text-slate-300">·</span><span><?php echo htmlspecialchars($rev['journal_name']); ?></span><?php endif; ?>
                <?php if (!empty($rev['submitted_date'])): ?><span class="text-slate-300">·</span><span><?php echo date('F Y',strtotime($rev['submitted_date'])); ?></span><?php endif; ?>
              </div>
            </div>
            <a href="generate_certificate.php?assignment_id=<?php echo (int)$rev['assignment_id']; ?>" target="_blank"
               class="flex items-center gap-2 bg-amber-500 hover:bg-amber-600 text-white text-xs px-3 md:px-4 py-2 rounded-lg font-semibold flex-shrink-0">
              <i class="fas fa-download"></i> <span class="hidden sm:inline">Download</span>
            </a>
          </div>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>
      </div>

      <div class="bg-blue-600 rounded-xl p-6 text-white mb-6">
        <h3 class="font-display font-bold text-lg mb-2">Benefits of Being a Reviewer</h3>
        <p class="text-blue-100 text-sm mb-4 leading-relaxed">Your contributions are formally recognised and help advance scholarly research.</p>
        <div class="grid sm:grid-cols-2 gap-3 text-sm">
          <?php foreach (array('Certificate of Appreciation for each review','APC discounts on your own publications','Priority consideration for editorial board roles','Expanded professional network') as $b): ?>
          <div class="flex items-start gap-2">
            <i class="fas fa-check-circle text-blue-200 mt-0.5 flex-shrink-0"></i>
            <span class="text-blue-50"><?php echo $b; ?></span>
          </div>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="bg-gradient-to-r from-indigo-50 to-blue-50 border border-indigo-200 rounded-2xl shadow-lg p-6 md:p-10">
        <div class="grid md:grid-cols-2 gap-8 md:gap-10 items-center">
          <div>
            <h3 class="text-xl md:text-2xl font-bold text-gray-800 mb-4 flex items-center gap-2">
              <i class="fas fa-user-tie text-indigo-600"></i>
              Showcase Your Reviewer Profile
            </h3>
            <p class="text-gray-700 text-base mb-6 leading-relaxed">
              Have you contributed reviews for CIJSS ?
              Highlight your academic achievements, expertise, and research interests
              by submitting your <strong>Reviewer Profile</strong>.
              Profiles are featured on our official website.
            </p>
            <ul class="text-gray-700 space-y-2 mb-6 text-sm">
              <li class="flex items-center gap-2"><i class="fas fa-check-circle text-green-600"></i> Increase academic visibility</li>
              <li class="flex items-center gap-2"><i class="fas fa-check-circle text-green-600"></i> Showcase your expertise and research interests</li>
              <li class="flex items-center gap-2"><i class="fas fa-check-circle text-green-600"></i> Be recognized as a distinguished reviewer</li>
            </ul>
            <a href="?section=reviewer_profiles" class="inline-flex items-center gap-2 bg-indigo-600 hover:bg-indigo-700 text-white px-6 md:px-8 py-3 rounded-lg font-semibold transition">
              <i class="fas fa-id-badge"></i> Submit Reviewer Profile
            </a>
          </div>
          <div class="text-center">
            <img src="https://rsisinternational.org/journals/common/admin/Dr.%20Rodzidah%20Mohd%20Rodzi.png" alt="Sample reviewer profile" class="mx-auto rounded-lg shadow max-w-full">
            <p class="text-gray-600 text-sm mt-3">Example of a published reviewer profile</p>
          </div>
        </div>
      </div>
    </div>

    <?php
    // ══════════════════════════════════════════════════════════
    // SECTION: REVIEWER PROFILES
    // ══════════════════════════════════════════════════════════
    elseif ($active === 'reviewer_profiles'):
    ?>
    <div class="bg-white rounded-xl shadow-md p-6 md:p-10">
      <h2 class="text-2xl md:text-3xl font-bold text-gray-800 mb-6 flex items-center gap-3">
        <i class="fas fa-user-tie text-blue-600"></i>
        Distinguished Reviewer Profiles
      </h2>
      <p class="text-gray-700 text-base md:text-lg mb-8">
        We are proud to showcase the profiles of our esteemed reviewers.
        Kindly complete the form below to submit your professional details
        so we can feature your Reviewer Profile on our website.
      </p>
      <div class="grid md:grid-cols-2 gap-6 md:gap-10 items-stretch mt-6">

        <div class="bg-white border border-gray-200 rounded-2xl shadow-lg p-6 md:p-8 hover:shadow-xl transition">
          <h3 class="text-xl md:text-2xl font-semibold text-gray-800 mb-6 flex items-center gap-2">
            <i class="fas fa-user text-blue-600"></i> Sample Reviewer Profile
          </h3>
          <div class="flex flex-col items-center text-center">
            <img src="https://rsisinternational.org/journals/common/admin/Dr.%20Rodzidah%20Mohd%20Rodzi.png"
                 alt="Reviewer Profile" class="rounded-lg shadow mb-4 max-w-full">
            <p class="text-gray-600 text-sm mb-6">View how a reviewer profile appears on our website.</p>
            <a href="#" target="_blank"
               class="inline-flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-5 md:px-6 py-3 rounded-lg font-semibold transition">
              <i class="fas fa-external-link-alt"></i> Check Sample Profile
            </a>
          </div>
        </div>

        <div class="bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-200 rounded-2xl shadow-lg p-6 md:p-8 text-center hover:shadow-xl transition">
          <div class="flex justify-center mb-4">
            <i class="fas fa-id-badge text-blue-600 text-5xl md:text-6xl"></i>
          </div>
          <h3 class="text-xl md:text-2xl font-semibold text-gray-800 mb-4">Submit Your Reviewer Profile</h3>
          <p class="text-gray-600 mb-6 leading-relaxed text-sm md:text-base">
            Share your professional background, research interests, and achievements
            so we can feature your profile on the CIJSS website and
            recognize your contribution to the peer-review process.
          </p>
          <a href="https://communeglobal.com/journals/social-science/registration" target="_blank"
             class="inline-flex items-center gap-2 bg-indigo-600 hover:bg-indigo-700 text-white px-5 md:px-7 py-3 rounded-lg font-semibold transition">
            <i class="fas fa-user-plus"></i> Submit Reviewer Profile
          </a>
        </div>

      </div>
    </div>

    <?php endif; ?>

  </main>
</div>

<script>
// ════════════════════════════════════════════════════════════
// SINGLE HAMBURGER HANDLER
// On mobile  (≤768px): toggles off-canvas sidebar + overlay
// On desktop (>768px): collapses/expands sidebar width
// ════════════════════════════════════════════════════════════
function handleHamburger() {
  if (window.innerWidth <= 768) {
    // Mobile: slide sidebar in/out
    var sb = document.getElementById('sidebar');
    if (sb.classList.contains('mobile-open')) {
      closeSidebar();
    } else {
      openSidebar();
    }
  } else {
    // Desktop: collapse/expand
    toggleSidebarDesktop();
  }
}

function openSidebar() {
  document.getElementById('sidebar').classList.add('mobile-open');
  document.getElementById('mobile-overlay').classList.add('active');
  document.body.style.overflow = 'hidden'; // prevent background scroll
}

function closeSidebar() {
  document.getElementById('sidebar').classList.remove('mobile-open');
  document.getElementById('mobile-overlay').classList.remove('active');
  document.body.style.overflow = '';
}

function toggleSidebarDesktop() {
  var sb = document.getElementById('sidebar');
  var mc = document.getElementById('main-content');
  sb.classList.toggle('collapsed');
  mc.style.marginLeft = sb.classList.contains('collapsed') ? '72px' : '256px';
}

// Re-evaluate on resize so switching between mobile/desktop works cleanly
window.addEventListener('resize', function() {
  if (window.innerWidth > 768) {
    // Ensure mobile-open class is cleaned up when resizing to desktop
    document.getElementById('sidebar').classList.remove('mobile-open');
    document.getElementById('mobile-overlay').classList.remove('active');
    document.body.style.overflow = '';
  }
});

// ── Accept / Decline confirmations ───────────────────────────
function confirmAccept(id, dueDate){
  Swal.fire({
    title: 'Accept Review Invitation?',
    html: 'You will commit to submitting your review by <strong>' + dueDate + '</strong>.',
    icon: 'question', showCancelButton: true,
    confirmButtonText: 'Yes, Accept', confirmButtonColor: '#059669',
    cancelButtonText: 'Not now'
  }).then(function(r){ if(r.isConfirmed) window.location.href = 'accept_review.php?assignment_id=' + id; });
}
function confirmDecline(id){
  Swal.fire({
    title: 'Decline Review?',
    text: 'This cannot be undone. The editor will be notified.',
    icon: 'warning', showCancelButton: true,
    confirmButtonColor: '#dc2626', confirmButtonText: 'Yes, Decline',
    cancelButtonText: 'Keep invitation'
  }).then(function(r){ if(r.isConfirmed) window.location.href = 'decline_review.php?assignment_id=' + id; });
}

// ── Stat card filter ─────────────────────────────────────────
function filterAssignments(filter, clickedCard) {
  document.querySelectorAll('.stat-card').forEach(function(c) {
    c.classList.remove('active-filter');
  });
  if (clickedCard) clickedCard.classList.add('active-filter');

  var cards   = document.querySelectorAll('.assignment-card');
  var visible = 0;
  cards.forEach(function(card) {
    var match = (filter === 'all' || card.dataset.status === filter);
    card.style.display = match ? '' : 'none';
    if (match) visible++;
  });

  var badge = document.querySelector('.assignment-count');
  if (badge) badge.textContent = visible;

  var emptyEl = document.getElementById('filter-empty');
  if (emptyEl) emptyEl.style.display = (visible === 0) ? '' : 'none';

  var filterLabel = document.getElementById('active-filter-label');
  var clearBtn    = document.getElementById('clear-filter-btn');
  if (filter === 'all') {
    if (filterLabel) filterLabel.classList.add('hidden');
    if (clearBtn)    clearBtn.classList.add('hidden');
  } else {
    var labels = {
      'request_sent': 'Pending', 'accepted': 'Accepted',
      'review_submitted': 'Submitted', 'declined': 'Declined'
    };
    if (filterLabel) {
      filterLabel.textContent = (labels[filter] || filter) + ' only';
      filterLabel.classList.remove('hidden');
    }
    if (clearBtn) clearBtn.classList.remove('hidden');
  }
}

// ── Password strength ────────────────────────────────────────
function pwStrength(val){
  var fill = document.getElementById('pw-fill');
  var lbl  = document.getElementById('pw-lbl');
  if (!val) { if(fill) fill.style.width='0%'; if(lbl) lbl.textContent=''; return; }
  var s = 0;
  if (val.length >= 8)  s++;
  if (val.length >= 12) s++;
  if (/[A-Z]/.test(val))       s++;
  if (/[0-9]/.test(val))       s++;
  if (/[^A-Za-z0-9]/.test(val)) s++;
  var lvl = [['Very Weak','#ef4444'],['Weak','#f97316'],['Fair','#f59e0b'],['Strong','#22c55e'],['Very Strong','#16a34a']];
  var i = Math.min(s, 4);
  if (fill) { fill.style.width = ((s/5)*100)+'%'; fill.style.background = lvl[i][1]; }
  if (lbl)  { lbl.textContent = lvl[i][0]; lbl.style.color = lvl[i][1]; }
}

// ── Reply char count ─────────────────────────────────────────
var ta = document.getElementById('replyText');
var cc = document.getElementById('charCount');
if (ta && cc) {
  ta.addEventListener('input', function(){ cc.textContent = this.value.length + ' chars'; });
}

// ── Scroll to last message in ticket thread ──────────────────
(function(){
  var msgs = document.querySelectorAll('.bubble-you,.bubble-admin');
  if (msgs.length) { msgs[msgs.length-1].scrollIntoView({behavior:'smooth', block:'nearest'}); }
})();
</script>
</body>
</html>