import Phaser from 'phaser';

/**
 * Scène de menu - Demande permission gyroscope et lance le jeu
 */
export class MenuScene extends Phaser.Scene {
    private startButton?: Phaser.GameObjects.Text;
    private gyroStatus?: Phaser.GameObjects.Text;
    private hasStarted: boolean = false;
    private debugText?: Phaser.GameObjects.Text;
    private debugLines: string[] = [];
    private hasGyroDebugListener: boolean = false;
    private isRequestingPermission: boolean = false;

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

    create(): void {
        const width = this.cameras.main.width;
        const height = this.cameras.main.height;

        // Réinitialiser le flag à chaque création du menu
        this.hasStarted = false;
        this.registry.set('gyroPermission', 'unknown');
        this.registry.set('gyroPermissionError', '');

        // Titre
        const title = this.add.text(width / 2, height / 3, 'MARIO RUNNER', {
            fontSize: '64px',
            color: '#ffffff',
            fontStyle: 'bold',
            stroke: '#000000',
            strokeThickness: 6,
        });
        title.setOrigin(0.5);

        // Instructions
        const instructions = this.add.text(
            width / 2,
            height / 2,
            'Inclinez le téléphone pour avancer/reculer\nAppuyez sur le bouton pour sauter',
            {
                fontSize: '24px',
                color: '#ffffff',
                align: 'center',
            }
        );
        instructions.setOrigin(0.5);

        // Bouton démarrer
        this.startButton = this.add.text(width / 2, height / 1.5, 'DÉMARRER', {
            fontSize: '48px',
            color: '#4CAF50',
            fontStyle: 'bold',
            backgroundColor: '#000000',
            padding: { x: 20, y: 10 },
        });
        this.startButton.setOrigin(0.5);
        this.startButton.setInteractive({ useHandCursor: true });

        // Status gyroscope
        this.gyroStatus = this.add.text(width / 2, height - 150, '', {
            fontSize: '16px',
            color: '#ffeb3b',
            align: 'center',
            backgroundColor: '#000000',
            padding: { x: 10, y: 10 },
            wordWrap: { width: width - 40 },
        });
        this.gyroStatus.setOrigin(0.5);

        // Debug gyroscope (logs a l'ecran)
        this.debugText = this.add.text(10, height - 110, '', {
            fontSize: '12px',
            color: '#ffffff',
            backgroundColor: '#000000',
            padding: { x: 6, y: 6 },
            wordWrap: { width: width - 20 },
        });
        this.debugText.setOrigin(0, 0);
        this.debugText.setScrollFactor(0);

        // Demande iOS dès le premier tap (exigé par la permission).
        this.input.once('pointerdown', () => {
            // IMPORTANT: Débloquer l'audio sur iOS
            this.unlockAudio();
            this.requestGyroPermission();
        });

        // Click sur le bouton (fallback si le tap global a déjà eu lieu).
        this.startButton.on('pointerdown', () => {
            // IMPORTANT: Débloquer l'audio sur iOS
            this.unlockAudio();
            this.requestGyroPermission();
        });

        // Effet hover
        this.startButton.on('pointerover', () => {
            this.startButton?.setScale(1.1);
        });

        this.startButton.on('pointerout', () => {
            this.startButton?.setScale(1);
        });
    }

    /**
     * Débloque l'audio sur iOS (requis après interaction utilisateur)
     */
    private unlockAudio(): void {
        // Sur iOS, l'audio doit être activé après une interaction utilisateur
        const soundManager = this.sound as Phaser.Sound.WebAudioSoundManager;

        if (soundManager.context) {
            console.log('[Audio] Context state:', soundManager.context.state);

            // Si le contexte est suspendu, le reprendre
            if (soundManager.context.state === 'suspended') {
                soundManager.context.resume().then(() => {
                    console.log('[Audio] ✅ Context audio débloqué pour iOS');
                }).catch((error: any) => {
                    console.error('[Audio] ❌ Erreur déblocage audio:', error);
                });
            }
        }

        // Jouer un son silencieux pour initialiser l'audio sur mobile
        // Cela garantit que les sons futurs fonctionneront
        try {
            const silentSound = this.sound.add('__silent__', { volume: 0 });
            silentSound.play();
            silentSound.destroy();
        } catch (error: any) {
            console.log('[Audio] Pas de son silencieux (normal)');
        }
    }

    /**
     * Demande la permission gyroscope (iOS) et lance le jeu
     */
    private async requestGyroPermission(): Promise<void> {
        if (this.isRequestingPermission) {
            this.logDebug('permission request in progress');
            return;
        }
        this.isRequestingPermission = true;

        try {
            console.log('[Gyro] request permission');
            console.log('[Gyro] userAgent:', navigator.userAgent);
            console.log('[Gyro] isSecureContext:', window.isSecureContext);
            this.gyroStatus?.setText("Demande d'autorisation du gyroscope...");

            const hasDeviceOrientation =
                typeof window.DeviceOrientationEvent !== 'undefined';
            const requestOrientationPermission =
                (window.DeviceOrientationEvent as any)?.requestPermission;
            const requestMotionPermission =
                (window.DeviceMotionEvent as any)?.requestPermission;
            const isIOS = /iP(ad|hone|od)/.test(navigator.userAgent);

        const userActivation = (navigator as any).userActivation;
        this.logDebug(`ua: ${navigator.userAgent}`);
        this.logDebug(`secure: ${window.isSecureContext}`);
        this.logDebug(`iOS: ${isIOS}`);
        this.logDebug(`DeviceOrientationEvent: ${hasDeviceOrientation}`);
        this.logDebug(
            `requestPermission: ${typeof requestOrientationPermission === 'function'}`
        );
        this.logDebug(
            `activation: ${userActivation?.isActive}/${userActivation?.hasBeenActive}`
        );
            this.logDebug(`top-level: ${window.top === window.self}`);
            this.logDebug(`visible: ${document.visibilityState}`);
            this.setupGyroDebugListener();

            if (isIOS && !window.isSecureContext) {
            this.gyroStatus?.setText(
                'Le gyroscope iOS requiert HTTPS. Ouvrez le jeu en https.'
            );
            this.logDebug('blocked: not https');
            this.registry.set('gyroPermission', 'blocked');
            return;
        }

            // iOS 13+ requires explicit permission from a user gesture.
            if (hasDeviceOrientation && typeof requestOrientationPermission === 'function') {
                try {
                    const orientationStatus = await requestOrientationPermission.call(
                        window.DeviceOrientationEvent
                    );
                    let motionStatus = 'granted';
                    if (typeof requestMotionPermission === 'function') {
                        motionStatus = await requestMotionPermission.call(
                            window.DeviceMotionEvent
                        );
                    }

                console.log('[Gyro] permission orientation:', orientationStatus);
                console.log('[Gyro] permission motion:', motionStatus);
                this.logDebug(`perm orientation: ${orientationStatus}`);
                this.logDebug(`perm motion: ${motionStatus}`);

                if (orientationStatus === 'granted' && motionStatus === 'granted') {
                    this.registry.set('gyroPermission', 'granted');
                    this.gyroStatus?.setText('Gyroscope activé. Lancement...');
                    this.startGame();
                    return;
                }

                this.gyroStatus?.setText(
                    'Acces au gyroscope refuse. Activez-le dans les reglages iOS.'
                );
                const permState =
                    orientationStatus === 'granted' || motionStatus === 'granted'
                        ? 'partial'
                        : 'denied';
                this.registry.set('gyroPermission', permState);
                this.logDebug('permission refused');
                this.logDebug('starting without gyro');
                this.startGame();
                return;
            } catch (error) {
                console.warn('[MenuScene] Permission gyroscope refusée', error);
                this.gyroStatus?.setText(
                    "Impossible d'activer le gyroscope. Reessayez."
                );
                const errorText =
                    error instanceof Error ? error.message : String(error);
                this.logDebug(`permission error: ${errorText}`);
                this.registry.set('gyroPermission', 'error');
                this.registry.set('gyroPermissionError', errorText);
                this.logDebug('starting without gyro');
                this.startGame();
                return;
            }
        }

        // Android/desktop or older iOS: no permission API.
        this.registry.set('gyroPermission', 'not-required');
        this.gyroStatus?.setText('Gyroscope prêt. Lancement...');
        this.startGame();
        } finally {
            this.isRequestingPermission = false;
        }
    }

    private logDebug(line: string): void {
        this.debugLines.push(line);
        if (this.debugLines.length > 6) {
            this.debugLines.shift();
        }
        this.debugText?.setText(this.debugLines.join('\n'));
    }

    private setupGyroDebugListener(): void {
        if (this.hasGyroDebugListener) return;
        this.hasGyroDebugListener = true;

        let lastLogTime = 0;
        window.addEventListener('deviceorientation', (event) => {
            const now = Date.now();
            if (now - lastLogTime < 1000) return;
            lastLogTime = now;
            const beta = event.beta ?? 0;
            const gamma = event.gamma ?? 0;
            this.logDebug(`event beta:${beta.toFixed(1)} gamma:${gamma.toFixed(1)}`);
        });
    }

    /**
     * Lance la scène de jeu
     */
    private startGame(): void {
        if (this.hasStarted) return;
        this.hasStarted = true;

        console.log('[MenuScene] Démarrage de GameScene');

        // Arrêter GameScene si elle existe déjà
        if (this.scene.isActive('GameScene')) {
            this.scene.stop('GameScene');
        }

        // Démarrer une nouvelle partie
        this.scene.start('GameScene');
    }
}
