import Module from '../core/Module.js';

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

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

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

        this._vocabulary = [];
        this._currentMode = null;
        this._currentIndex = 0;
        this._score = 0;
        this._correctAnswers = 0;
        this._isRunning = false;
        this._studyState = 'menu';
        this._gameContainer = null;

        Object.seal(this);
    }

    static getMetadata() {
        return {
            id: 'chinese-study',
            name: 'Chinese Study',
            description: 'Comprehensive Chinese language learning with flashcards, recognition, and pinyin practice',
            version: '2.0.0',
            author: 'Class Generator',
            category: 'language',
            tags: ['chinese', 'vocabulary', 'pinyin', 'characters', 'study'],
            difficulty: {
                min: 1,
                max: 4,
                default: 2
            },
            estimatedDuration: 15,
            requiredContent: ['vocabulary']
        };
    }

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

        // Only compatible with Chinese content
        if (content.language !== 'zh-CN') {
            return 0;
        }

        let score = 30;

        if (typeof content.vocabulary === 'object') {
            const vocabCount = Object.keys(content.vocabulary).length;
            if (vocabCount >= 5) score += 20;
            if (vocabCount >= 15) score += 15;
            if (vocabCount >= 30) score += 10;

            const hasPinyin = Object.values(content.vocabulary).some(word =>
                typeof word === 'object' && word.pronunciation
            );
            const hasHSK = Object.values(content.vocabulary).some(word =>
                typeof word === 'object' && word.hskLevel
            );
            const hasChineseChars = Object.keys(content.vocabulary).some(key =>
                /[\u4e00-\u9fff]/.test(key)
            );

            if (hasPinyin) score += 10;
            if (hasHSK) score += 10;
            if (hasChineseChars) score += 5;
        }

        return Math.min(score, 100);
    }

    async init() {
        this._validateNotDestroyed();

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

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

    _handleNavigationChange(event) {
        this._validateInitialized();
        if (event.from === '/games/chinese-study') {
            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');
            }

            this._vocabulary = this._extractVocabulary(content);

            if (this._vocabulary.length === 0) {
                throw new Error('No Chinese vocabulary found for Chinese Study Game');
            }

            this._createGameInterface();

        } catch (error) {
            console.error('Error starting Chinese Study:', error);
            this._showInitError(error.message);
        }
    }

    _stopGame() {
        this._cleanup();
    }

    _cleanup() {
        this._isRunning = false;
        if (this._gameContainer) {
            this._gameContainer.innerHTML = '';
        }
        if (window.chineseStudyInstance === this) {
            delete window.chineseStudyInstance;
        }
    }

    _showInitError(message) {
        this._gameContainer.innerHTML = `
            <div class="game-error">
                <h3>❌ Loading Error</h3>
                <p>${message}</p>
                <p>The game needs vocabulary with Chinese characters, translations, and optional pinyin.</p>
                <button onclick="window.app.getCore().router.navigate('/games')" class="back-btn">← Back to Games</button>
            </div>
        `;
    }

    _extractVocabulary(content) {
        let vocabulary = [];

        if (content.vocabulary && typeof content.vocabulary === 'object' && !Array.isArray(content.vocabulary)) {
            vocabulary = Object.entries(content.vocabulary).map(([word, data]) => {
                if (typeof data === 'object' && data.translation) {
                    return {
                        chinese: word,
                        translation: data.translation.split('；')[0],
                        fullTranslation: data.translation,
                        pronunciation: data.pronunciation || '',
                        type: data.type || 'general',
                        hskLevel: data.hskLevel || null,
                        examples: data.examples || [],
                        strokeOrder: data.strokeOrder || []
                    };
                } else if (typeof data === 'string') {
                    return {
                        chinese: word,
                        translation: data.split('；')[0],
                        fullTranslation: data,
                        pronunciation: '',
                        type: 'general',
                        hskLevel: null,
                        examples: [],
                        strokeOrder: []
                    };
                }
                return null;
            }).filter(Boolean);
        }

        vocabulary = vocabulary.sort(() => Math.random() - 0.5);
        console.log(`Chinese Study: ${vocabulary.length} vocabulary items loaded`);
        return vocabulary;
    }

    _createGameInterface() {
        if (this._studyState === 'menu') {
            this._createModeSelection();
        } else if (this._studyState === 'playing') {
            this._createStudyMode();
        }
    }

    _createModeSelection() {
        const hasPinyin = this._vocabulary.some(item => item.pronunciation);
        const hasHSK = this._vocabulary.some(item => item.hskLevel);

        this._gameContainer.innerHTML = `
            <div class="chinese-study-container">
                <div class="game-header">
                    <h2>🇨🇳 Chinese Study Mode</h2>
                    <div class="game-stats">
                        <div class="score-display">Score: <span id="score">${this._score}</span></div>
                        <div class="vocab-count">${this._vocabulary.length} characters available</div>
                        ${hasHSK ? '<div class="hsk-indicator">📊 HSK levels included</div>' : ''}
                        ${hasPinyin ? '<div class="pinyin-indicator">🗣️ Pinyin available</div>' : ''}
                    </div>
                </div>

                <div class="study-modes">
                    <div class="mode-card" data-mode="flashcards">
                        <div class="mode-icon">📚</div>
                        <h3>Flashcards</h3>
                        <p>Study characters with flip cards</p>
                        <button class="mode-btn">Start Learning</button>
                    </div>

                    <div class="mode-card" data-mode="recognition" ${!hasPinyin ? 'data-disabled="true"' : ''}>
                        <div class="mode-icon">🧠</div>
                        <h3>Character Recognition</h3>
                        <p>Match characters to their meanings</p>
                        ${!hasPinyin ? '<div class="mode-requirement">Requires pinyin data</div>' : ''}
                        <button class="mode-btn" ${!hasPinyin ? 'disabled' : ''}>Start Learning</button>
                    </div>

                    <div class="mode-card" data-mode="pinyin" ${!hasPinyin ? 'data-disabled="true"' : ''}>
                        <div class="mode-icon">🗣️</div>
                        <h3>Pinyin Practice</h3>
                        <p>Learn pronunciation with pinyin</p>
                        ${!hasPinyin ? '<div class="mode-requirement">Requires pinyin data</div>' : ''}
                        <button class="mode-btn" ${!hasPinyin ? 'disabled' : ''}>Start Learning</button>
                    </div>

                    <div class="mode-card" data-mode="hsk" ${!hasHSK ? 'data-disabled="true"' : ''}>
                        <div class="mode-icon">📊</div>
                        <h3>HSK Review</h3>
                        <p>Study by HSK difficulty levels</p>
                        ${!hasHSK ? '<div class="mode-requirement">Requires HSK level data</div>' : ''}
                        <button class="mode-btn" ${!hasHSK ? 'disabled' : ''}>Start Learning</button>
                    </div>
                </div>

                <div class="vocabulary-preview">
                    <h4>📖 Vocabulary Preview</h4>
                    <div class="preview-items">
                        ${this._vocabulary.slice(0, 6).map(item => `
                            <div class="preview-item">
                                <span class="chinese">${item.chinese}</span>
                                <span class="translation">${item.translation}</span>
                                ${item.pronunciation ? `<span class="pinyin">${item.pronunciation}</span>` : ''}
                                ${item.hskLevel ? `<span class="hsk-badge">${item.hskLevel}</span>` : ''}
                            </div>
                        `).join('')}
                        ${this._vocabulary.length > 6 ? `<div class="more-items">... and ${this._vocabulary.length - 6} more</div>` : ''}
                    </div>
                </div>

                <div class="game-controls">
                    <button onclick="window.app.getCore().router.navigate('/games')" class="back-btn">← Back to Games</button>
                </div>
            </div>
        `;

        this._setupModeListeners();
    }

    _setupModeListeners() {
        const modeCards = this._gameContainer.querySelectorAll('.mode-card:not([data-disabled])');
        modeCards.forEach(card => {
            card.addEventListener('click', (e) => {
                const mode = card.dataset.mode;
                this._startMode(mode);
            });
        });
    }

    _startMode(mode) {
        this._currentMode = mode;
        this._studyState = 'playing';
        this._currentIndex = 0;
        this._correctAnswers = 0;
        this._createGameInterface();
    }

    _createStudyMode() {
        const currentItem = this._vocabulary[this._currentIndex];
        const progress = Math.round(((this._currentIndex + 1) / this._vocabulary.length) * 100);

        let modeContent = '';
        switch (this._currentMode) {
            case 'flashcards':
                modeContent = this._createFlashcardMode(currentItem);
                break;
            case 'recognition':
                modeContent = this._createRecognitionMode(currentItem);
                break;
            case 'pinyin':
                modeContent = this._createPinyinMode(currentItem);
                break;
            case 'hsk':
                modeContent = this._createHSKMode(currentItem);
                break;
        }

        this._gameContainer.innerHTML = `
            <div class="chinese-study-container study-mode-active">
                <div class="study-header">
                    <div class="mode-title">
                        <h2>${this._getModeTitle()}</h2>
                        <button class="back-to-menu-btn">← Menu</button>
                    </div>
                    <div class="progress-section">
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: ${progress}%"></div>
                        </div>
                        <div class="progress-text">${this._currentIndex + 1} / ${this._vocabulary.length}</div>
                        <div class="score-display">Score: <span id="score">${this._score}</span></div>
                    </div>
                </div>

                <div class="study-content">
                    ${modeContent}
                </div>

                <div class="study-controls">
                    <button class="prev-btn" ${this._currentIndex === 0 ? 'disabled' : ''}>
                        ← Previous
                    </button>
                    <button class="next-btn" ${this._currentIndex === this._vocabulary.length - 1 ? 'disabled' : ''}>
                        Next →
                    </button>
                </div>
            </div>
        `;

        this._setupStudyListeners();
    }

    _setupStudyListeners() {
        window.chineseStudyInstance = this;

        this._gameContainer.querySelector('.back-to-menu-btn').onclick = () => this._backToMenu();
        this._gameContainer.querySelector('.prev-btn').onclick = () => this._previousItem();
        this._gameContainer.querySelector('.next-btn').onclick = () => this._nextItem();

        this._setupModeSpecificListeners();
    }

    _setupModeSpecificListeners() {
        if (this._currentMode === 'flashcards') {
            const flashcard = this._gameContainer.querySelector('.flashcard');
            if (flashcard) {
                flashcard.addEventListener('click', () => this._flipCard());
            }
        } else if (this._currentMode === 'recognition') {
            const options = this._gameContainer.querySelectorAll('.option-btn');
            options.forEach(option => {
                option.addEventListener('click', (e) => this._selectOption(e.target.dataset.translation));
            });
        } else if (this._currentMode === 'pinyin') {
            const pinyinInput = this._gameContainer.querySelector('.pinyin-input');
            if (pinyinInput) {
                pinyinInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') this._checkPinyinAnswer();
                });
            }
            const checkBtn = this._gameContainer.querySelector('.check-pinyin-btn');
            if (checkBtn) {
                checkBtn.onclick = () => this._checkPinyinAnswer();
            }
        }
    }

    _getModeTitle() {
        const titles = {
            flashcards: '📚 Flashcards',
            recognition: '🧠 Character Recognition',
            pinyin: '🗣️ Pinyin Practice',
            hsk: '📊 HSK Review'
        };
        return titles[this._currentMode] || 'Chinese Study';
    }

    _createFlashcardMode(item) {
        return `
            <div class="flashcard-container">
                <div class="flashcard" data-flipped="false">
                    <div class="flashcard-front">
                        <div class="chinese-character">${item.chinese}</div>
                        <div class="card-hint">Click to reveal translation</div>
                    </div>
                    <div class="flashcard-back">
                        <div class="translation">${item.translation}</div>
                        ${item.pronunciation ? `<div class="pronunciation">${item.pronunciation}</div>` : ''}
                        ${item.type ? `<div class="word-type">${item.type}</div>` : ''}
                        ${item.hskLevel ? `<div class="hsk-level">${item.hskLevel}</div>` : ''}
                    </div>
                </div>
                <div class="flashcard-actions">
                    <button class="know-btn" onclick="chineseStudyInstance._markAsKnown(true)">✅ I know this</button>
                    <button class="dont-know-btn" onclick="chineseStudyInstance._markAsKnown(false)">❌ Need practice</button>
                </div>
            </div>
        `;
    }

    _createRecognitionMode(item) {
        const wrongOptions = this._vocabulary
            .filter(v => v.chinese !== item.chinese)
            .sort(() => Math.random() - 0.5)
            .slice(0, 3)
            .map(v => v.translation);

        const allOptions = [...wrongOptions, item.translation].sort(() => Math.random() - 0.5);

        return `
            <div class="recognition-container">
                <div class="question-section">
                    <div class="chinese-character">${item.chinese}</div>
                    ${item.pronunciation ? `<div class="pronunciation-hint">${item.pronunciation}</div>` : ''}
                    <div class="question-text">What does this character mean?</div>
                </div>
                <div class="options-grid">
                    ${allOptions.map(option => `
                        <button class="option-btn" data-translation="${option}">
                            ${option}
                        </button>
                    `).join('')}
                </div>
                <div class="result-feedback" style="display: none;"></div>
            </div>
        `;
    }

    _createPinyinMode(item) {
        return `
            <div class="pinyin-container">
                <div class="character-section">
                    <div class="chinese-character">${item.chinese}</div>
                    <div class="translation-hint">${item.translation}</div>
                </div>
                <div class="pinyin-exercise">
                    <label class="pinyin-label">Enter the pinyin pronunciation:</label>
                    <input type="text" class="pinyin-input" placeholder="Type pinyin here..." />
                    <button class="check-pinyin-btn">Check Answer</button>
                </div>
                <div class="pinyin-feedback" style="display: none;"></div>
                ${item.pronunciation ? `<div class="correct-answer" style="display: none;">Correct: ${item.pronunciation}</div>` : ''}
            </div>
        `;
    }

    _createHSKMode(item) {
        const hskInfo = item.hskLevel || 'No HSK level';
        return `
            <div class="hsk-container">
                <div class="hsk-header">
                    <div class="hsk-level-badge">${hskInfo}</div>
                    <div class="character-difficulty">Chinese Character Study</div>
                </div>
                <div class="character-study">
                    <div class="chinese-character">${item.chinese}</div>
                    <div class="character-details">
                        <div class="translation">${item.translation}</div>
                        ${item.pronunciation ? `<div class="pronunciation">${item.pronunciation}</div>` : ''}
                        ${item.type ? `<div class="word-type">Type: ${item.type}</div>` : ''}
                        ${item.examples && item.examples.length > 0 ? `
                            <div class="examples">
                                <h5>Examples:</h5>
                                ${item.examples.slice(0, 2).map(ex => `<div class="example">${ex}</div>`).join('')}
                            </div>
                        ` : ''}
                    </div>
                </div>
                <div class="hsk-actions">
                    <button class="difficulty-btn easy" onclick="chineseStudyInstance._markDifficulty('easy')">😊 Easy</button>
                    <button class="difficulty-btn medium" onclick="chineseStudyInstance._markDifficulty('medium')">🤔 Medium</button>
                    <button class="difficulty-btn hard" onclick="chineseStudyInstance._markDifficulty('hard')">😅 Hard</button>
                </div>
            </div>
        `;
    }

    _nextItem() {
        if (this._currentIndex < this._vocabulary.length - 1) {
            this._currentIndex++;
            this._createStudyMode();
        }
    }

    _previousItem() {
        if (this._currentIndex > 0) {
            this._currentIndex--;
            this._createStudyMode();
        }
    }

    _backToMenu() {
        this._studyState = 'menu';
        this._currentMode = null;
        this._createGameInterface();
    }

    _flipCard() {
        const flashcard = this._gameContainer.querySelector('.flashcard');
        const isFlipped = flashcard.dataset.flipped === 'true';
        flashcard.dataset.flipped = (!isFlipped).toString();
    }

    _markAsKnown(known) {
        const points = known ? 10 : 5;
        this._score += points;
        this._correctAnswers += known ? 1 : 0;

        this._eventBus.emit('game:score-update', {
            gameId: 'chinese-study',
            score: this._score,
            module: this.name
        });

        this._updateScoreDisplay();

        setTimeout(() => {
            if (this._currentIndex < this._vocabulary.length - 1) {
                this._nextItem();
            } else {
                this._endStudySession();
            }
        }, 1000);
    }

    _selectOption(selectedTranslation) {
        const currentItem = this._vocabulary[this._currentIndex];
        const isCorrect = selectedTranslation === currentItem.translation;
        const feedback = this._gameContainer.querySelector('.result-feedback');

        if (isCorrect) {
            this._score += 15;
            this._correctAnswers++;
            feedback.innerHTML = '✅ Correct! Well done!';
            feedback.className = 'result-feedback correct';
        } else {
            this._score = Math.max(0, this._score - 5);
            feedback.innerHTML = `❌ Incorrect. The correct answer is: ${currentItem.translation}`;
            feedback.className = 'result-feedback incorrect';
        }

        feedback.style.display = 'block';

        this._eventBus.emit('game:score-update', {
            gameId: 'chinese-study',
            score: this._score,
            module: this.name
        });

        this._updateScoreDisplay();

        const options = this._gameContainer.querySelectorAll('.option-btn');
        options.forEach(btn => btn.disabled = true);

        setTimeout(() => {
            if (this._currentIndex < this._vocabulary.length - 1) {
                this._nextItem();
            } else {
                this._endStudySession();
            }
        }, 2000);
    }

    _checkPinyinAnswer() {
        const input = this._gameContainer.querySelector('.pinyin-input');
        const userAnswer = input.value.trim().toLowerCase();
        const currentItem = this._vocabulary[this._currentIndex];
        const correctPinyin = currentItem.pronunciation ? currentItem.pronunciation.toLowerCase() : '';

        const feedback = this._gameContainer.querySelector('.pinyin-feedback');
        const correctAnswer = this._gameContainer.querySelector('.correct-answer');

        if (correctPinyin && this._normalizePinyin(userAnswer) === this._normalizePinyin(correctPinyin)) {
            this._score += 20;
            this._correctAnswers++;
            feedback.innerHTML = '🎉 Excellent pronunciation!';
            feedback.className = 'pinyin-feedback correct';
        } else {
            this._score = Math.max(0, this._score - 3);
            feedback.innerHTML = '🤔 Not quite right. Try again or see the correct answer below.';
            feedback.className = 'pinyin-feedback incorrect';
            if (correctAnswer) correctAnswer.style.display = 'block';
        }

        feedback.style.display = 'block';
        input.disabled = true;
        this._gameContainer.querySelector('.check-pinyin-btn').disabled = true;

        this._eventBus.emit('game:score-update', {
            gameId: 'chinese-study',
            score: this._score,
            module: this.name
        });

        this._updateScoreDisplay();

        setTimeout(() => {
            if (this._currentIndex < this._vocabulary.length - 1) {
                this._nextItem();
            } else {
                this._endStudySession();
            }
        }, 3000);
    }

    _markDifficulty(difficulty) {
        const points = {
            'easy': 5,
            'medium': 8,
            'hard': 12
        };

        this._score += points[difficulty];
        this._correctAnswers++;

        this._eventBus.emit('game:score-update', {
            gameId: 'chinese-study',
            score: this._score,
            module: this.name
        });

        this._updateScoreDisplay();

        const buttons = this._gameContainer.querySelectorAll('.difficulty-btn');
        buttons.forEach(btn => btn.disabled = true);

        const selectedBtn = this._gameContainer.querySelector(`.difficulty-btn.${difficulty}`);
        selectedBtn.style.backgroundColor = '#10b981';
        selectedBtn.style.color = 'white';

        setTimeout(() => {
            if (this._currentIndex < this._vocabulary.length - 1) {
                this._nextItem();
            } else {
                this._endStudySession();
            }
        }, 1500);
    }

    _updateScoreDisplay() {
        const scoreElement = this._gameContainer.querySelector('#score');
        if (scoreElement) {
            scoreElement.textContent = this._score;
        }
    }

    _normalizePinyin(pinyin) {
        const toneMap = {
            'ā': 'a', 'á': 'a', 'ǎ': 'a', 'à': 'a',
            'ē': 'e', 'é': 'e', 'ě': 'e', 'è': 'e',
            'ī': 'i', 'í': 'i', 'ǐ': 'i', 'ì': 'i',
            'ō': 'o', 'ó': 'o', 'ǒ': 'o', 'ò': 'o',
            'ū': 'u', 'ú': 'u', 'ǔ': 'u', 'ù': 'u',
            'ü': 'u', 'ǖ': 'u', 'ǘ': 'u', 'ǚ': 'u', 'ǜ': 'u'
        };
        return pinyin.replace(/[āáǎàēéěèīíǐìōóǒòūúǔùüǖǘǚǜ]/g, (match) => {
            return toneMap[match] || match;
        }).replace(/\s+/g, '');
    }

    _endStudySession() {
        const accuracy = Math.round((this._correctAnswers / this._vocabulary.length) * 100);

        // Handle localStorage best score
        const currentScore = this._score;
        const bestScore = parseInt(localStorage.getItem('chinese-study-best-score') || '0');
        const isNewBest = currentScore > bestScore;

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

        this._showVictoryPopup({
            gameTitle: 'Chinese Study',
            currentScore,
            bestScore: isNewBest ? currentScore : bestScore,
            isNewBest,
            stats: {
                'Study Mode': this._currentMode || 'General',
                'Accuracy': `${accuracy}%`,
                'Correct Answers': `${this._correctAnswers}/${this._vocabulary.length}`,
                'Characters Studied': this._vocabulary.length
            }
        });
    }

    _restart() {
        this._score = 0;
        this._correctAnswers = 0;
        this._currentIndex = 0;
        this._studyState = 'menu';
        this._currentMode = null;

        this._vocabulary = this._vocabulary.sort(() => Math.random() - 0.5);
        this._createGameInterface();
        console.log('Chinese Study restarted');
    }

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

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

            .game-header {
                text-align: center;
                margin-bottom: 30px;
                border-bottom: 2px solid #e5e7eb;
                padding-bottom: 20px;
            }

            .game-header h2 {
                color: #dc2626;
                font-size: 2.2em;
                margin-bottom: 15px;
            }

            .game-stats {
                display: flex;
                justify-content: center;
                gap: 20px;
                flex-wrap: wrap;
                margin-top: 10px;
            }

            .score-display, .vocab-count, .hsk-indicator, .pinyin-indicator {
                font-size: 1em;
                padding: 5px 12px;
                border-radius: 20px;
                font-weight: bold;
            }

            .score-display {
                background: #10b981;
                color: white;
            }

            .vocab-count {
                background: #3b82f6;
                color: white;
            }

            .hsk-indicator, .pinyin-indicator {
                background: #f59e0b;
                color: white;
                font-size: 0.9em;
            }

            .study-modes {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
                gap: 20px;
                margin-bottom: 30px;
            }

            .mode-card {
                background: linear-gradient(135deg, #fff 0%, #f8fafc 100%);
                border: 2px solid #e5e7eb;
                border-radius: 16px;
                padding: 24px;
                text-align: center;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                position: relative;
            }

            .mode-card:not([data-disabled]):hover {
                border-color: #dc2626;
                transform: translateY(-4px);
                box-shadow: 0 8px 20px rgba(220, 38, 38, 0.15);
            }

            .mode-card[data-disabled="true"] {
                opacity: 0.6;
                cursor: not-allowed;
                background: #f9fafb;
            }

            .mode-requirement {
                background: #fee2e2;
                color: #dc2626;
                padding: 4px 8px;
                border-radius: 12px;
                font-size: 0.8em;
                margin-bottom: 10px;
            }

            .mode-icon {
                font-size: 3em;
                margin-bottom: 12px;
            }

            .mode-card h3 {
                color: #374151;
                margin-bottom: 8px;
                font-size: 1.3em;
            }

            .mode-card p {
                color: #6b7280;
                margin-bottom: 16px;
                line-height: 1.5;
            }

            .mode-btn {
                background: #dc2626;
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: 8px;
                cursor: pointer;
                font-weight: bold;
                transition: background 0.3s ease;
            }

            .mode-btn:hover:not(:disabled) {
                background: #b91c1c;
            }

            .mode-btn:disabled {
                background: #9ca3af;
                cursor: not-allowed;
            }

            .vocabulary-preview {
                background: #f8fafc;
                border: 1px solid #e5e7eb;
                border-radius: 12px;
                padding: 20px;
                margin-bottom: 30px;
            }

            .vocabulary-preview h4 {
                color: #374151;
                margin-bottom: 15px;
                text-align: center;
            }

            .preview-items {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 10px;
            }

            .preview-item {
                background: white;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                padding: 10px;
                display: flex;
                flex-direction: column;
                align-items: center;
                text-align: center;
                gap: 4px;
            }

            .preview-item .chinese {
                font-size: 1.4em;
                font-weight: bold;
                color: #dc2626;
            }

            .preview-item .translation {
                color: #374151;
                font-size: 0.9em;
            }

            .preview-item .pinyin {
                color: #6b7280;
                font-size: 0.8em;
                font-style: italic;
            }

            .preview-item .hsk-badge {
                background: #f59e0b;
                color: white;
                padding: 2px 6px;
                border-radius: 10px;
                font-size: 0.7em;
                font-weight: bold;
            }

            .more-items {
                grid-column: 1/-1;
                text-align: center;
                color: #6b7280;
                font-style: italic;
                padding: 10px;
            }

            .study-mode-active {
                max-width: 800px;
            }

            .study-header {
                background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
                color: white;
                border-radius: 12px;
                padding: 20px;
                margin-bottom: 30px;
            }

            .mode-title {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 15px;
            }

            .mode-title h2 {
                margin: 0;
                font-size: 1.8em;
            }

            .back-to-menu-btn {
                background: rgba(255,255,255,0.2);
                color: white;
                border: 1px solid rgba(255,255,255,0.3);
                padding: 8px 16px;
                border-radius: 6px;
                cursor: pointer;
                transition: background 0.3s ease;
            }

            .back-to-menu-btn:hover {
                background: rgba(255,255,255,0.3);
            }

            .progress-section {
                display: flex;
                align-items: center;
                gap: 15px;
                flex-wrap: wrap;
            }

            .progress-bar {
                flex: 1;
                min-width: 200px;
                height: 8px;
                background: rgba(255,255,255,0.3);
                border-radius: 4px;
                overflow: hidden;
            }

            .progress-fill {
                height: 100%;
                background: white;
                transition: width 0.3s ease;
            }

            .progress-text {
                font-weight: bold;
                min-width: 60px;
            }

            .study-content {
                background: white;
                border: 1px solid #e5e7eb;
                border-radius: 12px;
                padding: 30px;
                margin-bottom: 20px;
                min-height: 300px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .flashcard-container {
                width: 100%;
                max-width: 400px;
                text-align: center;
            }

            .flashcard {
                width: 100%;
                height: 250px;
                position: relative;
                transform-style: preserve-3d;
                transition: transform 0.6s;
                cursor: pointer;
                margin-bottom: 20px;
            }

            .flashcard[data-flipped="true"] {
                transform: rotateY(180deg);
            }

            .flashcard-front, .flashcard-back {
                position: absolute;
                width: 100%;
                height: 100%;
                backface-visibility: hidden;
                border: 2px solid #e5e7eb;
                border-radius: 12px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                padding: 20px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            }

            .flashcard-back {
                transform: rotateY(180deg);
                background: #f8fafc;
            }

            .chinese-character {
                font-size: 4em;
                font-weight: bold;
                color: #dc2626;
                margin-bottom: 10px;
            }

            .card-hint {
                color: #6b7280;
                font-style: italic;
            }

            .translation {
                font-size: 1.5em;
                color: #374151;
                margin-bottom: 10px;
            }

            .pronunciation {
                color: #6b7280;
                font-style: italic;
                margin-bottom: 8px;
            }

            .word-type, .hsk-level {
                background: #e5e7eb;
                color: #374151;
                padding: 4px 8px;
                border-radius: 12px;
                font-size: 0.8em;
                margin-bottom: 4px;
            }

            .hsk-level {
                background: #f59e0b;
                color: white;
            }

            .flashcard-actions {
                display: flex;
                gap: 15px;
                justify-content: center;
            }

            .know-btn, .dont-know-btn {
                padding: 12px 24px;
                border: none;
                border-radius: 8px;
                font-weight: bold;
                cursor: pointer;
                transition: all 0.3s ease;
            }

            .know-btn {
                background: #10b981;
                color: white;
            }

            .know-btn:hover {
                background: #059669;
            }

            .dont-know-btn {
                background: #f59e0b;
                color: white;
            }

            .dont-know-btn:hover {
                background: #d97706;
            }

            .recognition-container, .pinyin-container, .hsk-container {
                width: 100%;
                text-align: center;
            }

            .question-section, .character-section, .hsk-header {
                margin-bottom: 30px;
            }

            .pronunciation-hint, .translation-hint {
                color: #6b7280;
                font-style: italic;
                margin: 10px 0;
            }

            .question-text {
                font-size: 1.2em;
                color: #374151;
                margin-bottom: 20px;
            }

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

            .option-btn {
                background: #f8fafc;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                padding: 15px;
                cursor: pointer;
                font-size: 1em;
                transition: all 0.3s ease;
            }

            .option-btn:hover:not(:disabled) {
                border-color: #dc2626;
                background: #fef2f2;
            }

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

            .result-feedback, .pinyin-feedback {
                padding: 15px;
                border-radius: 8px;
                font-weight: bold;
                margin-bottom: 15px;
            }

            .result-feedback.correct, .pinyin-feedback.correct {
                background: #d1fae5;
                color: #065f46;
                border: 1px solid #10b981;
            }

            .result-feedback.incorrect, .pinyin-feedback.incorrect {
                background: #fee2e2;
                color: #991b1b;
                border: 1px solid #ef4444;
            }

            .pinyin-exercise {
                margin-bottom: 20px;
            }

            .pinyin-label {
                display: block;
                font-weight: bold;
                color: #374151;
                margin-bottom: 10px;
            }

            .pinyin-input {
                padding: 12px;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                font-size: 1.1em;
                width: 250px;
                max-width: 100%;
                margin-bottom: 15px;
                margin-right: 10px;
            }

            .pinyin-input:focus {
                outline: none;
                border-color: #dc2626;
            }

            .check-pinyin-btn {
                background: #dc2626;
                color: white;
                border: none;
                padding: 12px 20px;
                border-radius: 8px;
                cursor: pointer;
                font-weight: bold;
            }

            .check-pinyin-btn:hover:not(:disabled) {
                background: #b91c1c;
            }

            .check-pinyin-btn:disabled {
                background: #9ca3af;
                cursor: not-allowed;
            }

            .correct-answer {
                background: #f0f9ff;
                color: #0c4a6e;
                border: 1px solid #3b82f6;
                padding: 10px;
                border-radius: 8px;
                font-weight: bold;
            }

            .hsk-level-badge {
                background: #f59e0b;
                color: white;
                padding: 8px 16px;
                border-radius: 20px;
                font-weight: bold;
                display: inline-block;
                margin-bottom: 10px;
            }

            .character-difficulty {
                color: #6b7280;
                font-size: 1em;
            }

            .character-study {
                margin-bottom: 30px;
            }

            .character-details {
                background: #f8fafc;
                border-radius: 8px;
                padding: 20px;
                margin-top: 15px;
            }

            .character-details .translation {
                font-size: 1.3em;
                margin-bottom: 10px;
            }

            .character-details .word-type {
                background: #e5e7eb;
                color: #374151;
                padding: 4px 12px;
                border-radius: 12px;
                font-size: 0.9em;
                display: inline-block;
                margin-bottom: 15px;
            }

            .examples {
                text-align: left;
                margin-top: 15px;
            }

            .examples h5 {
                color: #374151;
                margin-bottom: 8px;
                text-align: center;
            }

            .example {
                background: white;
                border: 1px solid #e5e7eb;
                border-radius: 6px;
                padding: 8px;
                margin-bottom: 5px;
                color: #6b7280;
            }

            .hsk-actions {
                display: flex;
                gap: 15px;
                justify-content: center;
                flex-wrap: wrap;
            }

            .difficulty-btn {
                padding: 12px 20px;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                background: white;
                cursor: pointer;
                font-weight: bold;
                transition: all 0.3s ease;
                min-width: 100px;
            }

            .difficulty-btn.easy {
                border-color: #10b981;
                color: #10b981;
            }

            .difficulty-btn.easy:hover:not(:disabled) {
                background: #10b981;
                color: white;
            }

            .difficulty-btn.medium {
                border-color: #f59e0b;
                color: #f59e0b;
            }

            .difficulty-btn.medium:hover:not(:disabled) {
                background: #f59e0b;
                color: white;
            }

            .difficulty-btn.hard {
                border-color: #ef4444;
                color: #ef4444;
            }

            .difficulty-btn.hard:hover:not(:disabled) {
                background: #ef4444;
                color: white;
            }

            .difficulty-btn:disabled {
                cursor: not-allowed;
                opacity: 0.7;
            }

            .study-controls {
                display: flex;
                justify-content: space-between;
                gap: 15px;
            }

            .prev-btn, .next-btn {
                background: #6b7280;
                color: white;
                border: none;
                padding: 12px 24px;
                border-radius: 8px;
                cursor: pointer;
                font-weight: bold;
                transition: background 0.3s ease;
                flex: 1;
                max-width: 150px;
            }

            .prev-btn:hover:not(:disabled), .next-btn:hover:not(:disabled) {
                background: #4b5563;
            }

            .prev-btn:disabled, .next-btn:disabled {
                background: #9ca3af;
                cursor: not-allowed;
            }

            .study-complete {
                text-align: center;
                padding: 40px 20px;
            }

            .study-complete h2 {
                color: #dc2626;
                font-size: 2.5em;
                margin-bottom: 30px;
            }

            .final-stats {
                display: flex;
                justify-content: center;
                gap: 30px;
                margin-bottom: 30px;
                flex-wrap: wrap;
            }

            .stat-item {
                background: #f8fafc;
                border: 1px solid #e5e7eb;
                border-radius: 12px;
                padding: 20px;
                min-width: 120px;
            }

            .stat-value {
                font-size: 2em;
                font-weight: bold;
                color: #dc2626;
                margin-bottom: 5px;
            }

            .stat-label {
                color: #6b7280;
                font-size: 0.9em;
            }

            .completion-message {
                background: #f0f9ff;
                border: 1px solid #3b82f6;
                border-radius: 12px;
                padding: 20px;
                color: #1e40af;
                font-size: 1.1em;
                font-weight: bold;
                margin-bottom: 30px;
            }

            .final-actions {
                display: flex;
                gap: 15px;
                justify-content: center;
                flex-wrap: wrap;
            }

            .restart-btn, .menu-btn, .back-btn {
                padding: 12px 24px;
                border: none;
                border-radius: 8px;
                cursor: pointer;
                font-weight: bold;
                transition: background 0.3s ease;
                font-size: 1em;
            }

            .restart-btn {
                background: #10b981;
                color: white;
            }

            .restart-btn:hover {
                background: #059669;
            }

            .menu-btn {
                background: #3b82f6;
                color: white;
            }

            .menu-btn:hover {
                background: #2563eb;
            }

            .back-btn {
                background: #6b7280;
                color: white;
            }

            .back-btn:hover {
                background: #4b5563;
            }

            .game-controls {
                text-align: center;
            }

            .game-error {
                text-align: center;
                padding: 40px 20px;
                background: #fee2e2;
                border: 1px solid #ef4444;
                border-radius: 12px;
            }

            .game-error h3 {
                color: #991b1b;
                margin-bottom: 15px;
            }

            .game-error p {
                color: #7f1d1d;
                margin-bottom: 10px;
            }

            @media (max-width: 768px) {
                .chinese-study-container {
                    padding: 15px;
                }

                .game-header h2 {
                    font-size: 1.8em;
                }

                .study-modes {
                    grid-template-columns: 1fr;
                }

                .preview-items {
                    grid-template-columns: 1fr;
                }

                .game-stats {
                    flex-direction: column;
                    align-items: center;
                    gap: 10px;
                }

                .chinese-character {
                    font-size: 3em;
                }

                .flashcard {
                    height: 200px;
                }

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

                .final-stats {
                    flex-direction: column;
                    align-items: center;
                    gap: 15px;
                }

                .final-actions {
                    flex-direction: column;
                    align-items: center;
                }

                .hsk-actions {
                    flex-direction: column;
                    align-items: center;
                }

                .study-controls {
                    flex-direction: column;
                }

                .prev-btn, .next-btn {
                    max-width: none;
                }

                .mode-title {
                    flex-direction: column;
                    gap: 10px;
                    text-align: center;
                }

                .progress-section {
                    flex-direction: column;
                    gap: 10px;
                }
            }

            /* 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(); chineseStudyInstance._restart();">🔄 Play Again</button>
                    <button class="victory-btn secondary" onclick="this.closest('.victory-popup').remove(); window.app.getCore().router.navigate('/games'); setTimeout(() => { const chapterId = window.currentChapterId || 'sbs'; window.app.getCore().eventBus.emit('navigation:games', { path: \`/games/\${chapterId}\`, data: { path: \`/games/\${chapterId}\` } }, 'Application'); }, 100);">🎮 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: 'chinese-study',
            score: currentScore,
            accuracy: parseInt(stats['Accuracy'].replace('%', '')),
            mode: this._currentMode,
            totalItems: this._vocabulary.length,
            correctAnswers: this._correctAnswers,
            module: this.name
        });
    }

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

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

export default ChineseStudy;