class DivisionGame {
  constructor() {
    this.basket = document.getElementById('basket');
    this.gameArea = document.getElementById('game-area');
    this.scoreElement = document.getElementById('score');
    this.livesElement = document.getElementById('lives');
    this.levelElement = document.getElementById('level');
    this.startScreen = document.getElementById('start-screen');
    this.startButton = document.getElementById('start-button');
    this.questionElement = document.getElementById('question');
    
    this.score = 0;
    this.lives = 3;
    this.level = 1;
    this.gameActive = false;
    this.spawnRate = 2000;
    this.currentQuestion = null;
    
    this.basketLeft = 0;
    this.gameAreaWidth = this.gameArea.offsetWidth;
    this.basketWidth = this.basket.offsetWidth;
    
    this.colors = [
      ['#FF6B6B', '#FF5252'],
      ['#4ECB71', '#43A047'],
      ['#4AA5E5', '#1976D2'],
      ['#FFA726', '#FB8C00'],
      ['#9575CD', '#5E35B1'],
      ['#4DB6AC', '#00897B'],
      ['#FF7043', '#E64A19'],
      ['#7E57C2', '#512DA8'],
      ['#FFD54F', '#FFA000'],
      ['#F06292', '#C2185B'],
      ['#4FC3F7', '#0288D1'],
      ['#AED581', '#7CB342']
    ];
    
    this.init();
  }

  init() {
    this.setupEventListeners();
    this.startButton.addEventListener('click', () => this.startGame());
  }

  setupEventListeners() {
    document.addEventListener('mousemove', (e) => {
      if (!this.gameActive) return;
      
      const rect = this.gameArea.getBoundingClientRect();
      let newLeft = e.clientX - rect.left - this.basketWidth / 2;
      
      newLeft = Math.max(0, Math.min(newLeft, this.gameAreaWidth - this.basketWidth));
      this.basket.style.left = `${newLeft}px`;
    });
  }

  generateDivisibleNumbers() {
    // Generate divisor first (between 2 and 12)
    const divisor = Math.floor(Math.random() * 11) + 2;
    
    // Generate multiplier (between 1 and 12)
    const multiplier = Math.floor(Math.random() * 12) + 1;
    
    // Calculate dividend
    const dividend = divisor * multiplier;
    
    return { dividend, divisor, answer: multiplier };
  }

  generateQuestion() {
    const { dividend, divisor, answer } = this.generateDivisibleNumbers();
    this.currentQuestion = { dividend, divisor, answer };
    this.questionElement.textContent = `${dividend} ÷ ${divisor} = ?`;
  }

  generateWrongAnswer() {
    const correct = this.currentQuestion.answer;
    let wrong;
    do {
      const variation = Math.floor(Math.random() * 5) + 1;
      wrong = Math.random() < 0.5 ? correct + variation : correct - variation;
    } while (wrong === correct || wrong <= 0);
    return wrong;
  }

  startGame() {
    this.gameActive = true;
    this.score = 0;
    this.lives = 3;
    this.level = 1;
    this.spawnRate = 2500;
    
    this.updateHUD();
    this.startScreen.style.display = 'none';
    
    const fruits = document.querySelectorAll('.fruit');
    fruits.forEach(fruit => fruit.remove());
    
    this.generateQuestion();
    this.spawnNumber();
    this.gameLoop = setInterval(() => this.spawnNumber(), this.spawnRate);
  }

  spawnNumber() {
    if (!this.gameActive) return;
    
    const number = document.createElement('div');
    number.className = 'fruit';
    
    const isCorrect = Math.random() < 0.3;
    const displayNumber = isCorrect ? this.currentQuestion.answer : this.generateWrongAnswer();
    
    number.textContent = displayNumber;
    number.classList.add(isCorrect ? 'correct' : 'incorrect');
    
    number.style.background = this.getRandomColor();
    
    const numberWidth = 40;
    const maxLeft = this.gameAreaWidth - numberWidth;
    number.style.left = `${Math.random() * maxLeft}px`;
    
    const fallDuration = Math.random() * 2 + 2;
    number.style.animation = `fall ${fallDuration}s linear forwards`;
    
    this.gameArea.appendChild(number);
    
    const checkCollision = setInterval(() => {
      if (!number.isConnected) {
        clearInterval(checkCollision);
        return;
      }

      const numberRect = number.getBoundingClientRect();
      const basketRect = this.basket.getBoundingClientRect();
      
      if (this.isColliding(numberRect, basketRect)) {
        if (isCorrect) {
          this.score += 10;
          if (this.score % 50 === 0) {
            this.level++;
            this.spawnRate = Math.max(1000, this.spawnRate - 200);
            clearInterval(this.gameLoop);
            this.gameLoop = setInterval(() => this.spawnNumber(), this.spawnRate);
          }
          this.generateQuestion();
        } else {
          this.lives--;
        }
        
        this.updateHUD();
        number.style.animation = 'collect 0.2s ease-out forwards';
        setTimeout(() => number.remove(), 200);
        
        if (this.lives <= 0) {
          this.gameOver();
        }
        
        clearInterval(checkCollision);
      } else if (numberRect.bottom >= basketRect.bottom + 50) {
        if (isCorrect) {
          this.lives--;
          this.updateHUD();
          
          if (this.lives <= 0) {
            this.gameOver();
          }
        }
        number.remove();
        clearInterval(checkCollision);
      }
    }, 50);
  }

  updateHUD() {
    this.scoreElement.textContent = this.score;
    this.livesElement.textContent = this.lives;
    this.levelElement.textContent = this.level;
  }

  isColliding(rect1, rect2) {
    return !(rect1.right < rect2.left || 
             rect1.left > rect2.right || 
             rect1.bottom < rect2.top || 
             rect1.top > rect2.bottom);
  }

  gameOver() {
    this.gameActive = false;
    clearInterval(this.gameLoop);
    
    setTimeout(() => {
      this.startScreen.style.display = 'block';
      this.startScreen.querySelector('h1').textContent = `¡Juego Terminado! Puntos: ${this.score}`;
      this.startButton.textContent = '¡Jugar de Nuevo!';
    }, 1000);
  }

  getRandomColor() {
    const colorPair = this.colors[Math.floor(Math.random() * this.colors.length)];
    return `radial-gradient(circle at 30% 30%, ${colorPair[0]}, ${colorPair[1]})`;
  }
}

window.addEventListener('load', () => {
  new DivisionGame();
});