document.addEventListener('DOMContentLoaded', () => {
    const startButton = document.getElementById('startButton');
    const gameDiv = document.getElementById('game');
    const questionElem = document.getElementById('question');
    const answerForm = document.getElementById('answerForm');
    const answerInput = document.getElementById('answerInput');
    const timerElem = document.getElementById('timeLeft');
    const exam1Elem = document.getElementById('exam1');
    const exam2Elem = document.getElementById('exam2');
    const exam3Elem = document.getElementById('exam3');
    const exam4Elem = document.getElementById('exam4');
    const exam5Elem = document.getElementById('exam5');
    const resultMessageElem = document.getElementById('resultMessage');

    let questions = [];
    let currentQuestion = {};
    let timer;
    let timeLeft = 30;
    let questionCount = 0;
    const maxQuestions = 10;
    let score = 0;

    startButton.addEventListener('click', () => {
        resetGame(); 
        startButton.style.display = 'none';
        gameDiv.style.display = 'block';
        loadQuestions('pr-ad.csv');  
    });

    answerForm.addEventListener('submit', (e) => {
        e.preventDefault();
        checkAnswer();
    });

    function loadQuestions(file) {
        fetch(file)
            .then(response => response.text())
            .then(data => {
                questions = parseCSV(data);
                nextQuestion();
                startTimer();
            })
            .catch(error => console.error('Error loading questions:', error));
    }

    function parseCSV(data) {
        const lines = data.split('\n').slice(1);
        return lines.map(line => {
            const [question, answer, ex1, ex2, ex3, ex4, ex5] = line.split(',');
            if (question && answer) {
                return { question, answer, ex1, ex2, ex3, ex4, ex5 };
            }
            return null;
        }).filter(q => q !== null);
    }

    function nextQuestion() {
        if (questionCount >= maxQuestions || questions.length === 0) {
            endGame();
            return;
        }
        questionCount++;
        const randomIndex = Math.floor(Math.random() * questions.length);
        currentQuestion = questions[randomIndex];
        
        questionElem.textContent = currentQuestion.question;
        exam1Elem.textContent = currentQuestion.ex1 || '';
        exam2Elem.textContent = currentQuestion.ex2 || '';
        exam3Elem.textContent = currentQuestion.ex3 || '';
        exam4Elem.textContent = currentQuestion.ex4 || '';
        exam5Elem.textContent = currentQuestion.ex5 || '';

        answerInput.value = '';
        answerInput.focus();
        resultMessageElem.textContent = '';  
    }

    function checkAnswer() {
        if (answerInput.value === currentQuestion.answer) {
            score++;
            questions = questions.filter(q => q !== currentQuestion);
            nextQuestion();
            resetTimer();
        } else {
            answerInput.value = '';  
        }
    }

    function startTimer() {
        timeLeft = 30;
        timerElem.textContent = timeLeft;
        timer = setInterval(() => {
            timeLeft--;
            timerElem.textContent = timeLeft;
            if (timeLeft <= 0) {
                clearInterval(timer);
                resultMessageElem.textContent = `時間切れです！正解は：${currentQuestion.answer}。得点：${score}`; 
                setTimeout(endGame, 5000); 
            }
        }, 1000);
    }

    function resetTimer() {
        clearInterval(timer);
        startTimer();
    }

    function endGame() {
        resultMessageElem.textContent = `ゲーム終了！あなたの得点は${score}点です`;
        setTimeout(() => {
            startButton.style.display = 'block';
            gameDiv.style.display = 'none';
        }, 5000);  
        clearInterval(timer);
    }

    function resetGame() {
        score = 0;
        questionCount = 0;
        questions = [];
        clearInterval(timer);
        timerElem.textContent = '30';  
        resultMessageElem.textContent = '';  
        answerInput.value = '';  
    }
});
