let qIndex = 0;
let score = 0;
let questions = [];

function initQuiz(database) {
  questions = shuffle(database.flashcards);
  qIndex = 0;
  score = 0;
  renderQuestion();
}

function renderQuestion() {
  if (qIndex >= questions.length) {
    finishQuiz();
    return;
  }

  const correct = questions[qIndex];
  const options = shuffle([correct, ...shuffle(questions).slice(0, 3)]).slice(
    0,
    4
  );

  document.getElementById("question").textContent = correct.front;
  document.getElementById("options").innerHTML = options
    .map(
      (o) =>
        `<button onclick="answer('${o.romaji}','${correct.romaji}')">${o.romaji}</button>`
    )
    .join("");
}

function answer(selected, correct) {
  if (selected === correct) score++;
  qIndex++;
  renderQuestion();
}

function finishQuiz() {
  alert(`Skor kamu: ${score}/${questions.length}`);
}
