/**
 * FlashcardLearning - Advanced flashcard learning game with spaced repetition
 * Features: Multiple modes, progress tracking, statistics, achievements
 */

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

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

        // Validate dependencies
        if (!dependencies.eventBus) {
            throw new Error('FlashcardLearning requires EventBus dependency');
        }

        this._eventBus = dependencies.eventBus;
        this._content = dependencies.content || null;
        this._prerequisiteEngine = dependencies.prerequisiteEngine || null;
        this._config = {
            container: null,
            wordsPerSession: config.wordsPerSession || 5,
            mode: config.mode || 'mixed',
            difficulty: config.difficulty || 'all',
            ...config
        };

        // Game state
        this._container = null;
        this._isActive = false;
        this._currentCard = null;
        this._currentCardIndex = 0;
        this._sessionCards = [];
        this._retryCards = []; // Cards marked as "don't know" to retry in same session
        this._sessionStats = {
            total: 0,
            correct: 0,
            incorrect: 0,
            startTime: null,
            endTime: null
        };

        // Learning modes
        this._modes = {
            recognition: 'Show English → Guess Translation',
            production: 'Show Translation → Guess English',
            mixed: 'Random Mix of Both',
            pronunciation: 'Audio Practice Mode'
        };

        // Current study mode
        this._currentMode = this._config.mode;
        this._showingFront = true;
        this._isRevealed = false;

        // Progress tracking system
        this._progressKey = 'flashcard_progress';
        this._statsKey = 'flashcard_stats';
        this._achievementsKey = 'flashcard_achievements';

        // Load saved progress
        this._progress = this._loadProgress();
        this._globalStats = this._loadGlobalStats();
        this._achievements = this._loadAchievements();

        // Card data processing
        this._flashcards = [];

        Object.seal(this);
    }

    static getMetadata() {
        return {
            name: 'Flashcard Learning',
            description: 'Advanced flashcard learning with spaced repetition, multiple modes, and progress tracking',
            difficulty: 'adaptive',
            category: 'vocabulary',
            minPlayers: 1,
            maxPlayers: 1,
            estimatedDuration: '10-30 minutes',
            features: [
                'Spaced Repetition Algorithm',
                'Multiple Learning Modes',
                'Progress Tracking',
                'Statistics Dashboard',
                'Achievement System',
                'Audio Pronunciation',
                'Customizable Sessions'
            ]
        };
    }

    static getCompatibilityScore(content) {
        if (!content) {
            return { score: 0, reason: 'No content available' };
        }

        let wordCount = 0;
        let sentenceCount = 0;

        // Count vocabulary words
        if (content.vocabulary && typeof content.vocabulary === 'object') {
            wordCount = Object.keys(content.vocabulary).length;
        }

        // Count sentences
        if (content.sentences && Array.isArray(content.sentences)) {
            sentenceCount = content.sentences.length;
        }

        // Check story content for extractable vocabulary
        if (content.story && typeof content.story === 'string') {
            const words = content.story.match(/\b[a-zA-Z]+\b/g) || [];
            wordCount += Math.min(words.length / 10, 20); // Estimate extractable vocab
        }

        // Compatibility scoring
        const totalContent = wordCount + sentenceCount * 2;

        if (totalContent >= 15) {
            return {
                score: 0.95,
                reason: `Excellent content: ${wordCount} words, ${sentenceCount} sentences`,
                requirements: ['vocabulary', 'sentences'],
                wordCount,
                sentenceCount
            };
        } else if (totalContent >= 8) {
            return {
                score: 0.75,
                reason: `Good content: ${wordCount} words, ${sentenceCount} sentences`,
                requirements: ['vocabulary'],
                wordCount,
                sentenceCount
            };
        } else if (totalContent >= 3) {
            return {
                score: 0.50,
                reason: `Minimal content: ${wordCount} words, ${sentenceCount} sentences`,
                requirements: ['basic vocabulary'],
                wordCount,
                sentenceCount
            };
        }

        return {
            score: 0.1,
            reason: 'Insufficient vocabulary for flashcard learning',
            wordCount,
            sentenceCount
        };
    }

    async init() {
        this._validateNotDestroyed();

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

        console.log('🎯 Initializing FlashcardLearning game...');

        // Set up event listeners
        this._eventBus.on('game:stop', this._handleStop.bind(this), this.name);
        this._eventBus.on('flashcard:next', this._handleNext.bind(this), this.name);
        this._eventBus.on('flashcard:reveal', this._handleReveal.bind(this), this.name);
        this._eventBus.on('flashcard:rate', this._handleRate.bind(this), this.name);
        this._eventBus.on('flashcard:mode-change', this._handleModeChange.bind(this), this.name);

        // Start game immediately
        try {
            this._isActive = true; // Set active before starting
            this._container = this._config.container;

            // Prioritize content from dependencies (passed by GameLoader)
            // Fallback to window.contentLoader only if no content in dependencies
            const content = this._content || (window.contentLoader ? window.contentLoader.getContent(window.currentChapterId) : null);

            if (!content || (!content.vocabulary && !content.sentences)) {
                throw new Error('No suitable content available for flashcards');
            }

            // Process content into flashcards
            this._content = content;
            this._processContent();

            // Create game interface
            this._createGameUI();

            // Start first session
            this._startSession();

            // Emit game ready event
            this._eventBus.emit('game:ready', {
                gameId: 'flashcard-learning',
                instanceId: this.name,
                cards: this._flashcards.length
            }, this.name);

        } catch (error) {
            console.error('Error starting FlashcardLearning:', error);
            this._showError(error.message);
        }

        this._setInitialized();
        console.log('✅ FlashcardLearning initialized successfully');
    }

    _showError(message) {
        if (this._container) {
            this._container.innerHTML = `
                <div class="game-error" style="
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    height: 400px;
                    text-align: center;
                    font-family: Arial, sans-serif;
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    border-radius: 10px;
                    color: white;
                    padding: 40px;
                ">
                    <div style="font-size: 4em; margin-bottom: 20px;">🎴</div>
                    <h3 style="margin: 0 0 20px 0; font-size: 1.5em;">Flashcard Learning Error</h3>
                    <p style="margin: 0 0 30px 0; font-size: 1.1em; opacity: 0.9;">${message}</p>
                    <button onclick="history.back()" style="
                        background: rgba(255,255,255,0.2);
                        color: white;
                        border: 2px solid white;
                        padding: 12px 24px;
                        border-radius: 25px;
                        font-size: 1em;
                        cursor: pointer;
                        transition: all 0.3s ease;
                    " onmouseover="this.style.background='rgba(255,255,255,0.3)'" onmouseout="this.style.background='rgba(255,255,255,0.2)'">
                        ← Back to Games
                    </button>
                </div>
            `;
        }
    }

    async destroy() {
        this._validateNotDestroyed();

        // Save progress before destroying
        this._saveProgress();
        this._saveGlobalStats();
        this._saveAchievements();

        // Clean up UI
        if (this._container) {
            this._container.innerHTML = '';
        }

        this._isActive = false;
        this._setDestroyed();
    }

    // Game Control Methods
    async start() {
        this._validateInitialized();

        if (this._isActive) {
            console.warn('FlashcardLearning is already active');
            return;
        }

        console.log('🚀 Starting FlashcardLearning game...');

        // Get container
        this._container = document.getElementById(this._config.container);
        if (!this._container) {
            throw new Error(`Container element '${this._config.container}' not found`);
        }

        // Check if we have flashcards
        if (this._flashcards.length === 0) {
            this._showNoContentMessage();
            return;
        }

        this._isActive = true;
        this._setupSession();
        this._createGameUI();
        this._startSession();

        // Emit start event
        this._eventBus.emit('game:flashcard-started', {
            mode: this._currentMode,
            cardsCount: this._flashcards.length,
            wordsPerSession: this._config.wordsPerSession
        }, this.name);
    }

    async stop() {
        if (!this._isActive) return;

        console.log('⏹️ Stopping FlashcardLearning game...');

        // Save current session progress
        this._endSession();
        this._saveProgress();
        this._saveGlobalStats();

        // Clean up UI
        if (this._container) {
            this._container.innerHTML = '';
        }

        this._isActive = false;

        // Emit stop event
        this._eventBus.emit('game:flashcard-stopped', {
            sessionStats: this._sessionStats
        }, this.name);
    }

    // Content Processing
    _processContent() {
        console.log('🔄 Processing content into flashcards...');

        this._flashcards = [];

        if (!this._content) {
            console.warn('No content available for flashcard generation');
            return;
        }

        // Process vocabulary
        if (this._content.vocabulary && typeof this._content.vocabulary === 'object') {
            for (const [english, data] of Object.entries(this._content.vocabulary)) {
                if (english && data) {
                    let translation;
                    if (typeof data === 'string') {
                        translation = data;
                    } else if (data.user_language) {
                        translation = data.user_language.split('；')[0]; // Take first translation
                    } else if (data.translation) {
                        translation = data.translation;
                    } else {
                        continue; // Skip if no translation found
                    }

                    this._flashcards.push({
                        id: `vocab_${english.toLowerCase().replace(/\s+/g, '_')}`,
                        type: 'vocabulary',
                        front: english,
                        back: translation,
                        category: 'vocabulary',
                        difficulty: this._estimateDifficulty(english),
                        wordType: data.type || 'unknown',
                        pronunciation: data.pronunciation || null
                    });
                }
            }
        }

        // Process sentences
        if (this._content.sentences && Array.isArray(this._content.sentences)) {
            this._content.sentences.forEach((sentence, index) => {
                if (sentence.english && sentence.translation) {
                    this._flashcards.push({
                        id: `sentence_${index}`,
                        type: 'sentence',
                        front: sentence.english,
                        back: sentence.translation,
                        category: 'sentences',
                        difficulty: this._estimateDifficulty(sentence.english)
                    });
                }
            });
        }

        console.log(`✅ Generated ${this._flashcards.length} flashcards`);

        // Initialize progress for new cards
        this._initializeCardProgress();
    }

    _estimateDifficulty(text) {
        const wordCount = text.split(/\s+/).length;
        const charCount = text.length;
        const complexity = text.match(/[^\w\s]/g)?.length || 0;

        if (wordCount <= 2 && charCount <= 10) return 'beginner';
        if (wordCount <= 5 && charCount <= 25) return 'intermediate';
        return 'advanced';
    }

    _initializeCardProgress() {
        let updated = false;

        for (const card of this._flashcards) {
            if (!this._progress[card.id]) {
                this._progress[card.id] = {
                    cardId: card.id,
                    word: card.front,
                    translation: card.back,
                    timesStudied: 0,
                    timesCorrect: 0,
                    lastStudied: null,
                    nextReview: Date.now(),
                    difficultyLevel: 1,
                    masteryLevel: 'new',
                    averageResponseTime: 0,
                    confidenceHistory: []
                };
                updated = true;
            }
        }

        if (updated) {
            this._saveProgress();
        }
    }

    // Session Management
    _setupSession() {
        console.log('📚 Setting up study session...');

        // Reset retry cards for new session
        this._retryCards = [];

        // Get cards due for review using spaced repetition
        const dueCards = this._getDueCards();
        const newCards = this._getNewCards();

        // Mix due cards with new cards (70% due, 30% new)
        const maxDue = Math.min(dueCards.length, Math.floor(this._config.wordsPerSession * 0.7));
        const maxNew = Math.min(newCards.length, this._config.wordsPerSession - maxDue);

        this._sessionCards = [
            ...dueCards.slice(0, maxDue),
            ...newCards.slice(0, maxNew)
        ];

        // If no cards available, use all cards for practice
        if (this._sessionCards.length === 0) {
            console.log('📚 No due cards found, using all flashcards for practice');
            this._sessionCards = [...this._flashcards].slice(0, this._config.wordsPerSession);
        }

        // Shuffle cards
        this._shuffleArray(this._sessionCards);

        // Limit to session length
        this._sessionCards = this._sessionCards.slice(0, this._config.wordsPerSession);

        console.log(`📋 Session setup: ${this._sessionCards.length} cards (${maxDue} due, ${maxNew} new)`);

        // Reset session stats
        this._sessionStats = {
            total: this._sessionCards.length,
            correct: 0,
            incorrect: 0,
            startTime: Date.now(),
            endTime: null,
            cardsStudied: 0
        };
    }

    _getDueCards() {
        const now = Date.now();
        return this._flashcards.filter(card => {
            const progress = this._progress[card.id];
            return progress && progress.nextReview <= now && progress.masteryLevel !== 'mastered';
        }).sort((a, b) => {
            const aProgress = this._progress[a.id];
            const bProgress = this._progress[b.id];
            return aProgress.nextReview - bProgress.nextReview;
        });
    }

    _getNewCards() {
        return this._flashcards.filter(card => {
            const progress = this._progress[card.id];
            // If no progress exists, treat as new card
            return !progress || progress.masteryLevel === 'new';
        }).sort(() => Math.random() - 0.5);
    }

    _hasRemainingContent() {
        // Check if there are cards that haven't been studied yet or need review
        const dueCards = this._getDueCards();
        const newCards = this._getNewCards();
        return dueCards.length > 0 || newCards.length > 0;
    }

    _startSession() {
        if (this._sessionCards.length === 0) {
            // Fallback: If still no cards after setup, force use all flashcards
            if (this._flashcards.length > 0) {
                console.log('🚨 Forcing session with all available flashcards');
                this._sessionCards = [...this._flashcards].slice(0, this._config.wordsPerSession);
                this._shuffleArray(this._sessionCards);
            } else {
                this._showNoCardsMessage();
                return;
            }
        }

        this._currentCardIndex = 0;
        this._loadCard(0);
    }

    _endSession() {
        this._sessionStats.endTime = Date.now();

        // Update global stats
        this._updateGlobalStats();

        // Check for achievements
        this._checkAchievements();

        console.log('📊 Session completed:', this._sessionStats);
    }

    // Card Management
    _loadCard(index) {
        console.log(`🎯 _loadCard called with index ${index}, sessionCards length: ${this._sessionCards.length}, retryCards: ${this._retryCards.length}`);

        // Check if we've finished the main session cards
        if (index >= this._sessionCards.length) {
            console.log(`🏁 Reached end of session cards. Retry cards available: ${this._retryCards.length}`);

            // If there are retry cards, add them to the session and continue
            if (this._retryCards.length > 0) {
                const retryCount = this._retryCards.length;
                console.log(`🔄 Main session finished, starting retry phase with ${retryCount} cards`);
                console.log(`📋 Retry cards:`, this._retryCards.map(c => c.id));

                // Add retry cards to the end of session cards
                this._sessionCards.push(...this._retryCards);

                // Clear retry queue
                this._retryCards = [];

                // Set up the first retry card
                this._currentCardIndex = index;
                this._currentCard = this._sessionCards[index];
                this._showingFront = true;
                this._isRevealed = false;
                console.log(`📚 Loading retry card: ${this._currentCard.id}`);

                // Show retry phase message and return early to prevent immediate card display
                this._showRetryPhaseMessage(retryCount);
                return; // Don't continue with normal card display flow
            } else {
                // No retry cards, session is complete
                this._showSessionComplete();
                return;
            }
        } else {
            // Normal card loading
            this._currentCardIndex = index;
            this._currentCard = this._sessionCards[index];
            this._showingFront = true;
            this._isRevealed = false;
        }

        // Determine which side to show based on mode
        const shouldShowEnglishFirst = this._shouldShowEnglishFirst();

        if (shouldShowEnglishFirst) {
            this._currentCard.displayFront = this._currentCard.back; // English first
            this._currentCard.displayBack = this._currentCard.front; // Translation revealed
        } else {
            this._currentCard.displayFront = this._currentCard.front; // Translation first
            this._currentCard.displayBack = this._currentCard.back; // English revealed
        }

        this._updateCardDisplay();
        this._updateProgressIndicator();
    }

    _shouldShowEnglishFirst() {
        switch (this._currentMode) {
            case 'recognition':
                return true; // English → Translation
            case 'production':
                return false; // Translation → English
            case 'mixed':
                return Math.random() < 0.5; // Random
            case 'pronunciation':
                return true; // Show English, focus on pronunciation
            default:
                return true;
        }
    }

    _nextCard() {
        console.log(`🎯 _nextCard: current index ${this._currentCardIndex}, moving to ${this._currentCardIndex + 1}`);
        this._loadCard(this._currentCardIndex + 1);
    }

    // UI Creation and Management
    _createGameUI() {
        const gameHTML = `
            <div class="flashcard-game">
                <div class="game-header">
                    <div class="mode-selector">
                        <label>Study Mode:</label>
                        <select id="mode-select">
                            ${Object.entries(this._modes).map(([key, label]) =>
                                `<option value="${key}" ${key === this._currentMode ? 'selected' : ''}>${label}</option>`
                            ).join('')}
                        </select>
                    </div>
                    <div class="session-info">
                        <span id="progress-indicator">Card 0 of 0</span>
                        <div class="progress-bar">
                            <div id="progress-fill" class="progress-fill"></div>
                        </div>
                    </div>
                    <button id="settings-btn" class="btn-secondary">Settings</button>
                </div>

                <div class="flashcard-container">
                    <div id="flashcard" class="flashcard">
                        <div class="card-front">
                            <div class="card-content">
                                <div id="front-text" class="card-text"></div>
                                <div class="card-hint">Click to reveal</div>
                            </div>
                        </div>
                        <div class="card-back">
                            <div class="card-content">
                                <div id="back-text" class="card-text"></div>
                                <div id="pronunciation-text" class="pronunciation-text"></div>
                                <div class="confidence-buttons">
                                    <button data-rating="again" class="confidence-btn again">Again</button>
                                    <button data-rating="hard" class="confidence-btn hard">Hard</button>
                                    <button data-rating="good" class="confidence-btn good">Good</button>
                                    <button data-rating="easy" class="confidence-btn easy">Easy</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="game-controls">
                    <!-- Difficulty rating buttons will appear after reveal -->
                </div>

                <div class="session-stats">
                    <div class="stat">
                        <span class="stat-label">Correct:</span>
                        <span id="correct-count" class="stat-value">0</span>
                    </div>
                    <div class="stat">
                        <span class="stat-label">Incorrect:</span>
                        <span id="incorrect-count" class="stat-value">0</span>
                    </div>
                    <div class="stat">
                        <span class="stat-label">Accuracy:</span>
                        <span id="accuracy" class="stat-value">0%</span>
                    </div>
                </div>

                <div id="statistics-panel" class="statistics-panel" style="display: none;">
                    <h3>Study Statistics</h3>
                    <div class="stats-grid">
                        <div class="stat-item">
                            <span class="stat-number" id="content-coverage">0%</span>
                            <span class="stat-label">Content Coverage</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-number" id="mastery-rate">0%</span>
                            <span class="stat-label">Mastery Rate</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-number" id="study-streak">0</span>
                            <span class="stat-label">Study Streak</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-number" id="time-studied">0m</span>
                            <span class="stat-label">Time Studied</span>
                        </div>
                    </div>
                    <div class="achievements">
                        <h4>Achievements</h4>
                        <div id="achievements-list" class="achievements-list"></div>
                    </div>
                </div>
            </div>
        `;

        this._container.innerHTML = gameHTML;
        this._injectCSS();
        this._setupUIEvents();
        this._updateStatisticsPanel();
    }

    _injectCSS() {
        if (document.getElementById('flashcard-styles')) return;

        const style = document.createElement('style');
        style.id = 'flashcard-styles';
        style.textContent = `
            .flashcard-game {
                max-width: 800px;
                margin: 0 auto;
                padding: 20px;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            }

            .game-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 20px;
                flex-wrap: wrap;
                gap: 15px;
            }

            .mode-selector label {
                margin-right: 10px;
                font-weight: 600;
            }

            .mode-selector select {
                padding: 8px 12px;
                border: 2px solid #e0e0e0;
                border-radius: 8px;
                background: white;
                font-size: 14px;
            }

            .session-info {
                text-align: center;
                flex: 1;
                min-width: 200px;
            }

            #progress-indicator {
                display: block;
                font-weight: 600;
                margin-bottom: 8px;
                color: #555;
            }

            .progress-bar {
                width: 100%;
                height: 8px;
                background: #e0e0e0;
                border-radius: 4px;
                overflow: hidden;
            }

            .progress-fill {
                height: 100%;
                background: linear-gradient(90deg, #4CAF50, #45a049);
                width: 0%;
                transition: width 0.3s ease;
            }

            .flashcard-container {
                perspective: 1000px;
                margin: 30px 0;
                display: flex;
                justify-content: center;
            }

            .flashcard {
                width: 400px;
                height: 300px;
                position: relative;
                transform-style: preserve-3d;
                transition: transform 0.6s;
                cursor: pointer;
                margin: 0 auto;
            }

            .flashcard.flipped {
                transform: rotateY(180deg);
                box-shadow:
                    0 8px 32px rgba(25, 74, 156, 0.4),
                    0 4px 16px rgba(25, 74, 156, 0.3),
                    0 2px 8px rgba(0, 0, 0, 0.1);
                filter: drop-shadow(0 4px 20px rgba(25, 74, 156, 0.25));
            }

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

            .card-front {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
            }

            .card-back {
                background: linear-gradient(135deg, #1a4a9c 0%, #0d2b5f 100%);
                color: white;
                transform: rotateY(180deg) scaleX(-1);
                border: 2px solid rgba(255, 255, 255, 0.1);
            }

            .card-content {
                text-align: center;
                width: 100%;
            }

            .card-text {
                font-size: 24px;
                font-weight: 600;
                line-height: 1.4;
                margin-bottom: 15px;
                min-height: 60px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .card-hint {
                font-size: 14px;
                opacity: 0.8;
                font-style: italic;
            }

            .pronunciation-text {
                font-size: 16px;
                font-style: italic;
                opacity: 0.8;
                margin-top: 10px;
                margin-bottom: 15px;
                padding: 8px 12px;
                background: rgba(255, 255, 255, 0.1);
                border-radius: 20px;
                border: 1px solid rgba(255, 255, 255, 0.2);
            }

            .confidence-buttons {
                display: flex;
                gap: 10px;
                justify-content: center;
                flex-wrap: wrap;
            }

            .confidence-btn {
                padding: 8px 16px;
                border: none;
                border-radius: 6px;
                cursor: pointer;
                font-weight: 600;
                font-size: 12px;
                transition: all 0.3s ease;
                text-transform: uppercase;
            }

            .confidence-btn.again { background: #ff4757; color: white; }
            .confidence-btn.hard { background: #ff6b7a; color: white; }
            .confidence-btn.good { background: #26d0ce; color: white; }
            .confidence-btn.easy { background: #1dd1a1; color: white; }

            .confidence-btn:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0,0,0,0.2);
            }

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

            .btn-primary, .btn-secondary {
                padding: 12px 24px;
                border: none;
                border-radius: 8px;
                cursor: pointer;
                font-weight: 600;
                font-size: 14px;
                transition: all 0.3s ease;
            }

            .btn-primary {
                background: #4CAF50;
                color: white;
            }

            .btn-secondary {
                background: #e0e0e0;
                color: #555;
            }

            .btn-primary:hover, .btn-secondary:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0,0,0,0.2);
            }

            .session-stats {
                display: flex;
                gap: 30px;
                justify-content: center;
                margin: 20px 0;
                padding: 20px;
                background: #f8f9fa;
                border-radius: 12px;
            }

            .stat {
                text-align: center;
            }

            .stat-label {
                display: block;
                font-size: 12px;
                color: #666;
                text-transform: uppercase;
                font-weight: 600;
                margin-bottom: 5px;
            }

            .stat-value {
                display: block;
                font-size: 18px;
                font-weight: 700;
                color: #333;
            }

            .statistics-panel {
                background: white;
                border-radius: 12px;
                padding: 20px;
                margin-top: 20px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }

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

            .stat-item {
                text-align: center;
                padding: 15px;
                background: #f8f9fa;
                border-radius: 8px;
            }

            .stat-number {
                display: block;
                font-size: 24px;
                font-weight: 700;
                color: #4CAF50;
                margin-bottom: 5px;
            }

            .achievements-list {
                display: flex;
                flex-wrap: wrap;
                gap: 10px;
                margin-top: 10px;
            }

            .achievement {
                padding: 6px 12px;
                background: #4CAF50;
                color: white;
                border-radius: 20px;
                font-size: 12px;
                font-weight: 600;
            }

            .achievement.locked {
                background: #ccc;
                color: #666;
            }

            @media (max-width: 600px) {
                .flashcard {
                    width: 320px;
                    height: 240px;
                }

                .card-text {
                    font-size: 20px;
                }

                .game-header {
                    flex-direction: column;
                    align-items: stretch;
                }

                .session-stats {
                    flex-direction: column;
                    gap: 15px;
                }

                .confidence-buttons {
                    gap: 5px;
                }

                .confidence-btn {
                    padding: 6px 12px;
                    font-size: 11px;
                }
            }
        `;

        document.head.appendChild(style);
    }

    _setupUIEvents() {
        // Mode selector
        const modeSelect = document.getElementById('mode-select');
        if (modeSelect) {
            modeSelect.addEventListener('change', (e) => {
                this._handleModeChange({ data: { mode: e.target.value } });
            });
        }

        // Settings button
        const settingsBtn = document.getElementById('settings-btn');
        if (settingsBtn) {
            settingsBtn.addEventListener('click', () => {
                this._toggleStatisticsPanel();
            });
        }

        // Previous button removed - replaced by Don't know button after reveal

        // Reveal button
        const revealBtn = document.getElementById('reveal-btn');
        if (revealBtn) {
            revealBtn.addEventListener('click', () => {
                this._handleReveal();
            });
        }

        // Flashcard click
        const flashcard = document.getElementById('flashcard');
        if (flashcard) {
            flashcard.addEventListener('click', () => {
                this._handleReveal();
            });
        }

        // Next button removed - cards advance automatically after rating

        // Confidence rating buttons
        const confidenceBtns = document.querySelectorAll('.confidence-btn');
        confidenceBtns.forEach(btn => {
            btn.addEventListener('click', (e) => {
                const rating = e.target.getAttribute('data-rating');
                if (rating) {
                    this._handleRate(rating);
                }
            });
        });

        // Event delegation for dynamic buttons
        if (this._container) {
            this._container.addEventListener('click', (e) => {
                const target = e.target;

                // Handle dynamic buttons that appear in completion messages
                if (target.id === 'session-complete-stop' || target.id === 'no-cards-stop') {
                    this.stop();
                } else if (target.id === 'start-new-session') {
                    this._startNewSession();
                }
            });
        }

        // Keyboard shortcuts
        document.addEventListener('keydown', (e) => {
            if (!this._isActive) return;

            switch(e.code) {
                case 'Space':
                    e.preventDefault();
                    this._handleReveal();
                    break;
                case 'ArrowLeft':
                    e.preventDefault();
                    this._previousCard();
                    break;
                case 'ArrowRight':
                    e.preventDefault();
                    this._handleNext();
                    break;
                case 'Digit1':
                    e.preventDefault();
                    if (this._isRevealed) this._handleRate('again');
                    break;
                case 'Digit2':
                    e.preventDefault();
                    if (this._isRevealed) this._handleRate('hard');
                    break;
                case 'Digit3':
                    e.preventDefault();
                    if (this._isRevealed) this._handleRate('good');
                    break;
                case 'Digit4':
                    e.preventDefault();
                    if (this._isRevealed) this._handleRate('easy');
                    break;
            }
        });
    }

    _updateCardDisplay() {
        if (!this._currentCard) return;

        const flashcard = document.getElementById('flashcard');
        if (!flashcard) return;

        // Cancel any ongoing TTS when changing cards
        ttsService.cancel();

        // Add fade out animation
        flashcard.style.opacity = '0';
        flashcard.style.transform = 'scale(0.9)';
        flashcard.style.transition = 'all 0.3s ease';

        setTimeout(() => {
            // Recreate the front side of the card
            flashcard.innerHTML = `
                <div class="card-front" style="
                    width: 100%;
                    height: 100%;
                    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    border-radius: 12px;
                    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
                    padding: 20px;
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    cursor: pointer;
                    position: relative;
                ">
                    <div style="
                        font-size: 36px;
                        font-weight: bold;
                        text-align: center;
                        color: #2c3e50;
                        margin-bottom: 20px;
                    ">
                        ${this._currentCard.displayFront}
                    </div>
                    <button id="reveal-btn" class="btn-primary" style="
                        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                        color: white;
                        border: none;
                        padding: 12px 24px;
                        border-radius: 8px;
                        font-size: 16px;
                        font-weight: bold;
                        cursor: pointer;
                        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
                        transition: all 0.3s ease;
                    ">
                        Click to Reveal
                    </button>
                </div>
            `;

            // Only setup event listeners for flashcard elements, not all UI
            // Use event delegation and single listener to avoid duplicates
            const revealBtn = document.getElementById('reveal-btn');
            if (revealBtn) {
                revealBtn.addEventListener('click', (e) => {
                    e.stopPropagation(); // Prevent bubbling to flashcard
                    this._handleReveal();
                }, { once: true }); // Remove after first click
            }

            const flashcardElement = document.getElementById('flashcard');
            if (flashcardElement) {
                flashcardElement.addEventListener('click', () => {
                    this._handleReveal();
                }, { once: true }); // Remove after first click
            }

            // Fade in animation
            flashcard.style.opacity = '1';
            flashcard.style.transform = 'scale(1)';

            // Hide difficulty buttons when showing front of new card
            const gameControls = document.querySelector('.game-controls');
            if (gameControls) {
                gameControls.innerHTML = '<!-- Difficulty rating buttons will appear after reveal -->';
            }

            // Update button states
            this._updateButtonStates();

            // Don't auto-play on card display - only play after reveal
        }, 150);
    }

    _updateButtonStates() {
        // Button states are now managed by the reveal/rating system
        // No need to manage prev/next buttons as they have been removed
    }

    _updateProgressIndicator() {
        console.log(`📊 Updating progress indicator: ${this._currentCardIndex + 1} of ${this._sessionCards.length}`);

        const indicator = document.getElementById('progress-indicator');
        const progressFill = document.getElementById('progress-fill');

        if (indicator) {
            indicator.textContent = `Card ${this._currentCardIndex + 1} of ${this._sessionCards.length}`;
        }

        if (progressFill) {
            const progress = ((this._currentCardIndex + 1) / this._sessionCards.length) * 100;
            progressFill.style.width = `${progress}%`;
        }
    }

    _updateSessionStats() {
        const correctCount = document.getElementById('correct-count');
        const incorrectCount = document.getElementById('incorrect-count');
        const accuracy = document.getElementById('accuracy');

        if (correctCount) correctCount.textContent = this._sessionStats.correct;
        if (incorrectCount) incorrectCount.textContent = this._sessionStats.incorrect;

        if (accuracy) {
            const total = this._sessionStats.correct + this._sessionStats.incorrect;
            const accuracyRate = total > 0 ? Math.round((this._sessionStats.correct / total) * 100) : 0;
            accuracy.textContent = `${accuracyRate}%`;
        }
    }

    _updateStatisticsPanel() {
        const contentCoverage = document.getElementById('content-coverage');
        const masteryRate = document.getElementById('mastery-rate');
        const studyStreak = document.getElementById('study-streak');
        const timeStudied = document.getElementById('time-studied');
        const achievementsList = document.getElementById('achievements-list');

        if (contentCoverage) {
            const studiedCount = Object.values(this._progress).filter(p => p.timesStudied > 0).length;
            const totalWords = this._flashcards.length;
            const coveragePercent = totalWords > 0 ? Math.round((studiedCount / totalWords) * 100) : 0;
            contentCoverage.textContent = `${coveragePercent}%`;
        }

        if (masteryRate) {
            const masteredCount = Object.values(this._progress).filter(p => p.masteryLevel === 'mastered').length;
            const totalCount = this._flashcards.length;
            const rate = totalCount > 0 ? Math.round((masteredCount / totalCount) * 100) : 0;
            masteryRate.textContent = `${rate}%`;
        }

        if (studyStreak) {
            studyStreak.textContent = this._globalStats.currentStreak || 0;
        }

        if (timeStudied) {
            const totalMinutes = Math.round((this._globalStats.totalTimeStudied || 0) / (1000 * 60));
            timeStudied.textContent = `${totalMinutes}m`;
        }

        if (achievementsList) {
            achievementsList.innerHTML = this._generateAchievementsHTML();
        }
    }

    _generateAchievementsHTML() {
        const availableAchievements = [
            { id: 'first_study', name: 'First Steps', description: 'Complete your first study session' },
            { id: 'streak_3', name: '3-Day Streak', description: 'Study for 3 consecutive days' },
            { id: 'streak_7', name: 'Week Warrior', description: 'Study for 7 consecutive days' },
            { id: 'master_10', name: 'Mastery Beginner', description: 'Master 10 cards' },
            { id: 'master_50', name: 'Vocabulary Expert', description: 'Master 50 cards' },
            { id: 'speed_demon', name: 'Speed Demon', description: 'Answer 100 cards in a single session' },
            { id: 'perfectionist', name: 'Perfectionist', description: 'Get 100% accuracy in a 20+ card session' }
        ];

        return availableAchievements.map(achievement => {
            const unlocked = this._achievements.includes(achievement.id);
            return `<div class="achievement ${unlocked ? '' : 'locked'}" title="${achievement.description}">
                ${achievement.name}
            </div>`;
        }).join('');
    }

    _toggleStatisticsPanel() {
        const panel = document.getElementById('statistics-panel');
        if (panel) {
            const isVisible = panel.style.display !== 'none';
            panel.style.display = isVisible ? 'none' : 'block';
            if (!isVisible) {
                this._updateStatisticsPanel();
            }
        }
    }

    // Event Handlers
    _handleStart(event) {
        this.start();
    }

    _handleStop(event) {
        this.stop();
    }

    _handleNext(event) {
        if (this._isRevealed) {
            // If revealed, rate as "good" by default and move to next
            this._handleRate('good');
        } else {
            // If not revealed, just move to next card
            this._nextCard();
        }
    }

    _handleReveal(event) {
        if (!this._isActive || !this._currentCard) return;

        // Prevent multiple reveals
        if (this._isRevealed) return;

        const flashcard = document.getElementById('flashcard');

        if (!this._isRevealed) {
            // Add scale animation
            flashcard.style.transform = 'scale(0.95)';
            flashcard.style.transition = 'all 0.3s ease';

            setTimeout(() => {
                // Replace with reveal content
                flashcard.innerHTML = `
                    <div class="card-revealed" style="
                        width: 100%;
                        height: 100%;
                        background: linear-gradient(135deg, #1a4a9c 0%, #0d2b5f 100%);
                        color: white;
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        justify-content: center;
                        border-radius: 12px;
                        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
                        padding: 20px;
                        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    ">
                        <div style="
                            font-size: 24px;
                            margin-bottom: 15px;
                            text-align: center;
                            opacity: 0.7;
                            font-weight: normal;
                        ">
                            ${this._currentCard.displayFront}
                        </div>
                        <div id="answer-tts" style="
                            font-size: 48px;
                            font-weight: bold;
                            margin-bottom: 20px;
                            text-align: center;
                            text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
                            cursor: pointer;
                            transition: all 0.2s ease;
                        " title="Click to hear pronunciation">
                            ${this._currentCard.displayBack}
                        </div>
                        <div id="pronunciation-display" style="
                            font-size: 18px;
                            opacity: 0.8;
                            font-style: italic;
                            transition: all 0.3s ease;
                        ">
                            ${this._currentCard.pronunciation || ''}
                        </div>
                    </div>
                `;

                // Scale back up
                flashcard.style.transform = 'scale(1)';

                this._isRevealed = true;

                // Add click listener on answer for TTS
                const answerTTS = document.getElementById('answer-tts');
                if (answerTTS) {
                    answerTTS.addEventListener('click', () => {
                        // Cancel any ongoing TTS before playing new one
                        ttsService.cancel();
                        this._playAudio(this._currentCard.front);
                        this._highlightPronunciation();
                    });
                    answerTTS.addEventListener('mouseenter', () => {
                        answerTTS.style.transform = 'scale(1.05)';
                        answerTTS.style.color = '#6dd5fa';
                    });
                    answerTTS.addEventListener('mouseleave', () => {
                        answerTTS.style.transform = 'scale(1)';
                        answerTTS.style.color = 'white';
                    });
                }

                // Add difficulty buttons in game-controls section
                const gameControls = document.querySelector('.game-controls');
                if (gameControls) {
                    // Calculate next review times for each confidence level
                    const againTime = this._formatTimeUntilReview(this._calculateNextReviewTime('again'));
                    const hardTime = this._formatTimeUntilReview(this._calculateNextReviewTime('hard'));
                    const goodTime = this._formatTimeUntilReview(this._calculateNextReviewTime('good'));
                    const easyTime = this._formatTimeUntilReview(this._calculateNextReviewTime('easy'));

                    gameControls.innerHTML = `
                        <div style="
                            display: flex;
                            gap: 15px;
                            justify-content: center;
                            margin-top: 20px;
                        ">
                            <button id="dont-know-btn" style="
                                background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
                                color: white;
                                border: none;
                                padding: 10px 20px;
                                border-radius: 8px;
                                font-size: 12px;
                                font-weight: bold;
                                cursor: pointer;
                                box-shadow: 0 3px 10px rgba(231, 76, 60, 0.4);
                                transition: all 0.3s ease;
                                text-align: center;
                                min-width: 80px;
                            ">
                                <div>Don't know</div>
                                <div style="font-size: 10px; opacity: 0.8; margin-top: 3px;">${againTime}</div>
                            </button>
                            <button id="difficult-btn" style="
                                background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);
                                color: white;
                                border: none;
                                padding: 10px 20px;
                                border-radius: 8px;
                                font-size: 12px;
                                font-weight: bold;
                                cursor: pointer;
                                box-shadow: 0 3px 10px rgba(243, 156, 18, 0.4);
                                transition: all 0.3s ease;
                                text-align: center;
                                min-width: 80px;
                            ">
                                <div>Difficult</div>
                                <div style="font-size: 10px; opacity: 0.8; margin-top: 3px;">${hardTime}</div>
                            </button>
                            <button id="normal-btn" style="
                                background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
                                color: white;
                                border: none;
                                padding: 10px 20px;
                                border-radius: 8px;
                                font-size: 12px;
                                font-weight: bold;
                                cursor: pointer;
                                box-shadow: 0 3px 10px rgba(52, 152, 219, 0.4);
                                transition: all 0.3s ease;
                                text-align: center;
                                min-width: 80px;
                            ">
                                <div>Normal</div>
                                <div style="font-size: 10px; opacity: 0.8; margin-top: 3px;">${goodTime}</div>
                            </button>
                            <button id="easy-btn" style="
                                background: linear-gradient(135deg, #27ae60 0%, #229954 100%);
                                color: white;
                                border: none;
                                padding: 10px 20px;
                                border-radius: 8px;
                                font-size: 12px;
                                font-weight: bold;
                                cursor: pointer;
                                box-shadow: 0 3px 10px rgba(39, 174, 96, 0.4);
                                transition: all 0.3s ease;
                                text-align: center;
                                min-width: 80px;
                            ">
                                <div>Easy</div>
                                <div style="font-size: 10px; opacity: 0.8; margin-top: 3px;">${easyTime}</div>
                            </button>
                        </div>
                    `;

                    // Add event listeners for difficulty buttons
                    setTimeout(() => {
                        const dontKnowBtn = document.getElementById('dont-know-btn');
                        const difficultBtn = document.getElementById('difficult-btn');
                        const normalBtn = document.getElementById('normal-btn');
                        const easyBtn = document.getElementById('easy-btn');

                        if (dontKnowBtn) {
                            dontKnowBtn.onclick = () => {
                                console.log('🔴 Clicked Don\'t know');
                                this._handleRate('again');
                            };
                        }
                        if (difficultBtn) {
                            difficultBtn.onclick = () => {
                                console.log('🟠 Clicked Difficult');
                                this._handleRate('hard');
                            };
                        }
                        if (normalBtn) {
                            normalBtn.onclick = () => {
                                console.log('🔵 Clicked Normal');
                                this._handleRate('good');
                            };
                        }
                        if (easyBtn) {
                            easyBtn.onclick = () => {
                                console.log('🟢 Clicked Easy');
                                this._handleRate('easy');
                            };
                        }
                    }, 50);
                }

                // Always play audio for pronunciation, regardless of mode
                setTimeout(() => {
                    this._playAudio(this._currentCard.front);
                    this._highlightPronunciation();
                }, 200);
            }, 150);
        }
    }

    _handleRate(confidence) {
        console.log(`⭐ _handleRate called with: ${confidence}`);
        if (!this._currentCard || !this._isRevealed) return;

        const cardProgress = this._progress[this._currentCard.id];

        // Update card statistics
        cardProgress.timesStudied++;
        cardProgress.lastStudied = Date.now();
        cardProgress.confidenceHistory.push(confidence);

        // Keep only last 10 confidence ratings
        if (cardProgress.confidenceHistory.length > 10) {
            cardProgress.confidenceHistory = cardProgress.confidenceHistory.slice(-10);
        }

        // Update session stats
        this._sessionStats.cardsStudied++;

        if (confidence === 'easy' || confidence === 'good') {
            cardProgress.timesCorrect++;
            this._sessionStats.correct++;
        } else {
            this._sessionStats.incorrect++;
        }

        // Apply spaced repetition algorithm
        this._updateSpacedRepetition(cardProgress, confidence);

        // Update mastery level
        this._updateMasteryLevel(cardProgress);

        // Handle "don't know" cards - add them to retry queue
        if (confidence === 'again') {
            console.log(`❌ Card marked as "don't know", adding to retry queue: ${this._currentCard.id}`);
            console.log(`📊 Current retry queue before adding:`, this._retryCards.map(c => c.id));

            // Add current card to retry queue (avoid duplicates)
            const cardAlreadyInRetry = this._retryCards.some(card => card.id === this._currentCard.id);
            if (!cardAlreadyInRetry) {
                this._retryCards.push({ ...this._currentCard }); // Clone the card
                console.log(`📋 Retry queue now has ${this._retryCards.length} cards:`, this._retryCards.map(c => c.id));
            } else {
                console.log(`⚠️ Card already in retry queue, not adding duplicate`);
            }
        } else {
            console.log(`✅ Card rated as "${confidence}", not adding to retry queue`);
        }

        // Save progress
        this._saveProgress();

        // Update UI
        this._updateSessionStats();

        // Move to next card
        setTimeout(() => {
            console.log(`➡️ Moving to next card from index ${this._currentCardIndex}`);
            this._nextCard();
        }, 500);
    }

    _handleModeChange(event) {
        const newMode = event.data.mode;
        if (this._modes[newMode]) {
            this._currentMode = newMode;
            console.log(`📚 Mode changed to: ${this._modes[newMode]}`);

            // Reload current card with new mode
            if (this._currentCard) {
                this._isRevealed = false;
                this._loadCard(this._currentCardIndex);
            }
        }
    }

    // Spaced Repetition Algorithm
    _updateSpacedRepetition(cardProgress, confidence) {
        const now = Date.now();
        const baseUnitMs = 20 * 60 * 1000; // 20 minutes as base unit

        let multiplier;
        switch (confidence) {
            case 'again':
                multiplier = 0.1; // Review very soon (2 minutes)
                cardProgress.difficultyLevel = Math.max(1, cardProgress.difficultyLevel - 0.5);
                break;
            case 'hard':
                multiplier = 0.5; // Review sooner (10 minutes)
                cardProgress.difficultyLevel = Math.max(1, cardProgress.difficultyLevel - 0.2);
                break;
            case 'good':
                multiplier = 1.0; // Standard interval (20 minutes, 40m, 1h20, etc.)
                cardProgress.difficultyLevel = Math.min(5, cardProgress.difficultyLevel + 0.1);
                break;
            case 'easy':
                multiplier = 2.0; // Extended interval (40 minutes, 1h20, 2h40, etc.)
                cardProgress.difficultyLevel = Math.min(5, cardProgress.difficultyLevel + 0.3);
                break;
        }

        // Calculate next review time based on difficulty level and confidence
        const baseInterval = Math.pow(2, cardProgress.difficultyLevel - 1) * baseUnitMs;
        const interval = baseInterval * multiplier;

        cardProgress.nextReview = now + Math.max(interval, 60000); // Minimum 1 minute
    }

    _calculateNextReviewTime(confidence) {
        if (!this._currentCard) return null;

        const cardProgress = this._progress[this._currentCard.id];
        const now = Date.now();
        const baseUnitMs = 20 * 60 * 1000; // 20 minutes as base unit
        let multiplier;

        switch (confidence) {
            case 'again':
                multiplier = 0.1; // Review very soon (2 minutes)
                break;
            case 'hard':
                multiplier = 0.5; // Review sooner (10 minutes)
                break;
            case 'good':
                multiplier = 1.0; // Standard interval (20 minutes, 40m, 1h20, etc.)
                break;
            case 'easy':
                multiplier = 2.0; // Extended interval (40 minutes, 1h20, 2h40, etc.)
                break;
        }

        const baseInterval = Math.pow(2, cardProgress.difficultyLevel - 1) * baseUnitMs;
        const interval = baseInterval * multiplier;
        const nextReview = now + Math.max(interval, 60000); // Minimum 1 minute

        return nextReview;
    }

    _formatTimeUntilReview(timestamp) {
        if (!timestamp) return '';

        const now = Date.now();
        const diff = timestamp - now;
        const minutes = Math.floor(diff / (60 * 1000));
        const hours = Math.floor(diff / (60 * 60 * 1000));
        const days = Math.floor(diff / (24 * 60 * 60 * 1000));

        if (days > 0) {
            return `${days}j`;
        } else if (hours > 0) {
            return `${hours}h`;
        } else if (minutes > 0) {
            return `${minutes}m`;
        } else {
            return '1m';
        }
    }

    _updateMasteryLevel(cardProgress) {
        const correctRate = cardProgress.timesStudied > 0 ? cardProgress.timesCorrect / cardProgress.timesStudied : 0;
        const recentConfidence = cardProgress.confidenceHistory.slice(-3);
        const previousMasteryLevel = cardProgress.masteryLevel;

        if (cardProgress.timesStudied >= 8 && correctRate >= 0.8 &&
            recentConfidence.length >= 3 && recentConfidence.every(c => c === 'easy' || c === 'good')) {
            cardProgress.masteryLevel = 'mastered';
        } else if (cardProgress.timesStudied >= 3 && correctRate >= 0.6) {
            cardProgress.masteryLevel = 'review';
        } else if (cardProgress.timesStudied > 0) {
            cardProgress.masteryLevel = 'learning';
        } else {
            cardProgress.masteryLevel = 'new';
        }

        // Notify PrerequisiteEngine when word becomes mastered
        if (this._prerequisiteEngine &&
            cardProgress.masteryLevel === 'mastered' &&
            previousMasteryLevel !== 'mastered') {

            console.log(`🎯 Word mastered: ${cardProgress.word} - notifying PrerequisiteEngine`);
            this._prerequisiteEngine.markWordMastered(cardProgress.word, {
                attempts: cardProgress.timesStudied,
                accuracy: correctRate,
                source: 'flashcard-learning'
            });
        }
    }

    // Audio System
    async _playAudio(text) {
        const chapterLanguage = this._content?.language || 'en-US';
        await ttsService.speak(text, chapterLanguage, { rate: 0.8 });
    }

    _highlightPronunciation() {
        // Highlight pronunciation when TTS is played
        const pronunciation = document.getElementById('pronunciation-display');

        if (pronunciation) {
            // Store original styles
            const originalColor = pronunciation.style.color;
            const originalFontSize = pronunciation.style.fontSize;

            // Add highlight
            pronunciation.style.color = '#6dd5fa';
            pronunciation.style.fontWeight = 'bold';
            pronunciation.style.fontSize = '22px';
            pronunciation.style.transform = 'scale(1.1)';

            // Remove highlight after animation
            setTimeout(() => {
                pronunciation.style.color = originalColor;
                pronunciation.style.fontWeight = 'normal';
                pronunciation.style.fontSize = originalFontSize;
                pronunciation.style.transform = 'scale(1)';
            }, 2000);
        }
    }

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

    _previousCard() {
        if (this._currentCardIndex > 0) {
            this._loadCard(this._currentCardIndex - 1);
        }
    }

    // Progress & Statistics Management
    _loadProgress() {
        try {
            const saved = localStorage.getItem(this._progressKey);
            return saved ? JSON.parse(saved) : {};
        } catch (error) {
            console.warn('Failed to load progress:', error);
            return {};
        }
    }

    _saveProgress() {
        try {
            localStorage.setItem(this._progressKey, JSON.stringify(this._progress));
        } catch (error) {
            console.warn('Failed to save progress:', error);
        }
    }

    _loadGlobalStats() {
        try {
            const saved = localStorage.getItem(this._statsKey);
            return saved ? JSON.parse(saved) : {
                totalSessionsCompleted: 0,
                totalCardsStudied: 0,
                totalTimeStudied: 0,
                currentStreak: 0,
                longestStreak: 0,
                lastStudyDate: null
            };
        } catch (error) {
            console.warn('Failed to load global stats:', error);
            return {};
        }
    }

    _saveGlobalStats() {
        try {
            localStorage.setItem(this._statsKey, JSON.stringify(this._globalStats));
        } catch (error) {
            console.warn('Failed to save global stats:', error);
        }
    }

    _loadAchievements() {
        try {
            const saved = localStorage.getItem(this._achievementsKey);
            return saved ? JSON.parse(saved) : [];
        } catch (error) {
            console.warn('Failed to load achievements:', error);
            return [];
        }
    }

    _saveAchievements() {
        try {
            localStorage.setItem(this._achievementsKey, JSON.stringify(this._achievements));
        } catch (error) {
            console.warn('Failed to save achievements:', error);
        }
    }

    _updateGlobalStats() {
        const sessionDuration = Date.now() - this._sessionStats.startTime;

        this._globalStats.totalSessionsCompleted++;
        this._globalStats.totalCardsStudied += this._sessionStats.cardsStudied;
        this._globalStats.totalTimeStudied += sessionDuration;

        // Update study streak
        const today = new Date().toDateString();
        const lastStudy = this._globalStats.lastStudyDate;

        if (lastStudy === today) {
            // Already studied today, no change to streak
        } else if (lastStudy === new Date(Date.now() - 86400000).toDateString()) {
            // Studied yesterday, increment streak
            this._globalStats.currentStreak++;
        } else {
            // Gap in studying, reset streak
            this._globalStats.currentStreak = 1;
        }

        this._globalStats.longestStreak = Math.max(
            this._globalStats.longestStreak,
            this._globalStats.currentStreak
        );
        this._globalStats.lastStudyDate = today;
    }

    _checkAchievements() {
        const newAchievements = [];

        // First study session
        if (this._globalStats.totalSessionsCompleted === 1 &&
            !this._achievements.includes('first_study')) {
            newAchievements.push('first_study');
        }

        // Study streaks
        if (this._globalStats.currentStreak >= 3 &&
            !this._achievements.includes('streak_3')) {
            newAchievements.push('streak_3');
        }

        if (this._globalStats.currentStreak >= 7 &&
            !this._achievements.includes('streak_7')) {
            newAchievements.push('streak_7');
        }

        // Mastery achievements
        const masteredCount = Object.values(this._progress).filter(p => p.masteryLevel === 'mastered').length;

        if (masteredCount >= 10 && !this._achievements.includes('master_10')) {
            newAchievements.push('master_10');
        }

        if (masteredCount >= 50 && !this._achievements.includes('master_50')) {
            newAchievements.push('master_50');
        }

        // Session achievements
        if (this._sessionStats.cardsStudied >= 100 &&
            !this._achievements.includes('speed_demon')) {
            newAchievements.push('speed_demon');
        }

        if (this._sessionStats.cardsStudied >= 20 &&
            this._sessionStats.incorrect === 0 &&
            this._sessionStats.correct === this._sessionStats.cardsStudied &&
            !this._achievements.includes('perfectionist')) {
            newAchievements.push('perfectionist');
        }

        // Add new achievements
        this._achievements.push(...newAchievements);

        // Show achievement notifications
        newAchievements.forEach(achievementId => {
            this._showAchievementNotification(achievementId);
        });
    }

    _showAchievementNotification(achievementId) {
        const achievementNames = {
            'first_study': 'First Steps - Complete your first study session!',
            'streak_3': '3-Day Streak - Keep it up!',
            'streak_7': 'Week Warrior - Amazing dedication!',
            'master_10': 'Mastery Beginner - 10 cards mastered!',
            'master_50': 'Vocabulary Expert - 50 cards mastered!',
            'speed_demon': 'Speed Demon - 100 cards in one session!',
            'perfectionist': 'Perfectionist - Perfect score on 20+ cards!'
        };

        const message = achievementNames[achievementId] || 'New Achievement Unlocked!';
        console.log(`🏆 Achievement Unlocked: ${message}`);

        // Show visual notification (you could enhance this with a toast notification)
        if (window.alert) {
            setTimeout(() => {
                alert(`🏆 Achievement Unlocked!\n${message}`);
            }, 1000);
        }
    }

    // Show Messages
    _showNoContentMessage() {
        this._container.innerHTML = `
            <div class="no-content-message">
                <h3>🎴 No Content Available</h3>
                <p>There's no vocabulary or sentence content available for flashcard learning in this chapter.</p>
                <p>Please select a chapter with vocabulary words or sentences to study.</p>
                <button onclick="window.app.getCore().router.navigate('/chapters')" class="btn-primary">
                    Choose Chapter
                </button>
            </div>
        `;
    }

    _showNoCardsMessage() {
        this._container.innerHTML = `
            <div class="no-cards-message">
                <h3>📚 All Caught Up!</h3>
                <p>You've reviewed all available cards for today.</p>
                <p>Great job! Come back tomorrow for more practice.</p>
                <div class="stats-summary">
                    <p><strong>Cards Mastered:</strong> ${Object.values(this._progress).filter(p => p.masteryLevel === 'mastered').length}</p>
                    <p><strong>Study Streak:</strong> ${this._globalStats.currentStreak} days</p>
                </div>
                <button id="session-complete-stop" class="btn-primary">
                    Back to Games
                </button>
            </div>
        `;
    }

    _showSessionComplete() {
        const accuracy = this._sessionStats.total > 0 ?
            Math.round((this._sessionStats.correct / this._sessionStats.total) * 100) : 0;

        const sessionTime = Math.round((Date.now() - this._sessionStats.startTime) / 1000 / 60);

        // Check if there's more content to study
        if (this._hasRemainingContent()) {
            // Show brief completion message and continue automatically
            this._container.innerHTML = `
                <div class="session-complete">
                    <h2>🎉 Session Complete!</h2>
                    <div class="completion-stats">
                        <div class="stat-item">
                            <div class="stat-number">${this._sessionStats.total}</div>
                            <div class="stat-label">Cards Studied</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-number">${accuracy}%</div>
                            <div class="stat-label">Accuracy</div>
                        </div>
                    </div>
                    <div class="continuation-message">
                        <p>📚 Continuing with next batch...</p>
                        <div class="loading-indicator">●●●</div>
                    </div>
                </div>
            `;

            // Wait 2 seconds then continue with next session
            setTimeout(() => {
                this._startNewSession();
            }, 2000);
        } else {
            // All content completed - show final completion
            this._container.innerHTML = `
                <div class="session-complete">
                    <h2>🎉 All Content Completed!</h2>
                    <div class="completion-stats">
                        <div class="stat-item">
                            <div class="stat-number">100%</div>
                            <div class="stat-label">Content Coverage</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-number">${accuracy}%</div>
                            <div class="stat-label">Final Accuracy</div>
                        </div>
                    </div>

                    <div class="mastery-progress">
                        <h4>Final Progress Overview</h4>
                        ${this._generateMasteryProgressHTML()}
                    </div>

                    <div class="session-actions">
                        <button id="session-complete-stop" class="btn-primary">
                            Back to Games
                        </button>
                    </div>
                </div>
            `;
        }

        this._endSession();
    }

    _generateMasteryProgressHTML() {
        const levels = { new: 0, learning: 0, review: 0, mastered: 0 };

        Object.values(this._progress).forEach(progress => {
            levels[progress.masteryLevel]++;
        });

        const total = Object.values(levels).reduce((a, b) => a + b, 0);

        return Object.entries(levels).map(([level, count]) => {
            const percentage = total > 0 ? Math.round((count / total) * 100) : 0;
            const levelNames = {
                new: 'New',
                learning: 'Learning',
                review: 'Review',
                mastered: 'Mastered'
            };

            return `
                <div class="mastery-item">
                    <span class="mastery-label">${levelNames[level]}:</span>
                    <span class="mastery-count">${count} (${percentage}%)</span>
                </div>
            `;
        }).join('');
    }

    _startNewSession() {
        this._setupSession();
        this._createGameUI();
        this._startSession();
    }

    _showRetryPhaseMessage(retryCount) {
        const flashcard = document.getElementById('flashcard');
        if (!flashcard) return;

        flashcard.innerHTML = `
            <div style="
                width: 100%;
                height: 100%;
                background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
                color: white;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                border-radius: 12px;
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
                text-align: center;
                padding: 20px;
            ">
                <div style="font-size: 4rem; margin-bottom: 20px;">🔄</div>
                <div style="font-size: 1.5rem; font-weight: 700; margin-bottom: 10px;">
                    Retry Phase
                </div>
                <div style="font-size: 1rem; opacity: 0.9; line-height: 1.5;">
                    Let's review the ${retryCount} card${retryCount > 1 ? 's' : ''} you marked as "don't know"
                </div>
                <div style="font-size: 0.9rem; opacity: 0.7; margin-top: 15px;">
                    Starting in 2 seconds...
                </div>
            </div>
        `;

        // Show the retry message for 2 seconds, then continue
        setTimeout(() => {
            console.log(`🔄 Starting retry phase - showing card: ${this._currentCard?.id}`);

            // Set up the card display properties before showing
            const shouldShowEnglishFirst = this._shouldShowEnglishFirst();

            if (shouldShowEnglishFirst) {
                this._currentCard.displayFront = this._currentCard.back; // English first
                this._currentCard.displayBack = this._currentCard.front; // Translation revealed
            } else {
                this._currentCard.displayFront = this._currentCard.front; // Translation first
                this._currentCard.displayBack = this._currentCard.back; // English revealed
            }

            this._updateCardDisplay();
            this._updateProgressIndicator();
        }, 2000);
    }
}

export default FlashcardLearning;