let currentExamId = null;
let currentExamData = null;
let examSaved = false;
let currentExamStatus = 'draft';
let currentPreviewVersion = 'student';
let currentGenerationJobId = null;
let generationPollHandle = null;

$('#classSelect, #subjectSelect').on('change', function () {
    loadMaterials();
    loadQuestionBank();
});

$(document).on('click', '.workflow-action-btn', function () {
    runWorkflowAction($(this).data('action'));
});

$(document).on('click', '.insert-bank-question', function () {
    const encoded = $(this).data('question');
    insertQuestionFromBank(encoded);
});

$(document).on('click', '.regenerate-section-btn', function () {
    regeneratePart('section', $(this).data('section-index'));
});

$(document).on('click', '.regenerate-question-btn', function () {
    regeneratePart('question', $(this).data('section-index'), $(this).data('question-index'));
});

function showStatus(type, message, details = []) {
    const items = details.length ? '<ul class="mb-0 mt-2">' + details.map((detail) => '<li>' + escapeHtml(detail) + '</li>').join('') + '</ul>' : '';
    $('#generatorStatus').html('<div class="alert alert-' + type + '">' + escapeHtml(message) + items + '</div>');
}

function clearStatus() {
    $('#generatorStatus').html('');
}

function setOutputButtonsDisabled(disabled) {
    $("#downloadPdfBtn").prop("disabled", disabled);
    $("#teacherPdfBtn").prop("disabled", disabled);
    $("#printExamBtn").prop("disabled", disabled);
}

function loadMaterials() {
    const className = $('#classSelect').val();
    const subjectId = $('#subjectSelect').val();
    if (!className || !subjectId) {
        $('#materialsList').html('<div class="col-12"><div class="alert alert-info">Select a class and subject to view materials.</div></div>');
        return;
    }

    $.ajax({
        url: 'ajax/get_learning_materials.php',
        type: 'POST',
        data: { class: className, subject: subjectId },
        success: function(response) { $('#materialsList').html(response); },
        error: function() { $('#materialsList').html('<div class="col-12"><div class="alert alert-danger">Error loading materials</div></div>'); }
    });
}

function loadQuestionBank() {
    const className = $('#classSelect').val();
    const subjectId = $('#subjectSelect').val();
    if (!className || !subjectId) {
        $('#questionBankPanel').html('<div class="alert alert-info">Select a class and subject to load the question bank.</div>');
        return;
    }

    $.ajax({
        url: 'ajax/get_question_bank.php',
        type: 'POST',
        data: { class: className, subject: subjectId },
        success: function (response) { $('#questionBankPanel').html(response); },
        error: function () { $('#questionBankPanel').html('<div class="alert alert-danger">Could not load question bank.</div>'); }
    });
}

function getSelectedMaterials() {
    return $('input[name="materials[]"]:checked').map(function() { return $(this).val(); }).get().join(',');
}

function updateWorkflowPanel(html, status) {
    $('#workflowPanel').html(html || '');
    currentExamStatus = status || currentExamStatus;
}

function updateLoadingOverlay(title, message) {
    $('#generationOverlayTitle').text(title || 'AI is generating your exam paper...');
    $('#generationOverlayMessage').text(message || 'This may take 30-60 seconds. Status updates will appear automatically.');
}

function clearGenerationPolling() {
    if (generationPollHandle) {
        clearTimeout(generationPollHandle);
        generationPollHandle = null;
    }
}

function formatJobDetails(response) {
    const details = Array.isArray(response.details) ? response.details.slice() : [];
    if (response.attempts) {
        details.push('Attempt ' + response.attempts + ' of ' + (response.max_attempts || response.attempts));
    }
    (response.logs || []).slice(-3).forEach(function(log) {
        if (log && log.message) {
            details.push(log.message);
        }
    });
    return details;
}

function applyCompletedGeneration(response) {
    clearGenerationPolling();
    currentGenerationJobId = null;
    $('#loadingOverlay').fadeOut(300);
    currentExamId = response.exam_id;
    currentExamData = response.exam_data;
    currentExamStatus = response.status || 'draft';
    currentPreviewVersion = 'student';
    $('#generatorBadge').text('Generator: ' + (response.generator || 'unknown'));
    renderEditor(response.exam_data);
    updateWorkflowPanel(response.workflow_html, response.status);
    $('#examPreview').html(buildPreviewHtml(response.exam_data || currentExamData));
    $('#previewSection').fadeIn(300);
    loadQuestionBank();
    if (response.warnings && response.warnings.length) {
        showStatus('warning', 'Exam generated with warnings.', response.warnings);
    } else {
        showStatus('success', response.message || 'Exam generated. Save the draft, then move it through review, approval, or bank reuse.');
    }
    $('html, body').animate({ scrollTop: $('#previewSection').offset().top - 100 }, 500);
}

function pollGenerationStatus(jobId) {
    clearGenerationPolling();
    currentGenerationJobId = jobId;

    const poll = function() {
        $.ajax({
            url: 'ajax/generation_status.php',
            type: 'GET',
            dataType: 'json',
            data: { job_id: jobId },
            success: function(response) {
                if (response.job_status === 'completed' && response.success) {
                    applyCompletedGeneration(response);
                    return;
                }
                if (response.status === 'failed' || response.success === false) {
                    clearGenerationPolling();
                    currentGenerationJobId = null;
                    $('#loadingOverlay').fadeOut(300);
                    showStatus('danger', response.message || 'Generation failed.', formatJobDetails(response));
                    return;
                }
                updateLoadingOverlay('AI is generating your exam paper...', response.message || 'Generation is running in the background.');
                showStatus(response.status === 'retrying' ? 'warning' : 'info', response.message || 'Generation is in progress.', formatJobDetails(response));
                generationPollHandle = setTimeout(poll, 2500);
            },
            error: function() {
                generationPollHandle = setTimeout(poll, 4000);
            }
        });
    };

    poll();
}

function generateExam() {
    clearStatus();
    clearGenerationPolling();
    currentGenerationJobId = null;
    if (!$('#classSelect').val() || !$('#subjectSelect').val()) {
        showStatus('warning', 'Please select both class and subject.');
        return;
    }

    updateLoadingOverlay('Submitting exam generation request...', 'The request will be queued and processed in the background.');
    $('#loadingOverlay').fadeIn(300);
    $('#previewSection').hide();
    setOutputButtonsDisabled(true);
    examSaved = false;

    $.ajax({
        url: 'ajax/generate_exam.php',
        type: 'POST',
        dataType: 'json',
        timeout: 120000,
        data: {
            action: 'generate',
            class_name: $('#classSelect').val(),
            subject_id: $('#subjectSelect').val(),
            subject_name: $('#subjectSelect option:selected').text(),
            term: $('#termSelect').val(),
            exam_title: $('#examTitle').val(),
            duration: $('#duration').val(),
            total_marks: $('#totalMarks').val(),
            exam_type: $('input[name="examType"]:checked').val(),
            include_objective: $('#formatObjective').is(':checked') ? 'true' : 'false',
            include_subjective: $('#formatSubjective').is(':checked') ? 'true' : 'false',
            include_comprehension: $('#formatComprehension').is(':checked') ? 'true' : 'false',
            obj_count: $('#objCount').val(),
            obj_marks: $('#objMarks').val(),
            subj_count: $('#subjCount').val(),
            subj_marks: $('#subjMarks').val(),
            ai_notes: $('#aiNotes').val(),
            topics: $('#topics').val(),
            sample_questions: $('#sampleQuestions').val(),
            selected_materials: getSelectedMaterials()
        },
        success: function(response) {
            if (!response.success) {
                $('#loadingOverlay').fadeOut(300);
                showStatus('danger', response.message || 'Failed to generate exam.', response.details || []);
                return;
            }
            $('#generatorBadge').text('Generator: queued');
            showStatus('info', response.message || 'Generation queued.', formatJobDetails(response));
            pollGenerationStatus(response.job_id);
        },
        error: function(xhr) {
            $('#loadingOverlay').fadeOut(300);
            console.error(xhr.responseText);
            showStatus('danger', 'Failed to queue exam generation.');
        }
    });
}

function renderEditor(exam) {
    currentExamData = exam;
    $('#editorExamTitle').val($('#examTitle').val() || exam.title || '');
    $('#editorDuration').val(parseInt($('#duration').val(), 10) || 60);
    $('#editorTotalMarks').val(parseInt($('#totalMarks').val(), 10) || 100);
    $('#editorInstructions').val(exam.instructions || '');

    let html = '';
    (exam.sections || []).forEach(function(section, sectionIndex) {
        html += '<div class="question-editor" data-section-index="' + sectionIndex + '">';
        html += '<div class="d-flex justify-content-between align-items-center mb-2">';
        html += '<h6 class="mb-0">Section ' + escapeHtml(section.section || String.fromCharCode(65 + sectionIndex)) + '</h6>';
        html += '<button type="button" class="btn btn-sm btn-outline-secondary regenerate-section-btn" data-section-index="' + sectionIndex + '"><i class="fas fa-sync-alt me-1"></i>Regenerate Section</button>';
        html += '</div>';
        html += '<div class="row g-2 mb-2">';
        html += '<div class="col-md-3"><label class="form-label">Section Label</label><input class="form-control section-label" value="' + escapeHtml(section.section || '') + '"></div>';
        html += '<div class="col-md-5"><label class="form-label">Section Title</label><input class="form-control section-title-input" value="' + escapeHtml(section.title || '') + '"></div>';
        html += '<div class="col-md-4"><label class="form-label">Section Type</label><input class="form-control section-type" value="' + escapeHtml(section.type || '') + '" readonly></div>';
        html += '<div class="col-12"><label class="form-label">Section Instructions</label><textarea class="form-control section-instructions" rows="2">' + escapeHtml(section.instructions || '') + '</textarea></div>';
        html += '</div>';
        if (section.type === 'comprehension') {
            html += '<div class="mb-3"><label class="form-label">Passage</label><textarea class="form-control section-passage" rows="4">' + escapeHtml(section.passage || '') + '</textarea></div>';
        }
        (section.questions || []).forEach(function(question, questionIndex) {
            var diagAttr = (question.diagram && question.diagram.type) ? ' data-diagram="' + escapeHtml(JSON.stringify(question.diagram)) + '"' : '';
            html += '<div class="border rounded p-3 mb-3" data-question-index="' + questionIndex + '"' + diagAttr + '>';
            html += '<div class="d-flex justify-content-end mb-2">';
            html += '<button type="button" class="btn btn-sm btn-outline-secondary regenerate-question-btn" data-section-index="' + sectionIndex + '" data-question-index="' + questionIndex + '"><i class="fas fa-rotate me-1"></i>Regenerate Question</button>';
            html += '</div>';
            html += '<div class="row g-2">';
            html += '<div class="col-md-2"><label class="form-label">No.</label><input class="form-control question-number" type="number" value="' + (question.number || (questionIndex + 1)) + '"></div>';
            html += '<div class="col-md-2"><label class="form-label">Marks</label><input class="form-control question-marks" type="number" value="' + (question.marks || 1) + '"></div>';
            html += '<div class="col-md-8"><label class="form-label">Question Text</label><textarea class="form-control question-text" rows="2">' + escapeHtml(question.text || '') + '</textarea></div>';
            html += '</div>';
            // Answer key — preserved through edits and rendered in the teacher guide / marking scheme.
            html += '<div class="row g-2 mt-2 answer-key-block">';
            if (section.type === 'objective') {
                html += '<div class="col-md-3"><label class="form-label">Correct Option</label><input class="form-control answer-correct" value="' + escapeHtml(question.correct_option || '') + '" placeholder="A"></div>';
                html += '<div class="col-md-9"><label class="form-label">Model Answer</label><textarea class="form-control answer-model" rows="2">' + escapeHtml(question.model_answer || '') + '</textarea></div>';
            } else {
                html += '<div class="col-12"><label class="form-label">Model Answer</label><textarea class="form-control answer-model" rows="2">' + escapeHtml(question.model_answer || '') + '</textarea></div>';
            }
            html += '<div class="col-12"><label class="form-label">Marking Guide (one point per line)</label><textarea class="form-control answer-rubric" rows="2">' + escapeHtml((question.rubric || []).join('\n')) + '</textarea></div>';
            if (question.diagram && question.diagram.type) {
                html += '<div class="col-12"><div class="alert alert-light border mb-0 py-2 px-3 small diagram-indicator"><i class="fas fa-chart-bar me-1"></i><strong>Diagram:</strong> ' + escapeHtml(question.diagram.type) + (question.diagram.caption ? ' — ' + escapeHtml(question.diagram.caption) : '') + ' <span class="text-muted">(spec preserved; rendered on the paper)</span></div></div>';
            }
            html += '<div class="d-none answer-key-end"></div>';
            html += '</div>';
            if (section.type === 'objective' && question.options) {
                html += '<div class="row g-2 mt-2">';
                ['A', 'B', 'C', 'D'].forEach(function(optionKey) {
                    html += '<div class="col-md-6"><label class="form-label">Option ' + optionKey + '</label><input class="form-control option-input" data-option-key="' + optionKey + '" value="' + escapeHtml(question.options[optionKey] || '') + '"></div>';
                });
                html += '</div>';
            }
            html += '</div>';
        });
        html += '</div>';
    });
    $('#editorSections').html(html);
}

function serializeExamFromEditor() {
    const exam = {
        title: $('#editorExamTitle').val().trim(),
        subject: $('#subjectSelect option:selected').text(),
        class: $('#classSelect').val(),
        time: ($('#editorDuration').val() || '60') + ' minutes',
        instructions: $('#editorInstructions').val().trim(),
        sections: []
    };

    $('#editorSections .question-editor').each(function() {
        const sectionEl = $(this);
        const section = {
            section: sectionEl.find('.section-label').val().trim(),
            title: sectionEl.find('.section-title-input').val().trim(),
            instructions: sectionEl.find('.section-instructions').val().trim(),
            type: sectionEl.find('.section-type').val().trim(),
            questions: []
        };
        if (section.type === 'comprehension') {
            section.passage = sectionEl.find('.section-passage').val().trim();
        }
        sectionEl.find('[data-question-index]').each(function() {
            const questionEl = $(this);
            const question = {
                number: parseInt(questionEl.find('.question-number').val(), 10) || 1,
                text: questionEl.find('.question-text').val().trim(),
                marks: parseInt(questionEl.find('.question-marks').val(), 10) || 1
            };
            if (section.type === 'objective') {
                question.options = {};
                questionEl.find('.option-input').each(function() { question.options[$(this).data('option-key')] = $(this).val().trim(); });
            }
            // Preserve answer key so edits don't strip the marking scheme.
            var correctEl = questionEl.find('.answer-correct');
            if (correctEl.length) { question.correct_option = correctEl.val().trim(); }
            var modelEl = questionEl.find('.answer-model');
            if (modelEl.length) { question.model_answer = modelEl.val().trim(); }
            var rubricEl = questionEl.find('.answer-rubric');
            if (rubricEl.length) {
                var pts = rubricEl.val().split('\n').map(function(s) { return s.trim(); }).filter(Boolean);
                if (pts.length) { question.rubric = pts; }
            }
            // Preserve the diagram spec carried on the question element.
            var diagRaw = questionEl.attr('data-diagram');
            if (diagRaw) { try { question.diagram = JSON.parse(diagRaw); } catch (e) {} }
            section.questions.push(question);
        });
        exam.sections.push(section);
    });
    return exam;
}

function renderPreviewFromEditor() {
    currentExamData = serializeExamFromEditor();
    $('#examPreview').html(buildPreviewHtml(currentExamData));
    examSaved = false;
    setOutputButtonsDisabled(true);
    showStatus('warning', 'Preview refreshed. Save changes before printing or moving workflow status.');
}

function saveExamEdits() {
    if (!currentExamId) {
        showStatus('warning', 'No exam to save.');
        return;
    }
    $.ajax({
        url: 'ajax/save_exam.php',
        type: 'POST',
        dataType: 'json',
        data: {
            exam_id: currentExamId,
            exam_title: $('#editorExamTitle').val(),
            duration: $('#editorDuration').val(),
            total_marks: $('#editorTotalMarks').val(),
            instructions: $('#editorInstructions').val(),
            exam_data: JSON.stringify(serializeExamFromEditor())
        },
        success: function(response) {
            if (!response.success) {
                showStatus('danger', response.message || 'Could not save exam.', response.details || []);
                return;
            }
            currentExamData = response.exam_data;
            currentExamStatus = response.status || currentExamStatus;
            $('#examPreview').html(buildPreviewHtml(response.exam_data || currentExamData));
            updateWorkflowPanel(response.workflow_html, response.status);
            $('#examTitle').val($('#editorExamTitle').val());
            $('#duration').val($('#editorDuration').val());
            $('#totalMarks').val($('#editorTotalMarks').val());
            examSaved = true;
            setOutputButtonsDisabled(false);
            loadQuestionBank();
            if (response.warnings && response.warnings.length) {
                showStatus('warning', 'Exam saved with warnings.', response.warnings);
            } else {
                showStatus('success', 'Exam changes saved. You can print/download, use workflow actions, or save questions to the bank.');
            }
        },
        error: function() { showStatus('danger', 'Failed to save exam changes.'); }
    });
}

function saveCurrentExamToBank() {
    if (!currentExamId) {
        showStatus('warning', 'Generate and save an exam first.');
        return;
    }
    if (!examSaved) {
        showStatus('warning', 'Save the draft before sending questions to the bank.');
        return;
    }
    $.ajax({
        url: 'ajax/save_to_bank.php',
        type: 'POST',
        dataType: 'json',
        data: { exam_id: currentExamId },
        success: function (response) {
            if (!response.success) {
                showStatus('danger', response.message || 'Could not save questions to the bank.');
                return;
            }
            loadQuestionBank();
            showStatus('success', response.message || 'Questions saved to bank.');
        },
        error: function () { showStatus('danger', 'Could not save questions to the bank.'); }
    });
}

function insertQuestionFromBank(encodedPayload) {
    if (!encodedPayload) {
        showStatus('warning', 'Question payload is missing.');
        return;
    }
    try {
        const question = JSON.parse(decodeURIComponent(encodedPayload));
        currentExamData = serializeExamFromEditor();
        const targetSection = currentExamData.sections.find((section) => section.type === question.question_type) || currentExamData.sections[0];
        if (!targetSection) {
            showStatus('warning', 'Create or generate an exam draft before inserting bank questions.');
            return;
        }
        const nextNumber = (targetSection.questions[targetSection.questions.length - 1]?.number || targetSection.questions.length) + 1;
        const inserted = {
            number: nextNumber,
            text: question.question_text,
            marks: parseInt(question.marks, 10) || 1
        };
        if (question.question_type === 'objective') {
            inserted.options = question.options || { A: '', B: '', C: '', D: '' };
        }
        targetSection.questions.push(inserted);
        renderEditor(currentExamData);
        $('#examPreview').html(buildPreviewHtml(currentExamData));
        examSaved = false;
        setOutputButtonsDisabled(true);
        showStatus('warning', 'Question inserted from the bank. Save the draft to keep the change.');
    } catch (error) {
        console.error(error);
        showStatus('danger', 'Could not insert the selected bank question.');
    }
}

function regeneratePart(mode, sectionIndex, questionIndex = null) {
    if (!currentExamId) {
        showStatus('warning', 'No exam available for regeneration.');
        return;
    }
    $.ajax({
        url: 'ajax/regenerate_question.php',
        type: 'POST',
        dataType: 'json',
        data: {
            exam_id: currentExamId,
            mode: mode,
            section_index: sectionIndex,
            question_index: questionIndex
        },
        success: function (response) {
            if (!response.success) {
                showStatus('danger', response.message || 'Regeneration failed.');
                return;
            }
            currentExamData = response.exam_data;
            renderEditor(currentExamData);
            $('#examPreview').html(buildPreviewHtml(currentExamData));
            examSaved = false;
            setOutputButtonsDisabled(true);
            showStatus('warning', response.message + ' Save the draft to keep this regenerated content.');
        },
        error: function () { showStatus('danger', 'Regeneration failed.'); }
    });
}

function runWorkflowAction(action) {
    if (!currentExamId) {
        showStatus('warning', 'No exam selected for workflow action.');
        return;
    }
    if (!examSaved) {
        showStatus('warning', 'Save the draft before changing workflow status.');
        return;
    }
    $.ajax({
        url: 'ajax/workflow_action.php',
        type: 'POST',
        dataType: 'json',
        data: { exam_id: currentExamId, workflow_action: action, note: $('#workflowNote').val() || '' },
        success: function(response) {
            if (!response.success) {
                showStatus('danger', response.message || 'Workflow action failed.');
                return;
            }
            currentExamStatus = response.status || currentExamStatus;
            updateWorkflowPanel(response.workflow_html, response.status);
            $('#examPreview').html(buildPreviewHtml(currentExamData || serializeExamFromEditor()));
            showStatus('success', response.message || 'Workflow updated.');
        },
        error: function() { showStatus('danger', 'Workflow action failed.'); }
    });
}

function setPreviewVersion(version) {
    currentPreviewVersion = version === "teacher" ? "teacher" : "student";
    if (currentExamData) {
        $("#examPreview").html(buildPreviewHtml(currentExamData));
    }
}

function buildPreviewHtml(exam) {
    const teacher = currentPreviewVersion === "teacher";
    let html = '<div class="exam-paper">';
    html += '<div class="exam-header text-center mb-4">';
    html += '<h2 class="fw-bold">' + escapeHtml($("#editorExamTitle").val() || exam.title || '') + '</h2>';
    html += '<div class="row mt-3"><div class="col-md-3"><strong>Class:</strong> ' + escapeHtml($("#classSelect").val() || exam.class || '') + '</div><div class="col-md-3"><strong>Subject:</strong> ' + escapeHtml($("#subjectSelect option:selected").text() || exam.subject || '') + '</div><div class="col-md-3"><strong>Term:</strong> ' + escapeHtml($("#termSelect").val() || '') + '</div><div class="col-md-3"><strong>Duration:</strong> ' + escapeHtml($("#editorDuration").val() || '') + ' minutes</div></div>';
    html += '<div class="mt-2"><strong>Total Marks:</strong> ' + escapeHtml($("#editorTotalMarks").val() || '') + '</div>';
    if (teacher) {
        html += '<div class="mt-2"><span class="badge bg-dark">Teacher Guide</span></div>';
    }
    html += '<hr class="my-3"></div>';
    html += '<div class="instructions bg-light p-3 mb-4 rounded"><strong>INSTRUCTIONS TO CANDIDATES:</strong><br>' + nl2brHtml(exam.instructions || '') + '</div>';

    (exam.sections || []).forEach(function(section) {
        html += '<div class="section mt-4"><h4 class="section-title bg-primary text-white p-2 rounded">' + escapeHtml(section.title || 'Section') + '</h4>';
        if (section.instructions) {
            html += '<p class="text-muted mb-3">' + escapeHtml(section.instructions) + '</p>';
        }
        if (section.type === 'comprehension' && section.passage) {
            html += '<div class="passage bg-light p-3 mb-3 rounded"><strong>Passage:</strong><br>' + nl2brHtml(section.passage) + '</div>';
        }
        (section.questions || []).forEach(function(question) {
            html += '<div class="question-item"><div><strong>' + escapeHtml(String(question.number || '')) + '.</strong> ' + escapeHtml(question.text || '') + ' <span class="badge bg-info">[' + escapeHtml(String(question.marks || '')) + ' marks]</span></div>';
            if (section.type === 'objective' && question.options) {
                html += '<div class="options ms-4 mt-2">';
                ['A', 'B', 'C', 'D'].forEach(function(optionKey) {
                    html += '<div>' + optionKey + '. ' + escapeHtml(question.options[optionKey] || '') + '</div>';
                });
                html += '</div>';
            }
            if (question.diagram && question.diagram.type) {
                html += '<div class="exam-diagram border rounded p-3 my-2 text-center bg-white">';
                html += '<div class="text-muted small"><i class="fas fa-chart-bar me-1"></i>Diagram: ' + escapeHtml(question.diagram.type) + '</div>';
                if (question.diagram.title) { html += '<div><strong>' + escapeHtml(question.diagram.title) + '</strong></div>'; }
                if (question.diagram.caption) { html += '<div class="small">' + escapeHtml(question.diagram.caption) + '</div>'; }
                html += '<div class="small fst-italic text-secondary">[diagram will render here]</div></div>';
            }
            if (teacher) {
                html += '<div class="mt-3 p-3 border rounded bg-light">';
                if (section.type === 'objective') {
                    html += '<div><strong>Correct Option:</strong> ' + escapeHtml(question.correct_option || 'A') + '</div>';
                }
                html += '<div><strong>Model Answer:</strong> ' + nl2brHtml(question.model_answer || '') + '</div>';
                if (question.rubric && question.rubric.length) {
                    html += '<div class="mt-2"><strong>Marking Guide:</strong><ul class="mb-0">';
                    question.rubric.forEach(function(point) {
                        html += '<li>' + escapeHtml(point) + '</li>';
                    });
                    html += '</ul></div>';
                }
                html += '</div>';
            }
            html += '</div>';
        });
        html += '</div>';
    });

    html += '<div class="exam-footer mt-5 pt-3 border-top text-center"><p><strong>END OF ' + (teacher ? 'TEACHER GUIDE' : 'EXAMINATION') + '</strong></p></div></div>';
    return html;
}

function nl2brHtml(text) {
    return escapeHtml(text).replace(/\n/g, '<br>');
}

function escapeHtml(value) {
    return String(value || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
}
function downloadPDF() {
    if (!currentExamId || !examSaved) {
        showStatus('warning', 'Save the draft before downloading the PDF.');
        return;
    }
    window.location.href = 'download_pdf.php?id=' + currentExamId + '&version=' + currentPreviewVersion;
}

function printExam() {
    if (!currentExamId || !examSaved) {
        showStatus('warning', 'Save the draft before printing.');
        return;
    }
    const previewContent = buildPreviewHtml(currentExamData || serializeExamFromEditor());
    const printWindow = window.open('', '_blank', 'width=900,height=700');
    printWindow.document.write('<!DOCTYPE html><html><head><title>Examination Paper</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"><style>body{padding:40px;font-family:"Times New Roman",serif}.question-item{margin-bottom:25px;page-break-inside:avoid}</style></head><body>' + previewContent + '<script>window.onload=function(){window.print();window.close();}<\/script></body></html>');
    printWindow.document.close();
}

function regenerateExam() { if (confirm('Regenerate the exam draft? Unsaved edits will be lost.')) generateExam(); }
function viewExam(examId) { window.location.href = 'view_exams.php?view=' + examId; }
function downloadExam(examId) { window.location.href = 'download_pdf.php?id=' + examId; }
function resetForm() { if (confirm('Reset all form fields?')) location.reload(); }
