/**
 * Flappy Fart Game - Complete Implementation with Peter Image
 * Peter flies by farting and avoids toxic gas pipes
 */

class FlappyFartGame {
    constructor() {
        this.canvas = null;
        this.ctx = null;
        this.gameRunning = false;
        this.gameLoop = null;

        // Game settings
        this.canvasWidth = 400;
        this.canvasHeight = 600;

        // Peter image
        this.peterImage = new Image();
        this.peterImageLoaded = false;

        // Peter (bird) properties
        this.peter = {
            x: 80,
            y: 300,
            width: 50,
            height: 50,
            velocity: 0,
            fartPower: -8,
            gravity: 0.4,
            maxVelocity: 8,
            rotation: 0
        };

        // Pipe properties
        this.pipes = [];
        this.pipeWidth = 60;
        this.pipeGap = 180;
        this.pipeSpeed = 2;

        // Game state
        this.score = 0;
        this.bestScore = 0;
        this.totalFarts = 0;
        this.gameSpeed = 60; // FPS

        // UI elements
        this.modal = null;
        this.scoreElement = null;
        this.bestElement = null;
        this.fartsElement = null;

        // Background
        this.backgroundX = 0;

        // Fart trail system
        this.fartTrail = [];

        this.init();
    }

    init() {
        document.addEventListener('DOMContentLoaded', () => {
            this.loadPeterImage();
            this.setupElements();
            this.setupEventListeners();
            this.loadBestScore();
            console.log('🐦💨 Flappy Fart game initialized!');
        });
    }

    loadPeterImage() {
        this.peterImage.onload = () => {
            this.peterImageLoaded = true;
            console.log('🐦 Peter image loaded successfully!');
        };

        this.peterImage.onerror = () => {
            console.warn('⚠️ Could not load Peter image, using fallback');
            this.peterImageLoaded = false;
        };

        // Try to load the Peter image - using transparent version
        this.peterImage.src = '/static/images/peter-transparent.png';
    }

    setupElements() {
        this.modal = document.getElementById('flappyFartModal');
        this.canvas = document.getElementById('flappyFartCanvas');

        if (!this.canvas) {
            console.warn('Flappy Fart canvas not found');
            return;
        }

        this.ctx = this.canvas.getContext('2d');
        this.scoreElement = document.getElementById('fart-score');
        this.bestElement = document.getElementById('fart-best');
        this.fartsElement = document.getElementById('total-farts');
    }

    setupEventListeners() {
        const playButton = document.getElementById('play-flappy-fart');
        if (playButton) {
            playButton.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                this.openGame();
            });
        }

        const gameCard = document.getElementById('flappy-fart-card');
        if (gameCard) {
            gameCard.classList.remove('fart-button');
            gameCard.addEventListener('click', (e) => {
                if (e.target === gameCard || e.target.closest('.game-content')) {
                    if (!e.target.closest('button')) {
                        this.openGame();
                    }
                }
            });
        }

        const startButton = document.getElementById('start-fart');
        if (startButton) {
            startButton.addEventListener('click', (e) => {
                e.preventDefault();
                this.startGame();
            });
        }

        const restartButton = document.getElementById('restart-fart');
        if (restartButton) {
            restartButton.addEventListener('click', (e) => {
                e.preventDefault();
                this.restartGame();
            });
        }

        // Game controls
        document.addEventListener('keydown', (e) => {
            if (this.gameRunning && this.isModalOpen()) {
                if (e.code === 'Space') {
                    e.preventDefault();
                    this.fart();
                }
            }
        });

        // Canvas click/touch
        if (this.canvas) {
            this.canvas.addEventListener('click', () => {
                if (this.gameRunning) {
                    this.fart();
                }
            });

            this.canvas.addEventListener('touchstart', (e) => {
                e.preventDefault();
                if (this.gameRunning) {
                    this.fart();
                }
            });
        }

        if (this.modal) {
            this.modal.addEventListener('shown.bs.modal', () => {
                this.onModalShown();
            });

            this.modal.addEventListener('hidden.bs.modal', () => {
                this.stopGame();
            });
        }
    }

    isModalOpen() {
        return this.modal && this.modal.classList.contains('show');
    }

    onModalShown() {
        this.setupCanvas();
        this.showInstructions();
    }

    setupCanvas() {
        if (!this.canvas) return;

        const container = this.canvas.parentElement;
        const containerWidth = container.clientWidth;
        const aspectRatio = 16 / 10;

        let width = containerWidth;
        let height = width / aspectRatio;

        const minHeight = 400;
        const maxHeight = 600;

        if (height < minHeight) {
            height = minHeight;
            width = height * aspectRatio;
        } else if (height > maxHeight) {
            height = maxHeight;
            width = height * aspectRatio;
        }

        this.canvas.width = width;
        this.canvas.height = height;
        this.canvasWidth = width;
        this.canvasHeight = height;

        // Update game dimensions
        this.peter.y = height / 2;
        this.pipeGap = Math.max(120, height * 0.25);

        console.log(`🐦 Canvas setup: ${width}x${height}`);
    }

    openGame() {
        if (this.modal) {
            const modal = new bootstrap.Modal(this.modal);
            modal.show();
            this.playFartSound();
        }
    }

    showInstructions() {
        const instructions = document.getElementById('fart-instructions');
        const gameOver = document.getElementById('fart-game-over');

        if (instructions) instructions.style.display = 'flex';
        if (gameOver) gameOver.style.display = 'none';
    }

    startGame() {
        const instructions = document.getElementById('fart-instructions');
        if (instructions) instructions.style.display = 'none';

        this.setupCanvas();
        this.resetGame();

        setTimeout(() => {
            this.gameRunning = true;
            this.gameLoop = setInterval(() => {
                this.update();
                this.draw();
            }, 1000 / this.gameSpeed);

            console.log('🐦💨 Flappy Fart game started!');
        }, 100);
    }

    resetGame() {
        this.peter.x = 80;
        this.peter.y = this.canvasHeight / 2;
        this.peter.velocity = 0;
        this.peter.rotation = 0;
        this.score = 0;
        this.pipes = [];
        this.backgroundX = 0;
        this.fartTrail = [];

        // Generate first pipes
        this.generatePipe();

        this.updateUI();
        this.draw();
    }

    update() {
        if (!this.gameRunning) return;

        // Update Peter physics
        this.peter.velocity += this.peter.gravity;
        this.peter.velocity = Math.min(this.peter.velocity, this.peter.maxVelocity);
        this.peter.y += this.peter.velocity;

        // Update Peter rotation based on velocity
        this.peter.rotation = Math.min(Math.max(this.peter.velocity * 3, -30), 90);

        // Update background
        this.backgroundX -= this.pipeSpeed * 0.5;
        if (this.backgroundX <= -this.canvasWidth) {
            this.backgroundX = 0;
        }

        // Update fart trail
        this.updateFartTrail();

        // Update pipes
        for (let i = this.pipes.length - 1; i >= 0; i--) {
            const pipe = this.pipes[i];
            pipe.x -= this.pipeSpeed;

            // Check if Peter passed through pipe
            if (!pipe.scored && pipe.x + this.pipeWidth < this.peter.x) {
                pipe.scored = true;
                this.score++;
                this.showScorePopup();
                this.playFartSound();
            }

            // Remove pipes that are off screen
            if (pipe.x + this.pipeWidth < 0) {
                this.pipes.splice(i, 1);
            }
        }

        // Generate new pipes
        if (this.pipes.length === 0 || this.pipes[this.pipes.length - 1].x < this.canvasWidth - 200) {
            this.generatePipe();
        }

        // Check collisions
        if (this.checkCollisions()) {
            this.gameOver();
            return;
        }

        // Check boundaries
        if (this.peter.y < 0 || this.peter.y + this.peter.height > this.canvasHeight) {
            this.gameOver();
            return;
        }

        this.updateUI();
    }

    updateFartTrail() {
        // Remove old fart particles
        this.fartTrail = this.fartTrail.filter(fart => fart.life > 0);

        // Update existing fart particles
        this.fartTrail.forEach(fart => {
            fart.x -= this.pipeSpeed * 1.5; // Move faster than pipes
            fart.y += Math.sin(fart.age * 0.1) * 0.5; // Slight wave motion
            fart.life--;
            fart.age++;
            fart.opacity = fart.life / fart.maxLife;
        });
    }

    generatePipe() {
        const minPipeHeight = 50;
        const maxPipeHeight = this.canvasHeight - this.pipeGap - minPipeHeight;
        const pipeHeight = Math.random() * (maxPipeHeight - minPipeHeight) + minPipeHeight;

        this.pipes.push({
            x: this.canvasWidth,
            topHeight: pipeHeight,
            bottomY: pipeHeight + this.pipeGap,
            bottomHeight: this.canvasHeight - (pipeHeight + this.pipeGap),
            scored: false
        });
    }

    checkCollisions() {
        const peterLeft = this.peter.x + 5; // Small margin
        const peterRight = this.peter.x + this.peter.width - 5;
        const peterTop = this.peter.y + 5;
        const peterBottom = this.peter.y + this.peter.height - 5;

        for (const pipe of this.pipes) {
            const pipeLeft = pipe.x;
            const pipeRight = pipe.x + this.pipeWidth;

            // Check if Peter is in pipe's x range
            if (peterRight > pipeLeft && peterLeft < pipeRight) {
                // Check collision with top pipe
                if (peterTop < pipe.topHeight) {
                    return true;
                }
                // Check collision with bottom pipe
                if (peterBottom > pipe.bottomY) {
                    return true;
                }
            }
        }

        return false;
    }

    fart() {
        if (!this.gameRunning) return;

        this.peter.velocity = this.peter.fartPower;
        this.totalFarts++;

        // Add fart particle behind Peter
        this.addFartParticle();

        this.playFartSound();
        this.createFartEffect();

        // Update farts counter immediately
        if (this.fartsElement) {
            this.fartsElement.textContent = this.totalFarts;
        }
    }

    addFartParticle() {
        // Add multiple fart emojis in the trail
        for (let i = 0; i < 3; i++) {
            this.fartTrail.push({
                x: this.peter.x - 10 - (i * 8),
                y: this.peter.y + this.peter.height / 2 + (Math.random() - 0.5) * 20,
                life: 30 - (i * 5),
                maxLife: 30 - (i * 5),
                opacity: 1,
                age: 0,
                size: 0.8 + Math.random() * 0.4
            });
        }
    }

    draw() {
        if (!this.ctx || !this.canvas.width || !this.canvas.height) return;

        this.clearCanvas();
        this.drawBackground();
        this.drawFartTrail();
        this.drawPipes();
        this.drawPeter();
    }

    clearCanvas() {
        if (!this.ctx) return;
        this.ctx.fillStyle = '#87CEEB';
        this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
    }

    drawBackground() {
        // Draw moving clouds
        this.ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
        for (let i = 0; i < 3; i++) {
            const x = (this.backgroundX + i * 150) % (this.canvasWidth + 100);
            const y = 50 + i * 30;
            this.drawCloud(x, y);
        }
    }

    drawCloud(x, y) {
        this.ctx.beginPath();
        this.ctx.arc(x, y, 20, 0, Math.PI * 2);
        this.ctx.arc(x + 25, y, 25, 0, Math.PI * 2);
        this.ctx.arc(x + 50, y, 20, 0, Math.PI * 2);
        this.ctx.fill();
    }

    drawFartTrail() {
        // Draw fart particles behind Peter
        this.fartTrail.forEach(fart => {
            this.ctx.save();
            this.ctx.globalAlpha = fart.opacity;
            this.ctx.font = `${16 * fart.size}px Arial`;
            this.ctx.fillText('💨', fart.x, fart.y);
            this.ctx.restore();
        });
    }

    drawPipes() {
        this.ctx.fillStyle = '#2C5530';
        this.ctx.strokeStyle = '#1A3A1E';
        this.ctx.lineWidth = 2;

        for (const pipe of this.pipes) {
            // Draw top pipe
            this.ctx.fillRect(pipe.x, 0, this.pipeWidth, pipe.topHeight);
            this.ctx.strokeRect(pipe.x, 0, this.pipeWidth, pipe.topHeight);

            // Draw bottom pipe
            this.ctx.fillRect(pipe.x, pipe.bottomY, this.pipeWidth, pipe.bottomHeight);
            this.ctx.strokeRect(pipe.x, pipe.bottomY, this.pipeWidth, pipe.bottomHeight);

            // Draw pipe caps
            this.ctx.fillStyle = '#3A6B3F';
            this.ctx.fillRect(pipe.x - 5, pipe.topHeight - 20, this.pipeWidth + 10, 20);
            this.ctx.fillRect(pipe.x - 5, pipe.bottomY, this.pipeWidth + 10, 20);
            this.ctx.fillStyle = '#2C5530';
        }
    }

    drawPeter() {
        this.ctx.save();

        // Move to Peter's center for rotation
        this.ctx.translate(this.peter.x + this.peter.width / 2, this.peter.y + this.peter.height / 2);
        this.ctx.rotate(this.peter.rotation * Math.PI / 180);

        if (this.peterImageLoaded) {
            // Draw Peter image
            this.ctx.drawImage(
                this.peterImage,
                -this.peter.width / 2,
                -this.peter.height / 2,
                this.peter.width,
                this.peter.height
            );
        } else {
            // Fallback: Draw Peter as emoji
            this.ctx.font = `${this.peter.width}px Arial`;
            this.ctx.textAlign = 'center';
            this.ctx.textBaseline = 'middle';
            this.ctx.fillText('🐦', 0, 0);
        }

        this.ctx.restore();
    }

    createFartEffect() {
        const effect = document.createElement('span');
        effect.textContent = '💨';
        effect.className = 'fart-boost-effect';

        const rect = this.canvas.getBoundingClientRect();
        effect.style.cssText = `
            position: fixed;
            left: ${rect.left + this.peter.x}px;
            top: ${rect.top + this.peter.y + this.peter.height}px;
            font-size: 1.2rem;
            pointer-events: none;
            z-index: 25;
        `;

        document.body.appendChild(effect);

        setTimeout(() => {
            if (effect.parentNode) {
                effect.remove();
            }
        }, 800);
    }

    showScorePopup() {
        const popup = document.createElement('span');
        popup.textContent = '+1';
        popup.className = 'score-popup';

        const rect = this.canvas.getBoundingClientRect();
        popup.style.cssText = `
            position: fixed;
            left: ${rect.left + this.canvasWidth / 2}px;
            top: ${rect.top + 100}px;
            font-size: 1.5rem;
            font-weight: bold;
            color: #F1C40F;
            pointer-events: none;
            z-index: 25;
        `;

        document.body.appendChild(popup);

        setTimeout(() => {
            if (popup.parentNode) {
                popup.remove();
            }
        }, 1200);
    }

    updateUI() {
        if (this.scoreElement) this.scoreElement.textContent = this.score;
        if (this.bestElement) this.bestElement.textContent = this.bestScore;
        if (this.fartsElement) this.fartsElement.textContent = this.totalFarts;
    }

    gameOver() {
        this.gameRunning = false;
        clearInterval(this.gameLoop);

        // Update best score
        if (this.score > this.bestScore) {
            this.bestScore = this.score;
            this.saveBestScore();
        }

        // Update final stats
        const finalScore = document.getElementById('final-fart-score');
        const finalBest = document.getElementById('final-fart-best');
        const finalFarts = document.getElementById('final-total-farts');

        if (finalScore) finalScore.textContent = this.score;
        if (finalBest) finalBest.textContent = this.bestScore;
        if (finalFarts) finalFarts.textContent = this.totalFarts;

        // Generate social share buttons
        this.setupSocialShare();

        // Show game over screen
        const gameOverScreen = document.getElementById('fart-game-over');
        if (gameOverScreen) {
            gameOverScreen.style.display = 'flex';
        }

        this.playFartSound();
        this.createCrashEffect();
        console.log(`💨 Game Over! Final Score: ${this.score}`);
    }

    createCrashEffect() {
        const effect = document.createElement('span');
        effect.textContent = '💥';
        effect.className = 'crash-effect';

        const rect = this.canvas.getBoundingClientRect();
        effect.style.cssText = `
            position: fixed;
            left: ${rect.left + this.peter.x}px;
            top: ${rect.top + this.peter.y}px;
            font-size: 2rem;
            pointer-events: none;
            z-index: 25;
        `;

        document.body.appendChild(effect);

        setTimeout(() => {
            if (effect.parentNode) {
                effect.remove();
            }
        }, 1000);
    }

    setupSocialShare() {
        // Check if social share manager is available
        if (typeof window.SocialShare === 'undefined') {
            console.warn('Social Share Manager not loaded');
            return;
        }

        // Clear previous share buttons
        const shareContainer = document.getElementById('fart-share-container');
        if (shareContainer) {
            shareContainer.innerHTML = '';
        }

        // Generate share data for Flappy Fart
        const shareData = {
            text: `Just played Flappy Fart and survived the gas clouds! 💨🐦`,
            gameData: {
                score: this.score,
                gameName: 'Flappy Fart',
                achievement: `Got ${this.score} points with ${this.totalFarts} epic farts! Best: ${this.bestScore}`
            },
            hashtags: ['FlappyFart', 'PeterToken', 'SolanaGaming', 'GassyGamer', 'Solana', 'pumpfun']
        };

        // Add custom URL pointing to the game
        shareData.url = window.location.href;

        // Generate share buttons using the existing social share system
        window.SocialShare.generateShareButtons(shareData, 'fart-share-container');

        console.log('💨 Social share buttons generated for Flappy Fart');
    }

    restartGame() {
        const gameOverScreen = document.getElementById('fart-game-over');
        if (gameOverScreen) {
            gameOverScreen.style.display = 'none';
        }

        this.startGame();
    }

    stopGame() {
        this.gameRunning = false;
        if (this.gameLoop) {
            clearInterval(this.gameLoop);
            this.gameLoop = null;
        }
    }

    loadBestScore() {
        const saved = localStorage.getItem('flappyFartBestScore');
        if (saved) {
            this.bestScore = parseInt(saved, 10) || 0;
        }
    }

    saveBestScore() {
        localStorage.setItem('flappyFartBestScore', this.bestScore.toString());
    }

    playFartSound() {
        if (typeof peterManager !== 'undefined' && peterManager.playRandomFartSound) {
            peterManager.playRandomFartSound();
        }
    }
}

// Initialize the Flappy Fart game
const flappyFartGame = new FlappyFartGame();

console.log('🐦💨 Flappy Fart game loaded with Peter image and fart trail!');