let current = 0;
let score = 0;

const qEl = document.getElementById("question");
const qImg = document.getElementById("questionImage");
const optEl = document.getElementById("options");
const feedback = document.getElementById("feedback");
const explanationBox = document.getElementById("explanationBox");
const nextBtn = document.getElementById("nextBtn");

loadQuestion();

function loadQuestion() {
    const q = quizData[current];

    qEl.innerText = `Q${current + 1}. ${q.question}`;
    optEl.innerHTML = "";
    feedback.innerHTML = "";
    explanationBox.style.display = "none";
    nextBtn.disabled = true;

    if (q.image) {
        qImg.src = q.image;
        qImg.style.display = "block";
    } else {
        qImg.style.display = "none";
    }

    q.options.forEach((op, i) => {
        const div = document.createElement("div");
        div.className = "option";
        div.innerHTML = op.text;
        div.onclick = () => checkAnswer(div, i);
        optEl.appendChild(div);
    });
}

function checkAnswer(selected, index) {
    const q = quizData[current];
    const all = document.querySelectorAll(".option");
    all.forEach(op => op.onclick = null);

    if (index === q.correct) {
        selected.classList.add("correct");
        feedback.innerHTML = "✅ Correct";
        score++;
    } else {
        selected.classList.add("wrong");
        all[q.correct].classList.add("correct");
        feedback.innerHTML = "❌ Wrong";
    }

    explanationBox.style.display = "block";
    explanationBox.innerHTML = `<b>Explanation:</b><br>${q.explanation.text}`;
    nextBtn.disabled = false;
}

nextBtn.onclick = () => {
    current++;
    if (current < quizData.length) {
        loadQuestion();
    } else {
        document.querySelector(".quiz-container").innerHTML =
            `<h2>Quiz Finished</h2><h3>Score: ${score}/${quizData.length}</h3>`;
    }
};
