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

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

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

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

        this._currentPhase = 'discovery';
        this._discoveredWords = [];
        this._practiceWords = [];
        this._currentWordIndex = 0;
        this._currentPracticeLevel = 0;
        this._practiceCorrect = 0;
        this._practiceTotal = 0;
        this._timer = null;
        this._timeLeft = 0;
        this._gameContainer = null;
        this._imageCache = new Map();

        this._practiceOptions = [];
        this._correctAnswer = null;
        this._currentQuestion = null;

        // Session progress tracking (5 discovery / 3 practice cycle)
        this._sessionDiscoveryCount = 0; // Words discovered in current cycle
        this._sessionPracticeCount = 0;  // Practice questions answered in current cycle
        this._totalDiscoveryCount = 0;   // Total discoveries in session
        this._totalPracticeCount = 0;    // Total practice questions in session
        this._cycleDiscoveryMax = 5;     // Discover 5 words
        this._cyclePracticeMax = 3;      // Then 3 practice questions
        this._totalWordsAvailable = 0;   // Total vocab words (e.g., 76)

        Object.seal(this);
    }

    static getMetadata() {
        return {
            id: 'word-discovery',
            name: 'Word Discovery',
            description: 'Discover and practice vocabulary with adaptive difficulty',
            version: '2.0.0',
            author: 'Class Generator',
            category: 'vocabulary',
            tags: ['vocabulary', 'learning', 'discovery', 'practice'],
            difficulty: {
                min: 1,
                max: 4,
                default: 2
            },
            estimatedDuration: 15,
            requiredContent: ['vocabulary']
        };
    }

    static getCompatibilityScore(content) {
        if (!content || (!Array.isArray(content.vocabulary) && !content.vocabulary)) {
            return 0;
        }

        // Handle both array and object vocabulary formats
        let vocabCount;
        if (Array.isArray(content.vocabulary)) {
            vocabCount = content.vocabulary.length;
        } else if (content.vocabulary && typeof content.vocabulary === 'object') {
            vocabCount = Object.keys(content.vocabulary).length;
        } else {
            return 0;
        }

        let score = 50;

        if (vocabCount >= 10) score += 20;
        if (vocabCount >= 20) score += 15;
        if (vocabCount >= 50) score += 10;

        // Check for bonus features depending on format
        let hasImages, hasTranslations;

        if (Array.isArray(content.vocabulary)) {
            hasImages = content.vocabulary.some(word => word.image);
            hasTranslations = content.vocabulary.some(word => word.translation);
        } else {
            // Object format (SBS style)
            const vocabEntries = Object.values(content.vocabulary);
            hasImages = vocabEntries.some(entry => entry.image);
            hasTranslations = vocabEntries.some(entry => entry.user_language || entry.translation);
        }

        if (hasImages) score += 5;
        if (hasTranslations) score += 5;

        return Math.min(score, 100);
    }

    async init() {
        this._validateNotDestroyed();

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

        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 || !content.vocabulary || Object.keys(content.vocabulary).length === 0) {
                throw new Error('No vocabulary content available');
            }

            // Load words from both vocabulary AND letters sections
            const wordsFromVocab = Object.entries(content.vocabulary || {}).map(([word, data]) => ({
                word: word,
                translation: typeof data === 'string' ? data :
                           data.user_language || data.translation || 'unknown',
                pronunciation: data.pronunciation,
                type: data.type || 'general',
                image: data.image,
                definition: data.definition,
                example: data.example
            }));

            // Load words from letters section (phonics)
            const wordsFromLetters = [];
            if (content.letters) {
                for (const [letterKey, letterWords] of Object.entries(content.letters)) {
                    if (Array.isArray(letterWords)) {
                        for (const wordEntry of letterWords) {
                            wordsFromLetters.push({
                                word: wordEntry.word,
                                translation: wordEntry.translation,
                                pronunciation: wordEntry.pronunciation,
                                type: wordEntry.type || 'phonics',
                                image: wordEntry.image,
                                definition: wordEntry.definition,
                                example: wordEntry.example,
                                letterGroup: letterKey
                            });
                        }
                    }
                }
            }

            // Combine both sources, prioritizing letters (phonics) first
            this._practiceWords = [...wordsFromLetters, ...wordsFromVocab];
            this._totalWordsAvailable = this._practiceWords.length;

            console.log('📚 Loaded words:', {
                fromLetters: wordsFromLetters.length,
                fromVocabulary: wordsFromVocab.length,
                total: this._totalWordsAvailable,
                wordsWithImages: this._practiceWords.filter(w => w.image).length
            });

            // Restore session or start fresh
            this._restoreSession();

            await this._preloadAssets();
            this._renderCurrentPhase();

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

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

        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 === 'word-discovery') {
            this._startGame();
        }
    }

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

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

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

            const content = window.contentLoader ? window.contentLoader.getContent(window.currentChapterId) : await this._content.getCurrentContent();
            if (!content || !content.vocabulary || content.vocabulary.length === 0) {
                throw new Error('No vocabulary content available');
            }

            this._practiceWords = [...content.vocabulary];
            this._discoveredWords = [];
            this._currentWordIndex = 0;
            this._currentPhase = 'discovery';

            await this._preloadAssets();
            this._renderDiscoveryPhase();

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

    _stopGame() {
        this._cleanup();
    }

    _cleanup() {
        if (this._timer) {
            clearInterval(this._timer);
            this._timer = null;
        }

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

    /**
     * Save current session state to sessionStorage
     * @private
     */
    _saveSession() {
        const sessionData = {
            currentPhase: this._currentPhase,
            sessionDiscoveryCount: this._sessionDiscoveryCount,
            sessionPracticeCount: this._sessionPracticeCount,
            totalDiscoveryCount: this._totalDiscoveryCount,
            totalPracticeCount: this._totalPracticeCount,
            currentWordIndex: this._currentWordIndex,
            discoveredWords: this._discoveredWords.map(w => w.word),
            practiceCorrect: this._practiceCorrect,
            practiceTotal: this._practiceTotal
        };

        sessionStorage.setItem('wordDiscovery_session', JSON.stringify(sessionData));
    }

    /**
     * Restore session state from sessionStorage or start fresh
     * @private
     */
    _restoreSession() {
        const savedData = sessionStorage.getItem('wordDiscovery_session');

        if (savedData) {
            try {
                const session = JSON.parse(savedData);
                this._currentPhase = session.currentPhase || 'discovery';
                this._sessionDiscoveryCount = session.sessionDiscoveryCount || 0;
                this._sessionPracticeCount = session.sessionPracticeCount || 0;
                this._totalDiscoveryCount = session.totalDiscoveryCount || 0;
                this._totalPracticeCount = session.totalPracticeCount || 0;
                this._currentWordIndex = session.currentWordIndex || 0;
                this._practiceCorrect = session.practiceCorrect || 0;
                this._practiceTotal = session.practiceTotal || 0;

                // Restore discovered words
                if (session.discoveredWords && Array.isArray(session.discoveredWords)) {
                    this._discoveredWords = this._practiceWords.filter(w =>
                        session.discoveredWords.includes(w.word)
                    );
                }

                console.log('📖 Session restored:', session);
            } catch (error) {
                console.warn('Failed to restore session:', error);
                this._startFreshSession();
            }
        } else {
            this._startFreshSession();
        }
    }

    /**
     * Start a fresh session (reset all counters)
     * @private
     */
    _startFreshSession() {
        this._discoveredWords = [];
        this._currentWordIndex = 0;
        this._currentPhase = 'discovery';
        this._sessionDiscoveryCount = 0;
        this._sessionPracticeCount = 0;
        this._totalDiscoveryCount = 0;
        this._totalPracticeCount = 0;
        this._practiceCorrect = 0;
        this._practiceTotal = 0;
    }

    /**
     * Calculate total progress including both discovery and practice
     * Total = totalWordsAvailable + (totalWordsAvailable * 3/5)
     * @private
     */
    _calculateTotalProgress() {
        const maxDiscovery = this._totalWordsAvailable;
        const maxPractice = Math.floor(this._totalWordsAvailable * 3 / 5);
        const totalMax = maxDiscovery + maxPractice;
        const currentProgress = this._totalDiscoveryCount + this._totalPracticeCount;

        return {
            current: currentProgress,
            max: totalMax,
            percentage: totalMax > 0 ? (currentProgress / totalMax) * 100 : 0
        };
    }

    /**
     * Determine if we should switch phases based on cycle counts
     * @private
     */
    _shouldSwitchPhase() {
        if (this._currentPhase === 'discovery') {
            return this._sessionDiscoveryCount >= this._cycleDiscoveryMax;
        } else {
            return this._sessionPracticeCount >= this._cyclePracticeMax;
        }
    }

    /**
     * Render the appropriate phase based on current state
     * @private
     */
    _renderCurrentPhase() {
        // Check if we've completed everything
        const maxDiscovery = this._totalWordsAvailable;
        const maxPractice = Math.floor(this._totalWordsAvailable * 3 / 5);

        if (this._totalDiscoveryCount >= maxDiscovery && this._totalPracticeCount >= maxPractice) {
            this._showCompletionScreen();
            return;
        }

        if (this._currentPhase === 'discovery') {
            this._renderDiscoveryPhase();
        } else {
            this._renderPracticePhase();
        }
    }

    async _preloadAssets() {
        for (const word of this._practiceWords) {
            if (word.image) {
                try {
                    const img = new Image();
                    img.src = word.image;
                    await new Promise((resolve, reject) => {
                        img.onload = resolve;
                        img.onerror = reject;
                        setTimeout(reject, 5000);
                    });
                    this._imageCache.set(word.word, word.image);
                } catch (error) {
                    console.warn(`Failed to preload image for ${word.word}:`, error);
                }
            }
        }
    }

    _renderDiscoveryPhase() {
        // Check if we've discovered all words
        if (this._totalDiscoveryCount >= this._totalWordsAvailable) {
            this._currentPhase = 'practice';
            this._renderPracticePhase();
            return;
        }

        // Check if we need to switch to practice (5 discoveries done in this cycle)
        if (this._shouldSwitchPhase()) {
            this._currentPhase = 'practice';
            this._sessionPracticeCount = 0; // Reset practice counter for new cycle
            this._saveSession();
            this._renderPracticePhase();
            return;
        }

        const word = this._practiceWords[this._currentWordIndex];
        if (!word) {
            // No more words, finish discovery
            this._currentPhase = 'practice';
            this._renderPracticePhase();
            return;
        }

        const progress = this._calculateTotalProgress();

        this._gameContainer.innerHTML = `
            <div class="word-discovery-container">
                <div class="discovery-header">
                    <h2>Word Discovery (${this._sessionDiscoveryCount}/${this._cycleDiscoveryMax} in cycle)</h2>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: ${progress.percentage}%"></div>
                    </div>
                    <p>Total Progress: ${progress.current} / ${progress.max}</p>
                    <p class="cycle-info">After ${this._cycleDiscoveryMax} discoveries, ${this._cyclePracticeMax} practice questions</p>
                </div>

                <div class="word-card discovery-card">
                    ${word.image ? `<div class="word-image">
                        <img src="${word.image}" alt="${word.word}" onerror="this.style.display='none'">
                    </div>` : ''}

                    <div class="word-content">
                        <h3 class="word-text">
                            ${word.word}
                            ${word.pronunciation ? `<span class="word-pronunciation">[${word.pronunciation}]</span>` : ''}
                        </h3>
                        ${word.translation ? `<p class="word-translation">${word.translation}</p>` : ''}
                        ${word.definition ? `<p class="word-definition">${word.definition}</p>` : ''}
                        ${word.example ? `<p class="word-example">"${word.example}"</p>` : ''}
                    </div>

                    <div class="word-controls">
                        <button class="audio-btn" onclick="window.wordDiscovery._playWordSound('${word.word}')">
                            🔊 Listen
                        </button>
                        <button class="next-btn" onclick="window.wordDiscovery._nextWord()">
                            Next Word
                        </button>
                    </div>
                </div>
            </div>
        `;

        window.wordDiscovery = this;

        // Auto-play TTS when word is revealed (with slight delay for better UX)
        setTimeout(() => {
            this._playWordSound(word.word);
        }, 300);
    }

    _nextWord() {
        const currentWord = this._practiceWords[this._currentWordIndex];
        if (currentWord && !this._discoveredWords.find(w => w.word === currentWord.word)) {
            this._discoveredWords.push(currentWord);
            this._sessionDiscoveryCount++;
            this._totalDiscoveryCount++;
        }

        this._currentWordIndex++;
        this._saveSession();
        this._renderCurrentPhase();
    }

    async _playWordSound(text) {
        const targetLanguage = this._content?.language || 'en-US';
        await ttsService.speak(text, targetLanguage, { rate: 0.9, volume: 1.0 });
    }

    _renderPracticePhase() {
        // Check if we've completed all practice (max = totalWords * 3/5)
        const maxPractice = Math.floor(this._totalWordsAvailable * 3 / 5);
        if (this._totalPracticeCount >= maxPractice) {
            // All practice done, switch back to discovery or finish
            if (this._totalDiscoveryCount < this._totalWordsAvailable) {
                this._currentPhase = 'discovery';
                this._sessionDiscoveryCount = 0;
                this._saveSession();
                this._renderDiscoveryPhase();
            } else {
                this._showCompletionScreen();
            }
            return;
        }

        // Check if we need to switch back to discovery (3 practice done in this cycle)
        if (this._shouldSwitchPhase()) {
            this._currentPhase = 'discovery';
            this._sessionDiscoveryCount = 0; // Reset discovery counter for new cycle
            this._saveSession();
            this._renderDiscoveryPhase();
            return;
        }

        if (this._discoveredWords.length === 0) {
            // No words to practice yet
            this._currentPhase = 'discovery';
            this._renderDiscoveryPhase();
            return;
        }

        const progress = this._calculateTotalProgress();
        const config = { options: 4, type: 'translation' }; // Simple translation questions

        this._gameContainer.innerHTML = `
            <div class="word-discovery-container">
                <div class="practice-header">
                    <h2>Practice Phase (${this._sessionPracticeCount}/${this._cyclePracticeMax} in cycle)</h2>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: ${progress.percentage}%"></div>
                    </div>
                    <p>Total Progress: ${progress.current} / ${progress.max}</p>
                    <div class="practice-stats">
                        <span>Correct: ${this._practiceCorrect}</span>
                        <span>Total: ${this._practiceTotal}</span>
                        <span>Accuracy: ${this._practiceTotal > 0 ? Math.round((this._practiceCorrect / this._practiceTotal) * 100) : 0}%</span>
                    </div>
                </div>

                <div class="practice-question" id="practice-question">
                    Loading question...
                </div>
            </div>
        `;

        this._generateQuestion(config);
    }

    _generateQuestion(config = null) {
        if (!config) {
            const levelConfig = {
                0: { options: 4, type: 'translation' },
                1: { options: 3, type: 'mixed' },
                2: { options: 4, type: 'definition' }
            };
            config = levelConfig[this._currentPracticeLevel];
        }

        const questionContainer = document.getElementById('practice-question');
        if (!questionContainer) return;

        const availableWords = this._discoveredWords.filter(w => w);
        if (availableWords.length === 0) return;

        const correctWord = availableWords[Math.floor(Math.random() * availableWords.length)];
        this._correctAnswer = correctWord;

        const wrongWords = availableWords
            .filter(w => w.word !== correctWord.word)
            .sort(() => Math.random() - 0.5)
            .slice(0, config.options - 1);

        this._practiceOptions = [correctWord, ...wrongWords]
            .sort(() => Math.random() - 0.5);

        this._renderQuestion(config.type, correctWord);
    }

    _renderQuestion(type, correctWord) {
        const questionContainer = document.getElementById('practice-question');
        let questionHTML = '';

        switch (type) {
            case 'translation':
                questionHTML = this._renderTranslationQuestion(correctWord);
                break;
            case 'definition':
                questionHTML = this._renderDefinitionQuestion(correctWord);
                break;
            case 'mixed':
                const types = ['translation', 'definition'];
                const randomType = types[Math.floor(Math.random() * types.length)];
                questionHTML = this._renderQuestion(randomType, correctWord);
                return;
        }

        questionContainer.innerHTML = questionHTML;

        // Auto-play TTS for the target language word in practice mode
        setTimeout(() => {
            this._playWordSound(correctWord.word);
        }, 300);
    }

    _renderTranslationQuestion(correctWord) {
        return `
            <div class="question-content">
                <h3>What does this word mean?</h3>
                <div class="question-word">
                    <div class="word-with-pronunciation">
                        <span>${correctWord.word}</span>
                        ${correctWord.pronunciation ? `<span class="question-pronunciation">[${correctWord.pronunciation}]</span>` : ''}
                    </div>
                    <button class="audio-btn-small" onclick="window.wordDiscovery._playWordSound('${correctWord.word}')">🔊</button>
                </div>
                <div class="options-grid">
                    ${this._practiceOptions.map(option => `
                        <button class="option-btn" onclick="window.wordDiscovery._selectAnswer('${option.word}')">
                            ${option.translation || option.definition || option.word}
                        </button>
                    `).join('')}
                </div>
            </div>
        `;
    }

    _renderDefinitionQuestion(correctWord) {
        return `
            <div class="question-content">
                <h3>Which word matches this definition?</h3>
                <div class="question-definition">
                    ${correctWord.definition || correctWord.translation}
                </div>
                <div class="options-grid">
                    ${this._practiceOptions.map(option => `
                        <button class="option-btn" onclick="window.wordDiscovery._selectAnswer('${option.word}')">
                            <div class="option-word-with-pronunciation">
                                <span>${option.word}</span>
                                ${option.pronunciation ? `<span class="option-pronunciation">[${option.pronunciation}]</span>` : ''}
                            </div>
                        </button>
                    `).join('')}
                </div>
            </div>
        `;
    }

    _selectAnswer(selectedWord) {
        this._practiceTotal++;
        this._sessionPracticeCount++;
        this._totalPracticeCount++;

        const isCorrect = selectedWord === this._correctAnswer.word;

        if (isCorrect) {
            this._practiceCorrect++;
            // Play TTS for correct answer
            this._playWordSound(this._correctAnswer.word);
        }

        this._showResult(isCorrect, isCorrect ? 'Correct!' : `Wrong! The answer was: ${this._correctAnswer.word}`);

        this._saveSession();

        setTimeout(() => {
            this._renderCurrentPhase();
        }, 1500);
    }

    _showResult(isCorrect, message) {
        if (this._timer) {
            clearInterval(this._timer);
            this._timer = null;
        }

        const questionContainer = document.getElementById('practice-question');
        if (!questionContainer) return;

        questionContainer.innerHTML = `
            <div class="result-display ${isCorrect ? 'correct' : 'incorrect'}">
                <h3>${message}</h3>
                ${!isCorrect && this._correctAnswer.translation ? `<p>Translation: ${this._correctAnswer.translation}</p>` : ''}
            </div>
        `;

        this._updateStats();
    }

    _updateStats() {
        const statsElements = document.querySelectorAll('.practice-stats span');
        if (statsElements.length >= 3) {
            statsElements[0].textContent = `Correct: ${this._practiceCorrect}`;
            statsElements[1].textContent = `Total: ${this._practiceTotal}`;
            statsElements[2].textContent = `Accuracy: ${this._practiceTotal > 0 ? Math.round((this._practiceCorrect / this._practiceTotal) * 100) : 0}%`;
        }
    }

    _showCompletionScreen() {
        const progress = this._calculateTotalProgress();
        const accuracy = this._practiceTotal > 0 ? Math.round((this._practiceCorrect / this._practiceTotal) * 100) : 0;

        this._gameContainer.innerHTML = `
            <div class="word-discovery-container">
                <div class="completion-screen">
                    <h2>🎉 Congratulations!</h2>
                    <p>You've completed all vocabulary!</p>
                    <div class="completion-stats">
                        <div class="stat-item">
                            <span class="stat-label">Words Discovered:</span>
                            <span class="stat-value">${this._totalDiscoveryCount}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">Practice Questions:</span>
                            <span class="stat-value">${this._totalPracticeCount}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">Overall Accuracy:</span>
                            <span class="stat-value">${accuracy}%</span>
                        </div>
                    </div>
                    <div class="completion-controls">
                        <button class="restart-btn" onclick="window.wordDiscovery._restartSession()">
                            Start Over
                        </button>
                    </div>
                </div>
            </div>
        `;
    }

    _restartSession() {
        sessionStorage.removeItem('wordDiscovery_session');
        this._startFreshSession();
        this._saveSession();
        this._renderCurrentPhase();
    }

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

        const style = document.createElement('style');
        style.id = cssId;
        style.textContent = `
            .word-discovery-container {
                max-width: 800px;
                margin: 0 auto;
                padding: 20px;
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            }

            .discovery-header, .practice-header {
                text-align: center;
                margin-bottom: 30px;
            }

            .discovery-header h2, .practice-header h2 {
                color: #2c3e50;
                margin-bottom: 15px;
            }

            .cycle-info {
                font-size: 0.9em;
                color: #7f8c8d;
                font-style: italic;
                margin-top: 5px;
            }

            .progress-bar {
                width: 100%;
                height: 8px;
                background-color: #ecf0f1;
                border-radius: 4px;
                overflow: hidden;
                margin: 10px 0;
            }

            .progress-fill {
                height: 100%;
                background: linear-gradient(90deg, #3498db, #2980b9);
                transition: width 0.3s ease;
            }

            .word-card {
                background: white;
                border-radius: 12px;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                padding: 30px;
                margin: 20px 0;
                text-align: center;
                border: 2px solid #e74c3c;
            }

            .word-image img {
                max-width: 200px;
                max-height: 200px;
                border-radius: 8px;
                margin-bottom: 20px;
            }

            .word-text {
                font-size: 2.5em;
                color: #2c3e50;
                margin: 15px 0;
                font-weight: bold;
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 10px;
            }

            .word-pronunciation {
                font-size: 0.5em;
                color: #7f8c8d;
                font-style: italic;
                font-weight: normal;
            }

            .word-translation {
                font-size: 1.4em;
                color: #e74c3c;
                margin: 10px 0;
                font-weight: 600;
            }

            .word-definition {
                font-size: 1.1em;
                color: #7f8c8d;
                margin: 10px 0;
                font-style: italic;
            }

            .word-example {
                font-size: 1em;
                color: #95a5a6;
                margin: 15px 0;
                padding: 10px;
                background-color: #f8f9fa;
                border-radius: 6px;
            }

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

            .audio-btn, .next-btn, .practice-btn, .back-btn, .next-level-btn {
                padding: 12px 24px;
                border: none;
                border-radius: 8px;
                font-size: 1.1em;
                cursor: pointer;
                transition: all 0.3s ease;
                font-weight: 600;
            }

            .audio-btn {
                background: linear-gradient(135deg, #3498db, #2980b9);
                color: white;
            }

            .audio-btn:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(52, 152, 219, 0.4);
            }

            .next-btn, .next-level-btn {
                background: linear-gradient(135deg, #27ae60, #229954);
                color: white;
            }

            .next-btn:hover, .next-level-btn:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(39, 174, 96, 0.4);
            }

            .practice-btn {
                background: linear-gradient(135deg, #e74c3c, #c0392b);
                color: white;
                font-size: 1.3em;
                padding: 15px 30px;
            }

            .practice-btn:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(231, 76, 60, 0.4);
            }

            .back-btn {
                background: linear-gradient(135deg, #95a5a6, #7f8c8d);
                color: white;
            }

            .back-btn:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(149, 165, 166, 0.4);
            }

            .practice-stats {
                display: flex;
                gap: 20px;
                justify-content: center;
                margin: 15px 0;
                font-size: 1.1em;
                font-weight: 600;
            }

            .practice-stats span {
                color: #2c3e50;
            }

            .question-content {
                background: white;
                border-radius: 12px;
                padding: 30px;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                margin: 20px 0;
            }

            .question-content h3 {
                color: #2c3e50;
                margin-bottom: 20px;
                text-align: center;
            }

            .question-word {
                font-size: 2em;
                font-weight: bold;
                color: #e74c3c;
                text-align: center;
                margin: 20px 0;
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 10px;
                flex-wrap: wrap;
            }

            .word-with-pronunciation {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 5px;
            }

            .question-pronunciation {
                font-size: 0.5em;
                color: #7f8c8d;
                font-style: italic;
                font-weight: normal;
            }

            .option-word-with-pronunciation {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 5px;
            }

            .option-pronunciation {
                font-size: 0.8em;
                color: #7f8c8d;
                font-style: italic;
                font-weight: normal;
            }

            .question-definition, .question-context {
                font-size: 1.3em;
                color: #2c3e50;
                text-align: center;
                margin: 20px 0;
                padding: 15px;
                background-color: #f8f9fa;
                border-radius: 8px;
                border-left: 4px solid #3498db;
            }

            .audio-btn-small {
                padding: 8px 12px;
                background: linear-gradient(135deg, #3498db, #2980b9);
                color: white;
                border: none;
                border-radius: 6px;
                cursor: pointer;
                font-size: 0.9em;
            }

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

            .option-btn {
                padding: 15px 20px;
                background: linear-gradient(135deg, #ecf0f1, #bdc3c7);
                border: 2px solid #95a5a6;
                border-radius: 8px;
                cursor: pointer;
                font-size: 1.1em;
                font-weight: 600;
                color: #2c3e50;
                transition: all 0.3s ease;
            }

            .option-btn:hover {
                background: linear-gradient(135deg, #3498db, #2980b9);
                color: white;
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
            }

            .result-display {
                text-align: center;
                padding: 30px;
                border-radius: 12px;
                margin: 20px 0;
            }

            .result-display.correct {
                background: linear-gradient(135deg, #2ecc71, #27ae60);
                color: white;
            }

            .result-display.incorrect {
                background: linear-gradient(135deg, #e74c3c, #c0392b);
                color: white;
            }

            .result-display h3 {
                margin: 0 0 10px 0;
                font-size: 1.5em;
            }

            .result-display p {
                margin: 10px 0 0 0;
                font-size: 1.1em;
                opacity: 0.9;
            }

            .completion-screen {
                text-align: center;
                padding: 40px 20px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                border-radius: 16px;
                color: white;
                box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
            }

            .completion-screen h2 {
                font-size: 2.5em;
                margin-bottom: 20px;
                text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
            }

            .completion-stats {
                background: rgba(255, 255, 255, 0.1);
                border-radius: 12px;
                padding: 30px;
                margin: 30px 0;
                backdrop-filter: blur(10px);
            }

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

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

            .stat-label {
                font-size: 1.2em;
                font-weight: 500;
            }

            .stat-value {
                font-size: 1.5em;
                font-weight: bold;
                color: #ffd700;
            }

            .restart-btn {
                padding: 15px 40px;
                background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
                color: white;
                border: none;
                border-radius: 50px;
                font-size: 1.2em;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s ease;
                margin-top: 20px;
                box-shadow: 0 5px 15px rgba(245, 87, 108, 0.4);
            }

            .restart-btn:hover {
                transform: translateY(-3px);
                box-shadow: 0 8px 20px rgba(245, 87, 108, 0.6);
            }

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

                .word-text {
                    font-size: 2em;
                }

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

                .practice-stats {
                    flex-direction: column;
                    gap: 10px;
                }

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

                .question-word {
                    font-size: 1.5em;
                }
            }
        `;

        document.head.appendChild(style);
    }

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

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

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

export default WordDiscovery;