document.addEventListener("DOMContentLoaded", function() {
  let questions = [];
  let form = document.getElementById("quizForm");
  let result = document.getElementById("result");

  // CSV読み込み
  fetch("question.csv")
    .then(response => response.text())
    .then(data => {
      let lines = data.trim().split("\n");
      let headers = lines[0].split(",");
      for (let i = 1; i < lines.length; i++) {
        let cols = lines[i].split(",");
        questions.push({
          question: cols[0],
          options: [cols[1], cols[2], cols[3]],
          answer: parseInt(cols[4], 10)
        });
      }
      shuffle(questions); //追加部分
      renderQuestions();
    });
    
    //追加部分(Fisher-Yatesのシャッフル)
    function shuffle(array) {
    	for (let i = array.length -1; i > 0; i--) {
    		let j = Math.floor(Math.random() * (i + 1));
    		[array[i], array[j]] = [array[j], array[i]];
    	}
    } //ここまで

  function renderQuestions() {
    questions.forEach((q, index) => {
      let div = document.createElement("div");
      div.className = "question";
      let qText = document.createElement("p");
      qText.textContent = (index + 1) + ". " + q.question;
      div.appendChild(qText);
      
      //追加部分
      let options = [...q.options];
      shuffle(options); //ここまで

      options.forEach((opt, i) => { //変更部分(q.options → options)
        let label = document.createElement("label");
        let radio = document.createElement("input");
        radio.type = "radio";
        radio.name = "q" + index;
        //変更部分(i + 1; → q.options.indexOf(opt) + 1;)
        radio.value =  q.options.indexOf(opt) + 1;
        label.appendChild(radio);
        label.appendChild(document.createTextNode(opt));
        div.appendChild(label);
        div.appendChild(document.createElement("br"));
      });
      form.appendChild(div);
    });
  }

  document.getElementById("submitBtn").addEventListener("click", function() {
    let score = 0;
    questions.forEach((q, index) => {
      let selected = document.querySelector('input[name="q' + index + '"]:checked');
      if (selected && parseInt(selected.value, 10) === q.answer) {
        score++;
      }
    });
    result.textContent = "あなたのスコア: " + score + " / " + questions.length;
  });
});
