class AsteroidsGame {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        
        // Load images
        this.coinImage = new Image();
        this.coinImage.src = './assets/coin.png';
        this.explosionImage = new Image();
        this.explosionImage.src = './assets/explosion.png';
        
        // Explosion effects array
        this.explosions = [];
        
        // Game state
        this.lives = 5;
        this.round = 1;
        this.score = 0;
        this.gameActive = false; // Start inactive until Play Now is clicked
        this.gameStarted = false;
        this.gamePaused = false;
        this.currentGameId = null;
        this.currentRound = 1;
        this.roundScore = 0;
        this.gameOverSaved = false; // Track if game over was saved
        
        // Statistics tracking
        this.totalAsteroidsDestroyed = 0;
        this.roundAsteroidsDestroyed = 0;
        this.totalShotsFired = 0;
        this.roundShotsFired = 0;
        
        // Game objects
        this.ship = new Ship(this.canvas.width/2, this.canvas.height/2);
        this.asteroids = [];
        this.bullets = [];
        
        // Event listeners
        this.setupEventListeners();
        
        // Draw initial screen
        this.drawWaitingScreen();
    }
    
    spawnAsteroids(count) {
        for (let i = 0; i < count; i++) {
            this.asteroids.push(new Asteroid(
                Math.random() * this.canvas.width,
                Math.random() * this.canvas.height,
                'large',
                this.coinImage
            ));
        }
    }
    
    setupEventListeners() {
        document.addEventListener('keydown', (e) => this.handleKeyDown(e));
        document.addEventListener('keyup', (e) => this.handleKeyUp(e));
        document.getElementById('playAgain').addEventListener('click', () => this.resetGame());
        document.getElementById('endGameBtn').addEventListener('click', () => window.location.href = 'logout.php');
        document.getElementById('startGameBtn').addEventListener('click', () => this.startGame());
    }
    
    startGame() {
        // Hide the Play Now button
        document.getElementById('playNowButton').style.display = 'none';
        
        // Initialize game
        this.gameActive = true;
        this.gameStarted = true;
        
        // Spawn initial asteroids
        this.spawnAsteroids(4);
        
        // Start game loop
        this.gameLoop();
        
        // Start new game in database
        this.startNewGame();
    }
    
    drawWaitingScreen() {
        // Clear canvas
        this.ctx.fillStyle = 'black';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // Draw waiting message
        this.ctx.fillStyle = 'white';
        this.ctx.font = '24px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.fillText('Click PLAY NOW to start', this.canvas.width/2, this.canvas.height/2 - 50);
    }
    
    handleKeyDown(e) {
        if (!this.gameActive) return;
        
        // Toggle pause with 'P' key
        if (e.key === 'p' || e.key === 'P') {
            this.togglePause();
            return;
        }
        
        // Don't allow controls when paused
        if (this.gamePaused) return;
        
        switch(e.key) {
            case 'ArrowLeft': this.ship.rotateLeft = true; break;
            case 'ArrowRight': this.ship.rotateRight = true; break;
            case 'ArrowUp': this.ship.thrusting = true; break;
            case ' ': this.fireBullet(); break;
        }
    }
    
    handleKeyUp(e) {
        switch(e.key) {
            case 'ArrowLeft': this.ship.rotateLeft = false; break;
            case 'ArrowRight': this.ship.rotateRight = false; break;
            case 'ArrowUp': this.ship.thrusting = false; break;
        }
    }
    
    fireBullet() {
        if (!this.gameActive || this.gamePaused) return;
        this.bullets.push(new Bullet(
            this.ship.x,
            this.ship.y,
            this.ship.angle
        ));
        // Track shots fired
        this.totalShotsFired++;
        this.roundShotsFired++;
    }
    
    gameLoop() {
        if (!this.gameActive) {
            return;
        }
        
        if (this.gamePaused) {
            requestAnimationFrame(() => this.gameLoop());
            return;
        }
        
        this.update();
        this.draw();
        
        requestAnimationFrame(() => this.gameLoop());
    }
    
    update() {
        // Update ship
        this.ship.update(this.canvas.width, this.canvas.height);
        
        // Update bullets and remove off-screen ones
        this.bullets = this.bullets.filter(bullet => {
            bullet.update();
            return bullet.x > 0 && bullet.x < this.canvas.width && 
                   bullet.y > 0 && bullet.y < this.canvas.height;
        });
        
        // Update asteroids
        this.asteroids.forEach(asteroid => asteroid.update(this.canvas.width, this.canvas.height));
        
        // Update explosions
        for (let i = this.explosions.length - 1; i >= 0; i--) {
            this.explosions[i].update();
            if (this.explosions[i].finished) {
                this.explosions.splice(i, 1);
            }
        }
        
        // Remove expired small asteroids
        const currentTime = Date.now();
        for (let i = this.asteroids.length - 1; i >= 0; i--) {
            if (this.asteroids[i].size === 'small' && 
                currentTime - this.asteroids[i].creationTime > 15000) {
                this.asteroids.splice(i, 1);
            }
        }
        
        // Check collisions
        this.checkCollisions();
        
        // Check round completion
        if (this.asteroids.length === 0) {
            this.nextRound();
        }
    }
    
    checkCollisions() {
        // Bullet-asteroid collisions
        for (let i = this.bullets.length - 1; i >= 0; i--) {
            for (let j = this.asteroids.length - 1; j >= 0; j--) {
                if (this.checkCollision(this.bullets[i], this.asteroids[j])) {
                    const asteroid = this.asteroids[j];
                    
                    // Add score based on asteroid size
                    switch(asteroid.size) {
                        case 'large': this.addScore(20); break;
                        case 'medium': this.addScore(30); break;
                        case 'small': this.addScore(50); break;
                    }
                    
                    // Track asteroids destroyed
                    this.totalAsteroidsDestroyed++;
                    this.roundAsteroidsDestroyed++;
                    
                    // Create explosion effect
                    this.explosions.push(new Explosion(asteroid.x, asteroid.y, this.explosionImage));
                    
                    // Split asteroid if not small
                    if (asteroid.size !== 'small') {
                        const newSize = asteroid.size === 'large' ? 'medium' : 'small';
                        this.asteroids.push(new Asteroid(asteroid.x, asteroid.y, newSize, this.coinImage));
                        this.asteroids.push(new Asteroid(asteroid.x, asteroid.y, newSize, this.coinImage));
                    }
                    
                    // Remove bullet and asteroid
                    this.bullets.splice(i, 1);
                    this.asteroids.splice(j, 1);
                    break;
                }
            }
        }
        
        // Ship-asteroid collisions
        this.asteroids.forEach((asteroid, index) => {
            if (this.checkCollision(this.ship, asteroid)) {
                this.loseLife();
                this.asteroids.splice(index, 1);
            }
        });
    }
    
    checkCollision(obj1, obj2) {
        const dx = obj1.x - obj2.x;
        const dy = obj1.y - obj2.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        return distance < obj1.radius + obj2.radius;
    }
    
    addScore(points) {
        this.score += points;
        this.roundScore += points;
        this.updateUI();
    }
    
    loseLife() {
        this.lives--;
        this.updateUI();
        
        if (this.lives <= 0) {
            this.gameOver();
        } else {
            // Reset ship position
            this.ship.reset(this.canvas.width, this.canvas.height);
        }
    }
    
    nextRound() {
        // Save completed round statistics
        this.saveRoundScore();
        
        this.currentRound++;
        this.round++;
        this.roundScore = 0;
        this.roundAsteroidsDestroyed = 0;
        this.roundShotsFired = 0;
        this.spawnAsteroids(4 + this.round); // Increase difficulty
        this.updateUI();
    }
    
    gameOver() {
        this.gameActive = false;
        
        // Only save once per game
        if (!this.gameOverSaved) {
            this.gameOverSaved = true;
            this.saveFinalScore();
        }
        
        document.getElementById('finalScore').textContent = this.score;
        document.getElementById('gameOver').classList.remove('hidden');
    }
    
    resetGame() {
        this.lives = 5;
        this.round = 1;
        this.currentRound = 1;
        this.score = 0;
        this.roundScore = 0;
        this.gameOverSaved = false; // Reset the saved flag
        this.currentGameId = null; // Reset game ID for new game
        
        // Reset statistics
        this.totalAsteroidsDestroyed = 0;
        this.roundAsteroidsDestroyed = 0;
        this.totalShotsFired = 0;
        this.roundShotsFired = 0;
        
        this.asteroids = [];
        this.bullets = [];
        this.explosions = [];
        this.gameActive = true;
        this.ship.reset(this.canvas.width, this.canvas.height);
        
        document.getElementById('gameOver').classList.add('hidden');
        this.spawnAsteroids(4);
        this.updateUI();
        this.startNewGame();
        this.gameLoop();
    }
    
    updateUI() {
        document.getElementById('lives').textContent = this.lives;
        document.getElementById('round').textContent = this.round;
        document.getElementById('score').textContent = this.score;
        
        // Update pause indicator
        const pauseIndicator = document.getElementById('pauseIndicator');
        if (pauseIndicator) {
            pauseIndicator.textContent = this.gamePaused ? 'PAUSED' : '';
            pauseIndicator.style.display = this.gamePaused ? 'block' : 'none';
        }
    }
    
    togglePause() {
        this.gamePaused = !this.gamePaused;
        this.updateUI();
    }
    
    async startNewGame() {
        // Prevent multiple game creations
        if (this.currentGameId) {
            // Game already has ID, skipping creation
            return;
        }
        
        try {
            const response = await fetch('save_game.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({action: 'start_game'})
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            this.currentGameId = data.game_id;
        } catch (error) {
            // Error starting new game
        }
    }
    
    async saveFinalScore() {
        if (!this.currentGameId) {
            return;
        }
        
        // Calculate accuracy
        const accuracy = this.totalShotsFired > 0 ? 
            Math.round((this.totalAsteroidsDestroyed / this.totalShotsFired) * 100) : 0;
        
        const payload = {
            action: 'save_final_score',
            game_id: this.currentGameId,
            round_number: this.currentRound, // Save current round (not -1)
            score: this.score, // Save total score at death
            asteroids_destroyed: this.totalAsteroidsDestroyed,
            shots_fired: this.totalShotsFired,
            accuracy: accuracy
        };
        
        try {
            const response = await fetch('save_game.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(payload)
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const result = await response.json();
        } catch (error) {
            // Error saving final score
        }
    }
    
    async saveRoundScore() {
        if (!this.currentGameId) return;
        
        // Don't save if round score is 0 (unless it's the very first round)
        if (this.roundScore === 0 && this.currentRound > 1) return;
        
        // Calculate accuracy for this round
        const roundAccuracy = this.roundShotsFired > 0 ? 
            Math.round((this.roundAsteroidsDestroyed / this.roundShotsFired) * 100) : 0;
        
        try {
            const response = await fetch('save_game.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    action: 'save_round',
                    game_id: this.currentGameId,
                    round_number: this.currentRound - 1, // Save completed round (current - 1)
                    score: this.roundScore,
                    asteroids_destroyed: this.roundAsteroidsDestroyed,
                    shots_fired: this.roundShotsFired,
                    accuracy: roundAccuracy
                })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            // Round statistics saved successfully
        } catch (error) {
            // Error saving round score
        }
    }
}

// Ship class
class Ship {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.angle = 0;
        this.vx = 0;
        this.vy = 0;
        this.rotateLeft = false;
        this.rotateRight = false;
        this.thrusting = false;
        this.radius = 10;
    }
    
    update(canvasWidth, canvasHeight) {
        // Rotation
        if (this.rotateLeft) this.angle -= 0.05;
        if (this.rotateRight) this.angle += 0.05;
        
        // Thrust
        if (this.thrusting) {
            this.vx += Math.cos(this.angle) * 0.1;
            this.vy += Math.sin(this.angle) * 0.1;
        }
        
        // Apply velocity
        this.x += this.vx;
        this.y += this.vy;
        
        // Screen wrapping
        if (this.x < 0) this.x = canvasWidth;
        if (this.x > canvasWidth) this.x = 0;
        if (this.y < 0) this.y = canvasHeight;
        if (this.y > canvasHeight) this.y = 0;
        
        // Friction
        this.vx *= 0.99;
        this.vy *= 0.99;
    }
    
    reset(canvasWidth, canvasHeight) {
        this.x = canvasWidth / 2;
        this.y = canvasHeight / 2;
        this.vx = 0;
        this.vy = 0;
        this.angle = 0;
    }
    
    draw(ctx) {
        ctx.save();
        ctx.translate(this.x, this.y);
        ctx.rotate(this.angle);
        
        ctx.strokeStyle = 'white';
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.moveTo(10, 0);
        ctx.lineTo(-10, -7);
        ctx.lineTo(-10, 7);
        ctx.closePath();
        ctx.stroke();
        
        // Thruster
        if (this.thrusting) {
            ctx.beginPath();
            ctx.moveTo(-10, 0);
            ctx.lineTo(-15, 0);
            ctx.stroke();
        }
        
        ctx.restore();
    }
}

// Asteroid class
class Asteroid {
    constructor(x, y, size, coinImage) {
        this.x = x;
        this.y = y;
        this.size = size;
        this.image = coinImage;
        
        // Set properties based on size
        switch(size) {
            case 'large':
                this.radius = 30;
                this.speed = 1;
                break;
            case 'medium':
                this.radius = 20;
                this.speed = 1.5;
                break;
            case 'small':
                this.radius = 10;
                this.speed = 2;
                break;
        }
        
        // Random direction
        const angle = Math.random() * Math.PI * 2;
        this.vx = Math.cos(angle) * this.speed;
        this.vy = Math.sin(angle) * this.speed;
        
        // Small asteroids disappear after 15 seconds
        if (size === 'small') {
            this.creationTime = Date.now();
        }
    }
    
    update(canvasWidth, canvasHeight) {
        this.x += this.vx;
        this.y += this.vy;
        
        // Screen wrapping
        if (this.x < -this.radius) this.x = canvasWidth + this.radius;
        if (this.x > canvasWidth + this.radius) this.x = -this.radius;
        if (this.y < -this.radius) this.y = canvasHeight + this.radius;
        if (this.y > canvasHeight + this.radius) this.y = -this.radius;
    }
    
    draw(ctx) {
        ctx.save();
        ctx.translate(this.x, this.y);
        
        // Create circular clipping mask
        ctx.beginPath();
        ctx.arc(0, 0, this.radius, 0, Math.PI * 2);
        ctx.closePath();
        ctx.clip();
        
        // Draw the coin image scaled to size within the circular mask
        const imageSize = this.radius * 2;
        ctx.drawImage(this.image, -imageSize/2, -imageSize/2, imageSize, imageSize);
        
        ctx.restore();
    }
}

// Bullet class
class Bullet {
    constructor(x, y, angle) {
        this.x = x;
        this.y = y;
        this.angle = angle;
        this.speed = 5;
        this.vx = Math.cos(angle) * this.speed;
        this.vy = Math.sin(angle) * this.speed;
        this.radius = 2;
    }
    
    update() {
        this.x += this.vx;
        this.y += this.vy;
    }
    
    draw(ctx) {
        ctx.fillStyle = 'white';
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        ctx.fill();
    }
}

// Explosion class
class Explosion {
    constructor(x, y, explosionImage) {
        this.x = x;
        this.y = y;
        this.image = explosionImage;
        this.radius = 20;
        this.creationTime = Date.now();
        this.finished = false;
        this.opacity = 1;
    }
    
    update() {
        this.radius += 1;
        this.opacity -= 0.02;
        if (this.opacity <= 0) {
            this.finished = true;
        }
    }
    
    draw(ctx) {
        ctx.save();
        ctx.globalAlpha = this.opacity;
        ctx.translate(this.x, this.y);
        
        // Draw the explosion image scaled to size
        const imageSize = this.radius * 2;
        ctx.drawImage(this.image, -imageSize/2, -imageSize/2, imageSize, imageSize);
        
        ctx.restore();
    }
}

// Draw function for the game
AsteroidsGame.prototype.draw = function() {
    // Clear canvas
    this.ctx.fillStyle = 'black';
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    
    // Draw objects
    this.ship.draw(this.ctx);
    this.asteroids.forEach(asteroid => asteroid.draw(this.ctx));
    this.bullets.forEach(bullet => bullet.draw(this.ctx));
    this.explosions.forEach(explosion => explosion.draw(this.ctx));
};

// Initialize game when page loads
let game;
window.addEventListener('load', () => {
    game = new AsteroidsGame();
});