$(document).ready(function () {
    // Sample question data
    const questions = [
        {
            type: "singleBlank",
            question: "1. During their famous clash, Jung was ambivalent about Freud, so he attacked the father of modern psychoanalysis even as he ____ him.",
            choices: ["enlightened", "chastened", "revered", "despised", "understood"],
            correctAnswer: "despised"
        },
        {
            type: "multipleBlanks",
            question: "2. The issue of censorship on television is long-running; those few responsible for ____ what content is delivered to the public have an often-misguided sense of their ability to predict the ____ of the public to material that may not even be considered questionable by all.",
            blanks: [
                {
                    id: 1,
                    choices: ["creating", "expurgating", "edifying"],
                    correctAnswer: "expurgating"
                },
                {
                    id: 2,
                    choices: ["reaction", "distress", "outrage"],
                    correctAnswer: "outrage"
                }
            ]
        },
        {
            type: "multipleBlanks",
            question: "3. “Blog” is just one of the many ____ that have emerged as computers have become ____ fixtures of daily life. There are, of course, ____ linguists who refuse to accept these computer-related terms, even though these same linguists rely just as much on computers as the rest of the population.",
            blanks: [
                {
                    id: 1,
                    choices: ["publications", "neologisms", "advances"],
                    correctAnswer: "neologisms"
                },
                {
                    id: 2,
                    choices: ["inchoate", "indispensable", "temporary"],
                    correctAnswer: "indispensable"
                },
                {
                    id: 3,
                    choices: ["obstinate", "well-educated", "experienced"],
                    correctAnswer: "obstinate"
                }
            ]
        }
    ];
    // Collect the user's answers
    const userAnswers = [];
    // Global variables
    let currentQuestion = 0;
    let score = 0;

    // Function to display the current question
    function displayQuestion() {
        const questionElement = $('.question p');
        questionElement.html(questions[currentQuestion].question);

        if (questions[currentQuestion].type === "singleBlank") {
            // Display a single blank question
            displaySingleBlankQuestion();
        } else if (questions[currentQuestion].type === "multipleBlanks") {
            // Display a multiple blanks question
            displayMultipleBlanksQuestion();
        }
    }

    // Function to display a single blank question
    function displaySingleBlankQuestion() {
        const choicesElement = $('.choices');
        choicesElement.html('');

        questions[currentQuestion].choices.forEach(choice => {
            const label = $('<label>');
            const input = $('<input>').attr('type', 'radio').attr('name', 'answer').val(choice);
            input.on('change', handleAnswer);

            label.append(input);
            label.append(document.createTextNode(choice));

            choicesElement.append(label);
        });
    }

    // Function to display a multiple blanks question
    function displayMultipleBlanksQuestion() {
        const blanksElement = $('.blanks');
        blanksElement.html('');

        questions[currentQuestion].blanks.forEach(blank => {
            const blankDiv = $('<div>').addClass('blank');
            const select = $('<select>').attr('data-blank-id', blank.id);

            blank.choices.forEach(choice => {
                const option = $('<option>').val(choice).text(choice);
                select.append(option);
            });

            select.on('change', handleBlankSelection);

            blankDiv.append(select);
            blanksElement.append(blankDiv);
        });
    }

    // Function to handle user's answer selection for single blank questions
    function handleAnswer(event) {
        const selectedAnswer = event.target.value;
        const correctAnswer = questions[currentQuestion].correctAnswer;

        if (selectedAnswer === correctAnswer) {
            // You can handle scoring here if needed
            score++;
        }

        // moveToNextQuestion();
    }

    // Function to handle user's blank selections for multiple blanks questions
    function handleBlankSelection(event) {
        const selectedChoice = event.target.value;
        const blankId = event.target.getAttribute('data-blank-id');

        const correctAnswer = questions[currentQuestion].blanks.find(blank => blank.id === parseInt(blankId)).correctAnswer;

        if (selectedChoice === correctAnswer) {
            // You can handle scoring here if needed
            score++;
        }

        // Optionally, you can move to the next question when all blanks are filled
        const allBlanksFilled = Array.from(document.querySelectorAll('select')).every(select => select.value !== '');
        if (allBlanksFilled) {
            // moveToNextQuestion();
        }
    }

    // Function to move to the next question
    function moveToNextQuestion() {
        currentQuestion++;
        if (currentQuestion < questions.length) {
            // Clear the content of the previous question and options
            $('.question p').html('');
            $('.choices').html('');
            $('.blanks').html('');
            displayQuestion();
        } else {
            showResult();
        }
    }


    // Function to display the result
    function showResult() {
        const container = $('.container');
        container.html('');

        const resultElement = $('<div>').text(`Your score: ${score} out of ${questions.length}`);
        container.append(resultElement);
    }
    
    // Function to handle the submission
     // Function to handle the submission
     function handleSubmit() {
        // Loop through all questions
        questions.forEach((question, index) => {
            if (question.type === "singleBlank") {
                // For single-blank questions, find the selected answer or assign an empty string
                const selectedAnswer = $('input[name="answer"]:checked').val() || "";
                userAnswers[index + 1] = selectedAnswer; // Use question number as key
            } else if (question.type === "multipleBlanks") {
                // For multiple-blanks questions, populate answers or empty strings for each blank
                const blankAnswers = [];
                question.blanks.forEach(blank => {
                    const selectedChoice = $(`select[data-blank-id="${blank.id}"]`).val() || "";
                    blankAnswers.push(selectedChoice);
                });
                userAnswers[index + 1] = blankAnswers; // Use question number as key
            }
        });

        // Here, you can post all user answers to a server or perform any other desired actions
        // For now, we'll just log the user's answers
        console.log("User's Answers:", userAnswers);

        // Optionally, you can display a confirmation message or redirect the user
        // For example:
        // alert("Answers submitted successfully!");
        // window.location.href = "thankyou.html";
    }

    // Attach the submit function to the "Submit" button
    $('#submitBtn').on('click', handleSubmit);


    

    // Start the exam by displaying the first question
    displayQuestion();

    $('#continueBtn').click(function(){
        moveToNextQuestion();
    })
});
