import Module from '../core/Module.js';
import ttsService from '../services/TTSService.js';

class GrammarDiscovery extends Module {
    constructor(name, dependencies, config = {}) {
        super(name, ['eventBus']);

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

        this._eventBus = dependencies.eventBus;
        this._content = dependencies.content;
        this._config = {
            container: null,
            difficulty: 'medium',
            ...config
        };

        this._score = 0;
        this._rotationSteps = [
            'explanation-basic',
            'examples-simple',
            'exercise-basic',
            'explanation-detailed',
            'examples-complex',
            'exercise-intermediate',
            'summary',
            'exercise-global'
        ];

        this._currentStep = 0;
        this._grammarConcept = null;
        this._conceptData = {};
        this._stepProgress = {};
        this._availableConcepts = [];
        this._conceptSelected = false;
        this._gameContainer = null;

        this._simpleExamples = [];
        this._complexExamples = [];
        this._basicExercises = [];
        this._intermediateExercises = [];
        this._globalExercises = [];
        this._currentExerciseSet = [];
        this._currentExerciseIndex = 0;

        Object.seal(this);
    }

    static getMetadata() {
        return {
            id: 'grammar-discovery',
            name: 'Grammar Discovery',
            description: 'Interactive grammar learning with 8-step rotation system',
            version: '2.0.0',
            author: 'Class Generator',
            category: 'grammar',
            tags: ['grammar', 'learning', 'discovery', 'practice'],
            difficulty: {
                min: 1,
                max: 4,
                default: 2
            },
            estimatedDuration: 20,
            requiredContent: ['grammar']
        };
    }

    static getCompatibilityScore(content) {
        if (!content) {
            return 0;
        }

        // Handle both array and object vocabulary formats
        let vocabCount = 0;
        let hasVocabulary = false;

        if (Array.isArray(content.vocabulary)) {
            vocabCount = content.vocabulary.length;
            hasVocabulary = vocabCount > 0;
        } else if (content.vocabulary && typeof content.vocabulary === 'object') {
            vocabCount = Object.keys(content.vocabulary).length;
            hasVocabulary = vocabCount > 0;
        }

        // Check for dedicated grammar content
        if (content.grammar) {
            let score = 60;
            const grammarConcepts = Object.keys(content.grammar);
            if (grammarConcepts.length >= 1) score += 15;
            if (grammarConcepts.length >= 3) score += 10;
            if (grammarConcepts.length >= 5) score += 10;
            const hasExercises = content.fillInBlanks || content.corrections;
            if (hasExercises) score += 5;
            return Math.min(score, 100);
        }

        // Fallback: Use vocabulary to create basic grammar exercises
        if (hasVocabulary && vocabCount >= 5) {
            let score = 30; // Base score for vocabulary-based grammar

            if (vocabCount >= 10) score += 10;
            if (vocabCount >= 20) score += 10;
            if (vocabCount >= 30) score += 5;

            // Bonus if we have other useful content
            if (content.fillInBlanks) score += 10;
            if (content.corrections) score += 10;
            if (content.sentences) score += 5;

            return Math.min(score, 75); // Cap at 75 for vocabulary-only content
        }

        return 0;
    }

    async init() {
        this._validateNotDestroyed();

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

        // Log content language for TTS
        console.log('📚 Grammar Discovery - Content language:', this._content?.language || 'not specified');

        this._eventBus.on('game:start', this._handleGameStart.bind(this), this.name);
        this._eventBus.on('game:stop', this._handleGameStop.bind(this), this.name);
        this._eventBus.on('navigation:change', this._handleNavigationChange.bind(this), this.name);

        this._injectCSS();

        // Start game immediately
        try {
            this._gameContainer = this._config.container;
            const content = this._content;

            if (!content) {
                throw new Error('No content available');
            }

            // Check if we have grammar content or vocabulary to work with
            const hasGrammar = content.grammar && Object.keys(content.grammar).length > 0;
            let hasVocabulary = false;
            let vocabCount = 0;

            if (Array.isArray(content.vocabulary)) {
                vocabCount = content.vocabulary.length;
                hasVocabulary = vocabCount > 0;
            } else if (content.vocabulary && typeof content.vocabulary === 'object') {
                vocabCount = Object.keys(content.vocabulary).length;
                hasVocabulary = vocabCount > 0;
            }

            if (!hasGrammar && (!hasVocabulary || vocabCount < 5)) {
                throw new Error('No suitable content available for grammar learning');
            }

            this._extractAvailableConcepts(content);
            this._renderGameInterface();

            // Emit game ready event
            this._eventBus.emit('game:ready', {
                gameId: 'grammar-discovery',
                instanceId: this.name,
                concepts: this._availableConcepts.length,
                vocabulary: vocabCount
            }, this.name);

        } catch (error) {
            console.error('Error starting Grammar Discovery:', error);
            this._eventBus.emit('game:error', {
                gameId: 'grammar-discovery',
                error: error.message,
                module: this.name
            });
        }

        this._setInitialized();
    }

    async destroy() {
        this._validateNotDestroyed();

        this._cleanup();
        this._removeCSS();
        this._eventBus.off('game:start', this.name);
        this._eventBus.off('game:stop', this.name);
        this._eventBus.off('navigation:change', this.name);

        this._setDestroyed();
    }

    _handleGameStart(event) {
        this._validateInitialized();
        if (event.gameId === 'grammar-discovery') {
            this._startGame();
        }
    }

    _handleGameStop(event) {
        this._validateInitialized();
        if (event.gameId === 'grammar-discovery') {
            this._stopGame();
        }
    }

    _handleNavigationChange(event) {
        this._validateInitialized();
        if (event.from === '/games/grammar-discovery') {
            this._cleanup();
        }
    }

    async _startGame() {
        try {
            this._gameContainer = document.getElementById('game-content');
            if (!this._gameContainer) {
                throw new Error('Game container not found');
            }

            const content = await this._content.getCurrentContent();
            if (!content) {
                throw new Error('No content available');
            }

            // Check if we have grammar content or vocabulary to work with
            const hasGrammar = content.grammar && Object.keys(content.grammar).length > 0;
            let hasVocabulary = false;
            let vocabCount = 0;

            if (Array.isArray(content.vocabulary)) {
                vocabCount = content.vocabulary.length;
                hasVocabulary = vocabCount > 0;
            } else if (content.vocabulary && typeof content.vocabulary === 'object') {
                vocabCount = Object.keys(content.vocabulary).length;
                hasVocabulary = vocabCount > 0;
            }

            if (!hasGrammar && (!hasVocabulary || vocabCount < 5)) {
                throw new Error('No suitable content available for grammar learning');
            }

            this._extractAvailableConcepts(content);
            this._renderGameInterface();

        } catch (error) {
            console.error('Error starting Grammar Discovery:', error);
            this._eventBus.emit('game:error', {
                gameId: 'grammar-discovery',
                error: error.message,
                module: this.name
            });
        }
    }

    _stopGame() {
        this._cleanup();
    }

    _cleanup() {
        if (this._gameContainer) {
            this._gameContainer.innerHTML = '';
        }

        if (window.currentGrammarGame === this) {
            delete window.currentGrammarGame;
        }
    }

    _extractAvailableConcepts(content) {
        this._availableConcepts = [];

        // First, try to use dedicated grammar content
        if (content.grammar && Object.keys(content.grammar).length > 0) {
            this._availableConcepts = Object.entries(content.grammar).map(([key, conceptData]) => ({
                id: key,
                title: conceptData.title,
                explanation: conceptData.explanation,
                data: conceptData
            }));
        } else {
            // Fallback: Create basic grammar concepts from vocabulary
            this._createVocabularyBasedConcepts(content);
        }

        console.log(`Found ${this._availableConcepts.length} grammar concepts available`);
    }

    _createVocabularyBasedConcepts(content) {
        // Create basic grammar concepts that can work with vocabulary
        const basicConcepts = [
            {
                id: 'vocabulary-practice',
                title: 'Vocabulary Practice',
                explanation: 'Practice using new vocabulary words in context and build familiarity with their meanings.',
                data: {
                    title: 'Vocabulary Practice',
                    explanation: 'Practice using new vocabulary words in context and build familiarity with their meanings.',
                    examples: this._createVocabularyExamples(content),
                    mainRules: [
                        'Learn the meaning of each word',
                        'Practice pronunciation',
                        'Use words in different contexts',
                        'Remember common collocations'
                    ]
                }
            },
            {
                id: 'word-formation',
                title: 'Word Formation',
                explanation: 'Understanding how words are formed and how to recognize patterns in vocabulary.',
                data: {
                    title: 'Word Formation',
                    explanation: 'Understanding how words are formed and how to recognize patterns in vocabulary.',
                    examples: this._createWordFormationExamples(content),
                    mainRules: [
                        'Identify word roots and patterns',
                        'Recognize common prefixes and suffixes',
                        'Understand compound words',
                        'Learn word families'
                    ]
                }
            }
        ];

        this._availableConcepts = basicConcepts;
    }

    _createVocabularyExamples(content) {
        const examples = [];
        let vocabulary = [];

        // Extract vocabulary based on format
        if (Array.isArray(content.vocabulary)) {
            vocabulary = content.vocabulary.slice(0, 10); // Limit to first 10
        } else if (content.vocabulary && typeof content.vocabulary === 'object') {
            vocabulary = Object.entries(content.vocabulary).slice(0, 10).map(([word, data]) => {
                // Extract translation properly from different formats
                let translation;
                if (typeof data === 'string') {
                    translation = data;
                } else if (typeof data === 'object') {
                    translation = data.english || data.translation || data.user_language;
                    // If still an object, extract the user_language property
                    if (typeof translation === 'object' && translation.user_language) {
                        translation = translation.user_language;
                    }
                }

                return {
                    chinese: word,
                    english: translation || word,
                    pronunciation: (typeof data === 'object' ? (data.pronunciation || data.prononciation) : '') || '',
                    text: word
                };
            });
        }

        vocabulary.forEach(item => {
            if (typeof item === 'object') {
                // Extract translation - handle both string and object formats
                let translation = item.english || item.translation;
                if (typeof translation === 'object') {
                    translation = translation.english || translation.translation || JSON.stringify(translation);
                }

                examples.push({
                    chinese: item.chinese || item.text || item.word,
                    english: translation || `Translation for: ${item.chinese || item.text || item.word}`,
                    pronunciation: item.pronunciation || item.prononciation || '',
                    explanation: `Practice word: ${item.chinese || item.text || item.word}`
                });
            } else if (typeof item === 'string') {
                examples.push({
                    chinese: item,
                    english: `Translation for: ${item}`,
                    pronunciation: '',
                    explanation: `Practice word: ${item}`
                });
            }
        });

        return examples;
    }

    _createWordFormationExamples(content) {
        const examples = [];
        let vocabulary = [];

        // Extract vocabulary based on format
        if (Array.isArray(content.vocabulary)) {
            vocabulary = content.vocabulary.slice(0, 5);
        } else if (content.vocabulary && typeof content.vocabulary === 'object') {
            vocabulary = Object.entries(content.vocabulary).slice(0, 5).map(([word, data]) => {
                // Extract translation properly from different formats
                let translation;
                if (typeof data === 'string') {
                    translation = data;
                } else if (typeof data === 'object') {
                    translation = data.english || data.translation || data.user_language;
                    // If still an object, extract the user_language property
                    if (typeof translation === 'object' && translation.user_language) {
                        translation = translation.user_language;
                    }
                }

                return {
                    chinese: word,
                    english: translation || word,
                    pronunciation: (typeof data === 'object' ? (data.pronunciation || data.prononciation) : '') || '',
                    text: word
                };
            });
        }

        vocabulary.forEach(item => {
            if (typeof item === 'object') {
                const word = item.chinese || item.text || item.word;

                // Extract translation - handle both string and object formats
                let translation = item.english || item.translation;
                if (typeof translation === 'object') {
                    translation = translation.english || translation.translation || JSON.stringify(translation);
                }

                examples.push({
                    chinese: word,
                    english: translation || `Formation example: ${word}`,
                    pronunciation: item.pronunciation || item.prononciation || '',
                    explanation: `Analyze the structure and formation of: ${word}`
                });
            } else if (typeof item === 'string') {
                examples.push({
                    chinese: item,
                    english: `Formation example: ${item}`,
                    pronunciation: '',
                    explanation: `Analyze the structure and formation of: ${item}`
                });
            }
        });

        return examples;
    }

    _renderGameInterface() {
        this._gameContainer.innerHTML = `
            <div class="grammar-discovery">
                <div class="grammar-hud">
                    <div class="grammar-phase">
                        <span class="phase-icon" id="phase-icon">🎯</span>
                        <span id="phase-text">Select Grammar Concept</span>
                    </div>
                    <div class="step-progress" id="step-progress" style="display: none;">
                        Step <span id="current-step">1</span> of ${this._rotationSteps.length}
                    </div>
                    <div class="score">Score: <span id="score-value">0</span></div>
                </div>
                <div class="grammar-content" id="grammar-content">
                    <!-- Content will be populated dynamically -->
                </div>
            </div>
        `;

        window.currentGrammarGame = this;
        this._showConceptSelector();
    }

    _showConceptSelector() {
        if (this._availableConcepts.length === 0) {
            console.error('No concepts available for selection');
            return;
        }

        const contentDiv = document.getElementById('grammar-content');

        contentDiv.innerHTML = `
            <div class="concept-selector">
                <div class="selector-title">
                    🎯 Choose Grammar Concept
                </div>
                <div class="selector-description">
                    Select which grammar concept you want to focus on for intensive study with our 8-step rotation system.
                </div>

                <select class="concept-dropdown" id="concept-dropdown" onchange="window.currentGrammarGame._previewConcept(this.value)">
                    <option value="">-- Select a Grammar Concept --</option>
                    ${this._availableConcepts.map(concept => `
                        <option value="${concept.id}">${concept.title}</option>
                    `).join('')}
                </select>

                <div class="concept-preview" id="concept-preview">
                    <!-- Preview content will be shown here -->
                </div>

                <button class="discover-btn" id="start-btn" onclick="window.currentGrammarGame._startSelectedConcept()" disabled>
                    🚀 Start Learning This Concept
                </button>
            </div>
        `;
    }

    _previewConcept(conceptId) {
        const previewDiv = document.getElementById('concept-preview');
        const startBtn = document.getElementById('start-btn');

        if (!conceptId) {
            previewDiv.classList.remove('show');
            startBtn.disabled = true;
            return;
        }

        const concept = this._availableConcepts.find(c => c.id === conceptId);
        if (!concept) return;

        this._grammarConcept = conceptId;
        this._conceptData = concept.data;
        this._organizeConceptContent();

        previewDiv.innerHTML = `
            <div class="preview-title">${concept.title}</div>
            <div class="preview-explanation">${concept.explanation}</div>
            <div class="preview-stats">
                <div class="stat-item">
                    <strong>${this._simpleExamples.length}</strong><br>
                    Simple Examples
                </div>
                <div class="stat-item">
                    <strong>${this._complexExamples.length}</strong><br>
                    Complex Examples
                </div>
                <div class="stat-item">
                    <strong>${this._basicExercises.length}</strong><br>
                    Basic Exercises
                </div>
                <div class="stat-item">
                    <strong>${this._intermediateExercises.length}</strong><br>
                    Intermediate Exercises
                </div>
                <div class="stat-item">
                    <strong>${this._globalExercises.length}</strong><br>
                    Final Test Questions
                </div>
            </div>
        `;

        previewDiv.classList.add('show');
        startBtn.disabled = false;
    }

    _startSelectedConcept() {
        const dropdown = document.getElementById('concept-dropdown');
        const selectedConceptId = dropdown.value;

        if (!selectedConceptId) {
            alert('Please select a grammar concept first!');
            return;
        }

        document.getElementById('step-progress').style.display = 'block';
        document.getElementById('phase-icon').textContent = '📚';
        document.getElementById('phase-text').textContent = 'Basic Explanation';

        this._selectConcept(selectedConceptId);
    }

    _selectConcept(conceptId) {
        const selectedConcept = this._availableConcepts.find(c => c.id === conceptId);
        if (!selectedConcept) {
            console.error('Concept not found:', conceptId);
            return;
        }

        this._grammarConcept = conceptId;
        this._conceptData = selectedConcept.data;
        this._conceptSelected = true;

        this._organizeConceptContent();
        this._startRotationCycle();
    }

    _organizeConceptContent() {
        const concept = this._conceptData;

        this._simpleExamples = [];
        this._complexExamples = [];

        if (concept.examples) {
            this._simpleExamples = concept.examples.slice(0, 3);
            this._complexExamples = concept.examples.slice(3);
        }

        if (concept.detailedExplanation) {
            Object.values(concept.detailedExplanation).forEach(section => {
                if (section.examples) {
                    const sectionSimple = section.examples.slice(0, 2);
                    const sectionComplex = section.examples.slice(2);

                    this._simpleExamples.push(...sectionSimple);
                    this._complexExamples.push(...sectionComplex);
                }
            });
        }

        this._basicExercises = [];
        this._intermediateExercises = [];
        this._globalExercises = [];

        // this._content is already the content object, not a service with methods
        const content = this._content;

        if (content.fillInBlanks) {
            content.fillInBlanks.forEach(exercise => {
                const isGrammarLesson = content.type === 'grammar_course';
                const isRelevant = isGrammarLesson ||
                                 exercise.grammarFocus === this._grammarConcept ||
                                 exercise.grammarFocus === 'completion' ||
                                 exercise.grammarFocus === 'change-of-state';

                if (isRelevant) {
                    if (exercise.sentence.length < 15) {
                        this._basicExercises.push(exercise);
                    } else {
                        this._intermediateExercises.push(exercise);
                    }
                }
            });
        }

        if (content.corrections) {
            content.corrections.forEach(correction => {
                const isGrammarLesson = content.type === 'grammar_course';
                const isRelevant = isGrammarLesson ||
                                 correction.grammarFocus === this._grammarConcept;

                if (isRelevant) {
                    this._intermediateExercises.push({
                        type: 'correction',
                        question: 'Which sentence is correct?',
                        options: [correction.correct, correction.incorrect],
                        correctAnswer: correction.correct,
                        explanation: correction.explanation
                    });
                }
            });
        }

        this._globalExercises = [...this._basicExercises, ...this._intermediateExercises];
        this._globalExercises = this._shuffleArray(this._globalExercises).slice(0, 5);
    }

    _startRotationCycle() {
        this._currentStep = 0;
        this._showCurrentStep();
    }

    _showCurrentStep() {
        const stepType = this._rotationSteps[this._currentStep];
        const stepNumber = this._currentStep + 1;

        document.getElementById('current-step').textContent = stepNumber;

        const phaseInfo = this._getPhaseInfo(stepType);
        document.getElementById('phase-icon').textContent = phaseInfo.icon;
        document.getElementById('phase-text').textContent = phaseInfo.text;

        switch (stepType) {
            case 'explanation-basic':
                this._showBasicExplanation();
                break;
            case 'examples-simple':
                this._showSimpleExamples();
                break;
            case 'exercise-basic':
                this._showBasicExercises();
                break;
            case 'explanation-detailed':
                this._showDetailedExplanation();
                break;
            case 'examples-complex':
                this._showComplexExamples();
                break;
            case 'exercise-intermediate':
                this._showIntermediateExercises();
                break;
            case 'summary':
                this._showSummary();
                break;
            case 'exercise-global':
                this._showGlobalExercises();
                break;
        }
    }

    _getPhaseInfo(stepType) {
        const phaseMap = {
            'explanation-basic': { icon: '📚', text: 'Basic Explanation' },
            'examples-simple': { icon: '💡', text: 'Simple Examples' },
            'exercise-basic': { icon: '✏️', text: 'Basic Practice' },
            'explanation-detailed': { icon: '🔍', text: 'Detailed Explanation' },
            'examples-complex': { icon: '🧩', text: 'Complex Examples' },
            'exercise-intermediate': { icon: '💪', text: 'Intermediate Practice' },
            'summary': { icon: '📝', text: 'Summary' },
            'exercise-global': { icon: '🏆', text: 'Final Test' }
        };
        return phaseMap[stepType] || { icon: '❓', text: 'Unknown' };
    }

    _nextStep() {
        this._currentStep++;
        if (this._currentStep >= this._rotationSteps.length) {
            this._completeRotation();
        } else {
            this._showCurrentStep();
        }
    }

    _completeRotation() {
        // Handle localStorage best score
        const currentScore = this._score;
        const bestScore = parseInt(localStorage.getItem('grammar-discovery-best-score') || '0');
        const isNewBest = currentScore > bestScore;

        if (isNewBest) {
            localStorage.setItem('grammar-discovery-best-score', currentScore.toString());
        }

        // Calculate completion stats
        const completionRate = Math.round((this._currentStep / this._rotationSteps.length) * 100);

        this._showVictoryPopup({
            gameTitle: 'Grammar Discovery',
            currentScore,
            bestScore: isNewBest ? currentScore : bestScore,
            isNewBest,
            stats: {
                'Concept Studied': this._conceptData.title || 'Grammar Concept',
                'Steps Completed': `${this._currentStep}/${this._rotationSteps.length}`,
                'Completion Rate': `${completionRate}%`,
                'Learning Mode': 'Full Rotation'
            }
        });
    }

    _showBasicExplanation() {
        const concept = this._conceptData;
        const contentDiv = document.getElementById('grammar-content');

        contentDiv.innerHTML = `
            <div class="rule-card active">
                <div class="rule-title">
                    📚 ${concept.title}
                </div>
                <div class="rule-explanation">
                    ${concept.explanation}
                </div>

                ${concept.mainRules ? `
                    <div class="rules-list">
                        <h4>🎯 Key Rules:</h4>
                        <ul>
                            ${concept.mainRules.slice(0, 3).map(rule => `<li>${rule}</li>`).join('')}
                        </ul>
                    </div>
                ` : ''}

                <div class="discovery-controls">
                    <button class="discover-btn" onclick="window.currentGrammarGame._nextStep()">
                        ➡️ Continue to Examples
                    </button>
                </div>
            </div>
        `;
    }

    _showSimpleExamples() {
        const contentDiv = document.getElementById('grammar-content');

        contentDiv.innerHTML = `
            <div class="rule-card active">
                <div class="rule-title">
                    💡 Simple Examples
                </div>
                <div class="examples-section">
                    ${this._simpleExamples.map((example, index) => {
                        // For English courses: english is the main text, translation is Chinese
                        const mainText = example.english || example.chinese || example.text || example.sentence || '';
                        const translationText = example.translation || '';
                        return `
                        <div class="example-item revealed" id="simple-example-${index}">
                            <div class="chinese-text">${mainText}</div>
                            <div class="english-text">${translationText}</div>
                            <div class="pronunciation">${example.pronunciation || example.prononciation || ''}</div>
                            <div class="explanation-text">${example.explanation || example.breakdown || ''}</div>
                            <div class="tts-controls">
                                <button class="tts-btn" data-example-type="simple" data-example-index="${index}">
                                    🔊 Pronunciation
                                </button>
                            </div>
                        </div>
                    `;}).join('')}
                </div>

                <div class="discovery-controls">
                    <button class="discover-btn" onclick="window.currentGrammarGame._nextStep()">
                        ➡️ Practice Basic Exercises
                    </button>
                </div>
            </div>
        `;

        // Attach TTS event listeners
        this._attachTTSListeners();
    }

    _showBasicExercises() {
        if (this._basicExercises.length === 0) {
            this._nextStep();
            return;
        }

        this._currentExerciseSet = this._basicExercises;
        this._currentExerciseIndex = 0;
        this._showExercise('basic');
    }

    _showDetailedExplanation() {
        const concept = this._conceptData;
        const contentDiv = document.getElementById('grammar-content');

        let detailsHtml = '';
        if (concept.detailedExplanation) {
            detailsHtml = Object.entries(concept.detailedExplanation).map(([key, section]) => `
                <div class="detail-section">
                    <h4>🔍 ${section.title}</h4>
                    <p>${section.explanation}</p>
                    ${section.pattern ? `<div class="pattern">Pattern: <code>${section.pattern}</code></div>` : ''}
                </div>
            `).join('');
        }

        contentDiv.innerHTML = `
            <div class="rule-card active">
                <div class="rule-title">
                    🔍 Detailed Explanation
                </div>

                ${detailsHtml}

                ${concept.commonMistakes ? `
                    <div class="mistakes-section">
                        <h4>⚠️ Common Mistakes:</h4>
                        ${concept.commonMistakes.map(mistake => `
                            <div class="mistake-item">
                                <div class="mistake-wrong">❌ ${mistake.wrong}</div>
                                <div class="mistake-correct">✅ ${mistake.correct}</div>
                                <div class="mistake-explanation">${mistake.explanation}</div>
                            </div>
                        `).join('')}
                    </div>
                ` : ''}

                <div class="discovery-controls">
                    <button class="discover-btn" onclick="window.currentGrammarGame._nextStep()">
                        ➡️ See Complex Examples
                    </button>
                </div>
            </div>
        `;
    }

    _showComplexExamples() {
        const contentDiv = document.getElementById('grammar-content');

        contentDiv.innerHTML = `
            <div class="rule-card active">
                <div class="rule-title">
                    🧩 Complex Examples
                </div>
                <div class="examples-section">
                    ${this._complexExamples.map((example, index) => {
                        // For English courses: english is the main text, translation is Chinese
                        const mainText = example.english || example.chinese || example.text || example.sentence || '';
                        const translationText = example.translation || '';
                        return `
                        <div class="example-item revealed" id="complex-example-${index}">
                            <div class="chinese-text">${mainText}</div>
                            <div class="english-text">${translationText}</div>
                            <div class="pronunciation">${example.pronunciation || example.prononciation || ''}</div>
                            <div class="explanation-text">${example.explanation || example.breakdown || ''}</div>
                            <div class="tts-controls">
                                <button class="tts-btn" data-example-type="complex" data-example-index="${index}">
                                    🔊 Pronunciation
                                </button>
                            </div>
                        </div>
                    `;}).join('')}
                </div>

                <div class="discovery-controls">
                    <button class="discover-btn" onclick="window.currentGrammarGame._nextStep()">
                        ➡️ Intermediate Practice
                    </button>
                </div>
            </div>
        `;

        // Attach TTS event listeners
        this._attachTTSListeners();
    }

    _showIntermediateExercises() {
        if (this._intermediateExercises.length === 0) {
            this._nextStep();
            return;
        }

        this._currentExerciseSet = this._intermediateExercises;
        this._currentExerciseIndex = 0;
        this._showExercise('intermediate');
    }

    _showSummary() {
        const concept = this._conceptData;
        const contentDiv = document.getElementById('grammar-content');

        contentDiv.innerHTML = `
            <div class="rule-card active">
                <div class="rule-title">
                    📝 Summary: ${concept.title}
                </div>

                <div class="summary-section">
                    <h4>🎯 What You've Learned:</h4>
                    <div class="summary-grid">
                        <div class="summary-item">
                            <strong>Basic Concept:</strong><br>
                            ${concept.explanation}
                        </div>
                        ${concept.mainRules ? `
                            <div class="summary-item">
                                <strong>Key Rules:</strong><br>
                                ${concept.mainRules.map(rule => `• ${rule}`).join('<br>')}
                            </div>
                        ` : ''}
                        ${concept.practicePoints ? `
                            <div class="summary-item">
                                <strong>Practice Points:</strong><br>
                                ${concept.practicePoints.map(point => `• ${point}`).join('<br>')}
                            </div>
                        ` : ''}
                    </div>
                </div>

                <div class="discovery-controls">
                    <button class="discover-btn" onclick="window.currentGrammarGame._nextStep()">
                        🏆 Take Final Test
                    </button>
                </div>
            </div>
        `;
    }

    _showGlobalExercises() {
        if (this._globalExercises.length === 0) {
            this._completeRotation();
            return;
        }

        this._currentExerciseSet = this._globalExercises;
        this._currentExerciseIndex = 0;
        this._showExercise('global');
    }

    _showExercise(type) {
        const exercise = this._currentExerciseSet[this._currentExerciseIndex];
        if (!exercise) {
            this._nextStep();
            return;
        }

        const contentDiv = document.getElementById('grammar-content');
        const typeInfo = {
            'basic': { title: '✏️ Basic Practice', color: '#48bb78' },
            'intermediate': { title: '💪 Intermediate Practice', color: '#3182ce' },
            'global': { title: '🏆 Final Test', color: '#805ad5' }
        };

        const info = typeInfo[type] || typeInfo['basic'];

        if (exercise.type === 'correction') {
            contentDiv.innerHTML = `
                <div class="practice-question">
                    <div class="rule-title" style="color: ${info.color}">
                        ${info.title}
                    </div>
                    <div class="question-text">
                        ${exercise.question}
                    </div>
                    <div class="options-grid">
                        ${exercise.options.map(option => `
                            <button class="option-btn" onclick="window.currentGrammarGame._selectAnswer('${option.replace(/'/g, "\\'")}', '${exercise.correctAnswer.replace(/'/g, "\\'")}', '${type}')">
                                ${option}
                            </button>
                        `).join('')}
                    </div>
                    <div class="feedback" id="feedback">
                        <strong>Explanation:</strong> ${exercise.explanation}
                    </div>
                    <div class="exercise-progress">
                        Exercise ${this._currentExerciseIndex + 1} of ${this._currentExerciseSet.length}
                    </div>
                </div>
            `;
        } else {
            contentDiv.innerHTML = `
                <div class="practice-question">
                    <div class="rule-title" style="color: ${info.color}">
                        ${info.title}
                    </div>
                    <div class="question-text">
                        Fill in the blank: <strong>${exercise.sentence}</strong>
                    </div>
                    <div class="options-grid">
                        ${exercise.options.map(option => `
                            <button class="option-btn" onclick="window.currentGrammarGame._selectAnswer('${option}', '${exercise.correctAnswer}', '${type}')">
                                ${option}
                            </button>
                        `).join('')}
                    </div>
                    <div class="feedback" id="feedback">
                        <strong>Explanation:</strong> ${exercise.explanation}
                    </div>
                    <div class="exercise-progress">
                        Exercise ${this._currentExerciseIndex + 1} of ${this._currentExerciseSet.length}
                    </div>
                </div>
            `;
        }
    }

    _selectAnswer(selected, correct, exerciseType) {
        const buttons = document.querySelectorAll('.option-btn');
        const feedback = document.getElementById('feedback');

        buttons.forEach(btn => {
            btn.disabled = true;
            if (btn.textContent.trim() === correct) {
                btn.classList.add('correct');
            } else if (btn.textContent.trim() === selected && selected !== correct) {
                btn.classList.add('incorrect');
            }
        });

        if (selected === correct) {
            const points = exerciseType === 'global' ? 30 : (exerciseType === 'intermediate' ? 20 : 15);
            this._score += points;
        } else {
            this._score = Math.max(0, this._score - 5);
        }

        document.getElementById('score-value').textContent = this._score;
        feedback.classList.add('show');

        setTimeout(() => {
            this._currentExerciseIndex++;
            if (this._currentExerciseIndex >= this._currentExerciseSet.length) {
                this._nextStep();
            } else {
                this._showExercise(exerciseType);
            }
        }, 2500);
    }

    _restart() {
        this._score = 0;
        this._currentStep = 0;
        this._currentExerciseIndex = 0;
        this._conceptSelected = false;
        this._grammarConcept = null;
        this._conceptData = {};

        document.getElementById('score-value').textContent = '0';
        document.getElementById('phase-icon').textContent = '🎯';
        document.getElementById('phase-text').textContent = 'Select Grammar Concept';
        document.getElementById('step-progress').style.display = 'none';

        this._showConceptSelector();
    }

    _attachTTSListeners() {
        // Find all TTS buttons in the current view
        const ttsButtons = document.querySelectorAll('.tts-btn[data-example-index]');

        ttsButtons.forEach(button => {
            const exampleIndex = parseInt(button.getAttribute('data-example-index'));
            const exampleType = button.getAttribute('data-example-type');

            button.addEventListener('click', async (e) => {
                e.preventDefault();

                // Get the text from the appropriate array
                // For English courses: speak the english text
                let text = '';
                if (exampleType === 'simple' && this._simpleExamples[exampleIndex]) {
                    const example = this._simpleExamples[exampleIndex];
                    text = example.english || example.chinese || example.text || example.sentence || '';
                } else if (exampleType === 'complex' && this._complexExamples[exampleIndex]) {
                    const example = this._complexExamples[exampleIndex];
                    text = example.english || example.chinese || example.text || example.sentence || '';
                }

                if (text) {
                    try {
                        await this._speakText(text);
                    } catch (error) {
                        console.error('TTS error:', error);
                    }
                }
            });
        });
    }

    async _speakText(text, lang = null) {
        // Priority 1: Use language from loaded book content
        let targetLanguage = this._content?.language;

        // Priority 2: Use provided parameter
        if (!targetLanguage) {
            targetLanguage = lang;
        }

        // Priority 3: Auto-detect from text content
        if (!targetLanguage) {
            // Simple detection: if text contains Chinese characters, use zh-CN, else en-US
            targetLanguage = /[\u4e00-\u9fa5]/.test(text) ? 'zh-CN' : 'en-US';
        }

        console.log(`🔊 Speaking "${text.substring(0, 30)}..." in ${targetLanguage}`);

        // Use centralized TTS service
        await ttsService.speak(text, targetLanguage, {
            rate: 0.85,
            volume: 0.9
        });
    }

    _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;
    }

    _injectCSS() {
        const cssId = 'grammar-discovery-styles';
        if (document.getElementById(cssId)) return;

        const style = document.createElement('style');
        style.id = cssId;
        style.textContent = `
            .grammar-discovery {
                display: flex;
                flex-direction: column;
                height: 100vh;
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                max-width: 1000px;
                margin: 0 auto;
                padding: 20px;
            }

            .grammar-hud {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 15px 25px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                border-radius: 12px;
                margin-bottom: 20px;
                box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
            }

            .grammar-phase {
                font-size: 18px;
                font-weight: bold;
                display: flex;
                align-items: center;
                gap: 10px;
            }

            .phase-icon {
                font-size: 24px;
            }

            .step-progress {
                font-size: 16px;
                opacity: 0.9;
            }

            .score {
                font-size: 16px;
                font-weight: bold;
            }

            .grammar-content {
                flex: 1;
                background: linear-gradient(145deg, #f8f9ff, #e6e9ff);
                border-radius: 12px;
                padding: 20px;
                overflow-y: auto;
            }

            .concept-selector {
                background: white;
                border-radius: 15px;
                padding: 30px;
                box-shadow: 0 8px 32px rgba(102, 126, 234, 0.1);
                text-align: center;
                max-width: 600px;
                margin: 0 auto;
            }

            .selector-title {
                font-size: 28px;
                font-weight: bold;
                color: #4c51bf;
                margin-bottom: 20px;
            }

            .selector-description {
                font-size: 16px;
                color: #4a5568;
                margin-bottom: 25px;
                line-height: 1.6;
            }

            .concept-dropdown {
                width: 100%;
                max-width: 400px;
                padding: 15px;
                font-size: 16px;
                border: 2px solid #e2e8f0;
                border-radius: 10px;
                background: white;
                margin-bottom: 20px;
                cursor: pointer;
                transition: all 0.3s ease;
            }

            .concept-dropdown:hover {
                border-color: #667eea;
            }

            .concept-dropdown:focus {
                outline: none;
                border-color: #667eea;
                box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            }

            .concept-preview {
                background: #f7fafc;
                border-radius: 10px;
                padding: 20px;
                margin: 20px 0;
                text-align: left;
                display: none;
            }

            .concept-preview.show {
                display: block;
                animation: fadeIn 0.3s ease;
            }

            .preview-title {
                font-size: 18px;
                font-weight: bold;
                color: #2d3748;
                margin-bottom: 10px;
            }

            .preview-explanation {
                font-size: 14px;
                color: #4a5568;
                margin-bottom: 15px;
            }

            .preview-stats {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
                gap: 10px;
                font-size: 12px;
                color: #718096;
            }

            .stat-item {
                background: white;
                padding: 8px;
                border-radius: 6px;
                text-align: center;
            }

            .discover-btn {
                background: linear-gradient(135deg, #667eea, #764ba2);
                color: white;
                border: none;
                padding: 12px 25px;
                border-radius: 25px;
                font-size: 16px;
                font-weight: bold;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
            }

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

            .discover-btn:disabled {
                opacity: 0.6;
                cursor: not-allowed;
                transform: none;
            }

            .rule-card {
                background: white;
                border-radius: 15px;
                padding: 25px;
                margin-bottom: 20px;
                box-shadow: 0 8px 32px rgba(102, 126, 234, 0.1);
                border: 2px solid transparent;
                transition: all 0.3s ease;
            }

            .rule-card.active {
                border-color: #667eea;
                transform: translateY(-2px);
                box-shadow: 0 12px 40px rgba(102, 126, 234, 0.2);
            }

            .rule-title {
                font-size: 24px;
                font-weight: bold;
                color: #4c51bf;
                margin-bottom: 15px;
                display: flex;
                align-items: center;
                gap: 10px;
            }

            .rule-explanation {
                font-size: 16px;
                line-height: 1.6;
                color: #4a5568;
                margin-bottom: 20px;
                background: #f7fafc;
                padding: 15px;
                border-radius: 8px;
                border-left: 4px solid #667eea;
            }

            .rules-list h4 {
                color: #2d3748;
                margin-bottom: 10px;
            }

            .rules-list ul {
                margin: 0;
                padding-left: 20px;
            }

            .rules-list li {
                margin-bottom: 8px;
                color: #4a5568;
            }

            .examples-section {
                margin-top: 20px;
            }

            .example-item {
                background: #ffffff;
                border: 2px solid #e2e8f0;
                border-radius: 12px;
                padding: 20px;
                margin-bottom: 15px;
                transition: all 0.3s ease;
            }

            .example-item.revealed {
                border-color: #48bb78;
                background: linear-gradient(135deg, #f0fff4, #c6f6d5);
            }

            .chinese-text {
                font-size: 22px;
                font-weight: bold;
                color: #2d3748;
                margin-bottom: 8px;
            }

            .english-text {
                font-size: 18px;
                color: #4a5568;
                margin-bottom: 8px;
            }

            .pronunciation {
                font-size: 16px;
                color: #718096;
                font-style: italic;
                margin-bottom: 10px;
            }

            .explanation-text {
                font-size: 14px;
                color: #667eea;
                background: #edf2f7;
                padding: 10px;
                border-radius: 6px;
                margin-bottom: 10px;
            }

            .tts-controls {
                display: flex;
                gap: 10px;
                align-items: center;
            }

            .tts-btn {
                background: #667eea;
                color: white;
                border: none;
                border-radius: 20px;
                padding: 8px 15px;
                cursor: pointer;
                font-size: 14px;
                transition: all 0.2s ease;
            }

            .tts-btn:hover {
                background: #5a67d8;
                transform: scale(1.05);
            }

            .discovery-controls {
                display: flex;
                gap: 15px;
                margin-top: 20px;
                justify-content: center;
            }

            .detail-section {
                margin-bottom: 20px;
                padding: 15px;
                background: #f7fafc;
                border-radius: 8px;
                border-left: 4px solid #3182ce;
            }

            .detail-section h4 {
                color: #2d3748;
                margin-bottom: 10px;
            }

            .pattern {
                background: #edf2f7;
                padding: 8px;
                border-radius: 4px;
                margin-top: 10px;
                font-family: monospace;
            }

            .mistakes-section {
                margin-top: 20px;
                padding: 15px;
                background: #fed7d7;
                border-radius: 8px;
                border-left: 4px solid #f56565;
            }

            .mistakes-section h4 {
                color: #742a2a;
                margin-bottom: 15px;
            }

            .mistake-item {
                margin-bottom: 15px;
                padding: 10px;
                background: white;
                border-radius: 6px;
            }

            .mistake-wrong {
                color: #c53030;
                font-weight: bold;
                margin-bottom: 5px;
            }

            .mistake-correct {
                color: #38a169;
                font-weight: bold;
                margin-bottom: 5px;
            }

            .mistake-explanation {
                color: #4a5568;
                font-size: 14px;
            }

            .summary-section {
                background: #f7fafc;
                padding: 20px;
                border-radius: 10px;
                border-left: 4px solid #667eea;
            }

            .summary-section h4 {
                color: #2d3748;
                margin-bottom: 15px;
            }

            .summary-grid {
                display: grid;
                gap: 15px;
            }

            .summary-item {
                background: white;
                padding: 15px;
                border-radius: 8px;
                border-left: 4px solid #48bb78;
            }

            .practice-question {
                background: white;
                border-radius: 15px;
                padding: 25px;
                margin-bottom: 20px;
                box-shadow: 0 8px 32px rgba(102, 126, 234, 0.1);
            }

            .question-text {
                font-size: 20px;
                color: #2d3748;
                margin-bottom: 20px;
                line-height: 1.6;
            }

            .options-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 15px;
                margin-bottom: 20px;
            }

            .option-btn {
                background: white;
                border: 2px solid #e2e8f0;
                border-radius: 12px;
                padding: 15px;
                font-size: 16px;
                cursor: pointer;
                transition: all 0.3s ease;
                text-align: center;
            }

            .option-btn:hover:not(:disabled) {
                border-color: #667eea;
                background: #f7fafc;
            }

            .option-btn.correct {
                border-color: #48bb78;
                background: linear-gradient(135deg, #f0fff4, #c6f6d5);
                color: #22543d;
            }

            .option-btn.incorrect {
                border-color: #f56565;
                background: linear-gradient(135deg, #fed7d7, #feb2b2);
                color: #742a2a;
            }

            .option-btn:disabled {
                cursor: not-allowed;
            }

            .feedback {
                background: #f7fafc;
                border-radius: 10px;
                padding: 15px;
                margin-top: 15px;
                border-left: 4px solid #667eea;
                display: none;
            }

            .feedback.show {
                display: block;
                animation: slideIn 0.3s ease;
            }

            .exercise-progress {
                text-align: center;
                margin-top: 15px;
                font-size: 14px;
                color: #718096;
            }

            .phase-complete {
                text-align: center;
                padding: 40px;
                background: linear-gradient(135deg, #f0fff4, #c6f6d5);
                border-radius: 15px;
                margin: 20px 0;
            }

            .complete-icon {
                font-size: 48px;
                margin-bottom: 20px;
            }

            .complete-title {
                font-size: 24px;
                font-weight: bold;
                color: #22543d;
                margin-bottom: 15px;
            }

            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(-10px); }
                to { opacity: 1; transform: translateY(0); }
            }

            @keyframes slideIn {
                from { opacity: 0; transform: translateX(-20px); }
                to { opacity: 1; transform: translateX(0); }
            }

            @media (max-width: 768px) {
                .grammar-discovery {
                    padding: 10px;
                }

                .grammar-hud {
                    flex-direction: column;
                    gap: 10px;
                    text-align: center;
                }

                .options-grid {
                    grid-template-columns: 1fr;
                }

                .discovery-controls {
                    flex-direction: column;
                    align-items: center;
                }

                .preview-stats {
                    grid-template-columns: repeat(2, 1fr);
                }
            }

            /* Victory Popup Styles */
            .victory-popup {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.8);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 10000;
                animation: fadeIn 0.3s ease-out;
            }

            .victory-content {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                border-radius: 20px;
                padding: 40px;
                text-align: center;
                color: white;
                max-width: 500px;
                width: 90%;
                box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
                animation: slideUp 0.4s ease-out;
            }

            .victory-header {
                margin-bottom: 30px;
            }

            .victory-icon {
                font-size: 4rem;
                margin-bottom: 15px;
                animation: bounce 0.6s ease-out;
            }

            .victory-title {
                font-size: 2rem;
                font-weight: bold;
                margin: 0 0 10px 0;
                text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
            }

            .new-best-badge {
                background: linear-gradient(45deg, #f093fb 0%, #f5576c 100%);
                color: white;
                padding: 8px 20px;
                border-radius: 25px;
                font-size: 0.9rem;
                font-weight: bold;
                display: inline-block;
                margin-top: 10px;
                animation: glow 1s ease-in-out infinite alternate;
            }

            .victory-scores {
                display: flex;
                justify-content: space-around;
                margin: 30px 0;
                gap: 20px;
            }

            .score-display {
                background: rgba(255, 255, 255, 0.1);
                border-radius: 15px;
                padding: 20px;
                flex: 1;
                backdrop-filter: blur(10px);
                border: 1px solid rgba(255, 255, 255, 0.2);
            }

            .score-label {
                font-size: 0.9rem;
                opacity: 0.9;
                margin-bottom: 8px;
                text-transform: uppercase;
                letter-spacing: 1px;
            }

            .score-value {
                font-size: 2rem;
                font-weight: bold;
                text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
            }

            .victory-stats {
                background: rgba(255, 255, 255, 0.1);
                border-radius: 15px;
                padding: 20px;
                margin: 30px 0;
                backdrop-filter: blur(10px);
                border: 1px solid rgba(255, 255, 255, 0.2);
            }

            .stat-row {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 8px 0;
                border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            }

            .stat-row:last-child {
                border-bottom: none;
            }

            .stat-name {
                font-size: 0.95rem;
                opacity: 0.9;
            }

            .stat-value {
                font-weight: bold;
                font-size: 1rem;
            }

            .victory-buttons {
                display: flex;
                flex-direction: column;
                gap: 12px;
                margin-top: 30px;
            }

            .victory-btn {
                padding: 15px 30px;
                border: none;
                border-radius: 25px;
                font-size: 1rem;
                font-weight: bold;
                cursor: pointer;
                transition: all 0.3s ease;
                text-transform: uppercase;
                letter-spacing: 1px;
            }

            .victory-btn.primary {
                background: linear-gradient(45deg, #4facfe 0%, #00f2fe 100%);
                color: white;
                box-shadow: 0 8px 25px rgba(79, 172, 254, 0.3);
            }

            .victory-btn.primary:hover {
                transform: translateY(-2px);
                box-shadow: 0 12px 35px rgba(79, 172, 254, 0.4);
            }

            .victory-btn.secondary {
                background: linear-gradient(45deg, #a8edea 0%, #fed6e3 100%);
                color: #333;
                box-shadow: 0 8px 25px rgba(168, 237, 234, 0.3);
            }

            .victory-btn.secondary:hover {
                transform: translateY(-2px);
                box-shadow: 0 12px 35px rgba(168, 237, 234, 0.4);
            }

            .victory-btn.tertiary {
                background: rgba(255, 255, 255, 0.2);
                color: white;
                border: 2px solid rgba(255, 255, 255, 0.3);
                backdrop-filter: blur(10px);
            }

            .victory-btn.tertiary:hover {
                background: rgba(255, 255, 255, 0.3);
                transform: translateY(-2px);
            }

            @keyframes fadeIn {
                from { opacity: 0; }
                to { opacity: 1; }
            }

            @keyframes slideUp {
                from {
                    opacity: 0;
                    transform: translateY(30px) scale(0.9);
                }
                to {
                    opacity: 1;
                    transform: translateY(0) scale(1);
                }
            }

            @keyframes bounce {
                0%, 20%, 50%, 80%, 100% {
                    transform: translateY(0);
                }
                40% {
                    transform: translateY(-10px);
                }
                60% {
                    transform: translateY(-5px);
                }
            }

            @keyframes glow {
                from {
                    box-shadow: 0 0 20px rgba(245, 87, 108, 0.5);
                }
                to {
                    box-shadow: 0 0 30px rgba(245, 87, 108, 0.8);
                }
            }

            @media (max-width: 768px) {
                .victory-content {
                    padding: 30px 20px;
                    width: 95%;
                }

                .victory-scores {
                    flex-direction: column;
                    gap: 15px;
                }

                .victory-icon {
                    font-size: 3rem;
                }

                .victory-title {
                    font-size: 1.5rem;
                }

                .victory-buttons {
                    gap: 10px;
                }

                .victory-btn {
                    padding: 12px 25px;
                    font-size: 0.9rem;
                }
            }
        `;

        document.head.appendChild(style);
    }

    _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-row">
                            <span class="stat-name">${key}</span>
                            <span class="stat-value">${value}</span>
                        </div>
                    `).join('')}
                </div>

                <div class="victory-buttons">
                    <button class="victory-btn primary" onclick="this.closest('.victory-popup').remove(); window.currentGrammarGame._restart();">🔄 Play Again</button>
                    <button class="victory-btn secondary" onclick="this.closest('.victory-popup').remove(); window.app.getCore().router.navigate('/games');">🎮 Different Game</button>
                    <button class="victory-btn tertiary" onclick="this.closest('.victory-popup').remove(); window.app.getCore().router.navigate('/');">🏠 Main Menu</button>
                </div>
            </div>
        `;

        document.body.appendChild(popup);

        // Emit completion event after showing popup
        this._eventBus.emit('game:end', {
            gameId: 'grammar-discovery',
            score: currentScore
        }, this.name);
    }

    _removeCSS() {
        const cssElement = document.getElementById('grammar-discovery-styles');
        if (cssElement) {
            cssElement.remove();
        }

        if (window.currentGrammarGame === this) {
            delete window.currentGrammarGame;
        }
    }
}

export default GrammarDiscovery;