import Module from '../core/Module.js';
import { soundSystem } from '../gameHelpers/MarioEducational/SoundSystem.js';
import ttsService from '../services/TTSService.js';

/**
 * SentenceInvaders - Space Invaders-style game with TTS sentences
 * Aliens descend from the sky speaking sentences, players must select correct translations
 */
class SentenceInvaders extends Module {
    constructor(name, dependencies, config = {}) {
        super(name, ['eventBus']);

        // Validate dependencies
        if (!dependencies.eventBus || !dependencies.content) {
            throw new Error('SentenceInvaders requires eventBus and content dependencies');
        }

        this._eventBus = dependencies.eventBus;
        this._content = dependencies.content;
        this._config = {
            container: null,
            maxSentences: 40,
            baseFallSpeed: 10, // Base speed (vh/s)
            baseSpawnRate: 5000, // Base spawn rate (ms)
            fallSpeedVhPerSecond: 10, // Current speed
            spawnRate: 5000, // Current spawn rate
            sentenceLifetime: 12000, // ms before sentence disappears
            startingLives: 3,
            difficultyIncreaseInterval: 10000, // Increase difficulty every 10s
            maxFallSpeed: 50, // Maximum fall speed (vh/s)
            minSpawnRate: 1500, // Minimum spawn rate (ms)
            ...config
        };

        // Game state
        this._sentences = null;
        this._score = 0;
        this._level = 1;
        this._lives = this._config.startingLives;
        this._combo = 0;
        this._isGamePaused = false;
        this._isGameOver = false;
        this._gameStartTime = null;

        // Game mechanics
        this._fallingAliens = [];
        this._currentSentenceIndex = 0;
        this._spawnInterval = null;
        this._difficultyInterval = null; // Progressive difficulty timer
        this._activeTTS = null; // Track active TTS
        this._aliensKilled = 0;
        this._aliensMissed = 0;

        Object.seal(this);
    }

    /**
     * Get game metadata
     * @returns {Object} Game metadata
     */
    static getMetadata() {
        return {
            name: 'Sentence Invaders',
            description: 'Space Invaders with TTS sentences - listen and translate!',
            difficulty: 'intermediate',
            category: 'action',
            estimatedTime: 8, // minutes
            skills: ['listening', 'translation', 'speed', 'concentration']
        };
    }

    /**
     * Calculate compatibility score with content
     * @param {Object} content - Content to check compatibility with
     * @returns {Object} Compatibility score and details
     */
    static getCompatibilityScore(content) {
        let sentenceCount = 0;

        // Count from conversations (new format)
        if (content?.conversations) {
            sentenceCount += Object.values(content.conversations)
                .filter(c => c.sentences).length;
        }

        // Count from dialogs (SBS format)
        if (content?.dialogs) {
            const dialogLines = Object.values(content.dialogs)
                .flatMap(d => d.lines || [])
                .filter(line => line.text && line.user_language);
            sentenceCount += dialogLines.length;
        }

        // Count from phrases
        if (content?.phrases) {
            sentenceCount += Object.keys(content.phrases).length;
        }

        // Count from grammar examples
        if (content?.grammar) {
            const grammarSentences = Object.values(content.grammar)
                .flatMap(g => g.examples || [])
                .filter(ex => (ex.target_language || ex.chinese) && (ex.user_language || ex.translation));
            sentenceCount += grammarSentences.length;
        }

        // Count from vocabulary example sentences
        if (content?.vocabulary) {
            const vocabSentences = Object.values(content.vocabulary)
                .filter(v => v.example_sentence && v.example_sentence.target && v.example_sentence.user);
            sentenceCount += vocabSentences.length;
        }

        if (sentenceCount < 10) {
            return {
                score: 0,
                reason: `Insufficient sentences (${sentenceCount}/10 required)`,
                requirements: ['dialogs', 'phrases', 'grammar', 'conversations'],
                minSentences: 10,
                details: 'Sentence Invaders needs at least 10 sentences for meaningful gameplay'
            };
        }

        // Perfect score at 30+ sentences, partial score for 10-29
        const score = Math.min(sentenceCount / 30, 1);

        return {
            score,
            reason: `${sentenceCount} sentences available`,
            requirements: ['dialogs', 'phrases', 'grammar', 'conversations'],
            minSentences: 10,
            optimalSentences: 30,
            details: `Can create dynamic gameplay with ${Math.min(sentenceCount, 40)} sentences`
        };
    }

    async init() {
        this._validateNotDestroyed();

        try {
            // Validate container
            if (!this._config.container) {
                throw new Error('Game container is required');
            }

            // Extract and validate sentences
            this._sentences = this._extractSentences();
            if (this._sentences.length < 10) {
                throw new Error(`Insufficient sentences: need 10, got ${this._sentences.length}`);
            }

            // Set up event listeners
            this._eventBus.on('game:pause', this._handlePause.bind(this), this.name);
            this._eventBus.on('game:resume', this._handleResume.bind(this), this.name);

            // Initialize sound system
            soundSystem.initialize();

            // Inject CSS
            this._injectCSS();

            // Initialize game interface
            this._createGameInterface();
            this._setupEventListeners();

            // Start the game
            this._gameStartTime = Date.now();
            this._startSpawning();
            this._startProgressiveDifficulty();

            // Emit game ready event
            this._eventBus.emit('game:ready', {
                gameId: 'sentence-invaders',
                instanceId: this.name,
                sentences: this._sentences.length
            }, this.name);

            this._setInitialized();

        } catch (error) {
            this._showError(error.message);
            throw error;
        }
    }

    async destroy() {
        this._validateNotDestroyed();

        // Clear intervals
        if (this._spawnInterval) {
            clearInterval(this._spawnInterval);
            this._spawnInterval = null;
        }

        if (this._difficultyInterval) {
            clearInterval(this._difficultyInterval);
            this._difficultyInterval = null;
        }

        // Stop any active TTS
        ttsService.cancel();

        // Remove CSS
        this._removeCSS();

        // Clean up event listeners
        if (this._config.container) {
            this._config.container.innerHTML = '';
        }

        // Emit game end event
        this._eventBus.emit('game:ended', {
            gameId: 'sentence-invaders',
            instanceId: this.name,
            score: this._score,
            level: this._level,
            combo: this._combo,
            duration: this._gameStartTime ? Date.now() - this._gameStartTime : 0
        }, this.name);

        this._setDestroyed();
    }

    /**
     * Get current game state
     * @returns {Object} Current game state
     */
    getGameState() {
        this._validateInitialized();

        return {
            score: this._score,
            level: this._level,
            lives: this._lives,
            combo: this._combo,
            isGameOver: this._isGameOver,
            isPaused: this._isGamePaused,
            duration: this._gameStartTime ? Date.now() - this._gameStartTime : 0,
            fallingAliensCount: this._fallingAliens.length
        };
    }

    // Private methods
    _extractSentences() {
        const sentences = [];

        // 1. Extract from conversations (new format)
        const conversations = this._content?.conversations || {};
        for (const conv of Object.values(conversations)) {
            if (conv.sentences && conv.sentences.original && conv.sentences.user_language) {
                sentences.push({
                    original: conv.sentences.original,
                    translation: conv.sentences.user_language,
                    type: 'dialogue',
                    context: conv.context || ''
                });
            }
        }

        // 2. Extract from dialogs (SBS format)
        const dialogs = this._content?.dialogs || {};
        for (const dialog of Object.values(dialogs)) {
            if (dialog.lines && Array.isArray(dialog.lines)) {
                dialog.lines.forEach(line => {
                    if (line.text && line.user_language) {
                        sentences.push({
                            original: line.text,
                            translation: line.user_language,
                            type: 'dialogue',
                            context: dialog.title || ''
                        });
                    }
                });
            }
        }

        // 3. Extract from phrases
        const phrases = this._content?.phrases || {};
        for (const [phraseText, data] of Object.entries(phrases)) {
            if (data.user_language) {
                sentences.push({
                    original: phraseText,
                    translation: data.user_language,
                    type: 'phrase',
                    context: data.context || ''
                });
            }
        }

        // 4. Extract from grammar examples
        const grammar = this._content?.grammar || {};
        for (const rule of Object.values(grammar)) {
            if (rule.examples) {
                rule.examples.forEach(ex => {
                    // Handle both formats: target_language/user_language AND chinese/translation
                    const original = ex.target_language || ex.chinese;
                    const translation = ex.user_language || ex.translation;

                    if (original && translation) {
                        sentences.push({
                            original: original,
                            translation: translation,
                            type: 'grammar'
                        });
                    }
                });
            }
        }

        // 5. Extract from vocabulary example sentences (if available)
        const vocab = this._content?.vocabulary || {};
        for (const [word, data] of Object.entries(vocab)) {
            if (data.example_sentence && data.example_sentence.target && data.example_sentence.user) {
                sentences.push({
                    original: data.example_sentence.target,
                    translation: data.example_sentence.user,
                    type: 'vocabulary'
                });
            }
        }

        // Limit and shuffle
        return this._shuffleArray(sentences).slice(0, this._config.maxSentences);
    }

    _injectCSS() {
        const cssId = `sentence-invaders-styles-${this.name}`;
        if (document.getElementById(cssId)) return;

        const style = document.createElement('style');
        style.id = cssId;
        style.textContent = `
            .sentence-invaders-game {
                height: 100vh;
                overflow: hidden;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                position: relative;
                background: linear-gradient(180deg, #0a0e27 0%, #1a1f3a 100%);
            }

            .sentence-invaders-hud {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 15px 20px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                position: relative;
                z-index: 100;
            }

            .hud-section {
                display: flex;
                gap: 20px;
                align-items: center;
            }

            .hud-stat {
                display: flex;
                flex-direction: column;
                align-items: center;
                min-width: 60px;
            }

            .hud-label {
                font-size: 0.8rem;
                opacity: 0.9;
                margin-bottom: 2px;
            }

            .hud-value {
                font-size: 1.2rem;
                font-weight: bold;
            }

            .pause-btn {
                padding: 8px 15px;
                background: rgba(255, 255, 255, 0.2);
                border: 1px solid rgba(255, 255, 255, 0.3);
                color: white;
                border-radius: 6px;
                cursor: pointer;
                font-size: 0.9rem;
                transition: all 0.3s ease;
            }

            .pause-btn:hover {
                background: rgba(255, 255, 255, 0.3);
            }

            .sentence-invaders-area {
                position: relative;
                height: calc(80vh - 180px);
                background: linear-gradient(180deg, #0a0e27 0%, #1a1f3a 100%);
                overflow: hidden;
                border-radius: 20px 20px 0 0;
                margin: 10px 10px 0 10px;
                box-shadow: inset 0 0 50px rgba(102, 126, 234, 0.2);
            }

            /* Starfield background */
            .sentence-invaders-area::before {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-image:
                    radial-gradient(2px 2px at 20% 30%, white, transparent),
                    radial-gradient(2px 2px at 60% 70%, white, transparent),
                    radial-gradient(1px 1px at 50% 50%, white, transparent),
                    radial-gradient(1px 1px at 80% 10%, white, transparent),
                    radial-gradient(2px 2px at 90% 60%, white, transparent),
                    radial-gradient(1px 1px at 33% 80%, white, transparent);
                background-size: 200% 200%;
                animation: starfield 60s linear infinite;
                opacity: 0.6;
            }

            @keyframes starfield {
                from { background-position: 0% 0%; }
                to { background-position: 0% 100%; }
            }

            .falling-alien {
                position: absolute;
                display: flex;
                flex-direction: column;
                align-items: center;
                cursor: default;
                user-select: none;
                transform: translateX(-50%);
                z-index: 10;
            }

            .alien-body {
                font-size: 3rem;
                filter: drop-shadow(0 0 10px rgba(102, 126, 234, 0.8));
                animation: alienFloat 2s ease-in-out infinite;
            }

            @keyframes alienFloat {
                0%, 100% { transform: translateY(0px); }
                50% { transform: translateY(-10px); }
            }

            .speech-bubble {
                position: relative;
                background: rgba(255, 255, 255, 0.95);
                color: #1a1f3a;
                padding: 8px 12px;
                border-radius: 15px;
                margin-top: 10px;
                box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
                min-width: 50px;
                text-align: center;
            }

            .speech-bubble::before {
                content: '';
                position: absolute;
                top: -8px;
                left: 50%;
                transform: translateX(-50%);
                width: 0;
                height: 0;
                border-left: 8px solid transparent;
                border-right: 8px solid transparent;
                border-bottom: 8px solid rgba(255, 255, 255, 0.95);
            }

            .tts-replay-btn {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border: none;
                border-radius: 12px;
                padding: 6px 12px;
                font-size: 1rem;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 2px 8px rgba(102, 126, 234, 0.4);
            }

            .tts-replay-btn:hover {
                transform: scale(1.1);
                box-shadow: 0 4px 12px rgba(102, 126, 234, 0.6);
            }

            .tts-replay-btn:active {
                transform: scale(0.95);
            }

            .falling-alien.exploding .alien-body {
                animation: alienExplode 0.8s ease-out forwards;
            }

            .falling-alien.exploding .speech-bubble {
                animation: fadeOut 0.8s ease-out forwards;
            }

            @keyframes alienExplode {
                0% {
                    transform: scale(1) rotate(0deg);
                    opacity: 1;
                    filter: drop-shadow(0 0 10px rgba(102, 126, 234, 0.8));
                }
                25% {
                    transform: scale(1.5) rotate(15deg);
                    filter: drop-shadow(0 0 30px rgba(16, 185, 129, 0.8));
                }
                50% {
                    transform: scale(2) rotate(-10deg);
                    opacity: 0.7;
                    filter: drop-shadow(0 0 50px rgba(245, 158, 11, 0.9));
                }
                100% {
                    transform: scale(0.1) rotate(360deg);
                    opacity: 0;
                }
            }

            @keyframes fadeOut {
                to { opacity: 0; transform: scale(0.5); }
            }

            .sentence-invaders-answer-panel {
                position: relative;
                background: rgba(0, 0, 0, 0.9);
                padding: 15px;
                border-top: 3px solid #667eea;
                border-radius: 0 0 20px 20px;
                margin: 0 10px 10px 10px;
                z-index: 100;
            }

            .sentence-invaders-answer-panel.wrong-flash {
                animation: wrongFlash 0.5s ease-in-out;
            }

            .answer-buttons-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
                gap: 12px;
                max-width: 700px;
                margin: 0 auto;
            }

            .sentence-invaders-answer-btn {
                padding: 12px 18px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border: none;
                border-radius: 16px;
                font-size: 0.95rem;
                font-weight: 500;
                cursor: pointer;
                transition: all 0.3s ease;
                position: relative;
                overflow: hidden;
                line-height: 1.4;
            }

            .sentence-invaders-answer-btn:hover {
                transform: translateY(-2px);
                box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
            }

            .sentence-invaders-answer-btn:active {
                transform: translateY(0);
            }

            .sentence-invaders-answer-btn.correct {
                background: linear-gradient(135deg, #10b981 0%, #059669 100%);
                animation: correctPulse 0.6s ease-out;
            }

            .sentence-invaders-answer-btn.incorrect {
                background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
                animation: incorrectShake 0.6s ease-out;
            }

            .points-popup {
                position: absolute;
                font-size: 2rem;
                font-weight: bold;
                color: #10b981;
                pointer-events: none;
                z-index: 1000;
                text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
                animation: pointsFloat 1.5s ease-out forwards;
            }

            .level-up-popup {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: rgba(0, 0, 0, 0.9);
                color: white;
                padding: 30px;
                border-radius: 15px;
                text-align: center;
                z-index: 1000;
                animation: levelUpAppear 2s ease-out forwards;
            }

            @keyframes wrongFlash {
                0%, 100% { background: rgba(0, 0, 0, 0.9); }
                50% { background: rgba(239, 68, 68, 0.6); }
            }

            @keyframes correctPulse {
                0% { transform: scale(1); }
                50% { transform: scale(1.05); }
                100% { transform: scale(1); }
            }

            @keyframes incorrectShake {
                0%, 100% { transform: translateX(0); }
                25% { transform: translateX(-5px); }
                75% { transform: translateX(5px); }
            }

            @keyframes pointsFloat {
                0% {
                    transform: translateY(0) scale(1);
                    opacity: 1;
                }
                30% {
                    transform: translateY(-20px) scale(1.3);
                    opacity: 1;
                }
                100% {
                    transform: translateY(-80px) scale(0.5);
                    opacity: 0;
                }
            }

            @keyframes levelUpAppear {
                0% {
                    transform: translate(-50%, -50%) scale(0.5);
                    opacity: 0;
                }
                20% {
                    transform: translate(-50%, -50%) scale(1.2);
                    opacity: 1;
                }
                80% {
                    transform: translate(-50%, -50%) scale(1);
                    opacity: 1;
                }
                100% {
                    transform: translate(-50%, -50%) scale(1);
                    opacity: 0;
                }
            }

            @keyframes screenShake {
                0%, 100% { transform: translateX(0); }
                10% { transform: translateX(-3px) translateY(1px); }
                20% { transform: translateX(3px) translateY(-1px); }
                30% { transform: translateX(-2px) translateY(2px); }
                40% { transform: translateX(2px) translateY(-2px); }
                50% { transform: translateX(-1px) translateY(1px); }
                60% { transform: translateX(1px) translateY(-1px); }
                70% { transform: translateX(-2px) translateY(0px); }
                80% { transform: translateX(2px) translateY(1px); }
                90% { transform: translateX(-1px) translateY(-1px); }
            }

            @media (max-width: 768px) {
                .alien-body {
                    font-size: 2.5rem;
                }

                .answer-buttons-grid {
                    grid-template-columns: 1fr;
                    gap: 10px;
                }
            }
        `;

        document.head.appendChild(style);
    }

    _removeCSS() {
        const cssId = `sentence-invaders-styles-${this.name}`;
        const existingStyle = document.getElementById(cssId);
        if (existingStyle) {
            existingStyle.remove();
        }
    }

    _createGameInterface() {
        this._config.container.innerHTML = `
            <div class="sentence-invaders-game">
                <div class="sentence-invaders-hud">
                    <div class="hud-section">
                        <div class="hud-stat">
                            <div class="hud-label">Score</div>
                            <div class="hud-value" id="score-display">0</div>
                        </div>
                        <div class="hud-stat">
                            <div class="hud-label">Level</div>
                            <div class="hud-value" id="level-display">1</div>
                        </div>
                    </div>

                    <div class="hud-section">
                        <div class="hud-stat">
                            <div class="hud-label">Lives</div>
                            <div class="hud-value" id="lives-display">3</div>
                        </div>
                        <div class="hud-stat">
                            <div class="hud-label">Combo</div>
                            <div class="hud-value" id="combo-display">0</div>
                        </div>
                    </div>

                    <div class="hud-section">
                        <button class="pause-btn" id="pause-btn">⏸️ Pause</button>
                        <button class="btn btn-outline btn-sm" id="exit-invaders">
                            <span class="btn-icon">←</span>
                            <span class="btn-text">Exit</span>
                        </button>
                    </div>
                </div>

                <div class="sentence-invaders-area" id="game-area"></div>

                <div class="sentence-invaders-answer-panel" id="answer-panel">
                    <div class="answer-buttons-grid" id="answer-buttons">
                        <!-- Dynamic answer buttons -->
                    </div>
                </div>
            </div>
        `;
    }

    _setupEventListeners() {
        // Pause button
        const pauseBtn = document.getElementById('pause-btn');
        if (pauseBtn) {
            pauseBtn.addEventListener('click', () => this._togglePause());
        }

        // Exit button
        const exitButton = document.getElementById('exit-invaders');
        if (exitButton) {
            exitButton.addEventListener('click', () => {
                this._eventBus.emit('game:exit-request', { instanceId: this.name }, this.name);
            });
        }

        // Answer button clicks
        this._config.container.addEventListener('click', (event) => {
            if (event.target.matches('.sentence-invaders-answer-btn')) {
                const answer = event.target.textContent;
                this._checkAnswer(answer);
            }

            if (event.target.matches('.restart-btn')) {
                this._restartGame();
            }
        });

        // Keyboard support
        document.addEventListener('keydown', (event) => {
            if (event.key >= '1' && event.key <= '4') {
                const btnIndex = parseInt(event.key) - 1;
                const buttons = document.querySelectorAll('.sentence-invaders-answer-btn');
                if (buttons[btnIndex]) {
                    buttons[btnIndex].click();
                }
            }

            if (event.key === ' ' || event.key === 'Escape') {
                event.preventDefault();
                this._togglePause();
            }
        });
    }

    _startSpawning() {
        // Clear existing interval if any
        if (this._spawnInterval) {
            clearInterval(this._spawnInterval);
        }

        this._spawnInterval = setInterval(() => {
            if (!this._isGamePaused && !this._isGameOver) {
                this._spawnFallingAlien();
            }
        }, this._config.spawnRate);
    }

    _startProgressiveDifficulty() {
        // Clear existing interval if any
        if (this._difficultyInterval) {
            clearInterval(this._difficultyInterval);
        }

        this._difficultyInterval = setInterval(() => {
            if (!this._isGamePaused && !this._isGameOver) {
                this._increaseDifficulty();
            }
        }, this._config.difficultyIncreaseInterval);
    }

    _increaseDifficulty() {
        // Increase fall speed by 8% every interval (more aggressive than before)
        const newFallSpeed = Math.min(
            this._config.maxFallSpeed,
            this._config.fallSpeedVhPerSecond * 1.08
        );

        // Decrease spawn rate by 6% every interval (spawn faster)
        const newSpawnRate = Math.max(
            this._config.minSpawnRate,
            this._config.spawnRate * 0.94
        );

        // Only update if values changed
        if (newFallSpeed !== this._config.fallSpeedVhPerSecond ||
            newSpawnRate !== this._config.spawnRate) {

            this._config.fallSpeedVhPerSecond = newFallSpeed;
            this._config.spawnRate = newSpawnRate;

            // Restart spawning with new rate
            this._startSpawning();

            // Update existing aliens to use new speed
            this._fallingAliens.forEach(alien => {
                if (alien.element && alien.element.parentNode) {
                    this._animateFalling(alien.element);
                }
            });
        }
    }

    _spawnFallingAlien() {
        if (this._sentences.length === 0) return;

        const sentence = this._sentences[this._currentSentenceIndex % this._sentences.length];
        this._currentSentenceIndex++;

        // Generate options for THIS specific sentence
        const options = this._generateOptionsForSentence(sentence);

        const gameArea = document.getElementById('game-area');
        const alienElement = document.createElement('div');
        alienElement.className = 'falling-alien';
        alienElement.innerHTML = `
            <div class="alien-body">👾</div>
            <div class="speech-bubble">
                <button class="tts-replay-btn" title="Listen again">🔊</button>
            </div>
        `;

        alienElement.style.left = Math.random() * 80 + 10 + '%';
        alienElement.style.top = '0vh';

        gameArea.appendChild(alienElement);

        // Auto-play TTS on spawn
        this._playTTS(sentence.original);

        // Setup replay button
        const replayBtn = alienElement.querySelector('.tts-replay-btn');
        replayBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this._playTTS(sentence.original);
        });

        // Start position check
        const positionCheck = setInterval(() => {
            if (!alienElement.parentNode) {
                clearInterval(positionCheck);
                return;
            }

            const answerPanel = document.getElementById('answer-panel');
            if (!answerPanel) {
                clearInterval(positionCheck);
                return;
            }

            const alienRect = alienElement.getBoundingClientRect();
            const answerPanelRect = answerPanel.getBoundingClientRect();

            if (alienRect.bottom >= answerPanelRect.top) {
                clearInterval(positionCheck);
                if (alienElement.parentNode) {
                    this._missAlien(alienElement);
                }
            }
        }, 50);

        const fallingAlienData = {
            element: alienElement,
            sentence: sentence,
            options: options,
            startTime: Date.now(),
            positionCheck: positionCheck
        };

        this._fallingAliens.push(fallingAlienData);

        // Update answer panel with oldest alien's options
        this._updateAnswerPanelForOldestAlien();

        // Animate falling
        this._animateFalling(alienElement);
    }

    async _playTTS(text) {
        const targetLang = this._content?.language?.target || 'en-US';
        await ttsService.speak(text, targetLang, { rate: 0.85, volume: 1.0 });
    }

    _animateFalling(alienElement) {
        const gameArea = document.getElementById('game-area');
        if (!gameArea) return;

        const gameAreaHeight = gameArea.offsetHeight;
        const viewportHeight = window.innerHeight;
        const gameAreaHeightVh = (gameAreaHeight / viewportHeight) * 100;
        const fallDurationMs = (gameAreaHeightVh / this._config.fallSpeedVhPerSecond) * 1000;

        alienElement.style.transition = `top ${fallDurationMs}ms linear`;
        setTimeout(() => {
            alienElement.style.top = `${gameAreaHeight}px`;
        }, 50);
    }

    _generateOptionsForSentence(sentence) {
        const buttons = [];

        // Add correct answer
        buttons.push(sentence.translation);

        // Add 3 random incorrect answers
        while (buttons.length < 4) {
            const randomSentence = this._sentences[Math.floor(Math.random() * this._sentences.length)];
            if (!buttons.includes(randomSentence.translation)) {
                buttons.push(randomSentence.translation);
            }
        }

        // Shuffle and return
        return this._shuffleArray(buttons);
    }

    _updateAnswerPanelForOldestAlien() {
        const activeAliens = this._fallingAliens.filter(fa => fa.element.parentNode);

        if (activeAliens.length === 0) return;

        const oldestAlien = activeAliens[0];
        const options = oldestAlien.options;

        const answerButtons = document.getElementById('answer-buttons');
        if (answerButtons) {
            answerButtons.innerHTML = options.map(answer =>
                `<button class="sentence-invaders-answer-btn">${answer}</button>`
            ).join('');
        }
    }

    _checkAnswer(selectedAnswer) {
        const activeAliens = this._fallingAliens.filter(fa => fa.element.parentNode);

        for (let i = 0; i < activeAliens.length; i++) {
            const alien = activeAliens[i];
            if (alien.sentence.translation === selectedAnswer) {
                this._correctAnswer(alien);
                return;
            }
        }

        // Wrong answer
        this._wrongAnswer();
    }

    _correctAnswer(alien) {
        // Play success sound
        soundSystem.play('coin');

        // Clear position check
        if (alien.positionCheck) {
            clearInterval(alien.positionCheck);
        }

        // Remove with explosion
        if (alien.element.parentNode) {
            alien.element.classList.add('exploding');

            // Screen shake
            const gameArea = document.getElementById('game-area');
            if (gameArea) {
                gameArea.style.animation = 'none';
                gameArea.offsetHeight;
                gameArea.style.animation = 'screenShake 0.3s ease-in-out';
                setTimeout(() => {
                    gameArea.style.animation = '';
                }, 300);
            }

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

        // Remove from tracking
        this._fallingAliens = this._fallingAliens.filter(fa => fa !== alien);

        // Update score and combo
        this._combo++;
        this._aliensKilled++;
        const points = 15 + (this._combo * 3); // Higher base points for sentences
        this._score += points;

        // Combo provides temporary speed boost (doesn't reset base progression)
        // This adds excitement without disrupting the progressive difficulty
        const comboBoost = Math.min(this._combo * 0.02, 0.3); // Max 30% boost from combo
        const currentBaseSpeed = this._config.fallSpeedVhPerSecond;
        const boostedSpeed = Math.min(this._config.maxFallSpeed, currentBaseSpeed * (1 + comboBoost));

        // Apply boost to existing aliens
        this._fallingAliens.forEach(alien => {
            if (alien.element && alien.element.parentNode) {
                this._animateFalling(alien.element);
            }
        });

        this._updateHUD();
        this._showPointsPopup(points, alien.element);
        this._updateAnswerPanelForOldestAlien();

        // Vibration feedback
        if (navigator.vibrate) {
            navigator.vibrate([50, 30, 50]);
        }

        // Level up check
        if (this._score > 0 && this._score % 150 === 0) {
            this._levelUp();
        }

        this._eventBus.emit('sentence-invaders:correct-answer', {
            gameId: 'sentence-invaders',
            instanceId: this.name,
            sentence: alien.sentence,
            points,
            combo: this._combo,
            score: this._score
        }, this.name);
    }

    _wrongAnswer() {
        soundSystem.play('enemy_defeat');

        this._combo = 0;
        // Don't reset speed anymore - let progressive difficulty continue

        // Flash answer panel
        const answerPanel = document.getElementById('answer-panel');
        if (answerPanel) {
            answerPanel.classList.add('wrong-flash');
            setTimeout(() => {
                answerPanel.classList.remove('wrong-flash');
            }, 500);
        }

        // Screen flash
        const gameArea = document.getElementById('game-area');
        if (gameArea) {
            const overlay = document.createElement('div');
            overlay.style.cssText = `
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(239, 68, 68, 0.3);
                pointer-events: none;
                animation: wrongFlash 0.4s ease-in-out;
                z-index: 100;
            `;
            gameArea.appendChild(overlay);
            setTimeout(() => {
                if (overlay.parentNode) overlay.remove();
            }, 400);
        }

        this._updateHUD();

        if (navigator.vibrate) {
            navigator.vibrate([200, 100, 200, 100, 200]);
        }

        this._eventBus.emit('sentence-invaders:wrong-answer', {
            gameId: 'sentence-invaders',
            instanceId: this.name,
            score: this._score
        }, this.name);
    }

    _showPointsPopup(points, alienElement) {
        const popup = document.createElement('div');
        popup.textContent = `+${points}`;
        popup.className = 'points-popup';
        popup.style.left = alienElement.style.left;
        popup.style.top = alienElement.offsetTop + 'px';

        const gameArea = document.getElementById('game-area');
        if (gameArea) {
            gameArea.appendChild(popup);
            setTimeout(() => {
                if (popup.parentNode) popup.remove();
            }, 1500);
        }
    }

    _missAlien(alienElement) {
        const alien = this._fallingAliens.find(fa => fa.element === alienElement);

        if (alien && alien.positionCheck) {
            clearInterval(alien.positionCheck);
        }

        soundSystem.play('enemy_defeat');

        // Explosion animation
        if (alienElement.parentNode) {
            alienElement.classList.add('exploding');

            const gameArea = document.getElementById('game-area');
            if (gameArea) {
                gameArea.style.animation = 'none';
                gameArea.offsetHeight;
                gameArea.style.animation = 'screenShake 0.5s ease-in-out';
                setTimeout(() => {
                    gameArea.style.animation = '';
                }, 500);
            }

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

        this._fallingAliens = this._fallingAliens.filter(fa => fa.element !== alienElement);

        // Lose life
        this._lives--;
        this._combo = 0;
        this._aliensMissed++;

        this._updateHUD();
        this._updateAnswerPanelForOldestAlien();

        if (navigator.vibrate) {
            navigator.vibrate([200, 100, 200, 100, 200]);
        }

        if (this._lives <= 0) {
            this._gameOver();
        }

        this._eventBus.emit('sentence-invaders:alien-missed', {
            gameId: 'sentence-invaders',
            instanceId: this.name,
            lives: this._lives,
            score: this._score
        }, this.name);
    }

    _levelUp() {
        this._level++;

        // Level up gives a significant boost on top of progressive difficulty
        this._config.fallSpeedVhPerSecond = Math.min(
            this._config.maxFallSpeed,
            this._config.fallSpeedVhPerSecond * 1.15
        );
        this._config.spawnRate = Math.max(
            this._config.minSpawnRate,
            this._config.spawnRate * 0.85
        );

        // Restart intervals with new rates
        this._startSpawning();

        this._updateHUD();

        // Show level up message
        const gameArea = document.getElementById('game-area');
        const levelUpMsg = document.createElement('div');
        levelUpMsg.className = 'level-up-popup';
        levelUpMsg.innerHTML = `
            <h2>👾 LEVEL UP! 👾</h2>
            <p>Level ${this._level}</p>
            <p>Aliens invade faster!</p>
        `;
        gameArea.appendChild(levelUpMsg);

        setTimeout(() => {
            if (levelUpMsg.parentNode) {
                levelUpMsg.remove();
            }
        }, 2000);

        this._eventBus.emit('sentence-invaders:level-up', {
            gameId: 'sentence-invaders',
            instanceId: this.name,
            level: this._level,
            score: this._score
        }, this.name);
    }

    _togglePause() {
        this._isGamePaused = !this._isGamePaused;

        // Pause/resume TTS
        if (this._isGamePaused) {
            ttsService.pause();
        } else {
            ttsService.resume();
        }

        const pauseBtn = document.getElementById('pause-btn');
        if (pauseBtn) {
            pauseBtn.textContent = this._isGamePaused ? '▶️ Resume' : '⏸️ Pause';
        }

        if (this._isGamePaused) {
            this._eventBus.emit('game:paused', { instanceId: this.name }, this.name);
        } else {
            this._eventBus.emit('game:resumed', { instanceId: this.name }, this.name);
        }
    }

    _gameOver() {
        this._isGameOver = true;

        // Clear intervals
        if (this._spawnInterval) {
            clearInterval(this._spawnInterval);
            this._spawnInterval = null;
        }

        if (this._difficultyInterval) {
            clearInterval(this._difficultyInterval);
            this._difficultyInterval = null;
        }

        // Stop TTS
        ttsService.cancel();

        // Clear aliens
        this._fallingAliens.forEach(fa => {
            if (fa.positionCheck) {
                clearInterval(fa.positionCheck);
            }
            if (fa.element.parentNode) {
                fa.element.remove();
            }
        });
        this._fallingAliens = [];

        this._showGameOverScreen();

        this._eventBus.emit('game:completed', {
            gameId: 'sentence-invaders',
            instanceId: this.name,
            score: this._score,
            level: this._level,
            duration: this._gameStartTime ? Date.now() - this._gameStartTime : 0
        }, this.name);
    }

    _showGameOverScreen() {
        const duration = this._gameStartTime ? Math.round((Date.now() - this._gameStartTime) / 1000) : 0;

        const gameKey = 'sentence-invaders';
        const currentScore = this._score;
        const bestScore = parseInt(localStorage.getItem(`${gameKey}-best-score`) || '0');
        const isNewBest = currentScore > bestScore;

        if (isNewBest) {
            localStorage.setItem(`${gameKey}-best-score`, currentScore.toString());
        }

        const accuracy = (this._aliensKilled + this._aliensMissed) > 0
            ? Math.round((this._aliensKilled / (this._aliensKilled + this._aliensMissed)) * 100)
            : 0;

        this._showVictoryPopup({
            gameTitle: 'Sentence Invaders',
            currentScore,
            bestScore: isNewBest ? currentScore : bestScore,
            isNewBest,
            stats: {
                'Level Reached': this._level,
                'Duration': `${duration}s`,
                'Aliens Destroyed': this._aliensKilled,
                'Accuracy': `${accuracy}%`
            }
        });
    }

    _restartGame() {
        // Reset state
        this._score = 0;
        this._level = 1;
        this._lives = this._config.startingLives;
        this._combo = 0;
        this._isGamePaused = false;
        this._isGameOver = false;
        this._currentSentenceIndex = 0;
        this._gameStartTime = Date.now();
        this._aliensKilled = 0;
        this._aliensMissed = 0;

        // Reset config to base values
        this._config.fallSpeedVhPerSecond = this._config.baseFallSpeed;
        this._config.spawnRate = this._config.baseSpawnRate;

        // Clear intervals
        if (this._spawnInterval) {
            clearInterval(this._spawnInterval);
        }
        if (this._difficultyInterval) {
            clearInterval(this._difficultyInterval);
        }

        // Clear aliens
        this._fallingAliens.forEach(fa => {
            if (fa.positionCheck) {
                clearInterval(fa.positionCheck);
            }
            if (fa.element.parentNode) {
                fa.element.remove();
            }
        });
        this._fallingAliens = [];

        // Update and restart
        this._updateHUD();
        this._startSpawning();
        this._startProgressiveDifficulty();
    }

    _updateHUD() {
        const scoreDisplay = document.getElementById('score-display');
        const levelDisplay = document.getElementById('level-display');
        const livesDisplay = document.getElementById('lives-display');
        const comboDisplay = document.getElementById('combo-display');

        if (scoreDisplay) scoreDisplay.textContent = this._score;
        if (levelDisplay) levelDisplay.textContent = this._level;
        if (livesDisplay) livesDisplay.textContent = this._lives;
        if (comboDisplay) comboDisplay.textContent = this._combo;
    }

    _showError(message) {
        if (this._config.container) {
            this._config.container.innerHTML = `
                <div class="game-error">
                    <div class="error-icon">❌</div>
                    <h3>Sentence Invaders Error</h3>
                    <p>${message}</p>
                    <button class="btn btn-primary" onclick="history.back()">Go Back</button>
                </div>
            `;
        }
    }

    _shuffleArray(array) {
        const shuffled = [...array];
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        return shuffled;
    }

    _handlePause() {
        this._isGamePaused = true;
        ttsService.pause();
        const pauseBtn = document.getElementById('pause-btn');
        if (pauseBtn) {
            pauseBtn.textContent = '▶️ Resume';
        }
    }

    _handleResume() {
        this._isGamePaused = false;
        ttsService.resume();
        const pauseBtn = document.getElementById('pause-btn');
        if (pauseBtn) {
            pauseBtn.textContent = '⏸️ Pause';
        }
    }

    _showVictoryPopup({ gameTitle, currentScore, bestScore, isNewBest, stats }) {
        const popup = document.createElement('div');
        popup.className = 'victory-popup';
        popup.innerHTML = `
            <div class="victory-content">
                <div class="victory-header">
                    <div class="victory-icon">👾</div>
                    <h2 class="victory-title">${gameTitle} Complete!</h2>
                    ${isNewBest ? '<div class="new-best-badge">🎉 New Best Score!</div>' : ''}
                </div>

                <div class="victory-scores">
                    <div class="score-display">
                        <div class="score-label">Your Score</div>
                        <div class="score-value">${currentScore}</div>
                    </div>
                    <div class="score-display best-score">
                        <div class="score-label">Best Score</div>
                        <div class="score-value">${bestScore}</div>
                    </div>
                </div>

                <div class="victory-stats">
                    ${Object.entries(stats).map(([key, value]) => `
                        <div class="stat-item">
                            <div class="stat-label">${key}</div>
                            <div class="stat-value">${value}</div>
                        </div>
                    `).join('')}
                </div>

                <div class="victory-actions">
                    <button class="victory-btn victory-btn-primary" id="play-again-btn">
                        <span class="btn-icon">🔄</span>
                        <span class="btn-text">Play Again</span>
                    </button>
                    <button class="victory-btn victory-btn-secondary" id="different-game-btn">
                        <span class="btn-icon">🎮</span>
                        <span class="btn-text">Different Game</span>
                    </button>
                    <button class="victory-btn victory-btn-outline" id="main-menu-btn">
                        <span class="btn-icon">🏠</span>
                        <span class="btn-text">Main Menu</span>
                    </button>
                </div>
            </div>
        `;

        document.body.appendChild(popup);

        requestAnimationFrame(() => {
            popup.classList.add('show');
        });

        popup.querySelector('#play-again-btn').addEventListener('click', () => {
            popup.remove();
            this._restartGame();
        });

        popup.querySelector('#different-game-btn').addEventListener('click', () => {
            popup.remove();
            if (window.app && window.app.getCore().router) {
                window.app.getCore().router.navigate('/games');
            } else {
                window.location.href = '/#/games';
            }
        });

        popup.querySelector('#main-menu-btn').addEventListener('click', () => {
            popup.remove();
            if (window.app && window.app.getCore().router) {
                window.app.getCore().router.navigate('/');
            } else {
                window.location.href = '/';
            }
        });

        popup.addEventListener('click', (e) => {
            if (e.target === popup) {
                popup.remove();
                if (window.app && window.app.getCore().router) {
                    window.app.getCore().router.navigate('/games');
                } else {
                    window.location.href = '/#/games';
                }
            }
        });
    }
}

export default SentenceInvaders;
