// 2. Побег
export class Pobeg extends Phaser.Scene {
    constructor() {
        super('Pobeg');

        this.playerFrames = [
            ['  O  ', ' /|\\ ', ' / 7 ', '/    '],
            ['  O  ', ' /|\\ ', '  |\\ ',' /  L'],
            ['  O  ', ' /|\\ ', '_/|  ', '  L  ']
        ];
        this.playerStumbleFrame = [
            '     ',
            '     ',
            '     ',
            '==--\\-o'
        ];
        this.zombieFrame = [
            '\\o/  ',
            '  |  ',
            ' / \\ ',
            ' | | '
        ];
        
        this.initialZombieSpeed = 5; // characters per second
    }

    preload() {
        this.load.audio('footstep_1', 'assets/sounds/footstep_1.ogg');
        this.load.audio('footstep_2', 'assets/sounds/footstep_2.ogg');
        this.load.audio('slap', 'assets/sounds/slap.ogg');
    }

    create() {
        localStorage.setItem('Scene', this.scene.key);

        const graphics = this.add.graphics();
        graphics.fillStyle(0x000000, 1);
        graphics.fillRect(0, 0, 1280, 720);

        this.asciiScreen = this.add.text(40, 40, '', {
            fontFamily: 'monospace',
            fontSize: '20px',
            color: '#0000ff',
            align: 'left',
            resolution: window.devicePixelRatio,
        });

        this.initGame();

        this.input.keyboard.on('keydown-F', () => this.handleRun('F'));
        this.input.keyboard.on('keydown-J', () => this.handleRun('J'));

        this.input.keyboard.on('keydown', () => {
            if (this.gameOver) {
                this.scene.start('Start');
            }
        });
        
        this.add.text(40, 680, '[F] шаг левой [J] шаг правой', {
            fontFamily: 'monospace',
            fontSize: '20px',
            color: '#0000ff',
            align: 'left'
        });
    }

    initGame() {
        this.lastKeyPressed = null;
        this.playerAnimState = 0;
        this.distanceRun = 0;
        this.gameOver = false;
        this.isStumbling = false;
        this.footstepIndex = 0;

        // Play background music
        this.sound.stopAll();
        this.sound.play('backgroundMusic_Action1', { loop: true });
        
        this.worldWidth = 55;
        this.worldHeight = 15;
        this.playerPos = { x: this.worldWidth - 10, y: this.worldHeight - 6 };

        this.zombies = [{ x: 10 }, { x: 5 }];
        
        this.zombieSpeed = this.initialZombieSpeed;
        this.speedMilestone = 0;

        this.asciiScreen.setColor('#0000FF');
        this.drawScreen();
    }

    handleRun(key) {
        if (this.gameOver || this.isStumbling) return;

        const stepPower = 2;
        if (this.lastKeyPressed !== key) {
            this.distanceRun++;

            // Play footstep sound
            this.footstepIndex = 1 - this.footstepIndex; // Alternates between 0 and 1
            this.sound.play(`footstep_${this.footstepIndex + 1}`);

            if (this.distanceRun >= 200) {
                this.scene.start('Mech');
                return;
            }

            // Stumble and speed logic
            if (this.distanceRun >= this.speedMilestone + 25) {
                this.speedMilestone += 25;
                this.zombieSpeed += 2;

                const closestZombieX = Math.max(...this.zombies.map(z => z.x), 0);
                const distanceToZombie = this.playerPos.x - closestZombieX;
                if (distanceToZombie > 23) {
                    this.isStumbling = true;
                    this.sound.play('slap');
                }
            }

            this.zombies.forEach(zombie => {
                zombie.x -= stepPower;
            });

            this.playerAnimState += 1;
            if(this.playerAnimState == 3)
                this.playerAnimState = 0;
        }
        
        this.lastKeyPressed = key;
    }

    update(time, delta) {
        if (this.gameOver || !this.scene.isActive()) return;
        
        // Stumble recovery check
        if(this.isStumbling) {
            const closestZombieX = Math.max(...this.zombies.map(z => z.x), 0);
            const distanceToZombie = this.playerPos.x - closestZombieX;
            if (distanceToZombie <= 23) {
                this.isStumbling = false;
            }
        }

        const moveDistance = (this.zombieSpeed * delta) / 1000;
        this.zombies.forEach(zombie => {
            zombie.x += moveDistance;
        });

        this.zombies = this.zombies.filter(zombie => zombie.x > -5);
        if (Math.random() > 0.985 && this.zombies.length < 5) {
            this.zombies.push({ x: Math.floor(Math.random() * 5) });
        }
        
        this.drawScreen();

        if (this.zombies.some(z => z.x >= this.playerPos.x - 2)) {
            this.gameOver = true;
            this.drawGameOver();
        }
    }

    drawScreen() {
        if (this.gameOver) return;

        let screen = Array(this.worldHeight).fill(0).map(() => Array(this.worldWidth).fill(' '));

        // Draw zombies
        this.zombies.forEach(zombie => {
            const zx = Math.floor(zombie.x);
            const zy = this.worldHeight - 6;
            this.zombieFrame.forEach((line, i) => {
                for(let j=0; j < line.length; j++) {
                    if (zy + i < this.worldHeight && zx + j < this.worldWidth && zx+j >= 0) {
                       screen[zy + i][zx + j] = line[j];
                    }
                }
            });
        });

        // Draw player
        const playerFrame = this.isStumbling ? this.playerStumbleFrame : this.playerFrames[this.playerAnimState];
        playerFrame.forEach((line, i) => {
            for(let j=0; j < line.length; j++) {
                screen[this.playerPos.y + i][this.playerPos.x + j] = line[j];
            }
        });
        
        for(let i=0; i < this.worldWidth; i++){
            screen[this.worldHeight-2][i] = '-';
        }

        let screenText = screen.map(row => row.join('')).join('\n');
        /*screenText += `\n\nDistance: ${this.distanceRun}m / 200m`;
        screenText += `\nZombie Speed: ${this.zombieSpeed.toFixed(1)} c/s`;*/
        if (this.isStumbling) {
            screenText += `\n\n   !!! Упал !!!`;
        }
        this.asciiScreen.setText(screenText);
    }
    
    drawGameOver() {
        this.asciiScreen.setColor('#ff0000');
        let gameOverText = `\n\n`;
        gameOverText += `           \n`;
        gameOverText += `     Слишком медленно\n`;
        gameOverText += `   Вас догнали и съели.\n`;
        gameOverText += `   Попробуйте ещё раз`;
        
        let screenLines = this.asciiScreen.text.split('\n');
        let gameOverLines = gameOverText.split('\n');

        const startY = Math.floor((this.worldHeight / 2) - (gameOverLines.length / 2));
        for(let i=0; i<gameOverLines.length; i++) {
            const y = startY + i;
            if(y < screenLines.length) {
                const text = gameOverLines[i];
                const startX = Math.floor((this.worldWidth / 2) - (text.length / 2));
                screenLines[y] = screenLines[y].substr(0, startX) + text + screenLines[y].substr(startX + text.length);
            }
        }
        this.asciiScreen.setText(screenLines.join('\n'));
    }
}
