document.addEventListener('DOMContentLoaded', () => {
  const problemDiv = document.getElementById('problem');
  const answerInput = document.getElementById('answer');
  const submitButton = document.getElementById('submit');
  const feedbackDiv = document.getElementById('feedback');
  const scoreDiv = document.getElementById('score');
  const challengeDiv = document.getElementById('challenge');
  const challengeResultDiv = document.getElementById('challenge-result');
  const restartButton = document.createElement('button');

  let score = 0;
  let dividend, divisor, quotient;
  let challengeActive = false;
  let challengeTarget;
  let exercisesCompleted = 0;

  const backgroundDiv = document.querySelector('.background');
  backgroundDiv.innerHTML = '';

  function createStars() {
    for (let i = 0; i < 100; i++) {
      const star = document.createElement('div');
      star.style.position = 'absolute';
      star.style.left = Math.random() * 100 + '%';
      star.style.top = Math.random() * 100 + '%';
      star.style.width = '2px';
      star.style.height = '2px';
      star.style.backgroundColor = '#fff';
      star.style.borderRadius = '50%';
      star.style.opacity = '0.8';
      star.style.animation = `twinkle ${Math.random() * 3 + 2}s infinite`;
      backgroundDiv.appendChild(star);
    }
  }

  const style = document.createElement('style');
  style.textContent = `
    @keyframes twinkle {
      0%, 100% { opacity: 0.3; transform: scale(1); }
      50% { opacity: 1; transform: scale(1.5); }
    }
  `;
  document.head.appendChild(style);

  createStars();

  function generateProblem() {
    const dividendSign = Math.random() < 0.5 ? 1 : -1;
    const divisorSign = Math.random() < 0.5 ? 1 : -1;

    dividend = (Math.floor(Math.random() * 91) + 10) * dividendSign;
    divisor = (Math.floor(Math.random() * 9) + 2) * divisorSign;

    quotient = Math.floor(dividend / divisor);
    dividend = divisor * quotient;

    problemDiv.textContent = `(${dividend}) ÷ (${divisor}) = ?`;
  }

  function generateChallenge() {
    challengeTarget = Math.floor(Math.random() * 5) + 5;
    challengeDiv.textContent = ``;
    challengeResultDiv.textContent = '';
    challengeActive = true;
  }

  function endGame(success) {
    problemDiv.textContent = '';
    answerInput.style.display = 'none';
    submitButton.style.display = 'none';
    challengeDiv.style.display = 'none';

    if (success) {
      feedbackDiv.textContent = '¡Felicidades! ¡Has completado el juego!';
      feedbackDiv.style.color = '#64dd17';
    } else {
      feedbackDiv.textContent = '¡Juego terminado!';
      feedbackDiv.style.color = '#ef5350';
    }

    restartButton.textContent = 'Empezar de Nuevo';
    restartButton.id = 'restart-button';
    document.getElementById('game-area').appendChild(restartButton);
    restartButton.addEventListener('click', startGame);
  }

  function checkAnswer() {
    const userAnswer = parseInt(answerInput.value);

    if (userAnswer === quotient) {
      feedbackDiv.textContent = '¡Correcto!';
      feedbackDiv.style.color = '#ffeb3b';
      score++;
      exercisesCompleted++;

      if (challengeActive) {
        challengeTarget--;
        if (challengeTarget === 0) {
          challengeActive = false;
          score += 5;
          challengeResultDiv.textContent = '¡Desafío completado! ¡Bonificación de 5 puntos!';
          challengeResultDiv.style.color = '#64dd17';
        } else {
          challengeDiv.textContent = `¡${challengeTarget} problemas más para completar el desafío!`;
        }
      }

      if (exercisesCompleted >= 5) {
        endGame(true);
        return;
      }

    } else {
      feedbackDiv.textContent = `Incorrecto. La respuesta correcta es ${quotient}.`;
      feedbackDiv.style.color = '#ef5350';
      score--;
      challengeActive = false;
      challengeDiv.textContent = 'Desafío fallido. ¡Inténtalo de nuevo!';
      challengeResultDiv.textContent = '';
      exercisesCompleted = 0;
      if (score < -5) {
        endGame(false);
        return;
      }
    }

    scoreDiv.textContent = `Puntuación: ${score}`;
    answerInput.value = '';
    generateProblem();

    if (!challengeActive && score >= 5 && Math.random() < 0.3) {
      generateChallenge();
    }
  }

  function startGame() {
    score = 0;
    exercisesCompleted = 0;
    challengeActive = false;
    scoreDiv.textContent = `Puntuación: ${score}`;
    feedbackDiv.textContent = '';
    challengeDiv.textContent = '';
    challengeResultDiv.textContent = '';
    answerInput.style.display = 'block';
    submitButton.style.display = 'block';
    challengeDiv.style.display = 'block';

    if (document.getElementById('restart-button')) {
      document.getElementById('restart-button').remove();
    }

    generateProblem();
    generateChallenge();
  }

  submitButton.addEventListener('click', checkAnswer);

  startGame();
});