<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
$lms_config = require '../../config/lms.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

// Get exam ID from URL
$examId = $_GET['id'] ?? null;
if (!$examId) {
    header('Location: index.php');
    exit;
}

// Get exam data
$stmt = $db->prepare("
    SELECT e.*, c.title as course_title
    FROM exams e
    LEFT JOIN courses c ON e.course_id = c.id
    WHERE e.id = ? AND (e.instructor_id = ? OR ?)
");
$stmt->execute([$examId, $userId, hasRole('admin') ? true : false]);
$exam = $stmt->fetch();

if (!$exam) {
    $_SESSION['error_message'] = 'Exam not found or access denied';
    header('Location: index.php');
    exit;
}

// Get selected questions
$stmt = $db->prepare("
    SELECT q.id, q.title, q.question_type, q.difficulty, q.points, eq.points as exam_points, eq.sort_order
    FROM exam_questions eq
    JOIN questions q ON eq.question_id = q.id
    WHERE eq.exam_id = ?
    ORDER BY eq.sort_order
");
$stmt->execute([$examId]);
$selectedQuestions = $stmt->fetchAll();

// Get courses for dropdown
$role = $_SESSION['role'] ?? 'instructor';
$courses = $db->prepare("SELECT id, title FROM courses " . ($role === 'admin' ? "" : "WHERE instructor_id = ? ") . "ORDER BY title", $role === 'admin' ? [] : [$userId])->fetchAll();

// Decode JSON fields
$exam['proctoring_settings'] = json_decode($exam['proctoring_settings'], true) ?: [];
$exam['security_settings'] = json_decode($exam['security_settings'], true) ?: [];

$page_title = 'Edit Exam - ' . $lms_config['lms']['site_name'];
$active_link = 'exams';
?>
<!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); ?></title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Ensuring full page height and scrolling */
        html, body {
            height: 100%;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB; /* Gray 300 */
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }

        /* Custom Styles for Dashboard Layout */
        .admin-sidebar {
            transition: transform 0.3s ease-in-out;
            min-width: 250px;
            /* Using min-h-screen utility class */
        }
        @media (max-width: 1024px) {
            .admin-sidebar {
                position: fixed;
                top: 0;
                left: 0; /* Always positioned at 0, use transform to hide */
                transform: translateX(-100%); /* Hidden by default on mobile */
                z-index: 50;
                height: 100%;
            }
            .admin-container.sidebar-open .admin-sidebar {
                transform: translateX(0); /* Show on mobile */
            }
            .admin-container.sidebar-open .sidebar-overlay {
                display: block;
            }
        }

        /* Sidebar Overlay for Mobile */
        .sidebar-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 40;
            display: none;
            transition: opacity 0.3s ease;
        }

        /* Toast Notification Styles */
        #toast-container {
            position: fixed;
            top: 1.5rem;
            right: 1.5rem;
            z-index: 100;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            max-width: 350px;
        }

        .toast {
            padding: 1rem 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            color: white;
            opacity: 0;
            transform: translateX(100%);
            transition: opacity 0.3s ease-out, transform 0.3s ease-out;
        }

        .toast.show {
            opacity: 1;
            transform: translateX(0);
        }

        .toast-success { background-color: var(--success); }
        .toast-error { background-color: var(--danger); }

        /* Rating Stars */
        .rating .fas.fa-star {
            color: #ddd; /* Unfilled */
        }
        .rating .fas.fa-star.filled {
            color: #ffc107; /* Filled (Yellow/Gold) */
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

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

<!-- Sidebar Overlay (for closing sidebar on mobile tap outside) -->
<div id="sidebar-overlay" class="sidebar-overlay lg:hidden"></div>

<div class="flex">

    <?php include '../includes/sidebar.php'; ?>

    <!-- Top Bar (Mobile/Desktop Header) -->
    <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10 border-b border-accent-subtle">
        <div class="px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-3">
                <img src="../../assets/images/logo_1757657555.jpg" alt="Instructor Panel Logo" class="h-10 w-10">
                <div>
                    <h1 class="text-xl font-bold text-primary-blue"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></h1>
                    <p class="text-sm text-gray-600"><?php echo htmlspecialchars($page_title); ?></p>
                </div>
            </div>

            <div class="flex items-center space-x-4">
                <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username']); ?></span>
                <img class="h-10 w-10 rounded-full border-2 border-primary-blue object-cover" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($user['username'] ?? 'I'), 0, 1); ?>" alt="User Avatar">
                <!-- Mobile Menu Button (Hamburger) -->
                <button class="lg:hidden p-2 rounded-lg text-text-dark hover:bg-accent-subtle ml-4" id="mobileMenuButton">
                    <span class="text-xl">☰</span>
                </button>
            </div>
        </div>
    </header>

    <!-- Main Content Area -->
    <main class="flex-1 overflow-y-auto pt-16">

        <?php include '../includes/mobile_menu.php'; ?>

        <!-- Edit Exam Content -->
        <div class="p-6">
            <div class="flex justify-between items-center mb-6">
                <div>
                    <h1 class="text-3xl font-bold text-gray-800"><i class="fas fa-edit text-warning mr-3"></i>Edit Exam</h1>
                    <p class="text-gray-600">Modify exam details and question selection</p>
                </div>
                <a href="index.php" class="px-6 py-3 bg-gray-200 text-gray-800 rounded-lg shadow hover:bg-gray-300 transition">
                    <i class="fas fa-arrow-left mr-2"></i>Back to Exams
                </a>
            </div>

            <form id="examForm" method="POST" action="update.php">
                <input type="hidden" name="exam_id" value="<?php echo $exam['id']; ?>">
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    <!-- Main Exam Form -->
                    <div class="lg:col-span-2 space-y-6">
                        <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-200">
                            <div class="mb-6">
                                <h3 class="text-xl font-bold text-gray-800 mb-2"><i class="fas fa-file-alt mr-2"></i>Exam Information</h3>
                                <p class="text-gray-600">Modify the core elements of your assessment</p>
                            </div>
                            <!-- Exam Title -->
                            <div class="mb-4">
                                <label for="title" class="block text-sm font-medium text-gray-700 mb-2">Exam Title <span class="text-red-500">*</span></label>
                                <input type="text" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="title" name="title" required
                                       value="<?php echo htmlspecialchars($exam['title']); ?>"
                                       placeholder="Enter exam title">
                            </div>

                            <!-- Exam Type -->
                            <div class="mb-4">
                                <label for="exam_type" class="block text-sm font-medium text-gray-700 mb-2">Exam Type</label>
                                <select class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="exam_type" name="exam_type">
                                    <option value="quiz" <?php echo $exam['exam_type'] === 'quiz' ? 'selected' : ''; ?>>Quiz</option>
                                    <option value="midterm" <?php echo $exam['exam_type'] === 'midterm' ? 'selected' : ''; ?>>Midterm</option>
                                    <option value="final" <?php echo $exam['exam_type'] === 'final' ? 'selected' : ''; ?>>Final</option>
                                    <option value="practice" <?php echo $exam['exam_type'] === 'practice' ? 'selected' : ''; ?>>Practice</option>
                                    <option value="certification" <?php echo $exam['exam_type'] === 'certification' ? 'selected' : ''; ?>>Certification</option>
                                </select>
                            </div>

                            <!-- Description -->
                            <div class="mb-4">
                                <label for="description" class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                                <textarea class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="description" name="description" rows="3"
                                          placeholder="Describe the exam purpose"><?php echo htmlspecialchars($exam['description']); ?></textarea>
                            </div>

                            <!-- Instructions -->
                            <div class="mb-4">
                                <label for="instructions" class="block text-sm font-medium text-gray-700 mb-2">Instructions for Students</label>
                                <textarea class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="instructions" name="instructions" rows="4"
                                          placeholder="Special instructions, rules, or guidelines"><?php echo htmlspecialchars($exam['instructions']); ?></textarea>
                            </div>

                            <!-- Question Selection -->
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Selected Questions</label>
                                <div id="selected_questions" class="mb-4">
                                    <?php if (empty($selectedQuestions)): ?>
                                        <p class="text-gray-500">No questions selected yet.</p>
                                    <?php else: ?>
                                        <div class="selected-questions-list">
                                            <h6 class="font-semibold text-gray-800 mb-3">Selected Questions (<?php echo count($selectedQuestions); ?>)</h6>
                                            <?php foreach ($selectedQuestions as $index => $question): ?>
                                                <div class="question-order-item flex justify-between items-center p-3 bg-gray-50 border border-gray-200 rounded-lg mb-2">
                                                    <div class="flex-grow">
                                                        <span class="font-bold text-blue-600"><?php echo $index + 1; ?>.</span> <?php echo htmlspecialchars($question['title']); ?>
                                                        <small class="text-gray-500 ml-2">(<?php echo $question['exam_points']; ?> pts)</small>
                                                        <input type="hidden" name="question_ids[]" value="<?php echo $question['id']; ?>">
                                                        <input type="hidden" name="question_orders[]" value="<?php echo $index + 1; ?>">
                                                        <input type="hidden" name="question_points[]" value="<?php echo $question['exam_points']; ?>">
                                                    </div>
                                                    <button type="button" class="bg-red-500 text-white px-2 py-1 rounded hover:bg-red-600 transition duration-150" onclick="removeQuestion(<?php echo $index; ?>)">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <button type="button" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition" onclick="openQuestionBank()">
                                    <i class="fas fa-plus mr-1"></i>Manage Questions
                                </button>
                            </div>

                            <!-- Question Organization -->
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Question Organization</label>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div class="flex items-center">
                                        <input class="mr-2" type="checkbox" id="shuffle_questions" name="shuffle_questions" <?php echo $exam['shuffle_questions'] ? 'checked' : ''; ?>>
                                        <label class="text-sm text-gray-700" for="shuffle_questions">Shuffle question order</label>
                                    </div>
                                    <div class="flex items-center">
                                        <input class="mr-2" type="checkbox" id="shuffle_options" name="shuffle_options" <?php echo $exam['shuffle_options'] ? 'checked' : ''; ?>>
                                        <label class="text-sm text-gray-700" for="shuffle_options">Shuffle answer options</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Settings Sidebar -->
                    <div class="space-y-6">
                        <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-200">
                            <div class="mb-6">
                                <h3 class="text-xl font-bold text-gray-800 mb-2"><i class="fas fa-cogs mr-2"></i>Exam Settings</h3>
                                <p class="text-gray-600">Configure exam parameters and access control</p>
                            </div>
                            <!-- Timing & Scoring -->
                            <div class="mb-4">
                                <label for="time_limit" class="block text-sm font-medium text-gray-700 mb-2">Time Limit (minutes)</label>
                                <input type="number" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="time_limit" name="time_limit" min="0"
                                       value="<?php echo $exam['time_limit'] ?? ''; ?>"
                                       placeholder="Leave empty for no limit">
                            </div>

                            <div class="mb-4">
                                <label for="passing_score" class="block text-sm font-medium text-gray-700 mb-2">Passing Score (%)</label>
                                <input type="number" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="passing_score" name="passing_score" min="0" max="100"
                                       value="<?php echo $exam['passing_score']; ?>">
                            </div>

                            <div class="mb-4">
                                <label for="max_attempts" class="block text-sm font-medium text-gray-700 mb-2">Maximum Attempts</label>
                                <input type="number" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="max_attempts" name="max_attempts" min="1"
                                       value="<?php echo $exam['max_attempts']; ?>">
                            </div>

                            <div class="mb-4">
                                <label for="total_points" class="block text-sm font-medium text-gray-700 mb-2">Total Points</label>
                                <input type="number" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="total_points" name="total_points" readonly
                                       value="<?php echo $exam['total_points']; ?>">
                            </div>

                            <!-- Course -->
                            <div class="mb-4">
                                <label for="course_id" class="block text-sm font-medium text-gray-700 mb-2">Associated Course</label>
                                <select class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="course_id" name="course_id">
                                    <option value="">General exam (not course-specific)</option>
                                    <?php foreach ($courses as $course): ?>
                                        <option value="<?php echo $course['id']; ?>" <?php echo $exam['course_id'] == $course['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($course['title']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <!-- Status -->
                            <div class="mb-4">
                                <label for="status" class="block text-sm font-medium text-gray-700 mb-2">Exam Status</label>
                                <select class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="status" name="status">
                                    <option value="draft" <?php echo $exam['status'] === 'draft' ? 'selected' : ''; ?>>Draft</option>
                                    <option value="published" <?php echo $exam['status'] === 'published' ? 'selected' : ''; ?>>Published</option>
                                    <option value="archived" <?php echo $exam['status'] === 'archived' ? 'selected' : ''; ?>>Archived</option>
                                </select>
                            </div>

                            <!-- Schedule -->
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Schedule</label>
                                <div class="grid grid-cols-2 gap-2">
                                    <input type="datetime-local" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm" id="start_date" name="start_date"
                                           value="<?php echo $exam['start_date'] ? date('Y-m-d\TH:i', strtotime($exam['start_date'])) : ''; ?>">
                                    <input type="datetime-local" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm" id="end_date" name="end_date"
                                           value="<?php echo $exam['end_date'] ? date('Y-m-d\TH:i', strtotime($exam['end_date'])) : ''; ?>">
                                </div>
                            </div>

                            <!-- Security Options -->
                            <div class="mb-4">
                                <div class="flex items-center mb-2">
                                    <input class="mr-2" type="checkbox" id="is_proctored" name="is_proctored" <?php echo $exam['is_proctored'] ? 'checked' : ''; ?>>
                                    <label class="text-sm text-gray-700" for="is_proctored">Enable proctoring</label>
                                </div>

                                <div class="flex items-center mb-2">
                                    <input class="mr-2" type="checkbox" id="show_results" name="show_results" <?php echo $exam['show_results'] ? 'checked' : ''; ?>>
                                    <label class="text-sm text-gray-700" for="show_results">Show results after completion</label>
                                </div>

                                <div class="flex items-center mb-2">
                                    <input class="mr-2" type="checkbox" id="show_answers" name="show_answers" <?php echo $exam['show_answers'] ? 'checked' : ''; ?>>
                                    <label class="text-sm text-gray-700" for="show_answers">Show correct answers</label>
                                </div>

                                <div class="flex items-center">
                                    <input class="mr-2" type="checkbox" id="allow_review" name="allow_review" <?php echo $exam['allow_review'] ? 'checked' : ''; ?>>
                                    <label class="text-sm text-gray-700" for="allow_review">Allow review of answers</label>
                                </div>
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-200">
                            <div class="flex flex-col sm:flex-row gap-4">
                                <button type="submit" name="action" value="update" class="flex-1 px-6 py-3 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-lg shadow hover:from-blue-600 hover:to-purple-700 transition font-semibold">
                                    <i class="fas fa-save mr-2"></i>Update Exam
                                </button>
                                <button type="button" class="flex-1 px-6 py-3 bg-blue-500 text-white rounded-lg shadow hover:bg-blue-600 transition" onclick="previewExam()">
                                    <i class="fas fa-eye mr-2"></i>Preview Exam
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </main>
</div>

<!-- Question Bank Modal -->
<div class="fixed inset-0 bg-gray-900 bg-opacity-70 hidden items-center justify-center z-50 transition-opacity duration-300" id="questionBankModal">
    <div class="bg-white modal-content max-w-5xl w-full mx-4 max-h-[90vh] flex flex-col">
        <div class="modal-header flex justify-between items-center p-6 bg-gray-50 border-b border-gray-200 rounded-t-xl">
            <h5 class="text-2xl font-bold text-gray-800">Select Questions from Bank</h5>
            <button type="button" class="text-gray-400 hover:text-gray-700 transition" onclick="closeQuestionBank()">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>
        <div class="modal-body p-6 overflow-y-auto flex-grow">
            <!-- Question filters -->
            <div class="mb-4 p-4 bg-white rounded-lg border border-gray-200 shadow-sm sticky top-0 z-10">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <select class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="qb_type_filter">
                        <option value="">All Types</option>
                        <option value="mcq_single">MCQ Single</option>
                        <option value="mcq_multiple">MCQ Multiple</option>
                        <option value="true_false">True/False</option>
                        <option value="essay">Essay</option>
                        <option value="short_answer">Short Answer</option>
                        <option value="matching">Matching</option>
                        <option value="code">Code</option>
                        <option value="fill_blanks">Fill Blanks</option>
                    </select>
                    <select class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="qb_difficulty_filter">
                        <option value="">All Difficulties</option>
                        <option value="easy">Easy</option>
                        <option value="medium">Medium</option>
                        <option value="hard">Hard</option>
                    </select>
                    <input type="text" class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 md:col-span-2" id="qb_search" placeholder="Search questions by title or content...">
                </div>
            </div>

            <!-- Questions list -->
            <div class="question-bank-list p-2">
                <!-- Questions will be loaded here -->
            </div>
            <div id="no-questions-message" class="hidden text-center text-gray-500 p-8">
                No questions match your filter criteria.
            </div>
        </div>
        <div class="modal-footer flex justify-end p-4 border-t border-gray-200 bg-gray-50 rounded-b-xl">
            <button type="button" class="bg-gray-500 text-white px-5 py-2 rounded-lg hover:bg-gray-600 transition duration-150 font-medium" onclick="closeQuestionBank()">Close</button>
        </div>
    </div>
</div>

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

<div id="custom-modal" class="fixed inset-0 bg-gray-900 bg-opacity-70 hidden items-center justify-center z-[60]">
    <div class="bg-white rounded-xl p-6 shadow-2xl max-w-md w-full mx-4">
        <h3 class="text-xl font-bold mb-4 text-red-600" id="modal-title"></h3>
        <p class="text-gray-700 mb-6" id="modal-body-text"></p>
        <div class="flex justify-end">
            <button class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition" onclick="closeCustomModal()">OK</button>
        </div>
    </div>
</div>

<script>
    // --- Data and State ---
    let selectedQuestions = <?php echo json_encode($selectedQuestions); ?>;
    let totalPoints = <?php echo $exam['total_points']; ?>;

    // --- Utility Functions ---

    // Custom Modal (replaces alert/confirm)
    function showCustomModal(title, message) {
        document.getElementById('modal-title').textContent = title;
        document.getElementById('modal-body-text').textContent = message;
        document.getElementById('custom-modal').classList.remove('hidden');
        document.getElementById('custom-modal').classList.add('flex');
    }

    function closeCustomModal() {
        document.getElementById('custom-modal').classList.add('hidden');
        document.getElementById('custom-modal').classList.remove('flex');
    }

    // Toast Notification
    function showToast(message, type = 'info') {
        const container = document.getElementById('toast-container');
        const toast = document.createElement('div');
        toast.classList.add('toast', `toast-${type}`);
        toast.textContent = message;
        container.appendChild(toast);

        // Show
        setTimeout(() => {
            toast.classList.add('show');
        }, 10);

        // Hide and remove after 3 seconds
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                container.removeChild(toast);
            }, 300);
        }, 3000);
    }

    // Question Bank Modal
    function openQuestionBank() {
        document.getElementById('questionBankModal').classList.remove('hidden');
        document.getElementById('questionBankModal').classList.add('flex');
        loadQuestionBank();
    }

    function closeQuestionBank() {
        document.getElementById('questionBankModal').classList.add('hidden');
        document.getElementById('questionBankModal').classList.remove('flex');
    }

    let allQuestions = []; // Store all loaded questions

    function loadQuestionBank() {
        const typeFilter = document.getElementById('qb_type_filter').value;
        const difficultyFilter = document.getElementById('qb_difficulty_filter').value;
        const searchTerm = document.getElementById('qb_search').value;

        let url = '../../api/questions/index.php?limit=100';
        if (typeFilter) url += '&type=' + encodeURIComponent(typeFilter);
        if (difficultyFilter) url += '&difficulty=' + encodeURIComponent(difficultyFilter);
        if (searchTerm) url += '&search=' + encodeURIComponent(searchTerm);

        fetch(url)
            .then(response => response.json())
            .then(data => {
                allQuestions = data.data || [];
                renderQuestionBank();
            })
            .catch(error => {
                console.error('Error loading questions:', error);
            });
    }

    function getDifficultyClass(difficulty) {
        switch(difficulty) {
            case 'easy': return 'bg-green-100 text-green-800';
            case 'medium': return 'bg-yellow-100 text-yellow-800';
            case 'hard': return 'bg-red-100 text-red-800';
            default: return 'bg-gray-100 text-gray-800';
        }
    }

    function renderQuestionBank() {
        const listContainer = document.querySelector('.question-bank-list');
        listContainer.innerHTML = '';
        const noQuestionsMessage = document.getElementById('no-questions-message');

        let questionsFound = 0;

        allQuestions.forEach(q => {
            questionsFound++;
            const isSelected = selectedQuestions.some(sq => sq.id == q.id);
            const difficultyClass = getDifficultyClass(q.difficulty);

            const questionItem = document.createElement('div');
            questionItem.classList.add('question-item');
            questionItem.setAttribute('data-type', q.question_type);
            questionItem.setAttribute('data-difficulty', q.difficulty);
            questionItem.setAttribute('data-id', q.id);

            questionItem.innerHTML = `
                <div class="question-info">
                    <div class="question-title">${q.title}</div>
                    <div class="question-meta">${q.question_type.replace(/_/g, ' ').toUpperCase()} ${q.difficulty.toUpperCase()} ${q.points} pts ${q.category_name ? `Category: ${q.category_name}` : ''}</div>
                </div>
                <div class="question-action">
                    ${isSelected ? `<span class="added-indicator">ADDED</span>` : `<button class="add-question-btn btn btn-primary btn-sm" data-id="${q.id}" data-title="${q.title}" data-points="${q.points}">Add</button>`}
                </div>
            `;
            listContainer.appendChild(questionItem);
        });

        if (questionsFound === 0) {
            noQuestionsMessage.classList.remove('hidden');
        } else {
            noQuestionsMessage.classList.add('hidden');
        }
    }

    // --- Question Selection Logic ---

    // Add question to exam
    document.addEventListener('click', function(e) {
        const btn = e.target.closest('.add-question-btn');
        if (btn) {
            const questionId = parseInt(btn.dataset.id);
            const title = btn.dataset.title;
            const points = parseFloat(btn.dataset.points);

            // Check if already selected
            if (selectedQuestions.some(q => q.id === questionId)) {
                showToast('Question already added.', 'error');
                return;
            }

            // Add to selected questions
            selectedQuestions.push({
                id: questionId,
                title: title,
                exam_points: points,
                sort_order: selectedQuestions.length + 1
            });

            totalPoints += points;
            updateStateAndUI();

            // Re-render bank to show it's added
            renderQuestionBank();
        }
    });

    // Update selected questions display
    function updateSelectedQuestions() {
        const container = document.getElementById('selected_questions');

        if (selectedQuestions.length === 0) {
            container.innerHTML = '<p class="text-gray-500">No questions selected yet.</p>';
            return;
        }

        let html = '<div class="selected-questions-list">';
        html += '<h6 class="font-semibold text-gray-800 mb-3">Selected Questions (' + selectedQuestions.length + ')</h6>';

        selectedQuestions.forEach((question, index) => {
            html += `
                <div class="question-order-item flex justify-between items-center p-3 bg-gray-50 border border-gray-200 rounded-lg mb-2">
                    <div class="flex-grow">
                        <span class="font-bold text-blue-600">${index + 1}.</span> ${question.title}
                        <small class="text-gray-500 ml-2">(${question.exam_points} pts)</small>
                        <input type="hidden" name="question_ids[]" value="${question.id}">
                        <input type="hidden" name="question_orders[]" value="${index + 1}">
                        <input type="hidden" name="question_points[]" value="${question.exam_points}">
                    </div>
                    <button type="button" class="bg-red-500 text-white px-2 py-1 rounded hover:bg-red-600 transition duration-150" onclick="removeQuestion(${index})">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            `;
        });

        html += '</div>';
        container.innerHTML = html;
    }

    // Remove question from exam
    function removeQuestion(index) {
        const removedQuestion = selectedQuestions.splice(index, 1)[0];
        totalPoints -= removedQuestion.exam_points;

        // Reorder remaining questions
        selectedQuestions.forEach((q, i) => {
            q.sort_order = i + 1;
        });

        updateStateAndUI();

        // Re-render bank to show button again
        renderQuestionBank();

        showToast(`Removed: ${removedQuestion.title}`, 'error');
    }

    // Update total points display
    function updateTotalPoints() {
        document.getElementById('total_points').value = totalPoints;
    }

    function updateStateAndUI() {
        updateSelectedQuestions();
        updateTotalPoints();
    }

    // Question bank filtering
    document.getElementById('qb_type_filter').addEventListener('change', loadQuestionBank);
    document.getElementById('qb_difficulty_filter').addEventListener('change', loadQuestionBank);
    document.getElementById('qb_search').addEventListener('input', loadQuestionBank);

    function previewExam() {
        if (selectedQuestions.length === 0) {
            showCustomModal('Warning', 'Please add at least one question to preview the exam structure.');
            return;
        }

        const title = document.getElementById('title').value;
        const timeLimit = document.getElementById('time_limit').value || 'No limit';
        const totalQ = selectedQuestions.length;

        let previewHtml = `
            <h3 class="font-bold text-2xl mb-4 text-center">${title}</h3>
            <p class="text-lg mb-6 text-center text-gray-600">Total Questions: ${totalQ} | Total Points: ${totalPoints} | Time Limit: ${timeLimit} minutes</p>
            <div class="space-y-6 max-h-96 overflow-y-auto p-3 border rounded-lg bg-gray-50">
        `;

        selectedQuestions.forEach((q, index) => {
            const difficultyClass = getDifficultyClass('medium'); // Default for preview

            previewHtml += `
                <div class="p-4 bg-white shadow-md rounded-lg border border-gray-200">
                    <div class="flex justify-between items-center mb-2">
                        <p class="font-bold text-gray-800">Question ${index + 1}: ${q.title}</p>
                        <span class="text-sm font-semibold text-blue-600">${q.exam_points} pts</span>
                    </div>
                    <div class="flex space-x-3 text-sm text-gray-500">
                        <span class="px-2 py-0.5 bg-gray-200 rounded">QUESTION TYPE</span>
                        <span class="px-2 py-0.5 ${difficultyClass} rounded">DIFFICULTY</span>
                    </div>
                    <p class="mt-3 italic text-gray-600">
                        [Placeholder for question content / multiple-choice options]
                    </p>
                </div>
            `;
        });

        previewHtml += '</div>';

        // Show a more detailed preview in a custom modal
        const previewModal = document.getElementById('custom-modal');
        document.getElementById('modal-title').textContent = 'Exam Preview Structure';
        document.getElementById('modal-body-text').innerHTML = previewHtml;
        previewModal.classList.remove('hidden');
        previewModal.classList.add('flex');
    }

    // Initialize
    updateSelectedQuestions();
    updateTotalPoints();
</script>

<style>
    /* Additional styles for question bank */
    .question-bank-list {
        max-height: 400px;
        overflow-y: auto;
        border: 1px solid #e5e7eb;
        border-radius: 0.75rem;
        background: #ffffff;
    }

    .question-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1rem 1.5rem;
        border-bottom: 1px solid #e5e7eb;
        transition: all 0.3s ease;
    }

    .question-item:hover {
        background: white;
        transform: translateX(5px);
    }

    .question-item:last-child {
        border-bottom: none;
    }

    .selected-questions-list {
        margin-top: 1rem;
    }

    .question-order-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1rem;
        background: #f8fafc;
        border: 1px solid #e5e7eb;
        border-radius: 0.75rem;
        margin-bottom: 0.5rem;
    }

    .modal-content {
        border-radius: 1rem;
        border: none;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    }

    .modal-header {
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        border-radius: 1rem 1rem 0 0;
        border-bottom: 1px solid #e5e7eb;
        padding: 1.5rem 2rem;
    }

    .modal-body {
        padding: 2rem;
    }

    .toast-success { background-color: #10b981; }
    .toast-error { background-color: #ef4444; }

    .added-indicator {
        background: #10b981;
        color: white;
        padding: 0.25rem 0.5rem;
        border-radius: 0.25rem;
        font-size: 0.75rem;
        font-weight: bold;
    }
</style>

<script>
    // Mobile Menu Functionality
    const mobileMenuButton = document.getElementById('mobileMenuButton');
    const closeMobileMenu = document.getElementById('closeMobileMenu');
    const mobileMenu = document.getElementById('mobileMenu');

    if (mobileMenuButton && closeMobileMenu && mobileMenu) {
        mobileMenuButton.addEventListener('click', () => {
            mobileMenu.classList.remove('-translate-x-full');
        });

        closeMobileMenu.addEventListener('click', () => {
            mobileMenu.classList.add('-translate-x-full');
        });

        // Close menu when a link is clicked
        mobileMenu.querySelectorAll('a').forEach(link => {
            link.addEventListener('click', () => {
                mobileMenu.classList.add('-translate-x-full');
            });
        });
    }
</script>

</body>
</html>

<!-- Question Bank Modal -->
<div class="fixed inset-0 bg-gray-900 bg-opacity-70 hidden items-center justify-center z-50 transition-opacity duration-300" id="questionBankModal">
    <div class="bg-white modal-content max-w-5xl w-full mx-4 max-h-[90vh] flex flex-col">
        <div class="modal-header flex justify-between items-center p-6 bg-gray-50 border-b border-gray-200 rounded-t-xl">
            <h5 class="text-2xl font-bold text-gray-800">Select Questions from Bank</h5>
            <button type="button" class="text-gray-400 hover:text-gray-700 transition" onclick="closeQuestionBank()">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>
        <div class="modal-body p-6 overflow-y-auto flex-grow">
            <!-- Question filters -->
            <div class="mb-4 p-4 bg-white rounded-lg border border-gray-200 shadow-sm sticky top-0 z-10">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <select class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="qb_type_filter">
                        <option value="">All Types</option>
                        <option value="mcq_single">MCQ Single</option>
                        <option value="mcq_multiple">MCQ Multiple</option>
                        <option value="true_false">True/False</option>
                        <option value="essay">Essay</option>
                        <option value="short_answer">Short Answer</option>
                        <option value="matching">Matching</option>
                        <option value="code">Code</option>
                        <option value="fill_blanks">Fill Blanks</option>
                    </select>
                    <select class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" id="qb_difficulty_filter">
                        <option value="">All Difficulties</option>
                        <option value="easy">Easy</option>
                        <option value="medium">Medium</option>
                        <option value="hard">Hard</option>
                    </select>
                    <input type="text" class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 md:col-span-2" id="qb_search" placeholder="Search questions by title or content...">
                </div>
            </div>

            <!-- Questions list -->
            <div class="question-bank-list p-2">
                <!-- Questions will be loaded here -->
            </div>
            <div id="no-questions-message" class="hidden text-center text-gray-500 p-8">
                No questions match your filter criteria.
            </div>
        </div>
        <div class="modal-footer flex justify-end p-4 border-t border-gray-200 bg-gray-50 rounded-b-xl">
            <button type="button" class="bg-gray-500 text-white px-5 py-2 rounded-lg hover:bg-gray-600 transition duration-150 font-medium" onclick="closeQuestionBank()">Close</button>
        </div>
    </div>
</div>

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

<div id="custom-modal" class="fixed inset-0 bg-gray-900 bg-opacity-70 hidden items-center justify-center z-[60]">
    <div class="bg-white rounded-xl p-6 shadow-2xl max-w-md w-full mx-4">
        <h3 class="text-xl font-bold mb-4 text-red-600" id="modal-title"></h3>
        <p class="text-gray-700 mb-6" id="modal-body-text"></p>
        <div class="flex justify-end">
            <button class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition" onclick="closeCustomModal()">OK</button>
        </div>
    </div>
</div>

<script>
// --- Data and State ---
let selectedQuestions = <?php echo json_encode($selectedQuestions); ?>;
let totalPoints = <?php echo $exam['total_points']; ?>;

// --- Utility Functions ---

// Custom Modal (replaces alert/confirm)
function showCustomModal(title, message) {
    document.getElementById('modal-title').textContent = title;
    document.getElementById('modal-body-text').textContent = message;
    document.getElementById('custom-modal').classList.remove('hidden');
    document.getElementById('custom-modal').classList.add('flex');
}

function closeCustomModal() {
    document.getElementById('custom-modal').classList.add('hidden');
    document.getElementById('custom-modal').classList.remove('flex');
}

// Toast Notification
function showToast(message, type = 'info') {
    const container = document.getElementById('toast-container');
    const toast = document.createElement('div');
    toast.classList.add('toast', `toast-${type}`);
    toast.textContent = message;
    container.appendChild(toast);

    // Show
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);

    // Hide and remove after 3 seconds
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            container.removeChild(toast);
        }, 300);
    }, 3000);
}

// Question Bank Modal
function openQuestionBank() {
    document.getElementById('questionBankModal').classList.remove('hidden');
    document.getElementById('questionBankModal').classList.add('flex');
    loadQuestionBank();
}

function closeQuestionBank() {
    document.getElementById('questionBankModal').classList.add('hidden');
    document.getElementById('questionBankModal').classList.remove('flex');
}

let allQuestions = []; // Store all loaded questions

function loadQuestionBank() {
    const typeFilter = document.getElementById('qb_type_filter').value;
    const difficultyFilter = document.getElementById('qb_difficulty_filter').value;
    const searchTerm = document.getElementById('qb_search').value;

    let url = '../../api/questions/index.php?limit=100';
    if (typeFilter) url += '&type=' + encodeURIComponent(typeFilter);
    if (difficultyFilter) url += '&difficulty=' + encodeURIComponent(difficultyFilter);
    if (searchTerm) url += '&search=' + encodeURIComponent(searchTerm);

    fetch(url)
        .then(response => response.json())
        .then(data => {
            allQuestions = data.data || [];
            renderQuestionBank();
        })
        .catch(error => {
            console.error('Error loading questions:', error);
        });
}

function getDifficultyClass(difficulty) {
    switch(difficulty) {
        case 'easy': return 'bg-green-100 text-green-800';
        case 'medium': return 'bg-yellow-100 text-yellow-800';
        case 'hard': return 'bg-red-100 text-red-800';
        default: return 'bg-gray-100 text-gray-800';
    }
}

function renderQuestionBank() {
    const listContainer = document.querySelector('.question-bank-list');
    listContainer.innerHTML = '';
    const noQuestionsMessage = document.getElementById('no-questions-message');

    let questionsFound = 0;

    allQuestions.forEach(q => {
        questionsFound++;
        const isSelected = selectedQuestions.some(sq => sq.id == q.id);
        const difficultyClass = getDifficultyClass(q.difficulty);

        const questionItem = document.createElement('div');
        questionItem.classList.add('question-item');
        questionItem.setAttribute('data-type', q.question_type);
        questionItem.setAttribute('data-difficulty', q.difficulty);
        questionItem.setAttribute('data-id', q.id);

        questionItem.innerHTML = `
            <div class="question-info">
                <div class="question-title">${q.title}</div>
                <div class="question-meta">${q.question_type.replace(/_/g, ' ').toUpperCase()} ${q.difficulty.toUpperCase()} ${q.points} pts ${q.category_name ? `Category: ${q.category_name}` : ''}</div>
            </div>
            <div class="question-action">
                ${isSelected ? `<span class="added-indicator">ADDED</span>` : `<button class="add-question-btn btn btn-primary btn-sm" data-id="${q.id}" data-title="${q.title}" data-points="${q.points}">Add</button>`}
            </div>
        `;
        listContainer.appendChild(questionItem);
    });

    if (questionsFound === 0) {
        noQuestionsMessage.classList.remove('hidden');
    } else {
        noQuestionsMessage.classList.add('hidden');
    }
}

// --- Question Selection Logic ---

// Add question to exam
document.addEventListener('click', function(e) {
    const btn = e.target.closest('.add-question-btn');
    if (btn) {
        const questionId = parseInt(btn.dataset.id);
        const title = btn.dataset.title;
        const points = parseFloat(btn.dataset.points);

        // Check if already selected
        if (selectedQuestions.some(q => q.id === questionId)) {
            showToast('Question already added.', 'error');
            return;
        }

        // Add to selected questions
        selectedQuestions.push({
            id: questionId,
            title: title,
            exam_points: points,
            sort_order: selectedQuestions.length + 1
        });

        totalPoints += points;
        updateStateAndUI();

        // Re-render bank to show it's added
        renderQuestionBank();
    }
});

// Update selected questions display
function updateSelectedQuestions() {
    const container = document.getElementById('selected_questions');

    if (selectedQuestions.length === 0) {
        container.innerHTML = '<p class="text-gray-500">No questions selected yet.</p>';
        return;
    }

    let html = '<div class="selected-questions-list">';
    html += '<h6 class="font-semibold text-gray-800 mb-3">Selected Questions (' + selectedQuestions.length + ')</h6>';

    selectedQuestions.forEach((question, index) => {
        html += `
            <div class="question-order-item flex justify-between items-center p-3 bg-gray-50 border border-gray-200 rounded-lg mb-2">
                <div class="flex-grow">
                    <span class="font-bold text-blue-600">${index + 1}.</span> ${question.title}
                    <small class="text-gray-500 ml-2">(${question.exam_points} pts)</small>
                    <input type="hidden" name="question_ids[]" value="${question.id}">
                    <input type="hidden" name="question_orders[]" value="${index + 1}">
                    <input type="hidden" name="question_points[]" value="${question.exam_points}">
                </div>
                <button type="button" class="bg-red-500 text-white px-2 py-1 rounded hover:bg-red-600 transition duration-150" onclick="removeQuestion(${index})">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        `;
    });

    html += '</div>';
    container.innerHTML = html;
}

// Remove question from exam
function removeQuestion(index) {
    const removedQuestion = selectedQuestions.splice(index, 1)[0];
    totalPoints -= removedQuestion.exam_points;

    // Reorder remaining questions
    selectedQuestions.forEach((q, i) => {
        q.sort_order = i + 1;
    });

    updateStateAndUI();

    // Re-render bank to show button again
    renderQuestionBank();

    showToast(`Removed: ${removedQuestion.title}`, 'error');
}

// Update total points display
function updateTotalPoints() {
    document.getElementById('total_points').value = totalPoints;
}

function updateStateAndUI() {
    updateSelectedQuestions();
    updateTotalPoints();
}

// Question bank filtering
document.getElementById('qb_type_filter').addEventListener('change', loadQuestionBank);
document.getElementById('qb_difficulty_filter').addEventListener('change', loadQuestionBank);
document.getElementById('qb_search').addEventListener('input', loadQuestionBank);

function previewExam() {
    if (selectedQuestions.length === 0) {
        showCustomModal('Warning', 'Please add at least one question to preview the exam structure.');
        return;
    }

    const title = document.getElementById('title').value;
    const timeLimit = document.getElementById('time_limit').value || 'No limit';
    const totalQ = selectedQuestions.length;

    let previewHtml = `
        <h3 class="font-bold text-2xl mb-4 text-center">${title}</h3>
        <p class="text-lg mb-6 text-center text-gray-600">Total Questions: ${totalQ} | Total Points: ${totalPoints} | Time Limit: ${timeLimit} minutes</p>
        <div class="space-y-6 max-h-96 overflow-y-auto p-3 border rounded-lg bg-gray-50">
    `;

    selectedQuestions.forEach((q, index) => {
        const difficultyClass = getDifficultyClass('medium'); // Default for preview

        previewHtml += `
            <div class="p-4 bg-white shadow-md rounded-lg border border-gray-200">
                <div class="flex justify-between items-center mb-2">
                    <p class="font-bold text-gray-800">Question ${index + 1}: ${q.title}</p>
                    <span class="text-sm font-semibold text-blue-600">${q.exam_points} pts</span>
                </div>
                <div class="flex space-x-3 text-sm text-gray-500">
                    <span class="px-2 py-0.5 bg-gray-200 rounded">QUESTION TYPE</span>
                    <span class="px-2 py-0.5 ${difficultyClass} rounded">DIFFICULTY</span>
                </div>
                <p class="mt-3 italic text-gray-600">
                    [Placeholder for question content / multiple-choice options]
                </p>
            </div>
        `;
    });

    previewHtml += '</div>';

    // Show a more detailed preview in a custom modal
    const previewModal = document.getElementById('custom-modal');
    document.getElementById('modal-title').textContent = 'Exam Preview Structure';
    document.getElementById('modal-body-text').innerHTML = previewHtml;
    previewModal.classList.remove('hidden');
    previewModal.classList.add('flex');
}

// Sidebar toggle functionality
document.getElementById('sidebar-toggle').addEventListener('click', function() {
    document.querySelector('.admin-container').classList.toggle('sidebar-open');
});

document.getElementById('sidebar-overlay').addEventListener('click', function() {
    document.querySelector('.admin-container').classList.remove('sidebar-open');
});

// Initialize
updateSelectedQuestions();
updateTotalPoints();
</script>

<style>
/* Custom styles for Edit Exam page - similar to new.php */
.admin-container {
    display: flex;
    min-height: 100vh;
    background: #f3f4f6;
}

.admin-sidebar {
    width: 280px;
    background: #1f2937;
    color: white;
    flex-shrink: 0;
    min-height: 100vh;
    overflow-y: auto;
    box-shadow: 4px 0 15px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.sidebar-header {
    padding: 2rem 1.5rem;
    border-bottom: 1px solid #374151;
    text-align: center;
}

.sidebar-header h2 {
    font-size: 1.5rem;
    font-weight: 800;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    color: #60a5fa;
}

.sidebar-header p {
    color: #9ca3af;
}

.sidebar-nav ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.sidebar-nav li a {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 1rem 1.5rem;
    color: #cbd5e1;
    text-decoration: none;
    transition: all 0.3s ease;
    font-weight: 500;
    border-left: 3px solid transparent;
}

.sidebar-nav li a:hover,
.sidebar-nav li a.active {
    background: #374151;
    color: white;
    border-left-color: #3b82f6;
    transform: translateX(5px);
}

.admin-main {
    flex: 1;
    min-height: 100vh;
}

.admin-header {
    background: white;
    padding: 2rem;
    border-bottom: 1px solid #e5e7eb;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    position: sticky;
    top: 0;
    z-index: 1001;
}

.admin-header h1 {
    font-size: 2rem;
    font-weight: 800;
    color: #1f2937;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.admin-content {
    padding: 2rem;
}

.question-form-layout {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 2rem;
    align-items: start;
}

.question-main-form {
    display: flex;
    flex-direction: column;
    gap: 2rem;
}

.question-settings-sidebar {
    position: sticky;
    top: 2rem;
}

.form-card {
    background: white;
    border-radius: 1rem;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.8);
    overflow: hidden;
}

.form-card-header {
    padding: 2rem;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    border-bottom: 1px solid #e5e7eb;
}

.form-card-header h3 {
    font-size: 1.25rem;
    font-weight: 700;
    color: #1f2937;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.form-card-header p {
    color: #64748b;
    margin: 0;
    font-size: 0.9rem;
}

.form-card-body {
    padding: 2rem;
}

.form-control, .form-select {
    width: 100%;
    padding: 0.75rem 1rem;
    border: 2px solid #e5e7eb;
    border-radius: 0.75rem;
    font-size: 0.875rem;
    transition: all 0.3s ease;
    background: white;
}

.form-control:focus, .form-select:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    font-weight: 600;
    text-decoration: none;
    border-radius: 0.75rem;
    border: none;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 0.875rem;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
}

.btn-outline-primary {
    background: transparent;
    border: 2px solid #667eea;
    color: #667eea;
}

.btn-outline-primary:hover {
    background: #667eea;
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.btn-outline-info {
    background: transparent;
    border: 2px solid #3b82f6;
    color: #3b82f6;
}

.btn-outline-info:hover {
    background: #3b82f6;
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
}

.btn-outline-secondary {
    background: transparent;
    border: 2px solid #6b7280;
    color: #6b7280;
}

.btn-outline-secondary:hover {
    background: #6b7280;
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(107, 114, 128, 0.3);
}

.btn-lg {
    padding: 0.875rem 2rem;
    font-size: 1rem;
}

.form-actions-card {
    background: white;
    border-radius: 1rem;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.8);
    overflow: hidden;
}

.form-actions {
    padding: 2rem;
    display: flex;
    gap: 1rem;
    justify-content: center;
    flex-wrap: wrap;
}

.btn-sm {
    padding: 0.5rem 1rem;
    font-size: 0.8rem;
}

.text-danger {
    color: #dc2626 !important;
}

.text-muted {
    color: #64748b !important;
}

.question-bank-list {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #e5e7eb;
    border-radius: 0.75rem;
    background: #ffffff;
}

/* Toast Notification Styles */
#toast-container {
    position: fixed;
    top: 1.5rem;
    right: 1.5rem;
    z-index: 100;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    max-width: 350px;
}

.toast {
    padding: 1rem 1.5rem;
    border-radius: 0.5rem;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    color: white;
    opacity: 0;
    transform: translateX(100%);
    transition: opacity 0.3s ease-out, transform 0.3s ease-out;
}

.toast.show {
    opacity: 1;
    transform: translateX(0);
}

.toast-success { background-color: #10b981; }
.toast-error { background-color: #ef4444; }

.question-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 1.5rem;
    border-bottom: 1px solid #e5e7eb;
    transition: all 0.3s ease;
}

.question-item:hover {
    background: white;
    transform: translateX(5px);
}

.question-item:last-child {
    border-bottom: none;
}

.selected-questions-list {
    margin-top: 1rem;
}

.question-order-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem;
    background: #f8fafc;
    border: 1px solid #e5e7eb;
    border-radius: 0.75rem;
    margin-bottom: 0.5rem;
}

.modal-content {
    border-radius: 1rem;
    border: none;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.modal-header {
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    border-radius: 1rem 1rem 0 0;
    border-bottom: 1px solid #e5e7eb;
    padding: 1.5rem 2rem;
}

.modal-body {
    padding: 2rem;
}

/* Responsive Design */
@media (max-width: 1024px) {
    .admin-sidebar {
        display: none;
    }

    .admin-container.sidebar-open .admin-sidebar {
        display: block;
        position: fixed;
        top: 0;
        left: 0;
        height: 100vh;
        width: 280px;
        z-index: 1001;
    }

    .question-form-layout {
        grid-template-columns: 1fr;
        gap: 1.5rem;
    }

    .question-settings-sidebar {
        position: static;
    }

    .form-card-body {
        padding: 1.5rem;
    }

    .form-actions {
        flex-direction: column;
    }

    .btn {
        justify-content: center;
    }
}

@media (max-width: 768px) {
    .admin-header {
        padding: 1.5rem;
    }

    .admin-header h1 {
        font-size: 1.5rem;
    }

    .admin-content {
        padding: 1rem;
    }

    .form-card-header {
        padding: 1.5rem;
    }

    .form-card-body {
        padding: 1.5rem;
    }

    .form-actions {
        padding: 1.5rem;
    }
}

.sidebar-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 999;
}

.sidebar-toggle-btn {
    display: none;
    background: none;
    border: none;
    color: #6b7280;
    font-size: 1.25rem;
    padding: 0.5rem;
    margin-right: 1rem;
    border-radius: 0.5rem;
    transition: all 0.3s ease;
    cursor: pointer;
}

.sidebar-toggle-btn:hover {
    background: #f3f4f6;
    color: #374151;
}

@media (max-width: 1024px) {
    .sidebar-toggle-btn {
        display: block;
    }

    .admin-container.sidebar-open .sidebar-overlay {
        display: block;
    }
}
</style>