import Phaser from 'phaser';

/**
 * Scene de selection joueur (fonctionne en portrait et paysage).
 */
export class PlayerSelectScene extends Phaser.Scene {
    private selectContainer?: Phaser.GameObjects.Container;
    private titleText?: Phaser.GameObjects.Text;
    private user1Image?: Phaser.GameObjects.Image;
    private user2Image?: Phaser.GameObjects.Image;
    private user1Label?: Phaser.GameObjects.Text;
    private user2Label?: Phaser.GameObjects.Text;
    private handleResizeBound?: () => void;
    private isMobile: boolean = false;

    constructor() {
        super({ key: 'PlayerSelectScene' });
    }

    create(): void {
        this.isMobile = this.sys.game.device.os.android || this.sys.game.device.os.iOS;

        this.cameras.main.setBackgroundColor('#87CEEB');

        this.createSelectContainer();
        this.updateOrientation();

        this.handleResizeBound = () => this.updateOrientation();
        this.scale.on('resize', this.updateOrientation, this);
        if (this.isMobile) {
            window.addEventListener('orientationchange', this.handleResizeBound);
        }

        this.events.once('shutdown', () => {
            this.scale.off('resize', this.updateOrientation, this);
            if (this.handleResizeBound) {
                window.removeEventListener('orientationchange', this.handleResizeBound);
            }
        });
    }

    private createSelectContainer(): void {
        const title = this.add.text(0, 0, 'Selectionnez votre joueur', {
            fontSize: '28px',
            color: '#333333',
            align: 'center',
            fontFamily: 'Arial',
        });
        title.setOrigin(0.5);
        this.titleText = title;

        const user1 = this.add.image(0, 0, 'user1');
        const user2 = this.add.image(0, 0, 'user2');
        this.user1Image = user1;
        this.user2Image = user2;

        this.fitImage(user1, 260, 260);
        this.fitImage(user2, 260, 260);

        user1.setInteractive({ useHandCursor: true });
        user2.setInteractive({ useHandCursor: true });

        const label1 = this.add.text(0, 0, 'Baptiste', {
            fontSize: '24px',
            color: '#333333',
            fontFamily: 'Arial',
            fontStyle: 'bold',
        });
        label1.setOrigin(0.5);
        const label2 = this.add.text(0, 0, 'Julien', {
            fontSize: '24px',
            color: '#333333',
            fontFamily: 'Arial',
            fontStyle: 'bold',
        });
        label2.setOrigin(0.5);
        this.user1Label = label1;
        this.user2Label = label2;

        user1.on('pointerdown', () => this.selectPlayer('user1'));
        user2.on('pointerdown', () => this.selectPlayer('user2'));

        this.selectContainer = this.add.container(0, 0, [title, user1, user2, label1, label2]);
    }

    private fitImage(image: Phaser.GameObjects.Image, maxW: number, maxH: number): void {
        const scale = Math.min(maxW / image.width, maxH / image.height);
        image.setScale(scale);
    }

    private updateOrientation(): void {
        const { width, height } = this.scale;
        const isPortrait = this.getIsPortrait();

        // Afficher la sélection en portrait ou paysage
        if (this.selectContainer) {
            this.selectContainer.setVisible(true);
            if (isPortrait) {
                this.layoutSelectContainerPortrait(width, height);
            } else {
                this.layoutSelectContainerLandscape(width, height);
            }
        }
    }

    private getIsPortrait(): boolean {
        if (window.matchMedia) {
            return window.matchMedia('(orientation: portrait)').matches;
        }
        return window.innerHeight >= window.innerWidth;
    }

    private layoutSelectContainerPortrait(width: number, height: number): void {
        if (!this.titleText || !this.user1Image || !this.user2Image || !this.user1Label || !this.user2Label) {
            return;
        }

        const titleY = Math.max(50, height * 0.08);
        this.titleText.setPosition(width / 2, titleY);

        // Agrandir les images au maximum: 90% de la largeur, 40% de la hauteur par image
        const imageMaxW = Math.min(width * 0.90, 550);
        const imageMaxH = Math.min(height * 0.40, 500);
        this.fitImage(this.user1Image, imageMaxW, imageMaxH);
        this.fitImage(this.user2Image, imageMaxW, imageMaxH);

        const firstImageY = titleY + 60 + this.user1Image.displayHeight / 2;
        const secondImageY =
            firstImageY + this.user1Image.displayHeight / 2 + 40 + this.user2Image.displayHeight / 2;

        this.user1Image.setPosition(width / 2, firstImageY);
        this.user1Label.setPosition(width / 2, firstImageY + this.user1Image.displayHeight / 2 + 20);

        this.user2Image.setPosition(width / 2, secondImageY);
        this.user2Label.setPosition(width / 2, secondImageY + this.user2Image.displayHeight / 2 + 20);
    }

    private layoutSelectContainerLandscape(width: number, height: number): void {
        if (!this.titleText || !this.user1Image || !this.user2Image || !this.user1Label || !this.user2Label) {
            return;
        }

        // Titre en haut centré
        const titleY = Math.max(40, height * 0.12);
        this.titleText.setPosition(width / 2, titleY);

        // Images côte à côte - agrandir encore plus (80% de la hauteur disponible)
        const imageMaxW = Math.min(width * 0.45, 600);
        const imageMaxH = Math.min(height * 0.80, 650);
        this.fitImage(this.user1Image, imageMaxW, imageMaxH);
        this.fitImage(this.user2Image, imageMaxW, imageMaxH);

        const centerY = height / 2 + 20;
        const spacing = width * 0.25;

        this.user1Image.setPosition(width / 2 - spacing, centerY);
        this.user1Label.setPosition(width / 2 - spacing, centerY + this.user1Image.displayHeight / 2 + 30);

        this.user2Image.setPosition(width / 2 + spacing, centerY);
        this.user2Label.setPosition(width / 2 + spacing, centerY + this.user2Image.displayHeight / 2 + 30);
    }

    private selectPlayer(playerId: 'user1' | 'user2'): void {
        this.registry.set('selectedPlayer', playerId);
        // Passer directement à la vidéo d'intro (le manifest.json gère l'orientation)
        this.scene.start('IntroVideoScene');
    }
}
