(function () {
    "use strict";

    const app = document.getElementById("exam_session_app");
    if (!app) return;

    const ATTEMPT_ID = parseInt(app.dataset.attemptId);
    const EXAM_ID = parseInt(app.dataset.examId);
    const SESSION_TOKEN = app.dataset.sessionToken;

    let sections = [];
    let currentSection = 0;
    let currentQuestion = 0;
    let answers = {};
    let totalTime = 0;
    let timeLeft = 0;
    let timerInterval = null;

    const sidebar = document.getElementById("sidebar");
    const mainContent = document.getElementById("mainContent");
    const timerEl = document.getElementById("timer");
    const progressBar = document.getElementById("progressBar");

    async function fetchJSON(url, options) {
        options = options || {};
        options.headers = Object.assign(
            { "Content-Type": "application/json" },
            options.headers || {}
        );
        const res = await fetch(url, options);
        return res.json();
    }

    async function loadSession() {
        const data = await fetchJSON("/api/exam/" + EXAM_ID + "/session", {
            headers: { Authorization: "Bearer " + SESSION_TOKEN },
        });
        if (data.error) {
            mainContent.innerHTML =
                '<div class="ec-card"><h3>Error</h3><p>' +
                data.error +
                "</p></div>";
            return;
        }
        sections = data.sections || [];
        totalTime = (data.total_time_min || 30) * 60;
        timeLeft = totalTime;

        sections.forEach(function (sec) {
            (sec.questions || []).forEach(function (q) {
                if (q.saved_answer) answers[q.id] = q.saved_answer;
            });
        });

        buildSidebar();
        renderQuestion();
        startTimer();
    }

    function buildSidebar() {
        var html = "";
        sections.forEach(function (sec, si) {
            html += '<div class="section-title">' + sec.title + "</div><div>";
            (sec.questions || []).forEach(function (q, qi) {
                var cls = answers[q.id] ? "answered" : "";
                var act =
                    si === currentSection && qi === currentQuestion
                        ? "active"
                        : "";
                html +=
                    '<button class="q-btn ' +
                    cls +
                    " " +
                    act +
                    '" data-si="' +
                    si +
                    '" data-qi="' +
                    qi +
                    '">' +
                    (si * 5 + qi + 1) +
                    "</button>";
            });
            html += "</div>";
        });
        sidebar.innerHTML = html;
        sidebar.querySelectorAll(".q-btn").forEach(function (btn) {
            btn.addEventListener("click", function () {
                jumpTo(
                    parseInt(this.dataset.si),
                    parseInt(this.dataset.qi)
                );
            });
        });
    }

    function renderQuestion() {
        var sec = sections[currentSection];
        if (!sec) return;
        var q = sec.questions[currentQuestion];
        if (!q) return;

        var globalIdx =
            sections
                .slice(0, currentSection)
                .reduce(function (a, s) {
                    return a + s.questions.length;
                }, 0) +
            currentQuestion +
            1;
        var totalQ = sections.reduce(function (a, s) {
            return a + s.questions.length;
        }, 0);

        progressBar.style.width = (globalIdx / totalQ) * 100 + "%";

        var optionsHtml = "";
        if (q.options && q.options.length > 0) {
            q.options.forEach(function (opt) {
                var key = opt.key || opt.text;
                var sel = answers[q.id] === key ? "selected" : "";
                optionsHtml +=
                    '<label class="ec-option ' +
                    sel +
                    '" data-qid="' +
                    q.id +
                    '" data-key="' +
                    key +
                    '">' +
                    '<input type="radio" name="q' +
                    q.id +
                    '"' +
                    (sel ? " checked" : "") +
                    "/>" +
                    '<span class="ec-option-key">' +
                    (opt.key || "") +
                    "</span>" +
                    "<span>" +
                    (opt.text || key) +
                    "</span>" +
                    "</label>";
            });
        } else {
            var val = answers[q.id] || "";
            optionsHtml =
                '<input type="text" class="form-control" id="textAnswer" value="' +
                val +
                '" placeholder="Type your answer…"/>';
        }

        var isFirst = currentSection === 0 && currentQuestion === 0;
        var isLast =
            currentSection === sections.length - 1 &&
            currentQuestion === sec.questions.length - 1;

        mainContent.innerHTML =
            '<div class="ec-card">' +
            '<div style="color:#64748B;font-size:.85rem;margin-bottom:12px;">' +
            sec.title +
            " \u2014 Question " +
            (currentQuestion + 1) +
            " of " +
            sec.questions.length +
            '<span style="float:right;color:var(--ec-primary);font-weight:600;">' +
            (q.difficulty || "") +
            " \u2022 " +
            (q.marks || 1) +
            " mark" +
            ((q.marks || 1) > 1 ? "s" : "") +
            "</span></div>" +
            '<div class="ec-question-stem">' +
            q.stem +
            "</div>" +
            optionsHtml +
            "</div>" +
            '<div class="ec-nav">' +
            '<button class="btn btn-outline-secondary" id="btnPrev"' +
            (isFirst ? " disabled" : "") +
            ">\u2190 Previous</button>" +
            (isLast
                ? '<button class="btn btn-success btn-lg" id="btnSubmit">Submit Exam</button>'
                : '<button class="btn text-white" id="btnNext" style="background:var(--ec-primary)">Next \u2192</button>') +
            "</div>";

        mainContent.querySelectorAll(".ec-option").forEach(function (el) {
            el.addEventListener("click", function () {
                selectAnswer(
                    parseInt(this.dataset.qid),
                    this.dataset.key,
                    this
                );
            });
        });

        var textInput = document.getElementById("textAnswer");
        if (textInput) {
            textInput.addEventListener("change", function () {
                answers[q.id] = this.value;
            });
        }

        var btnPrev = document.getElementById("btnPrev");
        if (btnPrev)
            btnPrev.addEventListener("click", function () {
                navigate(-1);
            });

        var btnNext = document.getElementById("btnNext");
        if (btnNext)
            btnNext.addEventListener("click", function () {
                navigate(1);
            });

        var btnSubmit = document.getElementById("btnSubmit");
        if (btnSubmit) btnSubmit.addEventListener("click", submitExam);

        buildSidebar();
    }

    function selectAnswer(qid, key, el) {
        answers[qid] = key;
        el.closest(".ec-card")
            .querySelectorAll(".ec-option")
            .forEach(function (o) {
                o.classList.remove("selected");
            });
        el.classList.add("selected");
        buildSidebar();
    }

    function navigate(dir) {
        var sec = sections[currentSection];
        var next = currentQuestion + dir;
        if (next >= 0 && next < sec.questions.length) {
            currentQuestion = next;
        } else if (dir > 0 && currentSection < sections.length - 1) {
            currentSection++;
            currentQuestion = 0;
        } else if (dir < 0 && currentSection > 0) {
            currentSection--;
            currentQuestion = sections[currentSection].questions.length - 1;
        }
        renderQuestion();
        autoSave();
    }

    function jumpTo(si, qi) {
        currentSection = si;
        currentQuestion = qi;
        renderQuestion();
    }

    function startTimer() {
        timerInterval = setInterval(function () {
            timeLeft--;
            if (timeLeft <= 0) {
                clearInterval(timerInterval);
                submitExam();
                return;
            }
            var m = Math.floor(timeLeft / 60);
            var s = timeLeft % 60;
            timerEl.textContent =
                String(m).padStart(2, "0") + ":" + String(s).padStart(2, "0");
            timerEl.className =
                "ec-timer" +
                (timeLeft < 120
                    ? " danger"
                    : timeLeft < 300
                    ? " warning"
                    : "");
        }, 1000);
    }

    var saveTimeout;
    function autoSave() {
        clearTimeout(saveTimeout);
        saveTimeout = setTimeout(function () {
            var ansArr = Object.entries(answers).map(function (entry) {
                return { question_id: parseInt(entry[0]), answer: entry[1] };
            });
            fetchJSON("/api/exam/" + EXAM_ID + "/autosave", {
                method: "POST",
                headers: { Authorization: "Bearer " + SESSION_TOKEN },
                body: JSON.stringify({
                    attempt_id: ATTEMPT_ID,
                    answers: ansArr,
                    current_section:
                        sections[currentSection]
                            ? sections[currentSection].skill
                            : "",
                    time_remaining_sec: timeLeft,
                }),
            });
        }, 2000);
    }

    function submitExam() {
        if (
            !confirm(
                "Are you sure you want to submit? You cannot change answers after submission."
            )
        )
            return;
        clearInterval(timerInterval);
        mainContent.innerHTML =
            '<div class="ec-card" style="text-align:center;padding:48px">' +
            "<h2>Submitting\u2026</h2>" +
            '<div class="spinner-border text-primary mt-3"></div></div>';

        var ansArr = Object.entries(answers).map(function (entry) {
            return { question_id: parseInt(entry[0]), answer: entry[1] };
        });
        fetchJSON("/api/exam/" + EXAM_ID + "/submit", {
            method: "POST",
            headers: { Authorization: "Bearer " + SESSION_TOKEN },
            body: JSON.stringify({ attempt_id: ATTEMPT_ID, answers: ansArr }),
        }).then(function (result) {
            if (result.scores) {
                showResults(result.scores);
            } else {
                mainContent.innerHTML =
                    '<div class="ec-card ec-results">' +
                    "<h2>Exam Submitted</h2>" +
                    "<p>Status: " +
                    result.status +
                    "</p>" +
                    "<p>Your results will be released soon.</p></div>";
            }
            sidebar.innerHTML =
                '<div style="padding:16px;text-align:center;color:#64748B">Exam completed</div>';
        });
    }

    function showResults(scores) {
        var skills = ["listening", "reading", "writing", "speaking"].filter(
            function (s) {
                return scores[s] > 0;
            }
        );
        var rows = skills
            .map(function (s) {
                return (
                    '<div class="ec-skill-row"><span style="text-transform:capitalize">' +
                    s +
                    "</span><strong>" +
                    scores[s].toFixed(1) +
                    "</strong></div>"
                );
            })
            .join("");
        mainContent.innerHTML =
            '<div class="ec-card ec-results">' +
            '<h2 style="margin-bottom:8px">Exam Complete!</h2>' +
            '<div class="ec-band">' +
            scores.overall.toFixed(1) +
            "</div>" +
            '<div style="color:#64748B;margin-bottom:24px">Overall Band Score \u2014 CEFR ' +
            (scores.cefr || "").toUpperCase() +
            "</div>" +
            '<div style="max-width:400px;margin:0 auto;text-align:left">' +
            rows +
            "</div>" +
            '<a href="/web" class="btn btn-primary mt-4">Return to Dashboard</a>' +
            "</div>";
    }

    loadSession();
})();
