<?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 courses and questions for dropdowns
$courses = $db->prepare("SELECT id, title FROM courses WHERE instructor_id = ? ORDER BY title", [$userId])->fetchAll();

// Questions will be loaded via API

$page_title = 'Create Exam - ' . $lms_config['lms']['site_name'];
?>
<!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 CDN -->
    <script src="https://cdn.tailwindcss.com"></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>
        /* Custom Tailwind Configuration and Base Styles */
        :root {
            --primary: #2563eb; /* Blue-700 */
            --secondary: #6c757d; /* Gray */
            --success: #10b981; /* Green-500 */
            --danger: #ef4444; /* Red-500 */
            --info: #06b6d4; /* Cyan-500 */
        }
        .text-primary { color: var(--primary); }
        .bg-primary { background-color: var(--primary); }
        .bg-success { background-color: var(--success); }
        .bg-secondary { background-color: var(--secondary); }

        /* Ensure smooth scrolling and font */
        body { font-family: 'Inter', sans-serif; background-color: #f3f4f6; }


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

        /* Form Styles */
        .form-card {
            background: white;
            border-radius: 0.75rem;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

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

        .question-item {
            display: flex;
            flex-direction: column;
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #e5e7eb;
            transition: all 0.3s ease;
        }

        .question-item:hover {
            background: #f9fafb;
            cursor: pointer;
        }

        .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: #ffffff;
            border: 1px solid #d1d5db;
            border-radius: 0.5rem;
            margin-bottom: 0.5rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
        }

        .modal-content {
            border-radius: 1rem;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }
    </style>
</head>
<body class="antialiased">

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


<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="bg-white shadow-xl rounded-lg p-6 form-card">
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-3xl font-bold text-gray-900">Create Exam</h1>
            <a href="index.php" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 transition">
                <i class="fas fa-arrow-left mr-2"></i>Back to Exams
            </a>
        </div>

        <form id="examForm" method="POST" action="save.php" class="space-y-6">
            <!-- Basic Information -->
            <div class="bg-blue-50 p-6 rounded-xl border border-blue-200">
                <h2 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                    <i class="fas fa-info-circle mr-3 text-blue-600"></i>Exam Information
                </h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                        <label for="title" class="block text-sm font-medium text-gray-700 mb-1">Exam Title <span class="text-red-500">*</span></label>
                        <input type="text" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" id="title" name="title" required placeholder="Enter exam title">
                    </div>
                    <div>
                        <label for="exam_type" class="block text-sm font-medium text-gray-700 mb-1">Exam Type</label>
                        <select class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" id="exam_type" name="exam_type">
                            <option value="quiz">Quiz</option>
                            <option value="midterm">Midterm</option>
                            <option value="final">Final</option>
                            <option value="practice">Practice</option>
                            <option value="certification">Certification</option>
                        </select>
                    </div>
                </div>

                <div class="mb-4">
                    <label for="description" class="block text-sm font-medium text-gray-700 mb-1">Description</label>
                    <textarea class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" id="description" name="description" rows="3" placeholder="Describe the exam purpose and instructions"></textarea>
                </div>

                <div class="mb-4">
                    <label for="instructions" class="block text-sm font-medium text-gray-700 mb-1">Instructions for Students</label>
                    <textarea class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" id="instructions" name="instructions" rows="4" placeholder="Special instructions, rules, or guidelines for students"></textarea>
                </div>
            </div>

            <!-- Question Selection -->
            <div class="bg-green-50 p-6 rounded-xl border border-green-200">
                <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-4">
                    <h2 class="text-xl font-semibold text-gray-800 flex items-center mb-3 sm:mb-0">
                        <i class="fas fa-question-circle mr-3 text-green-600"></i>Question Selection
                    </h2>
                    <button type="button" class="bg-green-600 text-white px-5 py-2 rounded-lg hover:bg-green-700 transition duration-150 flex items-center font-medium" onclick="openQuestionBank()">
                        <i class="fas fa-plus mr-2"></i>Add Questions
                    </button>
                </div>
                <div id="selected_questions" class="mb-6 bg-white p-4 rounded-lg border border-gray-200 min-h-[5rem]">
                    <p class="text-gray-500 text-center py-4">No questions selected yet. Click "Add Questions" to choose from your question bank.</p>
                </div>

                <!-- Question sorting and organization -->
                <div class="p-4 bg-white rounded-lg border border-gray-200">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Question Presentation</label>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="flex items-center">
                            <input class="mr-2 h-4 w-4 text-green-600 border-gray-300 rounded focus:ring-green-500" type="checkbox" id="shuffle_questions" name="shuffle_questions" checked>
                            <label class="text-sm text-gray-700" for="shuffle_questions">Shuffle question order for each student</label>
                        </div>
                        <div class="flex items-center">
                            <input class="mr-2 h-4 w-4 text-green-600 border-gray-300 rounded focus:ring-green-500" type="checkbox" id="shuffle_options" name="shuffle_options" checked>
                            <label class="text-sm text-gray-700" for="shuffle_options">Shuffle answer options (for MCQs)</label>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Timing & Scoring -->
            <div class="bg-yellow-50 p-6 rounded-xl border border-yellow-200">
                <h2 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                    <i class="fas fa-clock mr-3 text-yellow-600"></i>Timing & Scoring
                </h2>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div class="md:col-span-1">
                        <label for="time_limit" class="block text-sm font-medium text-gray-700 mb-1">Time Limit (minutes)</label>
                        <input type="number" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-yellow-500" id="time_limit" name="time_limit" min="0" placeholder="e.g. 60">
                        <p class="text-xs text-gray-500 mt-1">Total time allowed</p>
                    </div>

                    <div class="md:col-span-1">
                        <label for="passing_score" class="block text-sm font-medium text-gray-700 mb-1">Passing Score (%)</label>
                        <input type="number" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-yellow-500" id="passing_score" name="passing_score" min="0" max="100" value="70">
                    </div>

                    <div class="md:col-span-1">
                        <label for="max_attempts" class="block text-sm font-medium text-gray-700 mb-1">Maximum Attempts</label>
                        <input type="number" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-yellow-500" id="max_attempts" name="max_attempts" min="1" value="2">
                    </div>

                    <div class="md:col-span-1">
                        <label for="total_points" class="block text-sm font-medium text-gray-700 mb-1">Total Points</label>
                        <input type="number" class="w-full border border-gray-300 rounded-lg px-3 py-2 bg-gray-100 font-bold text-lg text-blue-800" id="total_points" name="total_points" readonly value="0">
                        <p class="text-xs text-gray-500 mt-1">Calculated from selected questions</p>
                    </div>
                </div>
            </div>

            <!-- Access Control -->
            <div class="bg-indigo-50 p-6 rounded-xl border border-indigo-200">
                <h2 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                    <i class="fas fa-lock mr-3 text-indigo-600"></i>Access & Scheduling
                </h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label for="course_id" class="block text-sm font-medium text-gray-700 mb-1">Associated Course</label>
                        <select class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-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 htmlspecialchars($course['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="md:col-span-1">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Availability Schedule</label>
                        <div class="grid grid-cols-2 gap-2">
                            <input type="datetime-local" class="border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm" id="start_date" name="start_date">
                            <input type="datetime-local" class="border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm" id="end_date" name="end_date">
                        </div>
                        <p class="text-xs text-gray-500 mt-1">Start date (Optional) / End date (Optional)</p>
                    </div>
                </div>
            </div>

            <!-- Security & Behavior -->
            <div class="bg-red-50 p-6 rounded-xl border border-red-200">
                <h2 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                    <i class="fas fa-shield-alt mr-3 text-red-600"></i>Security & Feedback
                </h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="flex items-center">
                        <input class="mr-2 h-4 w-4 text-red-600 border-gray-300 rounded focus:ring-red-500" type="checkbox" id="is_proctored" name="is_proctored">
                        <label class="text-sm font-medium text-gray-700" for="is_proctored">Enable proctoring (Camera/Screen)</label>
                    </div>

                    <div class="flex items-center">
                        <input class="mr-2 h-4 w-4 text-red-600 border-gray-300 rounded focus:ring-red-500" type="checkbox" id="show_results" name="show_results" checked>
                        <label class="text-sm font-medium text-gray-700" for="show_results">Show results/score immediately after completion</label>
                    </div>

                    <div class="flex items-center">
                        <input class="mr-2 h-4 w-4 text-red-600 border-gray-300 rounded focus:ring-red-500" type="checkbox" id="show_answers" name="show_answers">
                        <label class="text-sm font-medium text-gray-700" for="show_answers">Show correct answers upon completion</label>
                    </div>

                    <div class="flex items-center">
                        <input class="mr-2 h-4 w-4 text-red-600 border-gray-300 rounded focus:ring-red-500" type="checkbox" id="allow_review" name="allow_review" checked>
                        <label class="text-sm font-medium text-gray-700" for="allow_review">Allow review of submitted answers</label>
                    </div>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="pt-4 flex justify-end space-x-4">
                <button type="submit" name="action" value="save_draft" class="bg-gray-500 text-white px-6 py-3 rounded-lg hover:bg-gray-600 transition font-medium shadow-md">
                    <i class="fas fa-save mr-2"></i>Save as Draft
                </button>
                <button type="submit" name="action" value="publish" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition font-medium shadow-md">
                    <i class="fas fa-globe mr-2"></i>Publish Exam
                </button>
                <button type="button" class="bg-cyan-600 text-white px-6 py-3 rounded-lg hover:bg-cyan-700 transition font-medium shadow-md" onclick="previewExam()">
                    <i class="fas fa-eye mr-2"></i>Preview Exam
                </button>
            </div>
        </form>
    </div>
</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>

<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 = [];
let totalPoints = 0;
let allQuestions = []; // Store all questions from API

// --- 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 Logic ---

async function openQuestionBank() {
    document.getElementById('questionBankModal').classList.remove('hidden');
    document.getElementById('questionBankModal').classList.add('flex');
    await loadQuestions(); // Load questions first
    renderQuestionBank(); // Then render
}

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

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';
    }
}

async function loadQuestions() {
    if (allQuestions.length > 0) return; // Already loaded

    try {
        const response = await fetch('../../api/questions/index.php', {
            credentials: 'include'
        });
        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`Failed to load questions: ${response.status} ${response.statusText} - ${errorText}`);
        }
        const data = await response.json();
        allQuestions = data.data || [];
    } catch (error) {
        console.error('Error loading questions:', error);
        showToast(`Failed to load questions: ${error.message}`, 'error');
    }
}

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

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

    // Filter questions
    const filteredQuestions = allQuestions.filter(question => {
        const typeMatch = !typeFilter || question.question_type === typeFilter;
        const difficultyMatch = !difficultyFilter || question.difficulty === difficultyFilter;
        const searchMatch = !searchTerm || question.title.toLowerCase().includes(searchTerm);
        return typeMatch && difficultyMatch && searchMatch;
    });

    // Clear existing questions
    listContainer.innerHTML = '';

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

    // Render filtered questions
    filteredQuestions.forEach(question => {
        const isSelected = selectedQuestions.some(sq => sq.id == question.id);
        const difficultyClass = getDifficultyClass(question.difficulty);

        const questionHtml = `
            <div class="question-item" data-type="${question.question_type}" data-difficulty="${question.difficulty}" data-id="${question.id}">
                <div class="flex justify-between items-start w-full">
                    <div class="flex-grow">
                        <h6 class="font-semibold text-gray-800 mb-1">${question.title}</h6>
                        <div class="flex items-center space-x-2 mt-1">
                            <span class="px-2 py-1 bg-gray-200 text-gray-700 rounded-full text-xs font-medium">${question.question_type.replace('_', ' ').toUpperCase()}</span>
                            <span class="px-2 py-1 ${difficultyClass} rounded-full text-xs font-medium">${question.difficulty.toUpperCase()}</span>
                            <small class="text-gray-500 font-medium">${question.points} pts</small>
                            ${question.category_name ? `<small class="text-gray-500 ml-2 italic">Category: ${question.category_name}</small>` : ''}
                        </div>
                    </div>
                    <button type="button" class="bg-blue-500 text-white px-3 py-1 rounded-lg hover:bg-blue-600 transition duration-150 text-sm add-question-btn shrink-0 shadow-md ${isSelected ? 'hidden' : ''}"
                            data-id="${question.id}"
                            data-title="${question.title}"
                            data-points="${question.points}">
                        <i class="fas fa-plus mr-1"></i> Add
                    </button>
                    ${isSelected ? '<span class="text-green-600 font-bold ml-4"><i class="fas fa-check-circle"></i> ADDED</span>' : ''}
                </div>
            </div>
        `;
        listContainer.insertAdjacentHTML('beforeend', questionHtml);
    });
}

document.getElementById('qb_type_filter').addEventListener('change', renderQuestionBank);
document.getElementById('qb_difficulty_filter').addEventListener('change', renderQuestionBank);
document.getElementById('qb_search').addEventListener('input', renderQuestionBank);

// --- 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,
            points: points,
            order: selectedQuestions.length + 1
        });

        totalPoints += points;
        updateStateAndUI();

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

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

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

    updateStateAndUI();

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

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

function updateSelectedQuestions() {
    const container = document.getElementById('selected_questions');

    if (selectedQuestions.length === 0) {
        container.innerHTML = '<p class="text-gray-500 text-center py-4">No questions selected yet. Click "Add Questions" to choose from your question bank.</p>';
        return;
    }

    let html = '';
    html += '<h3 class="font-bold text-lg text-gray-800 mb-3 border-b pb-2">Exam Questions (<span class="text-blue-600">' + selectedQuestions.length + '</span> Questions)</h3>';

    selectedQuestions.forEach((question, index) => {
        html += `
            <div class="question-order-item bg-white shadow-md">
                <div class="flex-grow flex items-center">
                    <span class="font-extrabold text-xl text-blue-600 mr-4 w-6 text-right">${index + 1}.</span>
                    <div>
                        <span class="text-gray-800 font-medium">${question.title}</span>
                        <small class="text-gray-500 ml-3">(${question.points} pts)</small>
                        <!-- Hidden inputs for form submission -->
                        <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.points}">
                    </div>
                </div>
                <button type="button" class="bg-red-500 text-white w-8 h-8 rounded-full hover:bg-red-600 transition duration-150 flex items-center justify-center shadow-lg" title="Remove Question" onclick="removeQuestion(${index})">
                    <i class="fas fa-trash-alt text-sm"></i>
                </button>
            </div>
        `;
    });

    container.innerHTML = html;
}

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

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

// --- Exam Preview Function ---

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.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');
}

// Initial update on load (in case of pre-selected questions, though none here)
document.addEventListener('DOMContentLoaded', updateStateAndUI);

</script>
</body>
</html>