// public/js/exam.js

document.addEventListener('DOMContentLoaded', () => {
  const tokenMeta = document.querySelector('meta[name="csrf-token"]');
  if (!tokenMeta) return;
  const token = tokenMeta.getAttribute('content');

  const exercises   = Array.from(document.querySelectorAll('.exercise'));
  const submitExam  = document.getElementById('submit-exam-btn');

  // 1) Fancy toast
  function showToast(message) {
    const toast = document.createElement('div');
    toast.classList.add('custom-alert');
    toast.textContent = message;
    document.body.append(toast);
    setTimeout(() => {
      toast.style.opacity = '0';
      setTimeout(() => toast.remove(), 500);
    }, 2500);
  }

  // 2) Mark a question attempted: disable & clear inputs, remove its button
  function markAttempted(el) {
    const type = el.dataset.exerciseType;
    // clear selections
    if (type === 'input') {
      const inp = el.querySelector('input[type="text"]');
      if (inp) inp.value = '';
    } else if (type === 'radio') {
      el.querySelectorAll('input[type="radio"]').forEach(i => i.checked = false);
    } else {
      el.querySelectorAll('input[type="checkbox"]').forEach(i => i.checked = false);
    }

    // disable everything in that exercise
    el.querySelectorAll('input, button').forEach(node => node.disabled = true);
    el.classList.add('attempted');

    // remove its Submit Answer button
    const btn = el.querySelector('.answer-btn');
    if (btn) btn.remove();
  }

  // 3) Reveal the final Submit Exam button once all are done
  function checkAllAttempted() {
    if (exercises.every(e => e.classList.contains('attempted'))) {
      submitExam.classList.remove('d-none');
      submitExam.disabled = false;
    }
  }

  // 4) Send a single answer
  function submitAnswer(el) {
    const exerciseId = el.dataset.exerciseId;
    const type       = el.dataset.exerciseType;
    let answer;

    // validate presence
    if (type === 'input') {
      const inp = el.querySelector('input[type="text"]');
      answer = inp.value.trim();
      if (!answer) { showToast('Please enter an answer.'); return; }
    }
    else if (type === 'radio') {
      const sel = el.querySelector('input[type="radio"]:checked');
      if (!sel) { showToast('Please select one option.'); return; }
      answer = parseInt(sel.value, 10);
    }
    else {
      const sel = Array.from(el.querySelectorAll('input[type="checkbox"]:checked'));
      if (!sel.length) { showToast('Please select at least one.'); return; }
      answer = sel.map(i => parseInt(i.value,10));
    }

    fetch('/exercise/answer', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': token,
      },
      body: JSON.stringify({ exercise_id: exerciseId, answer })
    })
    .then(() => {
      // regardless of server response (exam vs normal), mark it attempted
      markAttempted(el);
      checkAllAttempted();
    })
    .catch(err => {
      console.error('submitAnswer error', err);
      // still mark attempted so the user keeps moving
      markAttempted(el);
      checkAllAttempted();
    });
  }

  // 5) Wire up each “Submit Answer” button
  exercises.forEach(el => {
    const btn = el.querySelector('.answer-btn');
    if (!btn) return;
    btn.addEventListener('click', e => {
      e.preventDefault();
      submitAnswer(el);
    });
  });

  // initial show/hide
  checkAllAttempted();
});
