const QUIZ_TYPE    = 'event';
const QUIZ_ID      = <?= $eventId ?>;
const TOTAL_Q      = <?= count($questions) ?>;
const CSRF         = '<?= csrfToken() ?>';

// Track answers
const userAnswers = {};

// Update answered count when option selected
document.querySelectorAll('.quiz-option input').forEach(input => {
  input.addEventListener('change', () => {
    const qid = input.name.replace('q_', '');
    userAnswers[qid] = input.value;
    updateAnsweredCount();
    // Highlight selected option
    const block = input.closest('.quiz-options');
    block.querySelectorAll('.quiz-option').forEach(lbl => lbl.classList.remove('selected'));
    input.closest('.quiz-option').classList.add('selected');
  });
});

function updateAnsweredCount() {
  const count = Object.keys(userAnswers).length;
  document.getElementById('answeredCount').textContent = count + ' / ' + TOTAL_Q + ' answered';
  if (count === TOTAL_Q) {
    document.getElementById('btnSubmit').classList.add('ready');
  }
}

async function submitQuiz() {
  const answeredCount = Object.keys(userAnswers).length;
  if (answeredCount < TOTAL_Q) {
    showToast(`Please answer all ${TOTAL_Q} questions before submitting.`, 'warning');
    // Highlight unanswered
    document.querySelectorAll('.quiz-question-block').forEach(block => {
      const qid = block.id.replace('qblock_', '');
      if (!userAnswers[qid]) {
        block.classList.add('unanswered-highlight');
        setTimeout(() => block.classList.remove('unanswered-highlight'), 2000);
      }
    });
    return;
  }

  const answers = Object.entries(userAnswers).map(([qid, ans]) => ({
    question_id: parseInt(qid),
    answer: ans
  }));

  document.getElementById('btnSubmit').disabled = true;
  document.getElementById('btnSubmit').textContent = 'Submitting…';

  try {
    const res = await api('/src/api/quiz.php?action=submit', 'POST', {
      type: QUIZ_TYPE,
      id: QUIZ_ID,
      answers: answers,
      _csrf: CSRF
    });

    showQuizResults(res);
  } catch(e) {
    showToast('Error submitting quiz: ' + e.message, 'error');
    document.getElementById('btnSubmit').disabled = false;
    document.getElementById('btnSubmit').textContent = 'Submit Answers';
  }
}

function showQuizResults(res) {
  // Show feedback on each question
  res.details.forEach(detail => {
    const block   = document.getElementById('qblock_' + detail.question_id);
    const fb      = document.getElementById('feedback_' + detail.question_id);
    const options = block.querySelectorAll('.quiz-option');

    // Disable all inputs
    block.querySelectorAll('input[type=radio]').forEach(i => i.disabled = true);

    // Mark each option
    options.forEach(opt => {
      const optLetter = opt.dataset.opt;
      if (optLetter === detail.correct) {
        opt.classList.add('correct');
      } else if (optLetter === detail.given && !detail.is_correct) {
        opt.classList.add('incorrect');
      }
    });

    // Show explanation
    fb.style.display = 'block';
    fb.innerHTML = `<span class="${detail.is_correct ? 'fb-correct' : 'fb-wrong'}">${detail.is_correct ? '✓ Correct!' : '✗ Incorrect'}</span> ${escHtml(detail.explanation)}`;
