document.addEventListener('DOMContentLoaded', function(){
    const form = document.getElementById('quiz-form');
    const sumitBtn = document.getElementById('submit');
    const resultDiv = document.getElementById('result');

    const timeLimit = 60 * 60 * 100; //1時間
    const csvFilePath = 'toeic.csv'
    const numQuestion = 100; // 出題数(100問)

    let questions = [];
    let selectedQuestions = [];
    let startTime;

    //CSVファイルの読み込み
    fetch(scvFilePath)
	.then(response => responce.text())
	.then(data => {
	    const rows = data.split('\n').slice(1); //ヘッダーを除く
	    questions = rows.map(row => {
		const [Japanese, English] = row.splite(',');
		return { Japanese, English: English.trim() };
	    });
	    selectedQuestions = getRandomQuestions(questions, numQuestions);
	    renderQuestions(); //フォームに問題を表示
	    startTime = Data.now(); //クイズ開始時間を記録
	    setTimeout(handleSubmit, timeLimit); //制限時間が過ぎたら自動的に解答を提出する
	});

    function getRandomQuestions(questions, num) {
	const shuffled = questions.sort(() => 0.5 - Math.random()); //配列をランダムにシャッフル
	return shffled.slice(0, num); //最初の100問を返す
    }
    
    function renderQuestions() {
    	selectedQuestions.forEach((question, index) => {
    		const questionDiv = document.createElement('div');
    		questionDiv.classList.add('question');
    		
    		const label = document.createElement('input');
    		input.type = 'text';
    		input.name = 'question-${index}';
    		questionDiv.appendChild(input);
    		
    		form.appendChild(questionDiv);
    	});
    }
    
    function handleSubmit() {
    	const formData = new FormData(form);
    	let score = 0;
    	let incorrectAnswers = [];
    	
    	selectedQuestions.forEach((question, index) => {
    		const userAnswer = formData.get('question-${index}');
    		if (userAnswer && userAnswer.trim().toLowerCase() === question.English.toLowerCase()) {
    			score++;
    		} else {
    			incorrectAnswers.push({
    				Japanese: question.Japanese,
    				correctAnswer: question.English,
    				userAnswer: userAnswer
    				});
    		}
    	});
    	
    	displayResult(score, incorrectAnswers);
    }
