<?php require __DIR__ . '/../layouts/header.php'; ?>


<?php
if (file_exists(BASE_PATH . '/app/views/partials/i18n_sidebar_labels.php')) {
   require_once BASE_PATH . '/app/views/partials/i18n_sidebar_labels.php';
//echo 'love';
}
if (!function_exists('__rf')) {
    function __rf($key,$fallback=''){
        if (function_exists('t')) return t($key,$fallback ?: $key);
        return $fallback ?: $key;
    }
}
?>

<?php
$lang = function_exists('current_lang')
    ? current_lang()
    : ($_SESSION['lang'] ?? 'en');

$isRtl = $lang === 'ar';
?>

<!-- Professional EDAS/EasyConf Review Form with High Contrast & Proper Visibility -->
<style>
    /* ============================================
       CAIRO FONT - Google Fonts
    ============================================ */
    @import url('https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800;1000&display=swap');
    
    /* ============================================
       CSS VARIABLES - Light Theme (Default)
       HIGH CONTRAST - All text clearly visible
    ============================================ */
    :root {
        /* Light Theme Colors - High Contrast */
        --bg-primary: #eef2f7;
        --bg-secondary: #ffffff;
        --bg-card: #ffffff;
        --bg-card-hover: #f5f9ff;
        --bg-input: #ffffff;
        --bg-sidebar: #f8fafd;
        
        --text-primary: #1a2c3e;
        --text-secondary: #2c3e50;
        --text-muted: #546e7a;
        --text-light: #7f8c8d;
        --text-on-primary: #ffffff;
        --text-on-success: #ffffff;
        --text-on-danger: #ffffff;
        --text-on-warning: #1a2c3e;
        
        --border-color: #cbd5e1;
        --border-hover: #94a3b8;
        
        --accent-primary: #2c5f8a;
        --accent-primary-dark: #1e3a5f;
        --accent-primary-light: #e8f0f8;
        --accent-secondary: #3b82f6;
        --accent-success: #2e7d64;
        --accent-success-light: #d5f5e8;
        --accent-warning: #d4a13e;
        --accent-warning-light: #fef3c7;
        --accent-danger: #c9513c;
        --accent-danger-light: #fee2e2;
        --accent-info: #4a90e2;
        
        --gradient-hero: linear-gradient(135deg, #2c5f8a 0%, #1e3a5f 100%);
        --gradient-card: linear-gradient(135deg, #ffffff 0%, #f8fafd 100%);
        --gradient-success: linear-gradient(135deg, #2e7d64 0%, #236b54 100%);
        --gradient-primary: linear-gradient(135deg, #2c5f8a 0%, #3b82f6 100%);
        --gradient-danger: linear-gradient(135deg, #c9513c 0%, #b8432e 100%);
        --gradient-glass: linear-gradient(135deg, rgba(255,255,255,0.95) 0%, rgba(248,250,253,0.98) 100%);
        
        --shadow-sm: 0 2px 4px rgba(0,0,0,0.04), 0 1px 2px rgba(0,0,0,0.03);
        --shadow-md: 0 4px 12px rgba(0,0,0,0.08), 0 2px 4px rgba(0,0,0,0.04);
        --shadow-lg: 0 12px 28px rgba(0,0,0,0.12), 0 4px 12px rgba(0,0,0,0.06);
        --shadow-xl: 0 20px 40px rgba(0,0,0,0.15);
        
        --radius-sm: 8px;
        --radius-md: 12px;
        --radius-lg: 16px;
        --radius-xl: 24px;
        
        --transition-fast: 0.15s ease;
        --transition-normal: 0.25s ease;
        --transition-slow: 0.4s ease;
        
        --font-cairo: 'Cairo', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    }
    
    /* Dark Theme - High Contrast */
    [data-theme="dark"] {
        --bg-primary: #0f1724;
        --bg-secondary: #1e293b;
        --bg-card: #1e293b;
        --bg-card-hover: #2d3a4e;
        --bg-input: #0f1724;
        --bg-sidebar: #0f1724;
        
        --text-primary: #f1f5f9;
        --text-secondary: #cbd5e1;
        --text-muted: #94a3b8;
        --text-light: #64748b;
        --text-on-primary: #ffffff;
        --text-on-success: #ffffff;
        --text-on-danger: #ffffff;
        --text-on-warning: #1a2c3e;
        
        --border-color: #334155;
        --border-hover: #475569;
        
        --accent-primary: #5b9bd5;
        --accent-primary-dark: #3b7bb5;
        --accent-primary-light: #1e3a5f;
        --accent-secondary: #60a5fa;
        --accent-success: #34d399;
        --accent-success-light: #064e3b;
        --accent-warning: #fbbf24;
        --accent-warning-light: #78350f;
        --accent-danger: #f87171;
        --accent-danger-light: #7f1d1d;
        --accent-info: #60a5fa;
        
        --gradient-card: linear-gradient(135deg, #1e293b 0%, #162032 100%);
        --gradient-glass: linear-gradient(135deg, rgba(30,41,59,0.95) 0%, rgba(22,32,50,0.98) 100%);
        
        --shadow-sm: 0 2px 4px rgba(0,0,0,0.2);
        --shadow-md: 0 4px 12px rgba(0,0,0,0.3);
        --shadow-lg: 0 12px 28px rgba(0,0,0,0.4);
    }
    
    /* Global Reset */
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    
    body {
        font-family: var(--font-cairo) !important;
        background: var(--bg-primary) !important;
        color: var(--text-primary) !important;
        transition: background var(--transition-normal), color var(--transition-normal);
        line-height: 1.5;
        min-height: 100vh;
    }
    
    /* Theme Toggle Button */
    .theme-toggle {
        position: fixed;
        bottom: 24px;
        right: 24px;
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background: var(--gradient-primary);
        border: none;
        color: var(--text-on-primary);
        cursor: pointer;
        box-shadow: var(--shadow-lg);
        z-index: 1000;
        transition: transform var(--transition-fast), box-shadow var(--transition-fast);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.25rem;
    }
    
    .theme-toggle:hover {
        transform: scale(1.1);
        box-shadow: var(--shadow-xl);
    }
    
    /* Toast Notifications */
    .toast-container {
        position: fixed;
        top: 24px;
        right: 24px;
        z-index: 9999;
        display: flex;
        flex-direction: column;
        gap: 12px;
    }
    
    .toast-notification {
        background: var(--bg-card);
        backdrop-filter: blur(12px);
        border-radius: var(--radius-md);
        padding: 14px 20px;
        min-width: 280px;
        max-width: 400px;
        box-shadow: var(--shadow-lg);
        display: flex;
        align-items: center;
        gap: 12px;
        animation: slideInRight 0.3s ease;
        border-left: 4px solid;
        font-family: var(--font-cairo);
    }
    
    .toast-notification.toast-success {
        border-left-color: var(--accent-success);
    }
    .toast-notification.toast-error {
        border-left-color: var(--accent-danger);
    }
    .toast-notification.toast-info {
        border-left-color: var(--accent-info);
    }
    .toast-notification.toast-warning {
        border-left-color: var(--accent-warning);
    }
    
    .toast-icon {
        font-size: 1.25rem;
    }
    .toast-success .toast-icon { color: var(--accent-success); }
    .toast-error .toast-icon { color: var(--accent-danger); }
    .toast-info .toast-icon { color: var(--accent-info); }
    .toast-warning .toast-icon { color: var(--accent-warning); }
    
    .toast-message {
        flex: 1;
        font-size: 0.875rem;
        font-weight: 500;
        color: var(--text-primary);
    }
    
    .toast-close {
        background: none;
        border: none;
        cursor: pointer;
        color: var(--text-muted);
        font-size: 1rem;
        transition: color var(--transition-fast);
    }
    
    .toast-close:hover {
        color: var(--text-primary);
    }
    
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOutRight {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
    
    /* Typography - HIGH CONTRAST */
    h1, h2, h3, h4, h5, h6 {
        font-weight: 700 !important;
        color: var(--text-primary) !important;
        letter-spacing: -0.02em !important;
    }
    
    .page-title {
        font-size: 2rem !important;
        font-weight: 800 !important;
        background: var(--gradient-primary);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin-bottom: 0.25rem !important;
    }
    
    .section-title {
        font-size: 1rem !important;
        font-weight: 700 !important;
        color: var(--text-primary) !important;
        margin-bottom: 1.25rem !important;
        padding-bottom: 0.75rem !important;
        border-bottom: 2px solid var(--border-color) !important;
        display: flex !important;
        align-items: center !important;
        gap: 0.5rem !important;
    }
    
    .section-title i {
        color: var(--accent-primary) !important;
        font-size: 1.1rem !important;
    }
    
    /* Cards */
    .card {
        background: var(--gradient-card) !important;
        border: 1px solid var(--border-color) !important;
        border-radius: var(--radius-lg) !important;
        box-shadow: var(--shadow-sm) !important;
        margin-bottom: 1.5rem !important;
        transition: all var(--transition-normal) !important;
        backdrop-filter: blur(4px);
    }
    
    .card:hover {
        transform: translateY(-2px);
        box-shadow: var(--shadow-md) !important;
        border-color: var(--accent-primary) !important;
    }
    
    .card-body {
        padding: 1.5rem !important;
    }
    
    /* Alert - HIGH CONTRAST */
    .alert-info {
        background: var(--accent-primary-light) !important;
        border: 1px solid var(--accent-primary) !important;
        color: var(--text-primary) !important;
        border-radius: var(--radius-md) !important;
        font-size: 0.875rem !important;
        padding: 0.875rem 1.25rem !important;
        font-weight: 600 !important;
    }
    
    .alert-info strong {
        color: var(--accent-primary) !important;
    }
    
    /* Progress Card */
    .review-progress-card {
        background: var(--gradient-glass) !important;
        border: 1px solid var(--border-color) !important;
        backdrop-filter: blur(12px);
    }
    
    .progress {
        height: 8px !important;
        border-radius: 20px !important;
        background-color: var(--border-color) !important;
        overflow: hidden;
    }
    
    .progress-bar {
        background: var(--gradient-primary) !important;
        border-radius: 20px !important;
        transition: width var(--transition-normal);
    }
    
    .score-total {
        font-size: 2.5rem !important;
        font-weight: 800 !important;
        background: var(--gradient-primary);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    /* Criteria Cards */
    .reviewer-score-card {
        background: var(--bg-card) !important;
        border: 1px solid var(--border-color) !important;
        border-radius: var(--radius-md) !important;
        transition: all var(--transition-normal) !important;
        cursor: pointer;
    }
    
    .reviewer-score-card:hover {
        border-color: var(--accent-primary) !important;
        transform: translateY(-3px);
        box-shadow: var(--shadow-md) !important;
    }
    
    /* Slider */
    .form-range {
        height: 6px !important;
        padding: 0 !important;
        background: transparent;
    }
    
    .form-range::-webkit-slider-thumb {
        background: var(--accent-primary) !important;
        width: 18px !important;
        height: 18px !important;
        border-radius: 50% !important;
        cursor: pointer !important;
        border: none !important;
        transition: transform var(--transition-fast);
    }
    
    .form-range::-webkit-slider-thumb:hover {
        transform: scale(1.25);
        background: var(--accent-primary-dark) !important;
    }
    
    .form-range::-webkit-slider-runnable-track {
        background: var(--border-color) !important;
        border-radius: 10px !important;
        height: 6px !important;
    }
    
    /* Form Controls - HIGH CONTRAST */
    .form-label {
        font-weight: 700 !important;
        font-size: 0.875rem !important;
        margin-bottom: 0.5rem !important;
        color: var(--text-secondary) !important;
    }
    
    .form-control, .form-select {
        border: 1px solid var(--border-color) !important;
        border-radius: var(--radius-md) !important;
        padding: 0.75rem 1rem !important;
        font-size: 0.875rem !important;
        transition: all var(--transition-fast) !important;
        background: var(--bg-input) !important;
        color: var(--text-primary) !important;
        font-family: var(--font-cairo) !important;
    }
    
    .form-control::placeholder, .form-select::placeholder {
        color: var(--text-light) !important;
        opacity: 0.7;
    }
    
    .form-control:focus, .form-select:focus {
        border-color: var(--accent-primary) !important;
        box-shadow: 0 0 0 3px rgba(44, 95, 138, 0.2) !important;
        outline: none !important;
    }
    
    textarea.form-control {
        resize: vertical !important;
        min-height: 100px !important;
    }
    
    /* Buttons - HIGH CONTRAST with visible text */
    .btn {
        border-radius: var(--radius-md) !important;
        font-weight: 700 !important;
        font-size: 0.875rem !important;
        padding: 0.625rem 1.25rem !important;
        transition: all var(--transition-fast) !important;
        font-family: var(--font-cairo) !important;
        cursor: pointer;
    }
    
    .btn-primary {
        background: var(--gradient-primary) !important;
        border: none !important;
        color: #ffffff !important;
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: var(--shadow-md);
        color: #ffffff !important;
    }
    
    .btn-success {
        background: var(--gradient-success) !important;
        border: none !important;
        color: #ffffff !important;
    }
    
    .btn-success:hover {
        transform: translateY(-2px);
        box-shadow: var(--shadow-md);
        color: #ffffff !important;
    }
    
    .btn-danger {
        background: var(--gradient-danger) !important;
        border: none !important;
        color: #ffffff !important;
    }
    
    .btn-outline-primary {
        border: 2px solid var(--accent-primary) !important;
        color: var(--accent-primary) !important;
        background: transparent !important;
        font-weight: 700 !important;
    }
    
    .btn-outline-primary:hover {
        background: var(--gradient-primary) !important;
        color: #ffffff !important;
        border-color: transparent !important;
        transform: translateY(-2px);
    }
    
    .btn-outline-secondary {
        border: 2px solid var(--border-color) !important;
        color: var(--text-secondary) !important;
        background: transparent !important;
    }
    
    .btn-outline-secondary:hover {
        background: var(--bg-card-hover) !important;
        border-color: var(--accent-primary) !important;
        color: var(--accent-primary) !important;
    }
    
    .btn-outline-success {
        border: 2px solid var(--accent-success) !important;
        color: var(--accent-success) !important;
        background: transparent !important;
    }
    
    .btn-outline-success:hover {
        background: var(--accent-success) !important;
        color: #ffffff !important;
    }
    
    .btn-outline-danger {
        border: 2px solid var(--accent-danger) !important;
        color: var(--accent-danger) !important;
        background: transparent !important;
    }
    
    .btn-outline-danger:hover {
        background: var(--accent-danger) !important;
        color: #ffffff !important;
    }
    
    /* Badges & Pills - HIGH CONTRAST */
    .badge {
        font-weight: 700 !important;
        padding: 0.375rem 0.875rem !important;
        border-radius: 30px !important;
        font-size: 0.75rem !important;
    }
    
    .badge.bg-primary {
        background: var(--accent-primary) !important;
        color: #ffffff !important;
    }
    
    .badge.bg-success {
        background: var(--accent-success) !important;
        color: #ffffff !important;
    }
    
    .badge.bg-warning {
        background: var(--accent-warning) !important;
        color: var(--text-on-warning) !important;
    }
    
    .badge.bg-danger {
        background: var(--accent-danger) !important;
        color: #ffffff !important;
    }
    
    .badge.bg-light {
        background: var(--bg-primary) !important;
        color: var(--text-primary) !important;
        border: 1px solid var(--border-color);
    }
    
    /* Evidence Chips - HIGH CONTRAST */
    .evidence-chip {
        display: inline-flex !important;
        align-items: center !important;
        gap: 0.5rem !important;
        padding: 0.5rem 1rem !important;
        background: var(--bg-card) !important;
        border: 1px solid var(--border-color) !important;
        border-radius: 40px !important;
        font-size: 0.8rem !important;
        font-weight: 600 !important;
        color: var(--text-primary) !important;
        cursor: pointer !important;
        transition: all var(--transition-fast) !important;
        margin: 0.25rem !important;
    }
    
    .evidence-chip:hover {
        background: var(--accent-primary) !important;
        border-color: var(--accent-primary) !important;
        color: #ffffff !important;
        transform: translateY(-1px);
    }
    
    .evidence-chip:hover input {
        accent-color: #ffffff;
    }
    
    .evidence-chip input {
        margin: 0 !important;
        accent-color: var(--accent-primary) !important;
        width: 16px;
        height: 16px;
        cursor: pointer;
    }
    
    /* Decision Card - HIGH CONTRAST */
    .decision-card {
        background: var(--gradient-glass) !important;
        border: 1px solid var(--border-color) !important;
    }
    
    .decision-score {
        font-size: 3rem !important;
        font-weight: 800 !important;
        background: var(--gradient-primary);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    .decision-pill {
        display: inline-block !important;
        padding: 0.5rem 1.25rem !important;
        background: var(--accent-primary) !important;
        border-radius: 40px !important;
        font-size: 0.8rem !important;
        font-weight: 700 !important;
        color: #ffffff !important;
    }
    
    /* Deep Reading */
    .deep-reading {
        background: var(--bg-card) !important;
        border: 1px solid var(--border-color) !important;
    }
    
    .focus-clock {
        font-family: monospace !important;
        font-size: 1.75rem !important;
        font-weight: 800 !important;
        background: var(--gradient-primary);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    /* Confidence Panel - HIGH CONTRAST */
    .confidence-score {
        font-size: 2.5rem !important;
        font-weight: 800 !important;
        background: var(--gradient-primary);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    .compare-box {
        background: var(--bg-card) !important;
        border-radius: var(--radius-md) !important;
        padding: 1rem !important;
        border: 1px solid var(--border-color) !important;
        transition: all var(--transition-fast);
    }
    
    .compare-box:hover {
        border-color: var(--accent-primary);
        transform: translateY(-2px);
    }
    
    .compare-label {
        font-weight: 800 !important;
        font-size: 0.75rem !important;
        text-transform: uppercase !important;
        letter-spacing: 0.5px !important;
        color: var(--accent-primary) !important;
        margin-bottom: 0.75rem !important;
    }
    
    /* Table - HIGH CONTRAST */
    .table {
        font-size: 0.875rem !important;
    }
    
    .table thead th {
        background: var(--bg-primary) !important;
        border-bottom: 2px solid var(--border-color) !important;
        font-weight: 700 !important;
        color: var(--text-primary) !important;
        padding: 0.875rem 1rem !important;
    }
    
    .table tbody td {
        padding: 0.875rem 1rem !important;
        border-bottom: 1px solid var(--border-color) !important;
        color: var(--text-primary) !important;
    }
    
    .table tbody tr:hover {
        background: var(--bg-card-hover) !important;
    }
    
    /* Grid Layout for Criteria */
    .criteria-grid {
        display: grid !important;
        grid-template-columns: repeat(3, 1fr) !important;
        gap: 1rem !important;
    }
    
    @media (max-width: 1200px) {
        .criteria-grid {
            grid-template-columns: repeat(2, 1fr) !important;
        }
    }
    
    @media (max-width: 768px) {
        .criteria-grid {
            grid-template-columns: 1fr !important;
        }
    }
    
    /* Citation Chips - HIGH CONTRAST */
    .citation-chip {
        display: inline-block !important;
        padding: 0.375rem 0.875rem !important;
        background: var(--accent-primary) !important;
        border-radius: 20px !important;
        font-size: 0.75rem !important;
        font-weight: 600;
        color: #ffffff !important;
        margin: 0.25rem !important;
    }
    
    /* Session Tools */
    .session-tools {
        display: flex !important;
        gap: 0.5rem !important;
        flex-wrap: wrap !important;
    }
    
    .session-tools .btn-sm {
        padding: 0.375rem 0.875rem !important;
        font-size: 0.75rem !important;
    }
    
    /* Mobile Submit Bar */
    .mobile-submit-bar {
        display: none !important;
    }
    
    @media (max-width: 768px) {
        .mobile-submit-bar {
            display: flex !important;
            position: fixed !important;
            bottom: 0 !important;
            left: 0 !important;
            right: 0 !important;
            background: var(--bg-card) !important;
            padding: 1rem !important;
            box-shadow: var(--shadow-lg) !important;
            z-index: 1000 !important;
            gap: 0.75rem !important;
            backdrop-filter: blur(20px);
            border-top: 1px solid var(--border-color);
        }
        body {
            padding-bottom: 90px !important;
        }
        .card-body {
            padding: 1.25rem !important;
        }
    }
    
    /* Print Styles */
    @media print {
        .mobile-submit-bar, .print-toolbar, .btn, .theme-toggle, .toast-container {
            display: none !important;
        }
        body {
            background: #fff !important;
            padding: 0 !important;
        }
        .card {
            break-inside: avoid !important;
            box-shadow: none !important;
            border: 1px solid #ddd !important;
        }
    }
    
    /* Utility Classes */
    .text-muted {
        color: var(--text-muted) !important;
    }
    
    .small {
        font-size: 0.75rem !important;
    }
    
    /* Focus Mode */
    .kbd-mode {
        outline: 3px solid var(--accent-primary) !important;
        border-radius: var(--radius-md) !important;
    }
    
    .slider-hotkey {
        font-size: 0.65rem !important;
        color: var(--text-muted) !important;
    }
    
    /* Review Ready Text */
    .review-ready {
        font-size: 2rem !important;
        font-weight: 800 !important;
        background: var(--gradient-primary);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    /* Summary Stat */
    .summary-stat {
        font-size: 2rem !important;
        font-weight: 800 !important;
        background: var(--gradient-primary);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    /* Scrollbar */
    ::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }
    
    ::-webkit-scrollbar-track {
        background: var(--bg-primary);
    }
    
    ::-webkit-scrollbar-thumb {
        background: var(--accent-primary);
        border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb:hover {
        background: var(--accent-primary-dark);
    }
    
    /* Additional Contrast Fixes */
    .text-success {
        color: var(--accent-success) !important;
    }
    
    .text-danger {
        color: var(--accent-danger) !important;
    }
    
    .text-warning {
        color: var(--accent-warning) !important;
    }
    
    .text-primary {
        color: var(--accent-primary) !important;
    }
    
    .fw-bold, .fw-semibold, .fw-medium {
        color: var(--text-primary) !important;
    }
    
    .alert-light {
        background: var(--bg-primary) !important;
        color: var(--text-primary) !important;
        border: 1px solid var(--border-color);
    }
</style>

<!-- Toast Container -->
<div class="toast-container" id="toastContainer"></div>

<!-- Theme Toggle Button -->
<button class="theme-toggle" id="themeToggle" aria-label="Toggle theme">
    <i class="fa fa-moon-o" id="themeIcon"></i>
</button>

<?php if(!empty($assignment['file_path'])): ?>

<div
style="
margin:20px 0;
padding:18px;
border-radius:18px;
background:#ffffff;
border:1px solid #dbe7ff;
display:flex;
justify-content:space-between;
align-items:center;
flex-wrap:wrap;
gap:15px;
">

<div>

<div
style="
font-size:20px;
font-weight:700;
">

📄 Submitted Manuscript

</div>

<div
style="
color:#6b7280;
">

<?= htmlspecialchars(
$assignment['original_filename']
?? basename(
(string)$assignment['file_path']
)
) ?>

</div>

</div>

<a
class="btn btn-success"

target="_blank"

href="/easychair<?= htmlspecialchars(
str_replace(
'/public',
'',
(string)$assignment['file_path']
)
) ?>">

Download Manuscript

</a>

</div>

<?php endif; ?>

<div class="container-fluid px-3 px-md-4 py-3 py-md-4">
    
    <!-- Round Alert -->
    <div class="alert alert-info rounded-3 mb-4">
        <i class="fa fa-info-circle me-2"></i>
        <strong><?= $isRtl ? 'جولة التحكيم' : 'Review Round' ?>:</strong> <?= (int)($assignment['round_no'] ?? 1) ?>
    </div>

    <!-- Header Section -->
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-4 gap-3">
        <div>
            <h1 class="page-title"><?= $isRtl ? 'تحكيم البحث' : 'Review Assignment!!' ?></h1>
            <div class="text-muted small mt-1">
                <i class="fa fa-file-text-o me-1"></i>
                <span class="fw-medium"><?= e((string) ($assignment['submission_no'] ?? '')) ?></span>
                <span class="mx-2">—</span>
                <span><?= e((string) ($assignment['title'] ?? '')) ?></span>
            </div>
        </div>
        <a href="<?= e(base_path('reviewer/assignments')) ?>" class="btn btn-outline-secondary rounded-2">
            <i class="fa fa-arrow-left me-1"></i> <?= e(trans('back')) ?>
        </a>
    </div>

    <!-- Review Guidelines -->
    <div class="card">
        <div class="card-body">
            <div class="section-title">
                <i class="fa fa-file-text-o"></i>
                <span> <?= __rf('review.guidelines','Review Guide Lines') ?>  </span>
            </div>
            <div class="text-muted" style="line-height: 1.7;">
                <?= current_lang() === 'ar'
                    ? (string) ($assignment['review_instructions_ar'] ?? '')
                    : (string) ($assignment['review_instructions_en'] ?? '') ?>
            </div>
        </div>
    </div>

    <!-- Main Review Form -->
    <div class="card">
        <div class="card-body">
            
            <?php $totalCriteria = count($criteria ?? []); ?>

            <!-- Progress Card -->
            <div class="review-progress-card rounded-3 mb-4 p-4">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="fw-bold mb-1 text-primary">
                            <i class="fa fa-tasks me-2"></i><?= $isRtl ? 'استكمال التحكيم' : 'Review Completion' ?>
                        </div>
                        <div class="small text-muted review-autosave" id="autosaveStatus">
                            <i class="fa fa-save me-1"></i> <?= $isRtl ? 'حفظ تلقائي' : 'Auto Save' ?>
                        </div>
                    </div>
                    <div class="score-total" id="reviewPercent">0%</div>
                </div>
                <div class="progress mt-3">
                    <div class="progress-bar" id="reviewProgress" style="width: 0%;"></div>
                </div>
            </div>

            <form id="reviewForm" action="/easychair/reviewer/submit-review" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
                <input type="hidden" name="assignment_id" value="<?= e((string) $assignment['id']) ?>">

                <!-- REVIEW CRITERIA SECTION -->
                <div class="mb-5">
                    <div class="section-title">
                        <i class="fa fa-star-o"></i>
                        <span><?= $isRtl ? 'نموذج التحكيم' : 'Review Criteria' ?></span>
                        <span class="badge bg-primary ms-2"><?= count($criteria ?? []) ?> <?= $isRtl ? 'المعيار' : 'Criteria' ?></span>
                    </div>
                    
                    <div class="criteria-grid">
                        <?php foreach (($criteria ?? []) as $c): ?>
                            <?php
                            $criterionTitle = $lang === 'ar'
                                ? ($c['title_ar'] ?? $c['title_en'] ?? 'معيار')
                                : ($c['title_en'] ?? $c['title_ar'] ?? 'Criterion');
                            $maxScore = (float)($c['max_score'] ?? 5);
                            $weight = (float)($c['weight'] ?? 1);
                            ?>
                            <div class="reviewer-score-card p-4">
                                <div class="d-flex justify-content-between align-items-start mb-3">
                                    <div>
                                        <div class="fw-bold mb-1 text-primary"><?= htmlspecialchars($criterionTitle) ?></div>
                                        <div class="small text-muted">
                                            <i class="fa fa-balance-scale me-1"></i>Weight: <?= $weight ?>
                                        </div>
                                    </div>
                                    <div class="badge bg-light">
                                        <i class="fa fa-flag-checkered me-1"></i>Max: <?= $maxScore ?>
                                    </div>
                                </div>
                                
                                <input type="range" 
                                       name="criteria[<?= (int)$c['id'] ?>]" 
                                       class="form-range criterion-input focus-review" 
                                       min="0" 
                                       max="<?= $maxScore ?>" 
                                       step="0.1" 
                                       value="<?= $maxScore / 2 ?>"
                                       oninput="document.getElementById('score_<?= (int)$c['id'] ?>').innerText = this.value">
                                
                                <div class="d-flex justify-content-between align-items-center mt-3">
                                    <div class="small text-muted">
                                        <i class="fa fa-tachometer me-1"></i><?= $isRtl ? 'التقييم الحالي' : 'Current Score' ?>
                                    </div>
                                    <div class="slider-hotkey">
                                        <i class="fa fa-keyboard-o me-1"></i><?= $isRtl ? '← → للتعديل • Enter للانتقال' : '← → adjust • Enter next' ?>
                                    </div>
                                    <div id="score_<?= (int)$c['id'] ?>" class="badge bg-success px-3 py-2 fs-6"><?= $maxScore / 2 ?></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Recommendation & File Upload -->
                <div class="row g-3 mb-4">
                    <div class="col-md-6">
                        <label class="form-label">
                            <i class="fa fa-gavel me-1"></i><?= $isRtl ? 'التوصيات' : 'Recommendations' ?> <span class="text-danger">*</span>
                        </label>
                        <select id="recommendationSelect" name="recommendation" class="form-select" required>
                            <option value="accept"><?= $isRtl ? 'قبول' : 'Accept' ?></option>
                            <option value="minor_revision"><?= $isRtl ? 'تعديلات طفيفة' : 'Minor Revision' ?></option>
                            <option value="major_revision"><?= $isRtl ? 'تعديلات جوهرية' : 'Major Revision' ?></option>
                            <option value="reject"><?= $isRtl ? 'رفض' : 'Reject' ?></option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">
                            <i class="fa fa-upload me-1"></i><?= $isRtl ? 'رفع نسخة منقحة' : 'Upload Review File' ?> 
                        </label>
                        <input type="file" name="review_file" id="reviewFile" class="form-control">
                        <div class="small text-muted mt-1">
                            <i class="fa fa-info-circle me-1"></i><?= $isRtl ? 'الملفات المقبولة' : 'Accepted: PDF, DOC, DOCX, (Max. 10MB)' ?> 
                        </div>
                    </div>
                </div>

                <!-- Comments -->
                <div class="row g-3 mb-4">
                    <div class="col-md-6">
                        <label class="form-label">
                            <i class="fa fa-comment me-1"></i><?= $isRtl ? 'ملاحظات للمؤلفين' : 'Comments to Author(s)' ?>
                        </label>
                        <textarea name="comments" class="form-control" rows="5" placeholder="<?= $isRtl ? 'ملاحظات هنا ......' : 'Comments here ......' ?>"></textarea>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">
                            <i class="fa fa-lock me-1"></i><?= $isRtl ? 'ملاحظات للمحرر' : 'Comments to Editor (Confidential)' ?> 
                        </label>
                        <textarea name="comments_to_editor" class="form-control" rows="5" placeholder="Private comments for the editor only..."></textarea>
                    </div>
                </div>

                <!-- Reviewer Workspace -->
                <div class="card mb-4">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div class="section-title mb-0">
                                <i class="fa fa-comments-o"></i>
                                <span><?= $isRtl ? 'ملاحظات المحكّم' : 'Reviewer Workspace' ?></span>
                            </div>
                            <div class="review-ready" id="reviewReady">0%</div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">
                                <i class="fa fa-sticky-note-o me-1"></i><?= $isRtl ? 'ملاحظات شخصية (لا تُرسل)' : 'Private Notes (not submitted)' ?>
                            </label>
                            <textarea id="reviewPrivateNotes" class="form-control" rows="3" placeholder="Your personal notes, not visible to authors or editors..."></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label mb-2">
                                <i class="fa fa-check-square-o me-1"></i><?= $isRtl ? 'قائمة التحقق' : 'Review Checklist' ?>
                            </label>
                            <div>
                                <label class="evidence-chip"><input type="checkbox" class="review-check me-1"> <?= $isRtl ? 'النطاق و الملائمة' : 'Scope & Relevance' ?> </label>
                                <label class="evidence-chip"><input type="checkbox" class="review-check me-1"> <?= $isRtl ? 'المنهجية' : 'Methodology' ?> </label>
                                <label class="evidence-chip"><input type="checkbox" class="review-check me-1"> <?= $isRtl ? 'النتائج والتحليل' : 'Results & Analysis' ?> </label>
                                <label class="evidence-chip"><input type="checkbox" class="review-check me-1"> <?= $isRtl ? 'حداثة المراجع' : 'References' ?> </label>
                                <label class="evidence-chip"><input type="checkbox" class="review-check me-1"> <?= $isRtl ? 'اللغة والوضوح' : 'Language & Clarity' ?> </label>
                                <label class="evidence-chip"><input type="checkbox" class="review-check me-1"> <?= $isRtl ? 'الأصالة' : 'Originality' ?> </label>
                            </div>
                        </div>
                        
                        <div class="upload-preview small text-muted" id="uploadPreview">
                            <i class="fa fa-info-circle me-1"></i> <?= $isRtl ? 'لم يتم رفع نتائج التحكيم' : 'No Review evidence uploaded!!' ?> 
                        </div>
                    </div>
                </div>

                <!-- Decision Assistant -->
                <div class="card decision-card mb-4">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div>
                                <div class="section-title mb-0">
                                    <i class="fa fa-balance-scale"></i>
                                    <span><?= $isRtl ? 'مساعد القرار' : 'Recommendation Assistant' ?></span>
                                </div>
                                <div class="small text-muted mt-1">
                                    <i class="fa fa-lightbulb-o me-1"></i><?= $isRtl ? 'واجهة إرشادية فقط — القرار النهائي للمحكّم' : 'Visual guidance only — final decision belongs to reviewer' ?>
                                </div>
                            </div>
                            <div class="decision-score" id="decisionScore">0</div>
                        </div>
                        
                        <div class="progress mb-3" style="height: 10px;">
                            <div class="progress-bar" id="decisionProgress" style="width: 0%;"></div>
                        </div>
                        
                        <div class="decision-label fw-semibold mb-2 fs-5 text-primary" id="decisionLabel">—</div>
                        <div class="decision-pill" id="decisionReason">
                            <i class="fa fa-hourglass-half me-1"></i> <?= $isRtl ? 'بانتظار نتائج التحكيم' : 'Waiting for Evaluation' ?>
                        </div>
                        
                        <div class="mt-3">
                            <label class="form-label">
                                <i class="fa fa-pencil-square-o me-1"></i><?= $isRtl ? 'مبررات القرار (اختياري)' : 'Decision Notes (optional)' ?>
                            </label>
                            <textarea id="decisionNotes" class="form-control" rows="2" placeholder="Explain your recommendation rationale..."></textarea>
                        </div>
                    </div>
                </div>

                <!-- Mobile Navigation Buttons -->
                <div class="mobile-submit-bar gap-2">
                    <button type="button" class="btn btn-outline-primary flex-fill" id="prevCriterion">
                        <i class="fa fa-chevron-left"></i> Prev
                    </button>
                    <button type="submit" class="btn btn-success flex-fill" form="reviewForm">
                        <i class="fa fa-check"></i> <?= $isRtl ? 'إرسال' : 'Submit' ?>
                    </button>
                    <button type="button" class="btn btn-outline-primary flex-fill" id="nextCriterion">
                        Next <i class="fa fa-chevron-right"></i>
                    </button>
                </div>

                <!-- Deep Reading Workspace -->
                <div class="card deep-reading mb-4" id="readingWorkspace">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div class="section-title mb-0">
                                <i class="fa fa-book"></i>
                                <span><?= $isRtl ? 'وضع القراءة العميقة' : 'Deep Reading' ?></span>
                            </div>
                            <div class="focus-clock" id="focusClock">
                                <i class="fa fa-clock-o me-1"></i>25:00
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <button type="button" id="toggleReading" class="btn btn-outline-primary btn-sm">
                                <i class="fa fa-expand me-1"></i> <?= $isRtl ? 'عرض قريب' : 'Foucus Mode' ?>
                            </button>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">
                                <i class="fa fa-pencil me-1"></i> <?= $isRtl ? 'تعليقات توضحية' : 'Annotations' ?>
                            </label>
                            <textarea id="annotationBox" class="form-control" rows="4" placeholder="Add your reading notes and annotations here..."></textarea>
                        </div>
                        
                        <div>
                            <label class="form-label">
                                <i class="fa fa-quote-right me-1"></i> <?= $isRtl ? 'مركز الاستشهادات' : 'Citations Workspace' ?> 
                            </label>
                            <input id="citationInput" class="form-control mb-2" placeholder="Type a citation and press Enter...">
                            <div id="citationList" class="d-flex flex-wrap gap-1 mt-2"></div>
                        </div>
                    </div>
                </div>

                <!-- Review Confidence -->
                <div class="card confidence-panel mb-4">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div>
                                <div class="section-title mb-0">
                                    <i class="fa fa-line-chart"></i>
                                    <span><?= $isRtl ? 'مؤشر الثقة' : 'Review Confidence' ?></span>
                                </div>
                                <div class="small text-muted">
                                    <i class="fa fa-info-circle me-1"></i><?= $isRtl ? 'لا يؤثر على القرار النهائي' : 'Does not affect final decision' ?>
                                </div>
                            </div>
                            <div class="confidence-score" id="confidenceValue">50%</div>
                        </div>
                        
                        <div class="progress mb-4" style="height: 8px;">
                            <div class="progress-bar" id="confidenceBar" style="width: 50%;"></div>
                        </div>
                        
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="compare-box">
                                    <div class="compare-label">
                                        <i class="fa fa-thumbs-up me-1"></i> <?= $isRtl ? 'نقاط قوة' : 'Strengths' ?> 
                                    </div>
                                    <textarea id="strengthBox" class="form-control" rows="4" placeholder="What are the paper's strengths?"></textarea>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="compare-box">
                                    <div class="compare-label">
                                        <i class="fa fa-thumbs-down me-1"></i> <?= $isRtl ? 'نقاط الضعف' : 'Weeknesses' ?>
                                    </div>
                                    <textarea id="weaknessBox" class="form-control" rows="4" placeholder="What needs improvement?"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Executive Summary -->
                <div class="card summary-card mb-4" id="printReviewArea">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div class="section-title mb-0">
                                <i class="fa fa-file-text"></i>
                                <span><?= $isRtl ? 'الملخص التنفيذي' : 'Executive Summary' ?></span>
                            </div>
                            <div class="summary-stat" id="summaryScore">0%</div>
                        </div>
                        
                        <div class="print-toolbar mb-3 d-flex gap-2 flex-wrap">
                            <button type="button" id="generateSummary" class="btn btn-outline-primary btn-sm">
                                <i class="fa fa-magic me-1"></i>  <?= $isRtl ? 'توليد' : 'Generate' ?>
                            </button>
                            <button type="button" id="printReview" class="btn btn-outline-success btn-sm">
                                <i class="fa fa-print me-1"></i>  <?= $isRtl ? 'طباعة' : 'Print' ?>
                            </button>
                            <button type="button" id="clearSummary" class="btn btn-outline-danger btn-sm">
                                <i class="fa fa-trash-o me-1"></i> <?= $isRtl ? 'حذف' : 'Clear' ?>
                            </button>
                        </div>
                        
                        <textarea id="executiveSummary" class="form-control executive-summary" rows="6" placeholder="Executive summary will appear here..."></textarea>
                    </div>
                </div>

                <!-- Submit Button (Desktop) -->
                <div class="mt-4 d-none d-md-block">
                    <button type="submit" class="btn btn-success px-5 py-2">
                        <i class="fa fa-check-circle me-2"></i> <?= e(trans('save')) ?>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Review Session Snapshot -->
    <div class="card evidence-card mb-4">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <div class="section-title mb-0">
                        <i class="fa fa-folder-open-o"></i>
                        <span><?= $isRtl ? 'جلسة التحكيم' : 'Review Session' ?></span>
                    </div>
                    <div class="small text-muted">
                        <i class="fa fa-database me-1"></i><?= $isRtl ? 'استرجاع وحفظ محلي فقط' : 'Local recovery only' ?>
                    </div>
                </div>
                <div class="session-tools">
                    <button type="button" id="saveSnapshot" class="btn btn-outline-primary btn-sm">
                        <i class="fa fa-save me-1"></i> <?= $isRtl ? 'حفظ صورة' : 'Save Snapshot' ?>
                    </button>
                    <button type="button" id="restoreSnapshot" class="btn btn-outline-success btn-sm">
                        <i class="fa fa-undo me-1"></i> <?= $isRtl ? 'استرجاع' : 'Restore' ?>
                    </button>
                    <button type="button" id="clearSnapshot" class="btn btn-outline-danger btn-sm">
                        <i class="fa fa-eraser me-1"></i> <?= $isRtl ? 'حذف البيانات' : 'Clear' ?>
                    </button>
                </div>
            </div>
            <div id="snapshotStatus" class="alert alert-light mb-0 py-2 small">
                <i class="fa fa-check-circle text-success me-1"></i> <?= $isRtl ? 'جاهز' : 'Ready' ?>
            </div>
        </div>
    </div>

    <!-- Review Files -->
    <?php if (!empty($files)): ?>
    <div class="card">
        <div class="card-body">
            <div class="section-title">
                <i class="fa fa-paperclip"></i>
                <span><?= e(trans('review_files')) ?></span>
                <span class="badge bg-primary ms-2"><?= count($files) ?> <?= $isRtl ? 'ملفات' : 'Files' ?></span>
            </div>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th><i class="fa fa-file-o me-1"></i><?= e(trans('review_file')) ?></th>
                            <th><i class="fa fa-calendar me-1"></i><?= $isRtl ? 'التاريخ' : 'Dates' ?></th>
                            <th width="50"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($files as $f): ?>
                            <tr class="evidence-file">
                                <td>
                                    <div class="fw-semibold text-primary"><?= e((string)($f['original_filename'] ?? '')) ?></div>
                                    <div class="small text-muted">
                                        <i class="fa fa-file-<?= strtolower(pathinfo((string)($f['original_filename'] ?? ''), PATHINFO_EXTENSION)) ?>-o me-1"></i>
                                        <?= strtoupper(pathinfo((string)($f['original_filename'] ?? ''), PATHINFO_EXTENSION)) ?>
                                    </div>
                                </td>
                                <td>
                                    <i class="fa fa-clock-o me-1"></i><?= e((string) ($f['created_at'] ?? '')) ?>
                                </td>
                                <td>
                                    <a href="#" class="text-primary"><i class="fa fa-download"></i></a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php endif; ?>

</div>

<!-- ============================================
     JAVASCRIPT MODULES with Toast Notifications
     ============================================ -->

<script>
// Toast Notification System
function showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    if (!container) return;
    
    const toast = document.createElement('div');
    toast.className = `toast-notification toast-${type}`;
    
    let icon = '';
    switch(type) {
        case 'success': icon = 'fa fa-check-circle'; break;
        case 'error': icon = 'fa fa-exclamation-circle'; break;
        case 'warning': icon = 'fa fa-warning'; break;
        default: icon = 'fa fa-info-circle';
    }
    
    toast.innerHTML = `
        <div class="toast-icon"><i class="${icon}"></i></div>
        <div class="toast-message">${message}</div>
        <button class="toast-close" onclick="this.parentElement.remove()"><i class="fa fa-times"></i></button>
    `;
    
    container.appendChild(toast);
    
    setTimeout(() => {
        toast.style.animation = 'slideOutRight 0.3s ease';
        setTimeout(() => toast.remove(), 300);
    }, 4000);
}

// Theme Toggle
(function() {
    const themeToggle = document.getElementById('themeToggle');
    const themeIcon = document.getElementById('themeIcon');
    
    // Load saved theme
    const savedTheme = localStorage.getItem('theme') || 'light';
    if (savedTheme === 'dark') {
        document.documentElement.setAttribute('data-theme', 'dark');
        themeIcon.className = 'fa fa-sun-o';
    } else {
        themeIcon.className = 'fa fa-moon-o';
    }
    
    themeToggle.addEventListener('click', () => {
        const currentTheme = document.documentElement.getAttribute('data-theme');
        if (currentTheme === 'dark') {
            document.documentElement.removeAttribute('data-theme');
            localStorage.setItem('theme', 'light');
            themeIcon.className = 'fa fa-moon-o';
            showToast('Light theme activated', 'success');
        } else {
            document.documentElement.setAttribute('data-theme', 'dark');
            localStorage.setItem('theme', 'dark');
            themeIcon.className = 'fa fa-sun-o';
            showToast('Dark theme activated', 'success');
        }
    });
})();

// Auto-save Form Data with Toast
(function() {
    const KEY = "easychair_review_form";
    const form = document.querySelector("#reviewForm");
    if (!form) return;
    const fields = form.querySelectorAll("[name]");
    
    function restore() {
        try {
            const data = JSON.parse(localStorage.getItem(KEY) || "{}");
            fields.forEach(f => {
                if (data[f.name] !== undefined && f.type !== 'file') {
                    f.value = data[f.name];
                    if (f.classList && f.classList.contains('criterion-input')) {
                        f.dispatchEvent(new Event('input'));
                    }
                }
            });
            if (Object.keys(data).length > 0) {
                showToast('Draft restored from local storage', 'info');
            }
        } catch(e) {}
    }
    
    function persist() {
        let x = {};
        fields.forEach(f => { if (f.type !== 'file') x[f.name] = f.value; });
        localStorage.setItem(KEY, JSON.stringify(x));
        let st = document.getElementById('autosaveStatus');
        if (st) {
            st.innerHTML = '<i class="fa fa-check-circle me-1"></i> Draft saved';
            setTimeout(() => {
                if (st) st.innerHTML = '<i class="fa fa-save me-1"></i> Autosave enabled';
            }, 2000);
        }
        updateReviewProgress();
    }
    
    function updateReviewProgress() {
        let total = 0, done = 0;
        document.querySelectorAll('.criterion-input').forEach(x => {
            total++;
            if (x.value !== '' && Number(x.value) > 0) done++;
            let scoreSpan = document.getElementById('score_' + (x.name.match(/\d+/)?.[0]));
            if (scoreSpan) scoreSpan.innerHTML = x.value;
        });
        let pct = total ? Math.round((done / total) * 100) : 0;
        let p = document.getElementById('reviewPercent');
        if (p) p.innerHTML = pct + '%';
        let pb = document.getElementById('reviewProgress');
        if (pb) pb.style.width = pct + '%';
    }
    
    restore();
    fields.forEach(f => f.addEventListener('input', persist));
    updateReviewProgress();
    form.addEventListener('submit', () => {
        localStorage.removeItem(KEY);
        showToast('Review submitted successfully!', 'success');
    });
})();

// Private Notes & File Preview with Toast
(function() {
    const NOTES = "easychair_private_review";
    const note = document.getElementById('reviewPrivateNotes');
    if (note) {
        note.value = localStorage.getItem(NOTES) || '';
        note.addEventListener('input', () => localStorage.setItem(NOTES, note.value));
    }
    
    const file = document.getElementById('reviewFile');
    if (file) {
        file.addEventListener('change', () => {
            const p = document.getElementById('uploadPreview');
            if (p && file.files[0]) {
                p.innerHTML = '<i class="fa fa-file-pdf-o me-1"></i> Selected: ' + file.files[0].name;
                showToast('File selected: ' + file.files[0].name, 'info');
            } else if (p) {
                p.innerHTML = '<i class="fa fa-info-circle me-1"></i> No review evidence uploaded';
            }
        });
    }
    
    function updateChecklistProgress() {
        const all = document.querySelectorAll('.review-check');
        let done = 0;
        all.forEach(x => { if (x.checked) done++; });
        const pct = all.length ? Math.round((done / all.length) * 100) : 0;
        let r = document.getElementById('reviewReady');
        if (r) r.innerHTML = pct + '%';
        if (done === all.length && all.length > 0) {
            showToast('All checklist items completed!', 'success');
        }
    }
    
    document.querySelectorAll('.review-check').forEach(x => x.addEventListener('change', updateChecklistProgress));
    updateChecklistProgress();
})();

// Decision Assistant
(function() {
    const sliders = document.querySelectorAll('.criterion-input');
    const label = document.getElementById('decisionLabel');
    const scoreSpan = document.getElementById('decisionScore');
    const progress = document.getElementById('decisionProgress');
    const reason = document.getElementById('decisionReason');
    const select = document.getElementById('recommendationSelect');
    const notes = document.getElementById('decisionNotes');
    const KEY = "easychair_decision_notes";
    
    if (notes) {
        notes.value = localStorage.getItem(KEY) || '';
        notes.addEventListener('input', () => localStorage.setItem(KEY, notes.value));
    }
    
    function evaluate() {
        let total = 0, count = 0;
        sliders.forEach(s => { 
            let val = Number(s.value || 0);
            let max = Number(s.max || 100);
            if (max > 0) {
                total += (val / max) * 100;
                count++;
            }
        });
        let avg = count ? Math.round(total / count) : 0;
        if (scoreSpan) scoreSpan.innerHTML = avg;
        if (progress) progress.style.width = Math.min(100, avg) + '%';
        
        let txt = '', rec = '';
        if (avg >= 85) { txt = 'Strong Accept'; rec = 'High confidence - Excellent work'; }
        else if (avg >= 70) { txt = 'Minor Revision'; rec = 'Good paper with minor refinements needed'; }
        else if (avg >= 50) { txt = 'Major Revision'; rec = 'Substantial improvements required'; }
        else if (avg >= 30) { txt = 'Weak Reject'; rec = 'Significant flaws detected'; }
        else { txt = 'Reject'; rec = 'Insufficient quality for publication'; }
        
        if (label) label.innerHTML = txt;
        if (reason) {
            reason.innerHTML = '<i class="fa fa-gavel me-1"></i>' + rec;
        }
        
        if (select && (select.value === '' || select.dataset.auto !== '0')) {
            const map = { 
                'Strong Accept': 'accept', 
                'Minor Revision': 'minor_revision', 
                'Major Revision': 'major_revision', 
                'Weak Reject': 'reject',
                'Reject': 'reject' 
            };
            select.value = map[txt] || 'reject';
        }
    }
    
    sliders.forEach(x => x.addEventListener('input', evaluate));
    if (select) select.addEventListener('change', () => { select.dataset.auto = '0'; });
    evaluate();
})();

// Keyboard Navigation
(function() {
    const sliders = [...document.querySelectorAll('.criterion-input')];
    if (!sliders.length) return;
    let current = 0;
    
    function focusAt(i) {
        if (i < 0 || i >= sliders.length) return;
        current = i;
        sliders.forEach(s => s.classList.remove('kbd-mode'));
        let x = sliders[i];
        x.classList.add('kbd-mode');
        x.focus();
        x.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
    
    function move(delta) { focusAt(current + delta); }
    
    sliders.forEach((s, i) => {
        s.addEventListener('focus', () => { current = i; });
        s.addEventListener('keydown', e => {
            let step = Number(s.step || 1);
            let val = Number(s.value || 0);
            let mx = Number(s.max || 100);
            if (e.key === 'ArrowRight') {
                e.preventDefault();
                s.value = Math.min(mx, val + step);
                s.dispatchEvent(new Event('input'));
            }
            if (e.key === 'ArrowLeft') {
                e.preventDefault();
                s.value = Math.max(0, val - step);
                s.dispatchEvent(new Event('input'));
            }
            if (e.key === 'Enter') {
                e.preventDefault();
                move(1);
            }
        });
    });
    
    document.getElementById('nextCriterion')?.addEventListener('click', () => move(1));
    document.getElementById('prevCriterion')?.addEventListener('click', () => move(-1));
    focusAt(0);
})();

// Snapshot Save/Restore with Toast
(function() {
    const KEY = "easychair_review_snapshot";
    const form = document.querySelector("#reviewForm");
    if (!form) return;
    const statusSpan = document.getElementById('snapshotStatus');
    
    function collect() {
        let x = {};
        form.querySelectorAll('[name]').forEach(f => { if (f.type !== 'file') x[f.name] = f.value; });
        return x;
    }
    
    function apply(data) {
        Object.keys(data).forEach(k => {
            let el = form.querySelector('[name="' + k + '"]');
            if (el) { 
                el.value = data[k]; 
                el.dispatchEvent(new Event('input'));
                if (el.classList && el.classList.contains('criterion-input')) {
                    el.dispatchEvent(new Event('input'));
                }
            }
        });
    }
    
    document.getElementById('saveSnapshot')?.addEventListener('click', () => {
        localStorage.setItem(KEY, JSON.stringify(collect()));
        if (statusSpan) {
            statusSpan.innerHTML = '<i class="fa fa-check-circle text-success me-1"></i> Snapshot saved';
            setTimeout(() => { if(statusSpan) statusSpan.innerHTML = '<i class="fa fa-check-circle text-success me-1"></i> Ready'; }, 2000);
        }
        showToast('Review snapshot saved successfully', 'success');
    });
    
    document.getElementById('restoreSnapshot')?.addEventListener('click', () => {
        try { 
            const data = JSON.parse(localStorage.getItem(KEY) || '{}');
            if (Object.keys(data).length === 0) {
                showToast('No snapshot found to restore', 'warning');
                return;
            }
            apply(data); 
            if (statusSpan) {
                statusSpan.innerHTML = '<i class="fa fa-undo text-success me-1"></i> Recovered';
                setTimeout(() => { if(statusSpan) statusSpan.innerHTML = '<i class="fa fa-check-circle text-success me-1"></i> Ready'; }, 2000);
            }
            showToast('Snapshot restored successfully', 'success');
        } catch(e) {
            showToast('Failed to restore snapshot', 'error');
        }
    });
    
    document.getElementById('clearSnapshot')?.addEventListener('click', () => {
        localStorage.removeItem(KEY);
        if (statusSpan) {
            statusSpan.innerHTML = '<i class="fa fa-trash-o text-danger me-1"></i> Cleared';
            setTimeout(() => { if(statusSpan) statusSpan.innerHTML = '<i class="fa fa-check-circle text-success me-1"></i> Ready'; }, 2000);
        }
        showToast('Snapshot cleared', 'info');
    });
})();

// Deep Reading & Citations
(function() {
    const KEY = 'review_notes';
    const cite = 'review_citations';
    const box = document.getElementById('annotationBox');
    
    if (box) {
        box.value = localStorage.getItem(KEY) || '';
        box.addEventListener('input', () => localStorage.setItem(KEY, box.value));
    }
    
    const input = document.getElementById('citationInput');
    const list = document.getElementById('citationList');
    
    function renderCitations() {
        let arr = JSON.parse(localStorage.getItem(cite) || '[]');
        if (list) {
            list.innerHTML = '';
            arr.forEach(x => { 
                list.innerHTML += '<span class="citation-chip"><i class="fa fa-quote-left me-1"></i>' + escapeHtml(x) + '</span>'; 
            });
        }
    }
    
    function escapeHtml(str) {
        if (!str) return '';
        return str.replace(/[&<>]/g, function(m) {
            if (m === '&') return '&amp;';
            if (m === '<') return '&lt;';
            if (m === '>') return '&gt;';
            return m;
        });
    }
    
    input?.addEventListener('keydown', e => {
        if (e.key === 'Enter') {
            e.preventDefault();
            if (input.value.trim()) {
                let arr = JSON.parse(localStorage.getItem(cite) || '[]');
                arr.push(input.value.trim());
                localStorage.setItem(cite, JSON.stringify(arr));
                input.value = '';
                renderCitations();
                showToast('Citation added', 'success');
            }
        }
    });
    
    renderCitations();
    
    let t = 1500;
    let timerInterval = setInterval(() => {
        t--;
        if (t < 0) t = 1500;
        let m = String(Math.floor(t / 60)).padStart(2, '0');
        let s = String(t % 60).padStart(2, '0');
        let c = document.getElementById('focusClock');
        if (c) c.innerHTML = '<i class="fa fa-clock-o me-1"></i>' + m + ':' + s;
    }, 1000);
    
    document.getElementById('toggleReading')?.addEventListener('click', () => {
        const workspace = document.getElementById('readingWorkspace');
        workspace?.classList.toggle('deep-reading-active');
        if (workspace?.classList.contains('deep-reading-active')) {
            showToast('Focus mode activated', 'info');
        } else {
            showToast('Focus mode deactivated', 'info');
        }
    });
})();

// Confidence Score
(function() {
    const STORE = 'review_confidence';
    const sliders = [...document.querySelectorAll('.criterion-input')];
    const fields = ['strengthBox', 'weaknessBox'];
    
    fields.forEach(id => {
        let el = document.getElementById(id);
        if (!el) return;
        el.value = localStorage.getItem(STORE + id) || '';
        el.addEventListener('input', () => {
            localStorage.setItem(STORE + id, el.value);
            updateConfidence();
        });
    });
    
    function calculateConfidence() {
        let total = 0, max = 0;
        sliders.forEach(s => { 
            let val = Number(s.value || 0);
            let mx = Number(s.max || 100);
            total += val;
            max += mx;
        });
        return max ? Math.round((total / max) * 100) : 50;
    }
    
    function updateConfidence() {
        let score = calculateConfidence();
        let txt = 0;
        fields.forEach(id => { let el = document.getElementById(id); if (el) txt += el.value.length; });
        if (txt > 200) score = Math.min(100, score + 15);
        let v = document.getElementById('confidenceValue');
        if (v) v.innerHTML = score + '%';
        let b = document.getElementById('confidenceBar');
        if (b) b.style.width = score + '%';
    }
    
    sliders.forEach(x => x.addEventListener('input', updateConfidence));
    updateConfidence();
})();

// Executive Summary with Toast
(function() {
    const KEY = "review_summary";
    const summary = document.getElementById('executiveSummary');
    if (!summary) return;
    
    summary.value = localStorage.getItem(KEY) || '';
    summary.addEventListener('input', () => localStorage.setItem(KEY, summary.value));
    
    function calculateAverageScore() {
        let total = 0, max = 0;
        document.querySelectorAll('.criterion-input').forEach(s => {
            total += Number(s.value || 0);
            max += Number(s.max || 100);
        });
        return max ? Math.round((total / max) * 100) : 0;
    }
    
    document.getElementById('generateSummary')?.addEventListener('click', () => {
        let pct = calculateAverageScore();
        document.getElementById('summaryScore').innerHTML = pct + '%';
        let rec = document.querySelector('#recommendationSelect')?.value || '';
        let recText = rec.replace('_', ' ').toUpperCase();
        let strengths = document.getElementById('strengthBox')?.value || '';
        let weaknesses = document.getElementById('weaknessBox')?.value || '';
        
        let summaryText = '═══════════════════════════════════════\n';
        summaryText += 'OVERALL ASSESSMENT: ' + pct + '%\n';
        summaryText += 'RECOMMENDATION: ' + recText + '\n';
        summaryText += '═══════════════════════════════════════\n\n';
        summaryText += '📌 STRENGTHS:\n' + (strengths || '—') + '\n\n';
        summaryText += '⚠️ WEAKNESSES:\n' + (weaknesses || '—') + '\n\n';
        summaryText += '📝 SUMMARY:\n';
        summaryText += 'This paper demonstrates ' + (pct >= 70 ? 'good quality with minor issues' : (pct >= 50 ? 'mixed quality requiring revision' : 'significant limitations')) + '. ';
        summaryText += 'The reviewer recommends ' + recText.toLowerCase() + '.';
        
        summary.value = summaryText;
        summary.dispatchEvent(new Event('input'));
        showToast('Executive summary generated', 'success');
    });
    
    document.getElementById('printReview')?.addEventListener('click', () => {
        document.body.classList.add('print-mode');
        window.print();
        document.body.classList.remove('print-mode');
        showToast('Printing review', 'info');
    });
    
    document.getElementById('clearSummary')?.addEventListener('click', () => {
        summary.value = '';
        localStorage.removeItem(KEY);
        document.getElementById('summaryScore').innerHTML = '0%';
        showToast('Summary cleared', 'warning');
    });
})();

// Welcome Toast on Page Load
window.addEventListener('load', () => {
    setTimeout(() => {
        showToast('Welcome to the Review System! Use ← → arrows to navigate criteria.', 'info');
    }, 500);
});
</script>

<?php require __DIR__ . '/../layouts/footer.php'; ?>
