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

  // --- Función para mostrar alertas personalizadas ---
  function showAlert(message) {
    const alertDiv = document.createElement('div');
    alertDiv.textContent = message;
    alertDiv.classList.add('custom-alert');      // <<–– use alertDiv, not toast
    document.body.appendChild(alertDiv);
    setTimeout(() => {
      alertDiv.style.opacity = '0';
      setTimeout(() => alertDiv.remove(), 500);
    }, 3000);
  }

  document.querySelectorAll('.exercise').forEach(el => {
    const btn = el.querySelector('.answer-btn');
    if (!btn) return;  // already completed

    const exerciseId = el.dataset.exerciseId;
    const type       = el.dataset.exerciseType;

    btn.addEventListener('click', () => {
      let answer;

      if (type === 'input') {
        answer = el.querySelector('input[type="text"]').value.trim();
      } 
      else if (type === 'radio') {
        const checked = el.querySelector('input[type="radio"]:checked');
        answer = checked ? parseInt(checked.value, 10) : null;
      } 
      else { // checkbox
        answer = Array.from(
          el.querySelectorAll('input[type="checkbox"]:checked')
        ).map(i => parseInt(i.value, 10));
      }

      if ((type === 'input' && answer === '') ||
          (type === 'radio' && answer === null) ||
          (type === 'checkbox' && answer.length === 0)) {
        showAlert('Please select or enter an answer before submitting.');
        return;
      }

      submitAnswer(exerciseId, answer, el, btn);
    });
  });

  function submitAnswer(exerciseId, answer, container, btn) {
    fetch('/exercise/answer', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': token,
        'Accept': 'application/json'
      },
      body: JSON.stringify({ exercise_id: exerciseId, answer })
    })
    .then(response => response.json().then(json => ({ status: response.status, ok: response.ok, json })))
    .then(({ ok, json }) => {
      if (!ok) {
        showAlert(json.message || 'Incorrect answer, please try again.');
        // clear inputs
        container.querySelectorAll('input:not([disabled])').forEach(input => {
          if (input.type === 'text') {
            input.value = '';
          } else {
            input.checked = false;
          }
        });
        return;
      }

      // correct: disable inputs & remove button
      container.querySelectorAll('input').forEach(input => input.disabled = true);
      btn.remove();
      container.classList.add('completed');

      // show Next Chapter button if applicable
      if (json.allCompleted) {
        const nextBtn = document.getElementById('next-chapter-btn');
        if (nextBtn) nextBtn.classList.remove('d-none');
      }
    })
    .catch(err => {
      console.error('Error submitting answer:', err);
      showAlert('An error occurred. Please try again.');
    });
  }
});
