class PowerGame {
  constructor() {
    this.score = 0;
    this.streak = 0;
    this.currentQuestion = null;
    this.currentProperty = null;
    
    this.initializeElements();
    this.addEventListeners();
    this.initializeParticleSystem();
  }

  initializeElements() {
    this.questionElement = document.getElementById('question');
    this.answerInput = document.getElementById('answer');
    this.checkButton = document.getElementById('checkButton');
    this.scoreElement = document.getElementById('score');
    this.streakElement = document.getElementById('streak');
    this.feedbackElement = document.getElementById('feedback');
    this.propertyButtons = document.querySelectorAll('.property-buttons button');
  }

  initializeParticleSystem() {
    this.particles = [];
    this.canvas = document.createElement('canvas');
    this.canvas.style.position = 'fixed';
    this.canvas.style.top = '0';
    this.canvas.style.left = '0';
    this.canvas.style.width = '100%';
    this.canvas.style.height = '100%';
    this.canvas.style.pointerEvents = 'none';
    this.canvas.style.zIndex = '1000';
    document.body.appendChild(this.canvas);
    this.ctx = this.canvas.getContext('2d');
    this.resizeCanvas();
    window.addEventListener('resize', () => this.resizeCanvas());
  }

  resizeCanvas() {
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
  }

  addEventListeners() {
    this.propertyButtons.forEach(button => {
      button.addEventListener('click', () => {
        this.selectProperty(button.dataset.property);
        this.addClickEffect(button);
      });
    });

    this.checkButton.addEventListener('click', () => this.checkAnswer());
    this.answerInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') this.checkAnswer();
    });
  }

  addClickEffect(button) {
    button.style.transform = 'scale(0.95)';
    setTimeout(() => button.style.transform = '', 100);
  }

  selectProperty(property) {
    this.currentProperty = property;
    this.generateQuestion();
  }

  generateQuestion() {
    switch(this.currentProperty) {
      case 'multiply':
        this.generateMultiplyQuestion();
        break;
      case 'division':
        this.generateDivisionQuestion();
        break;
      case 'power':
        this.generatePowerQuestion();
        break;
      case 'product':
        this.generateProductQuestion();
        break;
      case 'quotient':
        this.generateQuotientQuestion();
        break;
    }
  }

  generateMultiplyQuestion() {
    const base = Math.floor(Math.random() * 5) + 2;
    const exp1 = Math.floor(Math.random() * 5) + 1;
    const exp2 = Math.floor(Math.random() * 5) + 1;
    
    this.currentQuestion = {
      question: `${base}^${exp1} × ${base}^${exp2} = ${base}^?`,
      answer: exp1 + exp2
    };
    
    this.displayQuestion();
  }

  generateDivisionQuestion() {
    const base = Math.floor(Math.random() * 5) + 2;
    const exp2 = Math.floor(Math.random() * 3) + 1;
    const exp1 = exp2 + Math.floor(Math.random() * 4) + 1;
    
    this.currentQuestion = {
      question: `${base}^${exp1} ÷ ${base}^${exp2} = ${base}^?`,
      answer: exp1 - exp2
    };
    
    this.displayQuestion();
  }

  generatePowerQuestion() {
    const base = Math.floor(Math.random() * 3) + 2;
    const exp1 = Math.floor(Math.random() * 3) + 2;
    const exp2 = Math.floor(Math.random() * 3) + 2;
    
    this.currentQuestion = {
      question: `(${base}^${exp1})^${exp2} = ${base}^?`,
      answer: exp1 * exp2
    };
    
    this.displayQuestion();
  }

  generateProductQuestion() {
    const base1 = Math.floor(Math.random() * 3) + 2;
    const base2 = Math.floor(Math.random() * 3) + 2;
    const exp = Math.floor(Math.random() * 3) + 2;
    
    // Randomly decide if the statement should be true or false
    const isTrue = Math.random() < 0.5;
    
    if (isTrue) {
      this.currentQuestion = {
        question: `(${base1} × ${base2})^${exp} = ${base1}^${exp} × ${base2}^${exp}`,
        answer: true
      };
    } else {
      // For false statements, we'll change the right side of the equation
      const wrongExp = exp + (Math.random() < 0.5 ? 1 : -1);
      this.currentQuestion = {
        question: `(${base1} × ${base2})^${exp} = ${base1}^${wrongExp} × ${base2}^${exp}`,
        answer: false
      };
    }
    
    this.displayQuestion();
  }

  generateQuotientQuestion() {
    const base1 = Math.floor(Math.random() * 3) + 2;
    const base2 = Math.floor(Math.random() * 3) + 2;
    const exp = Math.floor(Math.random() * 3) + 2;
    
    // Randomly decide if the statement should be true or false
    const isTrue = Math.random() < 0.5;
    
    if (isTrue) {
      this.currentQuestion = {
        question: `(${base1} ÷ ${base2})^${exp} = ${base1}^${exp} ÷ ${base2}^${exp}`,
        answer: true
      };
    } else {
      // For false statements, we'll change the right side of the equation
      const wrongExp = exp + (Math.random() < 0.5 ? 1 : -1);
      this.currentQuestion = {
        question: `(${base1} ÷ ${base2})^${exp} = ${base1}^${wrongExp} ÷ ${base2}^${exp}`,
        answer: false
      };
    }
    
    this.displayQuestion();
  }

  displayQuestion() {
    let questionText = this.currentQuestion.question;
    if (['product', 'quotient'].includes(this.currentProperty)) {
      questionText += "\n(Responde con Verdadero/V o Falso/F)";
    }
    this.questionElement.textContent = questionText;
    this.answerInput.value = '';
    this.feedbackElement.textContent = '';
    this.feedbackElement.className = 'feedback';
  }

  checkAnswer() {
    if (!this.currentQuestion) return;

    let userAnswer = this.answerInput.value.trim().toLowerCase();
    let isCorrect = false;

    if (['product', 'quotient'].includes(this.currentProperty)) {
      const userBooleanAnswer = userAnswer === 'verdadero' || userAnswer === 'v' || userAnswer === 'true' || userAnswer === 't';
      isCorrect = userBooleanAnswer === this.currentQuestion.answer;
    } else {
      isCorrect = parseInt(userAnswer) === this.currentQuestion.answer;
    }

    this.provideFeedback(isCorrect);
  }

  provideFeedback(isCorrect) {
    if (isCorrect) {
      this.score += 10;
      this.streak++;
      this.feedbackElement.textContent = '¡PODER MÁXIMO! ¡CORRECTO!';
      this.feedbackElement.className = 'feedback success';
      this.createParticleExplosion();
    } else {
      this.streak = 0;
      let correctAnswer = ['product', 'quotient'].includes(this.currentProperty) ? 
        (this.currentQuestion.answer ? 'Verdadero' : 'Falso') : 
        this.currentQuestion.answer;
      this.feedbackElement.textContent = `¡FALLO DE ENERGÍA! La respuesta correcta es: ${correctAnswer}`;
      this.feedbackElement.className = 'feedback error';
    }

    this.updateScore();
    if (isCorrect) {
      setTimeout(() => this.generateQuestion(), 1500);
    }
  }

  createParticleExplosion() {
    const colors = ['#ff00ff', '#00ffff', '#ffff00'];
    const center = {
      x: window.innerWidth / 2,
      y: window.innerHeight / 2
    };

    for (let i = 0; i < 50; i++) {
      const angle = (Math.PI * 2 * i) / 50;
      const velocity = 5 + Math.random() * 5;
      const particle = {
        x: center.x,
        y: center.y,
        vx: Math.cos(angle) * velocity,
        vy: Math.sin(angle) * velocity,
        color: colors[Math.floor(Math.random() * colors.length)],
        size: 5 + Math.random() * 5,
        life: 1
      };
      this.particles.push(particle);
    }

    this.animateParticles();
  }

  animateParticles() {
    if (this.particles.length === 0) return;

    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    for (let i = this.particles.length - 1; i >= 0; i--) {
      const p = this.particles[i];
      p.x += p.vx;
      p.y += p.vy;
      p.life -= 0.02;
      p.size *= 0.95;

      this.ctx.fillStyle = p.color;
      this.ctx.globalAlpha = p.life;
      this.ctx.fillRect(p.x, p.y, p.size, p.size);

      if (p.life <= 0) {
        this.particles.splice(i, 1);
      }
    }

    if (this.particles.length > 0) {
      requestAnimationFrame(() => this.animateParticles());
    }
  }

  updateScore() {
    this.scoreElement.textContent = this.score;
    this.streakElement.textContent = this.streak;
  }
}

// Initialize the game
const game = new PowerGame();