class NumberSortGame {
    constructor() {
        this.numbersContainer = document.getElementById('numbers-container');
        this.resultMessage = document.getElementById('result-message');
        this.checkButton = document.getElementById('checkButton');
        this.resetButton = document.getElementById('resetButton');
        
        this.numbers = [];
        this.selectedNumbers = [];
        
        this.initGame();
    }
    
    initGame() {
        this.generateRandomNumbers();
        this.renderNumbers();
        this.setupEventListeners();
    }
    
    generateRandomNumbers() {
        this.numbers = [];
        while (this.numbers.length < 5) {
            const randomNumber = Math.floor(Math.random() * 201) - 100;
            if (!this.numbers.includes(randomNumber)) {
                this.numbers.push(randomNumber);
            }
        }
    }
    
    renderNumbers() {
        this.numbersContainer.innerHTML = '';
        this.numbers.forEach(number => {
            const numberBox = document.createElement('div');
            numberBox.classList.add('number-box');
            numberBox.textContent = number;
            numberBox.addEventListener('click', () => this.selectNumber(number, numberBox));
            this.numbersContainer.appendChild(numberBox);
        });
    }
    
    setupEventListeners() {
        this.checkButton.addEventListener('click', () => this.checkOrder());
        this.resetButton.addEventListener('click', () => this.resetGame());
    }
    
    selectNumber(number, numberBox) {
        const index = this.selectedNumbers.indexOf(number);
        
        if (index !== -1) {
            this.selectedNumbers.splice(index, 1);
            numberBox.classList.remove('selected');
        } else {
            this.selectedNumbers.push(number);
            numberBox.classList.add('selected');
        }
    }
    
    checkOrder() {
        const sortedSelectedNumbers = [...this.selectedNumbers].sort((a, b) => a - b);
        const originalSortedNumbers = [...this.numbers].sort((a, b) => a - b);
        
        const isCorrect = JSON.stringify(sortedSelectedNumbers) === JSON.stringify(originalSortedNumbers);
        
        if (isCorrect) {
            this.resultMessage.textContent = '¡Correcto! Has ordenado los números';
            this.resultMessage.style.color = 'green';
        } else {
            this.resultMessage.textContent = 'Intenta de nuevo';
            this.resultMessage.style.color = 'red';
        }
    }
    
    resetGame() {
        this.selectedNumbers = [];
        this.resultMessage.textContent = '';
        this.generateRandomNumbers();
        this.renderNumbers();
        
        const numberBoxes = document.querySelectorAll('.number-box');
        numberBoxes.forEach(box => box.classList.remove('selected'));
    }
}

document.addEventListener('DOMContentLoaded', () => {
    new NumberSortGame();
});