let currentQuestionIndex = 0;
let score = 0;
let currentDifficulty = "easy";
let questions = {};

function startGame(difficulty) {
    currentDifficulty = difficulty;
    currentQuestionIndex = 0;
    score = 0;
    document.getElementById("game-intro").style.display = "none";
    document.getElementById("game-area").style.display = "block";
    loadQuestion();
}

function loadQuestionsFromCSV(csvFilePath, callback) {
    fetch(csvFilePath)
        .then(response => response.text())
        .then(data => {
            const parsedQuestions = parseCSV(data);
            questions = groupQuestionsByDifficulty(parsedQuestions);

            // 各難易度の質問をシャッフル
            Object.keys(questions).forEach(difficulty => {
                questions[difficulty] = shuffleArray(questions[difficulty]);
            });

            if (Object.keys(questions).length === 0) {
                throw new Error("No valid questions found in the CSV file.");
            }
            callback();
        })
        .catch(error => {
            console.error("Error loading CSV file:", error);
            document.getElementById("game-intro").innerText = "Failed to load questions. Please try again.";
        });
}

function parseCSV(data) {
    const rows = data.trim().split("\n");
    return rows
        .map(row => {
            const columns = row.split(",");
            if (columns.length < 5) {
                console.warn("Skipped invalid row:", row);
                return null;
            }
            const [difficulty, question, options, correctAnswer, explanation] = columns.map(col => col.trim());
            if (!difficulty || !question || !options || !correctAnswer || !explanation) {
                console.warn("Skipped row with missing fields:", row);
                return null;
            }
            return {
                difficulty,
                question,
                options: options.split("|"),
                correctAnswer,
                explanation,
            };
        })
        .filter(row => row !== null);
}

function groupQuestionsByDifficulty(parsedQuestions) {
    return parsedQuestions.reduce((acc, question) => {
        const { difficulty } = question;
        if (!acc[difficulty]) {
            acc[difficulty] = [];
        }
        acc[difficulty].push(question);
        return acc;
    }, {});
}

// 配列をランダムにシャッフルする関数
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

function loadQuestion() {
    const questionsForDifficulty = questions[currentDifficulty];
    if (!questionsForDifficulty || questionsForDifficulty.length === 0) {
        console.error(`No questions available for difficulty: ${currentDifficulty}`);
        document.getElementById("feedback").innerText = "No questions available.";
        return;
    }

    const questionData = questionsForDifficulty[currentQuestionIndex];
    if (!questionData) {
        console.error(`Question data not found for index: ${currentQuestionIndex}`);
        document.getElementById("feedback").innerText = "Question data missing.";
        return;
    }

    document.getElementById("question").innerText = questionData.question;
    const optionsContainer = document.getElementById("options");
    optionsContainer.innerHTML = "";

    questionData.options.forEach(option => {
        const button = document.createElement("button");
        button.innerText = option;
        button.onclick = () => checkAnswer(option);
        optionsContainer.appendChild(button);
    });

    document.getElementById("feedback").innerText = "";
    document.getElementById("next-button").style.display = "none";
}

function checkAnswer(selectedOption) {
    const questionData = questions[currentDifficulty][currentQuestionIndex];
    const feedback = document.getElementById("feedback");

    if (selectedOption === questionData.correctAnswer) {
        feedback.innerText = "Correct! " + questionData.explanation;
        feedback.style.color = "green";
        score++;
    } else {
        feedback.innerText = "Incorrect. " + questionData.explanation;
        feedback.style.color = "red";
    }

    document.getElementById("next-button").style.display = "block";
}

function nextQuestion() {
    currentQuestionIndex++;
    if (currentQuestionIndex < questions[currentDifficulty].length) {
        loadQuestion();
    } else {
        endGame();
    }
}

function endGame() {
    document.getElementById("game-area").style.display = "none";
    document.getElementById("game-over").style.display = "block";
    document.getElementById("final-score").innerText = score;
}

function restartGame() {
    document.getElementById("game-over").style.display = "none";
    document.getElementById("game-intro").style.display = "block";
}

// Initialize game by loading questions from CSV
loadQuestionsFromCSV("questions.csv", () => {
    console.log("Questions loaded successfully.");
});
