/**
 * UnifiedDRS - Modern DRS implementation using extracted UI components
 * Replaces individual DRS modules with a unified, component-based approach
 */

import Module from '../core/Module.js';
import componentRegistry from '../components/ComponentRegistry.js';
import ContentDependencyAnalyzer from './services/ContentDependencyAnalyzer.js';
import exerciseFactory from './factories/ExerciseFactory.js';

class UnifiedDRS extends Module {
    constructor(name, dependencies, config) {
        super(name, ['eventBus', 'contentLoader']);

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

        this._eventBus = dependencies.eventBus;
        this._contentLoader = dependencies.contentLoader;
        this._config = {
            exerciseTypes: ['reading-comprehension-AI', 'listening-comprehension-AI', 'visual-description-AI', 'grammar-practice-AI'],
            defaultDifficulty: 'medium',
            showProgress: true,
            showHints: true,
            autoNext: false,
            ...config
        };

        // UI state
        this._currentExercise = null;
        this._currentStep = 0;
        this._totalSteps = 0;
        this._userProgress = {
            correct: 0,
            total: 0,
            hints: 0,
            timeSpent: 0
        };

        // Content dependency analysis
        this._dependencyAnalyzer = null; // Initialized in init() when prerequisites are available

        // Debug & Monitoring
        this._sessionStats = {
            startTime: Date.now(),
            modulesCompleted: [],
            modulesFailed: [],
            totalExercises: 0,
            totalCorrect: 0,
            averageScore: 0,
            timePerModule: {},
            userFailures: [],
            retryCount: 0
        };

        // Module tracking
        this._moduleQueue = [];
        this._completedModules = new Set();
        this._failedModules = new Map(); // module -> failure count
        this._moduleWorkload = new Map(); // module -> estimated work units

        // Component instances
        this._components = {
            mainCard: null,
            progressBar: null,
            nextButton: null,
            hintButton: null,
            hintPanel: null,
            resultPanel: null
        };

        // Expose debug methods globally for console access
        if (typeof window !== 'undefined') {
            window.drsDebug = {
                getInfo: () => this.getDebugInfo(),
                logState: () => this.logDebugState(),
                getProgress: () => this.getProgressSummary(),
                instance: this
            };
        }

        // Container and timing
        this._container = null;
        this._isActive = false;
        this._startTime = null;
        this._currentModule = null; // For storing current exercise module reference

        // AI interface state
        this._userResponses = [];
        this._currentDialogIndex = 0;
        this._dialogues = [];

        // Config storage for vocabulary override detection
        this._lastConfig = null;

        // Shared PrerequisiteEngine (to avoid creating multiple instances)
        this._sharedPrerequisiteEngine = null;

        Object.seal(this);
    }

    async init() {
        this._validateNotDestroyed();

        console.log('🎓 Initializing Unified DRS...');

        // Initialize component registry
        await componentRegistry.init();

        // Set up event listeners
        this._eventBus.on('drs:start', this._handleStart.bind(this), this.name);
        this._eventBus.on('drs:next', this._handleNext.bind(this), this.name);
        this._eventBus.on('drs:hint', this._handleHint.bind(this), this.name);
        this._eventBus.on('drs:submit', this._handleSubmit.bind(this), this.name);
        this._eventBus.on('content:loaded', this._handleContentLoaded.bind(this), this.name);

        // Advanced DRS events
        this._eventBus.on('drs:exerciseCompleted', this._handleExerciseCompleted.bind(this), this.name);
        this._eventBus.on('drs:requestNextModule', this._handleRequestNextModule.bind(this), this.name);

        this._setInitialized();
        console.log('✅ Unified DRS initialized');
    }

    async destroy() {
        this._validateNotDestroyed();

        console.log('🧹 Destroying Unified DRS...');

        // Clean up current module
        if (this._currentModule && typeof this._currentModule.cleanup === 'function') {
            await this._currentModule.cleanup();
        }
        this._currentModule = null;

        // Clean up UI
        this._cleanupUI();

        // Clean up components
        Object.values(this._components).forEach(component => {
            if (component && componentRegistry) {
                componentRegistry.destroy(component);
            }
        });

        this._setDestroyed();
        console.log('✅ Unified DRS destroyed');
    }

    // Public API

    /**
     * Start a new exercise session
     * @param {HTMLElement} container - Container element
     * @param {Object} exerciseConfig - Exercise configuration
     */
    async start(container, exerciseConfig = {}) {
        this._validateInitialized();

        if (!container) {
            throw new Error('Container element is required');
        }

        console.log('🎯 Starting Unified DRS exercise...');

        this._container = container;
        this._currentStep = 0;
        this._totalSteps = 0;
        this._userProgress = { correct: 0, total: 0, hints: 0, timeSpent: 0 };
        this._isActive = true;

        // Store config for vocabulary override detection
        this._lastConfig = exerciseConfig;

        const exerciseType = exerciseConfig.type || this._config.exerciseTypes[0];

        // Priority 1: Check if we need word discovery first (first-time exposure)
        if (await this._shouldUseWordDiscovery(exerciseType, exerciseConfig)) {
            console.log(`📖 Using Word Discovery for ${exerciseType} (first-time word exposure)`);
            await this._loadWordDiscoveryModule(exerciseType, exerciseConfig);
            return;
        }

        // Priority 2: Check if we need intelligent vocabulary learning (review/mastery - Smart System)
        if (await this._shouldUseVocabularyModule(exerciseType, exerciseConfig)) {
            console.log(`📚 Using Smart VocabularyModule for ${exerciseType} (vocabulary review/mastery)`);
            await this._loadVocabularyModule(exerciseType, exerciseConfig);
            return;
        }

        if (this._shouldUseAIAnalysis(exerciseType, exerciseConfig)) {
            console.log(`🤖 Using AI Analysis Module for ${exerciseType}`);
            await this._loadAIAnalysisModule(exerciseType, exerciseConfig);
            return;
        }

        // Load traditional exercise content
        const content = await this._loadExerciseContent(exerciseType, exerciseConfig);

        if (!content) {
            throw new Error(`Failed to load exercise content for type: ${exerciseType}`);
        }

        this._currentExercise = content;
        this._totalSteps = content.steps ? content.steps.length : 1;

        // Create UI
        await this._createUI();

        // Start first step
        this._showCurrentStep();

        // Start timing
        this._startTime = Date.now();

        // Emit started event
        this._eventBus.emit('drs:started', {
            type: exerciseType,
            steps: this._totalSteps,
            config: exerciseConfig
        }, this.name);

        console.log(`✅ Exercise started: ${exerciseType} (${this._totalSteps} steps)`);
    }

    /**
     * Get current progress
     */
    getProgress() {
        return {
            currentStep: this._currentStep + 1,
            totalSteps: this._totalSteps,
            percentage: this._totalSteps > 0 ? Math.round(((this._currentStep + 1) / this._totalSteps) * 100) : 0,
            userStats: { ...this._userProgress },
            timeSpent: this._startTime ? Date.now() - this._startTime : 0
        };
    }

    /**
     * Check if exercise is currently active
     */
    isActive() {
        return this._isActive;
    }

    // Private methods

    /**
     * Extract real dialogues from chapter content
     */
    _extractRealDialogues(chapterContent) {
        let dialogues = [];

        // Check different possible locations for dialogues
        if (chapterContent.dialogs) {
            // Convert dialogs object to array (SBS format)
            Object.entries(chapterContent.dialogs).forEach(([id, dialog]) => {
                if (dialog.lines && Array.isArray(dialog.lines)) {
                    // SBS format: lines array with speaker/text objects
                    const formattedContent = dialog.lines
                        .map(line => `${line.speaker}: ${line.text}`)
                        .join('\n');

                    dialogues.push({
                        id: id,
                        title: dialog.title || `Dialog ${id}`,
                        content: formattedContent,
                        speakers: dialog.participants || []
                    });
                } else if (dialog.content || dialog.conversation) {
                    // Other formats
                    dialogues.push({
                        id: id,
                        title: dialog.title || `Dialog ${id}`,
                        content: dialog.content || dialog.conversation,
                        speakers: dialog.speakers || []
                    });
                }
            });
        }

        if (chapterContent.conversations) {
            chapterContent.conversations.forEach((conv, index) => {
                dialogues.push({
                    id: `conv_${index}`,
                    title: conv.title || `Conversation ${index + 1}`,
                    content: conv.dialog || conv.content,
                    speakers: conv.speakers || []
                });
            });
        }

        // Check if content has steps with text/passage
        if (chapterContent.steps && chapterContent.steps.length > 0) {
            chapterContent.steps.forEach((step, index) => {
                if (step.content && (step.content.passage || step.content.text)) {
                    dialogues.push({
                        id: `step_${index}`,
                        title: step.title || `Reading ${index + 1}`,
                        content: step.content.passage || step.content.text,
                        speakers: []
                    });
                }
            });
        }

        // Check for direct text content
        if (chapterContent.content && typeof chapterContent.content === 'string') {
            dialogues.push({
                id: 'main_content',
                title: chapterContent.title || 'Chapter Text',
                content: chapterContent.content,
                speakers: []
            });
        }

        // Check for passage field
        if (chapterContent.passage) {
            dialogues.push({
                id: 'passage',
                title: chapterContent.title || 'Reading Passage',
                content: chapterContent.passage,
                speakers: []
            });
        }

        // Check for text field
        if (chapterContent.text) {
            dialogues.push({
                id: 'text_content',
                title: chapterContent.title || 'Text Content',
                content: chapterContent.text,
                speakers: []
            });
        }

        console.log(`📚 Extracted ${dialogues.length} text content pieces from chapter`);
        return dialogues;
    }

    /**
     * Format dialog for proper display with line breaks
     */
    _formatDialogForDisplay(dialog) {
        if (!dialog || !dialog.content) {
            return '<p>No dialog content available</p>';
        }

        let content = dialog.content;

        // Handle different dialog formats
        if (typeof content === 'string') {
            // Split on common speaker patterns
            content = content
                .replace(/\n\n/g, '\n') // Remove double newlines
                .split(/\n(?=[A-Z][a-z]*\s*:)/g) // Split on "Speaker:" patterns
                .map(line => {
                    line = line.trim();
                    if (line.includes(':')) {
                        // Speaker line
                        const [speaker, ...textParts] = line.split(':');
                        return `<div class="dialog-line">
                            <span class="speaker">${speaker.trim()}:</span>
                            <span class="text">${textParts.join(':').trim()}</span>
                        </div>`;
                    } else {
                        // Narrative or continuation
                        return `<div class="dialog-narrative">${line}</div>`;
                    }
                })
                .join('');
        } else if (Array.isArray(content)) {
            // Array of dialog objects
            content = content
                .map(line => {
                    if (line.speaker && line.text) {
                        return `<div class="dialog-line">
                            <span class="speaker">${line.speaker}:</span>
                            <span class="text">${line.text}</span>
                        </div>`;
                    } else {
                        return `<div class="dialog-narrative">${line.text || line}</div>`;
                    }
                })
                .join('');
        }

        return content || '<p>Dialog content could not be formatted</p>';
    }

    /**
     * Add CSS styling for AI analysis interface
     */
    _addAIAnalysisStyles() {
        const existingStyle = document.getElementById('ai-analysis-styles');
        if (existingStyle) return;

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

            .ai-header {
                text-align: center;
                margin-bottom: 30px;
                padding: 20px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border-radius: 12px;
            }

            .ai-header h2 {
                margin: 0 0 10px 0;
                font-size: 24px;
            }

            .chapter-info {
                font-size: 14px;
                opacity: 0.9;
            }

            .dialog-content {
                background: #f8f9fa;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 25px;
                border-left: 4px solid #007bff;
            }

            .dialog-content h3 {
                margin: 0 0 15px 0;
                color: #333;
            }

            .dialog-text {
                background: white;
                padding: 15px;
                border-radius: 6px;
                line-height: 1.6;
                border: 1px solid #e0e0e0;
                max-height: 300px;
                overflow-y: auto;
            }

            .dialog-line {
                margin-bottom: 8px;
                display: flex;
                gap: 10px;
            }

            .speaker {
                font-weight: bold;
                color: #0066cc;
                min-width: 80px;
                flex-shrink: 0;
            }

            .text {
                flex: 1;
            }

            .dialog-narrative {
                font-style: italic;
                color: #666;
                margin: 5px 0;
                padding-left: 20px;
            }

            .analysis-section {
                background: white;
                border-radius: 8px;
                padding: 20px;
                border: 1px solid #e0e0e0;
                margin-bottom: 25px;
            }

            .analysis-section h3 {
                margin: 0 0 15px 0;
                color: #333;
            }

            .question-text {
                background: #e8f4f8;
                padding: 15px;
                border-radius: 6px;
                margin-bottom: 20px;
                font-weight: 500;
                border-left: 3px solid #17a2b8;
            }

            .response-area textarea {
                width: 100%;
                padding: 12px;
                border: 2px solid #e0e0e0;
                border-radius: 6px;
                resize: vertical;
                font-family: inherit;
                font-size: 14px;
                transition: border-color 0.3s;
            }

            .response-area textarea:focus {
                outline: none;
                border-color: #007bff;
            }

            .input-info {
                display: flex;
                justify-content: space-between;
                margin: 8px 0 15px 0;
                font-size: 12px;
                color: #666;
            }

            .submit-btn {
                background: #28a745;
                color: white;
                border: none;
                padding: 12px 24px;
                border-radius: 6px;
                font-size: 16px;
                cursor: pointer;
                transition: background-color 0.3s;
            }

            .submit-btn:hover:not(:disabled) {
                background: #218838;
            }

            .submit-btn:disabled {
                background: #ccc;
                cursor: not-allowed;
            }

            .feedback-section {
                background: white;
                border-radius: 8px;
                padding: 20px;
                border: 1px solid #e0e0e0;
            }

            .feedback-section h3 {
                margin: 0 0 15px 0;
                color: #333;
            }

            .feedback-content {
                margin-bottom: 20px;
            }

            .feedback-score {
                display: flex;
                justify-content: space-between;
                background: #d4edda;
                padding: 10px 15px;
                border-radius: 6px;
                margin-bottom: 15px;
                border-left: 3px solid #28a745;
            }

            .score-value {
                font-weight: bold;
                font-size: 18px;
                color: #155724;
            }

            .feedback-positive {
                background: #d4edda;
                color: #155724;
                padding: 15px;
                border-radius: 6px;
                border-left: 3px solid #28a745;
            }

            .feedback-needs-improvement {
                background: #f8d7da;
                color: #721c24;
                padding: 15px;
                border-radius: 6px;
                border-left: 3px solid #dc3545;
            }

            .ai-error {
                text-align: center;
                padding: 40px 20px;
                background: #f8d7da;
                border-radius: 8px;
                color: #721c24;
            }

            .retry-btn {
                background: #007bff;
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: 6px;
                cursor: pointer;
                margin-top: 15px;
            }

            .action-buttons {
                display: flex;
                gap: 10px;
            }

            .action-buttons button {
                padding: 10px 20px;
                border: none;
                border-radius: 6px;
                cursor: pointer;
                font-size: 14px;
            }

            .next-button {
                background: #007bff;
                color: white;
            }

            .finish-button {
                background: #28a745;
                color: white;
            }
        `;

        document.head.appendChild(style);
    }

    /**
     * Setup AI interface event handlers
     */
    _setupAIInterface(dialogues, chapterContent) {
        const userResponse = document.getElementById('userResponse');
        const submitButton = document.getElementById('submitResponse');
        const charCount = document.getElementById('charCount');

        // Initialize instance variables
        this._dialogues = dialogues;
        this._currentDialogIndex = 0;
        this._userResponses = [];

        // Character count and submit button management
        userResponse.addEventListener('input', () => {
            const length = userResponse.value.length;
            charCount.textContent = length;

            // Color coding for character count
            if (length < 30) {
                charCount.style.color = '#dc3545';
            } else if (length > 450) {
                charCount.style.color = '#ffc107';
            } else {
                charCount.style.color = '#28a745';
            }

            // Enable/disable submit button
            submitButton.disabled = length < 30;
        });

        // Submit response for AI validation
        submitButton.addEventListener('click', async () => {
            const responseText = userResponse.value.trim();
            if (responseText.length < 30) {
                alert('Please write a more detailed response (minimum 30 characters).');
                return;
            }

            // Disable UI during validation
            userResponse.disabled = true;
            submitButton.disabled = true;
            submitButton.textContent = '🔄 Getting AI Feedback...';

            try {
                // Use the shared IAEngine for validation
                const iaEngine = await this._contentLoader._getIAEngine();

                const validationResult = await iaEngine.validateComprehension(
                    this._dialogues[this._currentDialogIndex].content,
                    responseText,
                    {
                        difficulty: 'medium',
                        language: 'English',
                        context: 'dialog analysis'
                    }
                );

                // Store response
                this._userResponses.push({
                    dialogId: this._dialogues[this._currentDialogIndex].id,
                    question: document.getElementById('questionText').textContent,
                    response: responseText,
                    result: validationResult,
                    timestamp: new Date().toISOString()
                });

                // Display AI feedback
                this._displayAIFeedback(validationResult, this._currentDialogIndex, this._dialogues.length);

            } catch (error) {
                console.error('❌ AI validation failed:', error);
                this._displayAIFeedback({
                    success: false,
                    score: 0,
                    feedback: 'Unable to get AI feedback due to technical issues. Please try again.',
                    error: error.message
                }, currentDialogIndex, dialogues.length);
            }

            // Re-enable UI
            userResponse.disabled = false;
            submitButton.textContent = '🔍 Get AI Feedback';
            this._updateSubmitButtonState();
        });

        console.log('✅ AI interface event handlers set up');
    }

    /**
     * Display AI feedback and scoring
     */
    _displayAIFeedback(result, currentIndex, totalDialogs) {
        const feedbackSection = document.getElementById('feedbackSection');
        const feedbackContent = document.getElementById('feedbackContent');
        const actionButtons = document.getElementById('actionButtons');

        let feedbackHTML = '';

        if (result.success && result.score !== undefined) {
            const scorePercent = Math.round((result.score || 0) * 100);
            feedbackHTML = `
                <div class="feedback-score">
                    <span>AI Quality Score:</span>
                    <span class="score-value">${scorePercent}%</span>
                </div>
                <div class="feedback-positive">
                    <strong>✅ AI Analysis:</strong><br>
                    ${result.feedback || 'Good analysis of the dialog content!'}
                </div>
            `;
        } else {
            feedbackHTML = `
                <div class="feedback-needs-improvement">
                    <strong>💡 AI Feedback:</strong><br>
                    ${result.feedback || 'Your response could be improved. Try to be more specific about the dialog content.'}
                </div>
            `;
        }

        if (result.error) {
            feedbackHTML += `
                <div class="feedback-error" style="background: #f8d7da; color: #721c24; padding: 10px; border-radius: 6px; margin-top: 10px;">
                    <strong>⚠️ Technical Issue:</strong> ${result.error}
                </div>
            `;
        }

        feedbackContent.innerHTML = feedbackHTML;

        // Action buttons with proper event handlers
        actionButtons.innerHTML = '';

        if (currentIndex < totalDialogs - 1) {
            const nextButton = document.createElement('button');
            nextButton.className = 'next-button';
            nextButton.innerHTML = '➡️ Next Dialog';
            nextButton.addEventListener('click', () => {
                // Move to next dialog
                this._currentDialogIndex++;

                if (this._currentDialogIndex < this._dialogues.length) {
                    // Update dialog display
                    const dialogText = document.getElementById('dialogText');
                    const chapterInfo = document.querySelector('.chapter-info');

                    dialogText.innerHTML = this._formatDialogForDisplay(this._dialogues[this._currentDialogIndex]);
                    chapterInfo.innerHTML = `
                        <strong>Chapter:</strong> ${this._dialogues[this._currentDialogIndex].title} |
                        <strong>Dialog:</strong> ${this._currentDialogIndex + 1} of ${this._dialogues.length}
                    `;

                    // Reset response area
                    document.getElementById('userResponse').value = '';
                    document.getElementById('charCount').textContent = '0';
                    document.getElementById('submitResponse').disabled = true;

                    // Hide feedback section
                    document.getElementById('feedbackSection').style.display = 'none';

                    console.log(`📖 Moved to dialog ${this._currentDialogIndex + 1}/${this._dialogues.length}`);
                }
            });
            actionButtons.appendChild(nextButton);
        } else {
            const finishButton = document.createElement('button');
            finishButton.className = 'finish-button';
            finishButton.innerHTML = '🎉 Finish Analysis';
            finishButton.addEventListener('click', () => {
                // Emit completion event via EventBus
                this._eventBus.emit('drs:completed', {
                    moduleType: 'ai-text-analysis',
                    responses: this._userResponses,
                    totalDialogs: totalDialogs,
                    timestamp: new Date().toISOString()
                }, this.name);

                // Show completion message
                const completionMessage = document.createElement('div');
                completionMessage.className = 'completion-message';
                completionMessage.style.cssText = `
                    background: #d4edda;
                    color: #155724;
                    padding: 20px;
                    border-radius: 8px;
                    margin-top: 20px;
                    text-align: center;
                    border: 1px solid #c3e6cb;
                `;
                completionMessage.innerHTML = `
                    <h3>🎉 Analysis Complete!</h3>
                    <p>You have successfully analyzed all available dialogues.</p>
                    <p><strong>Total responses:</strong> ${this._userResponses.length}</p>
                `;

                this._container.appendChild(completionMessage);
                finishButton.disabled = true;
                finishButton.textContent = '✅ Completed';

                console.log('🎉 AI Text Analysis completed:', this._userResponses);
            });
            actionButtons.appendChild(finishButton);
        }

        // Show feedback section
        feedbackSection.style.display = 'block';
        feedbackSection.scrollIntoView({ behavior: 'smooth' });

        console.log('📊 AI feedback displayed:', {
            success: result.success,
            score: result.score,
            hasError: !!result.error
        });
    }

    /**
     * Update submit button state based on input
     */
    _updateSubmitButtonState() {
        const userResponse = document.getElementById('userResponse');
        const submitButton = document.getElementById('submitResponse');

        if (userResponse && submitButton) {
            const length = userResponse.value.length;
            submitButton.disabled = length < 30;
        }
    }

    /**
     * Check if we should use AI Analysis modules instead of traditional QCM
     */
    _shouldUseAIAnalysis(exerciseType, config) {
        // Only use AI Analysis for text and grammar exercises
        // Audio and image exercises need real media files
        return exerciseType === 'reading-comprehension-AI' ||
               exerciseType === 'grammar-practice-AI';
    }

    /**
     * Check if we should use Word Discovery system first
     */
    async _shouldUseWordDiscovery(exerciseType, config) {
        // Always use word discovery for vocabulary-discovery type
        if (exerciseType === 'vocabulary-discovery') {
            return true;
        }

        // Force word discovery if there are undiscovered words
        try {
            // Get or reuse shared PrerequisiteEngine
            let prerequisiteEngine = null;

            try {
                const moduleLoader = window.app.getCore().moduleLoader;
                const orchestrator = moduleLoader.getModule('smartPreviewOrchestrator');
                prerequisiteEngine = orchestrator?.sharedServices?.prerequisiteEngine;
            } catch (error) {
                console.log('Could not get prerequisiteEngine from orchestrator:', error.message);
            }

            // Use shared instance if available, create if needed
            if (!prerequisiteEngine) {
                if (this._sharedPrerequisiteEngine) {
                    console.log('♻️ Reusing shared PrerequisiteEngine for word discovery check');
                    prerequisiteEngine = this._sharedPrerequisiteEngine;
                } else {
                    console.log('🔧 Creating shared PrerequisiteEngine for word discovery check');
                    const { default: PrerequisiteEngine } = await import('./services/PrerequisiteEngine.js');
                    prerequisiteEngine = new PrerequisiteEngine();
                    await prerequisiteEngine.init(config.bookId, config.chapterId);
                    this._sharedPrerequisiteEngine = prerequisiteEngine;
                    console.log('✅ Shared PrerequisiteEngine created and stored');
                }
            }

            // Load chapter content if not already loaded
            let chapterContent = config.chapterContent;
            if (!chapterContent && config.chapterId) {
                console.log(`📚 Loading chapter content for word discovery check: ${config.chapterId}`);
                chapterContent = await this._contentLoader.getContent(config.chapterId);
            }

            if (chapterContent && chapterContent.vocabulary) {
                const allWords = Object.keys(chapterContent.vocabulary);
                const undiscoveredWords = allWords.filter(word =>
                    !prerequisiteEngine.isDiscovered(word)
                );

                console.log(`📖 Word discovery check: ${undiscoveredWords.length}/${allWords.length} words undiscovered`);

                if (undiscoveredWords.length > 0) {
                    console.log(`🔄 Forcing WordDiscovery for ${undiscoveredWords.length} undiscovered words`);

                    // Signal vocabulary override to Smart Guide UI
                    window.vocabularyOverrideActive = {
                        originalType: exerciseType,
                        reason: `Word Discovery required - ${undiscoveredWords.length} new words to discover`,
                        missingWords: undiscoveredWords.slice(0, 10), // Show first 10
                        totalMissing: undiscoveredWords.length,
                        mode: 'discovery' // Passive discovery, not flashcards
                    };
                    console.log('📖 Word Discovery override signaled to Smart Guide:', window.vocabularyOverrideActive);

                    return true;
                } else {
                    console.log(`✅ All ${allWords.length} words already discovered, skipping WordDiscovery`);
                }
            }
        } catch (error) {
            console.error('❌ Error checking word discovery status:', error);
        }

        return false;
    }

    /**
     * Check if we should use DRS VocabularyModule (integrated flashcard system)
     * NEW: Uses intelligent content dependency analysis
     */
    async _shouldUseVocabularyModule(exerciseType, config) {
        // Always use VocabularyModule for vocabulary-flashcards type
        if (exerciseType === 'vocabulary-flashcards') {
            return true;
        }

        try {
            console.log('🔍 Analyzing content dependencies for intelligent vocabulary override...');

            // 1. Load the real chapter content first using apiService
            const { default: apiService } = await import('../services/APIService.js');
            const chapterContent = await apiService.loadChapter(config.chapterId);

            if (!chapterContent) {
                console.log('⚠️ No chapter content available for analysis');
                return await this._fallbackMasteryCheck(config);
            }

            // 2. Get real vocabulary from chapter (not from engine)
            const vocabularyWords = chapterContent.vocabulary ? Object.keys(chapterContent.vocabulary) : [];
            console.log('📚 Chapter vocabulary loaded:', vocabularyWords.length, 'words');

            if (vocabularyWords.length === 0) {
                console.log('📚 No vocabulary in chapter, skipping analysis');
                return false;
            }

            // 3. Extract text content for analysis
            const textSources = [];

            if (chapterContent.dialogs) {
                Object.values(chapterContent.dialogs).forEach(dialog => {
                    if (dialog.lines && Array.isArray(dialog.lines)) {
                        textSources.push(...dialog.lines);
                    }
                });
            }

            if (chapterContent.lessons) {
                Object.values(chapterContent.lessons).forEach(lesson => {
                    if (lesson.content) textSources.push(lesson.content);
                    if (lesson.text) textSources.push(lesson.text);
                });
            }

            const contentToAnalyze = {
                type: 'chapter-content',
                text: textSources.join(' '),
                metadata: { source: 'real-chapter-content' }
            };

            console.log('📖 Extracted content for analysis:', textSources.length, 'text sources');

            // 4. Initialize dependency analyzer with shared PrerequisiteEngine
            if (!this._dependencyAnalyzer) {
                let prerequisiteEngine = null;

                try {
                    const moduleLoader = window.app.getCore().moduleLoader;
                    const orchestrator = moduleLoader.getModule('smartPreviewOrchestrator');
                    prerequisiteEngine = orchestrator?.sharedServices?.prerequisiteEngine;
                } catch (error) {
                    console.log('Could not get prerequisiteEngine from orchestrator:', error.message);
                }

                // Use shared instance if available, create if needed
                if (!prerequisiteEngine) {
                    if (this._sharedPrerequisiteEngine) {
                        console.log('♻️ Reusing shared PrerequisiteEngine for dependency analysis');
                        prerequisiteEngine = this._sharedPrerequisiteEngine;
                    } else {
                        console.log('🔧 Creating shared PrerequisiteEngine for dependency analysis');
                        const { default: PrerequisiteEngine } = await import('./services/PrerequisiteEngine.js');
                        prerequisiteEngine = new PrerequisiteEngine();

                        // Initialize with current chapter data
                        await prerequisiteEngine.init(config.bookId, config.chapterId);
                        this._sharedPrerequisiteEngine = prerequisiteEngine;
                        console.log('✅ Shared PrerequisiteEngine created and stored');
                    }
                }

                this._dependencyAnalyzer = new ContentDependencyAnalyzer(prerequisiteEngine);
                console.log('🧠 ContentDependencyAnalyzer initialized with shared PrerequisiteEngine');
            }

            // 5. Create vocabulary module with real data
            const vocabularyModule = {
                getVocabularyWords: () => vocabularyWords
            };

            // 6. Perform analysis
            const analysis = this._dependencyAnalyzer.analyzeContentDependencies(contentToAnalyze, vocabularyModule);
            console.log('📊 Content dependency analysis:', this._dependencyAnalyzer.getAnalysisSummary(analysis));

            // 7. Make decision
            if (analysis.hasUnmetDependencies) {
                console.log(`🔄 Content requires ${analysis.missingWords.length} undiscovered vocabulary words`);

                if (typeof window !== 'undefined') {
                    window.vocabularyOverrideActive = {
                        originalType: this._lastConfig?.type || 'unknown',
                        originalDifficulty: this._lastConfig?.difficulty || 'unknown',
                        missingWords: analysis.missingWords,
                        totalContentWords: analysis.totalWordsInContent,
                        vocabularyWordsInContent: analysis.vocabularyWordsInContent,
                        reason: `Content requires ${analysis.missingWords.length} undiscovered words`,
                        analysisType: 'content-dependency'
                    };
                    console.log('📚 Smart vocabulary override signaled to Smart Guide:', window.vocabularyOverrideActive);
                }
                return true;
            } else {
                console.log('✅ All vocabulary dependencies met, proceeding with original exercise');

                if (typeof window !== 'undefined') {
                    window.vocabularyOverrideActive = null;
                }
                return false;
            }

        } catch (error) {
            console.error('❌ Error in vocabulary dependency analysis:', error);
            return await this._fallbackMasteryCheck(config);
        }
    }
    /**
     * Fallback mastery check when content analysis fails
     */
    async _fallbackMasteryCheck(config) {
        try {
            console.log('🔄 Using unified system fallback mastery check...');

            // Use unified VocabularyProgressManager instead of orchestrator
            const { default: VocabularyProgressManager } = await import('./services/VocabularyProgressManager.js');
            const progressManager = new VocabularyProgressManager();

            // Get unified progress data
            const progressData = await progressManager.loadProgress(config.bookId, config.chapterId);
            const masteredWords = Object.keys(progressData.mastered || {});

            // Load chapter content to get total vocabulary count using apiService
            const { default: apiService } = await import('../services/APIService.js');
            const chapterContent = await apiService.loadChapter(config.chapterId);
            const totalVocabWords = chapterContent?.vocabulary ? Object.keys(chapterContent.vocabulary).length : 1;

            const vocabularyMastery = totalVocabWords > 0 ? Math.round((masteredWords.length / totalVocabWords) * 100) : 0;

            console.log(`📊 Unified fallback vocabulary mastery: ${vocabularyMastery}% (${masteredWords.length}/${totalVocabWords})`);

            if (vocabularyMastery < 20) {
                console.log(`🔄 Fallback: Vocabulary mastery too low (${vocabularyMastery}%)`);

                if (typeof window !== 'undefined') {
                    window.vocabularyOverrideActive = {
                        originalType: this._lastConfig?.type || 'unknown',
                        originalDifficulty: this._lastConfig?.difficulty || 'unknown',
                        vocabularyMastery: vocabularyMastery,
                        reason: `Vocabulary mastery too low (${vocabularyMastery}%) - unified fallback check`,
                        analysisType: 'unified-fallback-mastery'
                    };
                }

                return true;
            } else {
                console.log(`✅ Unified fallback: Vocabulary mastery sufficient (${vocabularyMastery}%)`);
                return false;
            }
        } catch (error) {
            console.log('Unified fallback mastery check failed:', error);
            return false; // If fallback fails, don't force vocabulary
        }
    }

    /**
     * Load Word Discovery Module using ExerciseFactory
     */
    async _loadWordDiscoveryModule(exerciseType, config) {
        try {
            console.log('📖 Loading Word Discovery Module...');

            // Get chapter content
            const chapterContent = await this._contentLoader.getContent(config.chapterId);

            const content = {
                chapterContent: chapterContent,
                exerciseType: exerciseType
            };

            // Use generic helper
            await this._loadExerciseViaFactory('vocabulary-discovery', config, content);

        } catch (error) {
            console.error('❌ Error loading Word Discovery Module:', error);
            this._handleModuleError(error, 'Word Discovery');
        }
    }

    /**
     * Load DRS VocabularyModule (integrated flashcard system) using ExerciseFactory
     */
    async _loadVocabularyModule(exerciseType, config) {
        try {
            console.log('📚 Loading DRS VocabularyModule...');

            // Load content for vocabulary exercises
            const chapterContent = await this._contentLoader.getContent(config.chapterId);
            console.log('📚 Vocabulary content loaded for', config.chapterId);

            if (!chapterContent || !chapterContent.vocabulary) {
                throw new Error('No vocabulary content found for flashcards');
            }

            // Prepare exercise data - convert vocabulary to expected format
            const vocabularyArray = Object.entries(chapterContent.vocabulary).map(([word, data]) => {
                // Extract translation string from various possible formats
                let translation;
                if (typeof data === 'string') {
                    translation = data;
                } else if (data && typeof data === 'object') {
                    // Try various translation fields in order of preference
                    translation = data.translation ||
                                data.meaning ||
                                data.user_language ||    // Primary: user_language field
                                data.target_language ||  // Alternative: target_language field
                                data.fr ||
                                data.definition ||
                                Object.values(data).find(val => typeof val === 'string' && val !== word) || // Find any string value that's not the word itself
                                word; // Fallback to the word itself
                } else {
                    translation = String(data || word);
                }

                return {
                    word: word,
                    translation: translation,
                    pronunciation: data && typeof data === 'object' ? data.pronunciation : null,
                    type: data && typeof data === 'object' ? (data.type || 'word') : 'word'
                };
            });

            const content = {
                vocabulary: vocabularyArray,
                chapterId: config.chapterId,
                exerciseType: exerciseType
            };

            // Use generic helper - always use 'vocabulary-flashcards' type for vocabulary module
            await this._loadExerciseViaFactory('vocabulary-flashcards', config, content);

        } catch (error) {
            console.error('❌ Failed to load DRS VocabularyModule:', error);
            this._container.innerHTML = `
                <div class="error-message">
                    <h3>❌ Vocabulary Error</h3>
                    <p>Failed to load vocabulary flashcards: ${error.message}</p>
                    <p>This is the DRS integrated system, not an external game.</p>
                </div>
            `;
        }
    }

    /**
     * Load and initialize AI Analysis Module using ExerciseFactory
     */
    async _loadAIAnalysisModule(exerciseType, config) {
        try {
            console.log('🤖 Loading AI Analysis Module...');

            // Load real chapter content first
            const contentRequest = {
                type: 'exercise',
                subtype: exerciseType,
                bookId: config.bookId,
                chapterId: config.chapterId,
                difficulty: config.difficulty || 'medium'
            };

            let chapterContent;
            try {
                chapterContent = await this._contentLoader.loadExercise(contentRequest);
                console.log('📚 Chapter content loaded:', {
                    contentKeys: Object.keys(chapterContent),
                    hasDialogs: !!chapterContent.dialogs,
                    hasVocabulary: !!chapterContent.vocabulary
                });
            } catch (error) {
                console.warn('⚠️ Failed to load chapter content:', error);
                throw new Error('Real chapter content is required for AI analysis');
            }

            // Extract real dialogues from chapter content
            const dialogues = this._extractRealDialogues(chapterContent);
            if (!dialogues || dialogues.length === 0) {
                throw new Error('No real content found in chapter. AI Analysis requires real chapter content - no fallback available.');
            }

            // Prepare content for the module
            const content = {
                dialogues: dialogues,
                chapterContent: chapterContent,
                exerciseType: exerciseType
            };

            // Use generic helper
            await this._loadExerciseViaFactory(exerciseType, config, content);

        } catch (error) {
            console.error('❌ Failed to load AI Analysis Module:', error);

            // Show error message to user
            this._container.innerHTML = `
                <div class="ai-error">
                    <h3>❌ Unable to Load AI Analysis</h3>
                    <p><strong>Error:</strong> ${error.message}</p>
                    <p>This feature requires real chapter content with dialogues.</p>
                    <button onclick="window.location.reload()" class="retry-btn">
                        🔄 Try Again
                    </button>
                </div>
            `;
        }
    }

    /**
     * Load exercise content based on type
     */
    async _loadExerciseContent(type, config) {
        try {
            console.log(`📚 Loading ${type} exercise content...`);

            // Request content from ContentLoader
            const contentRequest = {
                type: 'exercise',
                subtype: type,
                difficulty: config.difficulty || this._config.defaultDifficulty,
                bookId: config.bookId,
                chapterId: config.chapterId,
                ...config
            };

            console.log('📋 UnifiedDRS content request:', contentRequest);
            const content = await this._contentLoader.loadExercise(contentRequest);

            console.log(`✅ UnifiedDRS content loaded:`, {
                title: content.title,
                stepsCount: content.steps ? content.steps.length : 0,
                hasSteps: !!content.steps,
                contentKeys: Object.keys(content),
                firstStep: content.steps ? content.steps[0] : null
            });

            return content;
        } catch (error) {
            console.error(`❌ Failed to load ${type} exercise:`, error);
            return null;
        }
    }

    /**
     * Create the main UI using components
     */
    async _createUI() {
        if (!this._container) return;

        // Clear container
        this._container.innerHTML = '';

        // Create main exercise card
        this._components.mainCard = componentRegistry.create('Card', {
            title: this._currentExercise.title || 'Exercise',
            type: 'exercise',
            className: 'drs-main-card'
        });

        // Create progress bar if enabled
        if (this._config.showProgress) {
            this._components.progressBar = componentRegistry.create('ProgressBar', {
                value: 0,
                max: this._totalSteps,
                color: 'primary',
                showLabel: true,
                className: 'drs-progress'
            });
        }

        // Create navigation buttons
        this._components.nextButton = componentRegistry.create('Button', {
            text: this._currentStep === this._totalSteps - 1 ? 'Finish' : 'Next',
            type: 'primary',
            onClick: (e) => {
                console.log('🖱️ Next button clicked (from component)');
                // Prevent default form submission
                if (e) {
                    e.preventDefault();
                    e.stopPropagation();
                }
                this._handleNext();
            },
            className: 'drs-next-btn'
        });

        // Create hint button if enabled
        if (this._config.showHints) {
            this._components.hintButton = componentRegistry.create('Button', {
                text: 'Hint',
                icon: '💡',
                type: 'outline',
                onClick: () => this._handleHint(),
                className: 'drs-hint-btn'
            });
        }

        // Create hint panel (initially hidden)
        this._components.hintPanel = componentRegistry.create('Panel', {
            title: 'Hint',
            type: 'hint',
            collapsible: true,
            collapsed: true,
            className: 'drs-hint-panel'
        });

        // Create result panel (initially hidden)
        this._components.resultPanel = componentRegistry.create('Panel', {
            title: 'Result',
            type: 'success',
            className: 'drs-result-panel'
        });

        // Assemble UI
        this._assembleUI();
    }

    /**
     * Assemble all UI components into the container
     */
    _assembleUI() {
        // Progress bar at top
        if (this._components.progressBar) {
            this._container.appendChild(this._components.progressBar.getElement());
        }

        // Main card
        this._container.appendChild(this._components.mainCard.getElement());

        // Action buttons container
        const actionsDiv = document.createElement('div');
        actionsDiv.className = 'drs-actions';
        actionsDiv.style.cssText = `
            display: flex;
            gap: 12px;
            margin-top: 16px;
            justify-content: space-between;
        `;

        // Left side: hint button
        if (this._components.hintButton) {
            actionsDiv.appendChild(this._components.hintButton.getElement());
        }

        // Right side: next button
        const rightActions = document.createElement('div');
        rightActions.style.cssText = 'margin-left: auto;';
        rightActions.appendChild(this._components.nextButton.getElement());
        actionsDiv.appendChild(rightActions);

        this._container.appendChild(actionsDiv);

        // Panels at bottom
        this._container.appendChild(this._components.hintPanel.getElement());
        this._container.appendChild(this._components.resultPanel.getElement());

        // Initially hide panels
        this._components.hintPanel.hide();
        this._components.resultPanel.hide();
    }

    /**
     * Show current exercise step
     */
    _showCurrentStep() {
        if (!this._currentExercise || !this._components.mainCard) return;

        const step = this._currentExercise.steps?.[this._currentStep] || this._currentExercise;
        console.log(`📖 Showing step ${this._currentStep + 1}/${this._totalSteps}:`, {
            id: step.id,
            type: step.type,
            hasContent: !!step.content,
            contentKeys: step.content ? Object.keys(step.content) : [],
            step: step
        });

        const progress = this.getProgress();

        // Update progress bar
        if (this._components.progressBar) {
            this._components.progressBar.setValue(this._currentStep + 1);
            this._components.progressBar.setLabel(`Step ${progress.currentStep} of ${progress.totalSteps}`);
        }

        // Update main card content
        const stepContent = this._generateStepContent(step);
        this._components.mainCard.setContent(stepContent);

        // Update next button text
        if (this._components.nextButton) {
            const isLast = this._currentStep === this._totalSteps - 1;
            this._components.nextButton.setText(isLast ? 'Finish' : 'Next');
        }

        // Hide result panel for new step
        if (this._components.resultPanel) {
            this._components.resultPanel.hide();
        }
    }

    /**
     * Generate HTML content for current step
     */
    _generateStepContent(step) {
        let content = '';

        // Step instruction
        if (step.instruction) {
            content += `<div class="drs-instruction">${step.instruction}</div>`;
        }

        // Content based on type
        if (step.type === 'text' || step.type === 'multiple-choice' || !step.type) {
            content += this._generateTextContent(step);
        } else if (step.type === 'audio') {
            content += this._generateAudioContent(step);
        } else if (step.type === 'image') {
            content += this._generateImageContent(step);
        } else if (step.type === 'grammar' || step.type === 'fill-blank') {
            content += this._generateGrammarContent(step);
        } else if (step.type === 'phrase') {
            content += this._generatePhraseContent(step);
        } else {
            // Fallback for unknown types
            console.warn(`⚠️ Unknown step type: ${step.type}, falling back to text`);
            content += this._generateTextContent(step);
        }

        return content;
    }

    /**
     * Generate text exercise content
     */
    _generateTextContent(step) {
        let content = `<div class="drs-text-content">`;

        // Use step.content if available (new format from ContentLoader)
        const stepData = step.content || step;

        // Show passage/text
        if (stepData.passage) {
            content += `<div class="drs-text-passage">${stepData.passage}</div>`;
        } else if (stepData.text) {
            content += `<div class="drs-text-passage">${stepData.text}</div>`;
        }

        // Show question
        if (stepData.question) {
            content += `<div class="drs-question">${stepData.question}</div>`;
        }

        // Show options (multiple choice)
        const options = stepData.options || step.options;
        if (options && options.length > 0) {
            console.log('🎯 Generating radio options:', options);
            content += `<div class="drs-options">`;
            options.forEach((option, index) => {
                content += `
                    <label class="drs-option">
                        <input type="radio" name="answer" value="${index}" required>
                        <span>${option}</span>
                    </label>
                `;
            });
            content += `</div>`;
        } else {
            console.warn('⚠️ No options found for multiple choice step:', step);
        }

        content += `</div>`;
        return content;
    }

    /**
     * Generate audio exercise content
     */
    _generateAudioContent(step) {
        let content = `<div class="drs-audio-content">`;

        if (step.audioUrl) {
            content += `
                <div class="drs-audio-player">
                    <audio controls>
                        <source src="${step.audioUrl}" type="audio/mpeg">
                        Your browser does not support audio playback.
                    </audio>
                </div>
            `;
        }

        if (step.transcript) {
            content += `<div class="drs-transcript" style="display: none;">${step.transcript}</div>`;
            content += `<button class="drs-show-transcript btn btn-secondary">Show Transcript</button>`;
        }

        if (step.question) {
            content += `<div class="drs-question">${step.question}</div>`;
        }

        content += `</div>`;
        return content;
    }

    /**
     * Generate image exercise content
     */
    _generateImageContent(step) {
        let content = `<div class="drs-image-content">`;

        if (step.imageUrl) {
            content += `
                <div class="drs-image-container">
                    <img src="${step.imageUrl}" alt="${step.description || 'Exercise image'}" class="drs-image">
                </div>
            `;
        }

        if (step.question) {
            content += `<div class="drs-question">${step.question}</div>`;
        }

        content += `</div>`;
        return content;
    }

    /**
     * Generate grammar exercise content
     */
    _generateGrammarContent(step) {
        let content = `<div class="drs-grammar-content">`;

        if (step.sentence) {
            // Fill-in-the-blank style
            const processedSentence = step.sentence.replace(/_+/g, '<input type="text" class="drs-blank">');
            content += `<div class="drs-sentence">${processedSentence}</div>`;
        }

        if (step.explanation) {
            content += `<div class="drs-explanation">${step.explanation}</div>`;
        }

        content += `</div>`;
        return content;
    }

    /**
     * Generate phrase exercise content
     */
    _generatePhraseContent(step) {
        // Use step.content if available (new format from ContentLoader)
        const stepData = step.content || step;

        console.log('💬 Generating phrase content:', stepData);

        // Extract phrase data - handle nested structure (now comes from step.content.phrase)
        let phraseData = stepData.phrase || stepData;

        // Get the phrase text
        const phraseText = phraseData.english || phraseData.text || phraseData.id || 'No phrase text';
        const pronunciation = phraseData.pronunciation || '';
        const context = phraseData.context || '';
        const expectedTranslation = phraseData.user_language || phraseData.translation || '';

        let content = `
            <div class="drs-phrase-content">
                <div class="drs-phrase-container">
                    <!-- English Phrase Card -->
                    <div class="drs-phrase-card">
                        <div class="drs-phrase-icon">💬</div>
                        <div class="drs-phrase-body">
                            <div class="drs-phrase-label">English Phrase</div>
                            <div class="drs-phrase-text">${phraseText}</div>
                        </div>
                    </div>

                    <!-- Pronunciation -->
                    ${pronunciation ? `
                        <div class="drs-phrase-meta">
                            <span class="drs-meta-icon">🗣️</span>
                            <span class="drs-meta-text">${pronunciation}</span>
                        </div>
                    ` : ''}

                    <!-- Context -->
                    ${context ? `
                        <div class="drs-phrase-meta">
                            <span class="drs-meta-icon">📌</span>
                            <span class="drs-meta-label">Context:</span>
                            <span class="drs-meta-text">${context}</span>
                        </div>
                    ` : ''}

                    <!-- Translation Input -->
                    <div class="drs-phrase-answer">
                        <label class="drs-answer-label">
                            <span class="drs-label-icon">✍️</span>
                            <span>Your translation in French:</span>
                        </label>
                        <textarea
                            class="drs-phrase-input"
                            name="answer"
                            rows="3"
                            placeholder="Tapez votre traduction ici..."
                            required
                        ></textarea>
                        <div class="drs-input-hint">AI will validate your translation</div>
                    </div>
                </div>

                <!-- Hidden hint for AI validation -->
                ${expectedTranslation ? `
                    <div class="drs-phrase-expected" style="display: none;" data-expected="${expectedTranslation}">
                        ${expectedTranslation}
                    </div>
                ` : ''}
            </div>

            <style>
                .drs-phrase-content {
                    width: 100%;
                    max-width: 700px;
                    margin: 0 auto;
                }

                .drs-phrase-container {
                    display: flex;
                    flex-direction: column;
                    gap: 20px;
                }

                .drs-phrase-card {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    border-radius: 16px;
                    padding: 24px;
                    display: flex;
                    align-items: center;
                    gap: 16px;
                    box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
                    transition: transform 0.2s ease;
                }

                .drs-phrase-card:hover {
                    transform: translateY(-2px);
                }

                .drs-phrase-icon {
                    font-size: 36px;
                    filter: drop-shadow(0 2px 4px rgba(0,0,0,0.2));
                }

                .drs-phrase-body {
                    flex: 1;
                }

                .drs-phrase-label {
                    color: rgba(255, 255, 255, 0.9);
                    font-size: 12px;
                    text-transform: uppercase;
                    letter-spacing: 1px;
                    font-weight: 600;
                    margin-bottom: 8px;
                }

                .drs-phrase-text {
                    color: white;
                    font-size: 20px;
                    font-weight: 500;
                    line-height: 1.4;
                }

                .drs-phrase-meta {
                    background: #f8f9fa;
                    border-radius: 12px;
                    padding: 12px 16px;
                    display: flex;
                    align-items: center;
                    gap: 10px;
                    font-size: 14px;
                    color: #495057;
                }

                .drs-meta-icon {
                    font-size: 20px;
                }

                .drs-meta-label {
                    font-weight: 600;
                    color: #6c757d;
                }

                .drs-meta-text {
                    color: #212529;
                }

                .drs-phrase-answer {
                    background: white;
                    border-radius: 12px;
                    padding: 20px;
                    border: 2px solid #e9ecef;
                }

                .drs-answer-label {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    font-weight: 600;
                    color: #495057;
                    margin-bottom: 12px;
                    font-size: 15px;
                }

                .drs-label-icon {
                    font-size: 20px;
                }

                .drs-phrase-input {
                    width: 100%;
                    padding: 14px;
                    border: 2px solid #dee2e6;
                    border-radius: 8px;
                    font-size: 16px;
                    font-family: inherit;
                    transition: all 0.2s ease;
                    resize: vertical;
                    min-height: 80px;
                }

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

                .drs-input-hint {
                    margin-top: 8px;
                    font-size: 12px;
                    color: #6c757d;
                    font-style: italic;
                }
            </style>
        `;

        return content;
    }

    /**
     * Event handlers
     */
    _handleStart() {
        console.log('📢 DRS start event received');
    }

    async _handleNext() {
        console.log('📋 ========== Next button clicked ==========');
        console.log('   Active:', this._isActive);
        console.log('   Step:', `${this._currentStep}/${this._totalSteps}`);

        if (!this._isActive) {
            console.log('⚠️ DRS not active, ignoring next');
            return;
        }

        // Validate current step
        console.log('🔍 Validating current step...');
        const isValid = this._validateCurrentStep();
        if (!isValid) {
            console.log('❌ Validation failed, showing error');
            this._showValidationError();
            return;
        }

        console.log('✅ Validation passed, showing loading overlay...');

        // Show loading indicator during AI validation
        const loadingOverlay = this._showAILoadingOverlay();
        console.log('   Loading overlay created:', !!loadingOverlay);

        try {
            console.log('📊 Starting _storeStepResult (async)...');
            // Store step results before moving on (now async for AI validation)
            await this._storeStepResult();
            console.log('✅ _storeStepResult completed!');

            // Hide loading
            console.log('🚫 Removing loading overlay...');
            loadingOverlay.remove();

            // Move to next step or finish
            if (this._currentStep < this._totalSteps - 1) {
                console.log('➡️ Moving to next step...');
                // Emit step completed (for the step we just finished)
                this._eventBus.emit('drs:step-completed', {
                    step: this._currentStep, // The step we just completed
                    total: this._totalSteps
                }, this.name);

                this._currentStep++;
                this._showCurrentStep();
            } else {
                console.log('🏁 Finishing exercise...');
                // Emit final step completed
                this._eventBus.emit('drs:step-completed', {
                    step: this._currentStep,
                    total: this._totalSteps
                }, this.name);

                this._finishExercise();
            }
        } catch (error) {
            console.error('❌ Error during validation:', error);
            console.error('   Stack:', error.stack);
            loadingOverlay.remove();
            this._showValidationError();
        }

        console.log('📋 ========== _handleNext completed ==========');
    }

    _showAILoadingOverlay() {
        const overlay = document.createElement('div');
        overlay.className = 'drs-ai-loading-overlay';
        overlay.innerHTML = `
            <div class="drs-ai-loading-content">
                <div class="drs-ai-spinner"></div>
                <div class="drs-ai-loading-text">
                    <div class="drs-loading-title">🤖 AI Validation in Progress...</div>
                    <div class="drs-loading-subtitle">Analyzing your answer</div>
                </div>
            </div>
            <style>
                .drs-ai-loading-overlay {
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background: rgba(0, 0, 0, 0.8);
                    backdrop-filter: blur(4px);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    z-index: 9999;
                    animation: fadeIn 0.2s ease;
                }

                .drs-ai-loading-content {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    gap: 20px;
                }

                .drs-ai-spinner {
                    width: 60px;
                    height: 60px;
                    border: 4px solid rgba(255, 255, 255, 0.2);
                    border-top-color: #667eea;
                    border-radius: 50%;
                    animation: spin 1s linear infinite;
                }

                @keyframes spin {
                    to { transform: rotate(360deg); }
                }

                .drs-ai-loading-text {
                    text-align: center;
                    color: white;
                }

                .drs-loading-title {
                    font-size: 24px;
                    font-weight: 700;
                    margin-bottom: 8px;
                }

                .drs-loading-subtitle {
                    font-size: 16px;
                    opacity: 0.8;
                }
            </style>
        `;
        document.body.appendChild(overlay);
        return overlay;
    }

    async _storeStepResult() {
        // Initialize stepResults if not exists
        if (!this._userProgress.stepResults) {
            this._userProgress.stepResults = [];
        }

        const step = this._currentExercise.steps?.[this._currentStep] || this._currentExercise;
        const stepData = step.content || step;

        // Get user's answer
        let userAnswer = '';
        let isCorrect = false;
        let expectedAnswer = '';
        let score = 0;
        let feedback = '';
        let questionText = '';

        // Check for radio buttons (multiple choice)
        const radioChecked = this._container.querySelector('input[type="radio"]:checked');
        if (radioChecked) {
            const selectedIndex = parseInt(radioChecked.value);
            const options = stepData.options || step.options || [];
            userAnswer = options[selectedIndex] || `Option ${selectedIndex + 1}`;

            // Check if correct
            const correctIndex = stepData.correct_answer ?? stepData.correctAnswer ?? -1;
            isCorrect = (selectedIndex === correctIndex);
            expectedAnswer = options[correctIndex] || '';
            score = isCorrect ? 100 : 0;
            questionText = stepData.question || stepData.passage || 'Multiple choice question';
        }

        // Check for text input or textarea (phrase translation)
        const textInput = this._container.querySelector('textarea[name="answer"], input[type="text"][name="answer"]');
        if (textInput && textInput.value.trim()) {
            console.log('📝 Text input found, validating...');
            userAnswer = textInput.value.trim();

            // Get phrase data for AI validation - MUST extract phraseData first!
            const phraseData = stepData.phrase || stepData;
            const englishPhrase = phraseData.english || phraseData.text || phraseData.id || '';
            expectedAnswer = phraseData.user_language || phraseData.translation || stepData.expectedAnswer || '';
            questionText = englishPhrase;

            console.log('📊 Validation data:', {
                userAnswer,
                expectedAnswer,
                englishPhrase,
                hasExpected: !!expectedAnswer,
                hasEnglish: !!englishPhrase
            });

            if (expectedAnswer && englishPhrase) {
                // Use AI validation for phrases
                console.log('🤖 Starting AI validation...');
                console.log('   English:', englishPhrase);
                console.log('   User answer:', userAnswer);
                console.log('   Expected:', expectedAnswer);

                try {
                    // Get LLMValidator from SmartPreviewOrchestrator
                    console.log('🔍 Looking for LLMValidator...');
                    const orchestrator = window.app?.getCore()?.moduleLoader?.getModule('smartPreviewOrchestrator');
                    console.log('   Orchestrator:', orchestrator ? 'Found' : 'NOT FOUND');

                    const validator = orchestrator?.llmValidator;
                    console.log('   Validator:', validator ? 'Found' : 'NOT FOUND');

                    if (validator) {
                        console.log('✅ LLMValidator found, calling validateTranslation...');
                        const validationResult = await validator.validateTranslation(
                            englishPhrase,
                            userAnswer,
                            expectedAnswer,
                            'French'
                        );

                        isCorrect = validationResult.isCorrect;
                        score = validationResult.score;
                        feedback = validationResult.feedback;

                        console.log('✅ AI validation complete:', { isCorrect, score, feedback });
                    } else {
                        console.warn('⚠️ LLMValidator not available, using fuzzy match');
                        // Fallback to fuzzy match
                        const userLower = userAnswer.toLowerCase();
                        const expectedLower = expectedAnswer.toLowerCase();
                        isCorrect = userLower.includes(expectedLower) || expectedLower.includes(userLower);
                        score = isCorrect ? 100 : 0;
                        console.log('   Fuzzy match result:', { isCorrect, score });
                    }
                } catch (error) {
                    console.error('❌ AI validation error:', error);
                    console.error('   Error details:', error.message, error.stack);
                    // Fallback to fuzzy match
                    const userLower = userAnswer.toLowerCase();
                    const expectedLower = expectedAnswer.toLowerCase();
                    isCorrect = userLower.includes(expectedLower) || expectedLower.includes(userLower);
                    score = isCorrect ? 100 : 0;
                    console.log('   Fallback fuzzy match result:', { isCorrect, score });
                }
            } else {
                console.warn('⚠️ Missing data for AI validation, assuming correct');
                isCorrect = true; // No expected answer, assume correct
                score = 100;
            }
        }

        // Store the result
        const result = {
            question: questionText || stepData.question || stepData.text || 'Question',
            userAnswer,
            expectedAnswer,
            isCorrect,
            feedback: feedback || stepData.feedback || stepData.explanation || '',
            score
        };

        this._userProgress.stepResults.push(result);
        console.log('📊 Stored step result:', result);
    }

    _handleHint() {
        if (!this._components.hintPanel) return;

        const step = this._currentExercise.steps?.[this._currentStep] || this._currentExercise;

        if (step.hint) {
            this._components.hintPanel.setContent(step.hint);
            this._components.hintPanel.show();
            this._components.hintPanel.expand();

            // Track hint usage
            this._userProgress.hints++;

            // Emit hint used event
            this._eventBus.emit('drs:hint-used', {
                step: this._currentStep,
                hint: step.hint
            }, this.name);
        }
    }

    _handleSubmit(event) {
        console.log('📝 Submit event:', event);
        this._handleNext();
    }

    _handleContentLoaded(event) {
        console.log('📚 Content loaded event:', event);
    }

    /**
     * Handle exercise completion from modules like VocabularyModule
     */
    _handleExerciseCompleted(event) {
        console.group('🏁 Exercise completed event received');
        console.log('📊 Event data:', event);

        const { moduleType, results, progress } = event;

        // Calculate score from results
        let totalScore = 0;
        let totalItems = 0;

        if (Array.isArray(results)) {
            totalItems = results.length;
            totalScore = results.reduce((sum, result) => sum + (result.score || 0), 0);
        } else if (results && typeof results.score === 'number') {
            totalScore = results.score;
            totalItems = 1;
        }

        const averageScore = totalItems > 0 ? Math.round(totalScore / totalItems) : 0;

        // Create result object
        const result = {
            success: averageScore >= 50, // 50% threshold for success
            score: averageScore,
            duration: Date.now() - (this._startTime || Date.now()),
            moduleType: moduleType,
            details: results
        };

        console.log('📈 Calculated result:', result);

        // Set current module reference for tracking
        this._currentModule = { name: moduleType };

        // Use the completion system
        const completion = this.completeCurrentModule(result);
        console.log('✅ Completion processed:', completion);

        console.groupEnd();
    }

    /**
     * Handle request for next module
     */
    _handleRequestNextModule(event) {
        console.group('🎯 Next module request received');
        console.log('📊 Request data:', event);

        // This would integrate with the main module loading system
        // For now, just log the request
        console.log('🔄 Would decide next module based on:', {
            currentProgress: event.currentProgress,
            userLevel: event.userLevel
        });

        console.groupEnd();

        // Emit back to system for handling
        this._eventBus.emit('drs:nextModuleDecided', {
            recommendation: 'continue',
            nextModuleType: 'auto-select'
        }, this.name);
    }

    /**
     * Validate current step input
     */
    _validateCurrentStep() {
        console.log('🔍 Validating current step...');

        // Basic validation - check for required inputs
        const inputs = this._container.querySelectorAll('input[required], input[type="radio"]');
        console.log(`Found ${inputs.length} inputs to validate`);

        if (inputs.length === 0) {
            console.log('✅ No validation needed');
            return true; // No validation needed
        }

        // Check radio buttons
        const radioGroups = this._container.querySelectorAll('input[type="radio"]');
        if (radioGroups.length > 0) {
            console.log(`Checking ${radioGroups.length} radio buttons...`);
            const groupNames = new Set();
            radioGroups.forEach(radio => groupNames.add(radio.name));

            for (const groupName of groupNames) {
                const checked = this._container.querySelector(`input[name="${groupName}"]:checked`);
                if (!checked) {
                    console.log(`❌ No radio button selected for group: ${groupName}`);
                    return false;
                }
                console.log(`✅ Radio group "${groupName}" has selection: ${checked.value}`);
            }
        }

        // Check text inputs
        const textInputs = this._container.querySelectorAll('input[required]:not([type="radio"])');
        if (textInputs.length > 0) {
            console.log(`Checking ${textInputs.length} text inputs...`);
            for (const input of textInputs) {
                if (!input.value.trim()) {
                    console.log(`❌ Required text input is empty: ${input.name || input.id}`);
                    return false;
                }
                console.log(`✅ Text input has value: ${input.value}`);
            }
        }

        console.log('✅ All validations passed');
        return true;
    }

    /**
     * Show validation error
     */
    _showValidationError() {
        if (this._components.resultPanel) {
            this._components.resultPanel.setType('warning');
            this._components.resultPanel.setContent('Please answer all questions before continuing.');
            this._components.resultPanel.show();

            setTimeout(() => {
                this._components.resultPanel.hide();
            }, 3000);
        }
    }

    /**
     * Finish exercise
     */
    _finishExercise() {
        this._isActive = false;

        // Calculate final stats
        this._userProgress.timeSpent = Date.now() - this._startTime;
        const finalStats = this.getProgress();

        // Calculate score
        const totalSteps = this._currentExercise.steps?.length || 1;
        const correctAnswers = this._userProgress.stepResults?.filter(r => r.isCorrect).length || 0;
        const scorePercentage = Math.round((correctAnswers / totalSteps) * 100);

        // Calculate display duration: 2× exercise duration
        const exerciseDuration = finalStats.timeSpent;
        const displayDuration = exerciseDuration * 2;

        console.log('🎉 Exercise completed!', {
            score: `${correctAnswers}/${totalSteps}`,
            percentage: `${scorePercentage}%`,
            time: `${Math.round(finalStats.timeSpent / 1000)}s`,
            popupDuration: `${Math.round(displayDuration / 1000)}s`
        });

        // Show detailed results in popup
        this._showResultsPopup(finalStats, correctAnswers, totalSteps, scorePercentage, displayDuration);

        // Hide next button
        if (this._components.nextButton) {
            this._components.nextButton.hide();
        }

        // Emit completion event
        this._eventBus.emit('drs:completed', {
            stats: finalStats,
            exercise: this._currentExercise,
            score: scorePercentage,
            correctAnswers,
            totalSteps
        }, this.name);
    }

    _showResultsPopup(finalStats, correctAnswers, totalSteps, scorePercentage, displayDuration) {
        const resultsHTML = this._generateDetailedResults(finalStats, correctAnswers, totalSteps, scorePercentage);

        // Create popup overlay
        const popup = document.createElement('div');
        popup.className = 'drs-results-popup';
        popup.innerHTML = `
            <div class="drs-popup-overlay"></div>
            <div class="drs-popup-content">
                <div class="drs-popup-timer">
                    <span class="drs-timer-icon">⏱️</span>
                    <span class="drs-timer-text">Closing in <span id="drs-timer-seconds">${Math.ceil(displayDuration / 1000)}</span>s</span>
                </div>
                ${resultsHTML}
            </div>
            <style>
                .drs-results-popup {
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    z-index: 10000;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    animation: fadeIn 0.3s ease;
                }

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

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

                .drs-popup-overlay {
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background: rgba(0, 0, 0, 0.75);
                    backdrop-filter: blur(8px);
                }

                .drs-popup-content {
                    position: relative;
                    max-width: 900px;
                    max-height: 90vh;
                    width: 90%;
                    background: white;
                    border-radius: 24px;
                    box-shadow: 0 25px 50px rgba(0, 0, 0, 0.3);
                    overflow-y: auto;
                    animation: slideUp 0.4s ease;
                }

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

                .drs-popup-timer {
                    position: sticky;
                    top: 0;
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white;
                    padding: 12px 20px;
                    border-radius: 24px 24px 0 0;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    gap: 8px;
                    font-size: 14px;
                    font-weight: 600;
                    z-index: 10;
                    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                }

                .drs-timer-icon {
                    font-size: 18px;
                }

                .drs-timer-text {
                    letter-spacing: 0.5px;
                }

                /* Override continue button in popup */
                .drs-results-popup .drs-continue-btn {
                    margin-top: 20px;
                }
            </style>
        `;

        document.body.appendChild(popup);

        // Countdown timer
        let remainingSeconds = Math.ceil(displayDuration / 1000);
        const timerElement = popup.querySelector('#drs-timer-seconds');

        const countdown = setInterval(() => {
            remainingSeconds--;
            if (timerElement) {
                timerElement.textContent = remainingSeconds;
            }

            if (remainingSeconds <= 0) {
                clearInterval(countdown);
            }
        }, 1000);

        // Helper function to close popup and load next exercise
        const closeAndContinue = async () => {
            clearInterval(countdown);
            popup.style.animation = 'fadeOut 0.3s ease';
            setTimeout(async () => {
                popup.remove();
                await this._loadNextExerciseFluid();
            }, 300);
        };

        // Auto-close after duration
        setTimeout(() => {
            closeAndContinue();
        }, displayDuration);

        // Manual close on continue button click
        const continueBtn = popup.querySelector('.drs-continue-btn');
        if (continueBtn) {
            continueBtn.onclick = () => {
                closeAndContinue();
            };
        }
    }

    /**
     * Load next exercise fluidly without page reload
     * @private
     */
    async _loadNextExerciseFluid() {
        try {
            console.log('🔄 Loading next exercise fluidly...');

            // Update progress bar with latest data
            if (typeof window.updateProgressBar === 'function') {
                window.updateProgressBar();
                console.log('📊 Progress bar updated');
            }

            // Get Smart Guide components
            const moduleLoader = window.app?.getCore()?.moduleLoader;
            if (!moduleLoader) {
                console.warn('⚠️ ModuleLoader not available - reloading page as fallback');
                window.location.reload();
                return;
            }

            const intelligentSequencer = moduleLoader.getModule('intelligentSequencer');
            if (!intelligentSequencer) {
                console.warn('⚠️ IntelligentSequencer not available - reloading page as fallback');
                window.location.reload();
                return;
            }

            console.log('🎯 Requesting next exercise from Smart Guide...');
            window.updateGuideStatus?.('🔄 Preparing next exercise...');

            // Get next exercise
            const nextExercise = await intelligentSequencer.getNextExercise();

            if (nextExercise) {
                console.log('✅ Next exercise found:', nextExercise);

                // Start next exercise if function available
                if (typeof window.startGuidedExercise === 'function') {
                    setTimeout(() => {
                        window.startGuidedExercise(nextExercise);
                    }, 500);
                } else {
                    console.error('❌ startGuidedExercise function not found');
                    window.location.reload();
                }
            } else {
                console.log('🎉 Session completed - no more exercises');
                window.updateGuideStatus?.('🎉 Session Complete!');

                // Show completion message
                const container = document.querySelector('.drs-container');
                if (container) {
                    container.innerHTML = `
                        <div style="text-align: center; padding: 60px 20px;">
                            <div style="font-size: 72px; margin-bottom: 20px;">🎉</div>
                            <h2 style="color: #2c3e50; margin-bottom: 10px;">Session Complete!</h2>
                            <p style="color: #666; font-size: 18px;">Great work! You've completed all available exercises.</p>
                            <button onclick="window.location.reload()" style="margin-top: 30px; padding: 12px 24px; background: linear-gradient(135deg, #667eea, #764ba2); color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; font-weight: 500;">
                                Back to Menu
                            </button>
                        </div>
                    `;
                }
            }

        } catch (error) {
            console.error('❌ Error loading next exercise:', error);
            window.updateGuideStatus?.('❌ Error loading next exercise');

            // Fallback to reload on error
            console.warn('⚠️ Falling back to page reload');
            setTimeout(() => window.location.reload(), 2000);
        }
    }

    _generateDetailedResults(finalStats, correctAnswers, totalSteps, scorePercentage) {
        const timeSpent = Math.round(finalStats.timeSpent / 1000);
        const minutes = Math.floor(timeSpent / 60);
        const seconds = timeSpent % 60;
        const timeDisplay = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;

        // Get step results
        const stepResults = this._userProgress.stepResults || [];

        let html = `
            <div class="drs-results-container">
                <!-- Header -->
                <div class="drs-results-header">
                    <div class="drs-results-icon">${scorePercentage >= 70 ? '🎉' : '💪'}</div>
                    <h2 class="drs-results-title">
                        ${scorePercentage >= 90 ? 'Excellent!' : scorePercentage >= 70 ? 'Well Done!' : 'Keep Practicing!'}
                    </h2>
                </div>

                <!-- Score Card -->
                <div class="drs-score-card">
                    <div class="drs-score-main">
                        <div class="drs-score-number">${scorePercentage}%</div>
                        <div class="drs-score-label">Score</div>
                    </div>
                    <div class="drs-score-details">
                        <div class="drs-score-stat">
                            <span class="drs-stat-icon">✅</span>
                            <span class="drs-stat-value">${correctAnswers}/${totalSteps}</span>
                            <span class="drs-stat-label">Correct</span>
                        </div>
                        <div class="drs-score-stat">
                            <span class="drs-stat-icon">⏱️</span>
                            <span class="drs-stat-value">${timeDisplay}</span>
                            <span class="drs-stat-label">Time</span>
                        </div>
                        ${this._userProgress.hints > 0 ? `
                            <div class="drs-score-stat">
                                <span class="drs-stat-icon">💡</span>
                                <span class="drs-stat-value">${this._userProgress.hints}</span>
                                <span class="drs-stat-label">Hints</span>
                            </div>
                        ` : ''}
                    </div>
                </div>

                <!-- Step by step results -->
                ${stepResults.length > 0 ? `
                    <div class="drs-step-results">
                        <h3 class="drs-section-title">📝 Detailed Results</h3>
                        ${stepResults.map((result, index) => this._generateStepResult(result, index + 1)).join('')}
                    </div>
                ` : ''}

                <!-- Continue button -->
                <button class="drs-continue-btn">
                    Continue Learning →
                </button>
            </div>

            <style>
                .drs-results-container {
                    max-width: 800px;
                    margin: 0 auto;
                    padding: 20px;
                }

                .drs-results-header {
                    text-align: center;
                    margin-bottom: 30px;
                }

                .drs-results-icon {
                    font-size: 64px;
                    margin-bottom: 10px;
                }

                .drs-results-title {
                    font-size: 32px;
                    font-weight: 700;
                    color: #2d3748;
                    margin: 0;
                }

                .drs-score-card {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    border-radius: 20px;
                    padding: 30px;
                    color: white;
                    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
                    margin-bottom: 30px;
                }

                .drs-score-main {
                    text-align: center;
                    margin-bottom: 24px;
                }

                .drs-score-number {
                    font-size: 56px;
                    font-weight: 800;
                    line-height: 1;
                    margin-bottom: 8px;
                }

                .drs-score-label {
                    font-size: 18px;
                    opacity: 0.9;
                    text-transform: uppercase;
                    letter-spacing: 2px;
                }

                .drs-score-details {
                    display: flex;
                    justify-content: center;
                    gap: 40px;
                    flex-wrap: wrap;
                }

                .drs-score-stat {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    gap: 4px;
                }

                .drs-stat-icon {
                    font-size: 24px;
                }

                .drs-stat-value {
                    font-size: 24px;
                    font-weight: 700;
                }

                .drs-stat-label {
                    font-size: 12px;
                    opacity: 0.8;
                    text-transform: uppercase;
                    letter-spacing: 1px;
                }

                .drs-step-results {
                    margin-bottom: 30px;
                }

                .drs-section-title {
                    font-size: 20px;
                    font-weight: 600;
                    color: #2d3748;
                    margin-bottom: 16px;
                }

                .drs-step-result {
                    background: white;
                    border: 2px solid #e2e8f0;
                    border-radius: 12px;
                    padding: 20px;
                    margin-bottom: 12px;
                    transition: all 0.2s ease;
                }

                .drs-step-result:hover {
                    border-color: #cbd5e0;
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
                }

                .drs-step-result.correct {
                    border-color: #48bb78;
                    background: #f0fff4;
                }

                .drs-step-result.incorrect {
                    border-color: #f56565;
                    background: #fff5f5;
                }

                .drs-step-header {
                    display: flex;
                    align-items: center;
                    gap: 12px;
                    margin-bottom: 12px;
                }

                .drs-step-icon {
                    font-size: 24px;
                }

                .drs-step-number {
                    font-size: 14px;
                    font-weight: 600;
                    color: #718096;
                }

                .drs-step-question {
                    font-size: 16px;
                    font-weight: 500;
                    color: #2d3748;
                    margin-bottom: 12px;
                }

                .drs-answer-row {
                    display: flex;
                    align-items: start;
                    gap: 8px;
                    margin-bottom: 8px;
                    font-size: 14px;
                }

                .drs-answer-label {
                    font-weight: 600;
                    color: #4a5568;
                    min-width: 100px;
                }

                .drs-answer-text {
                    color: #2d3748;
                    flex: 1;
                }

                .drs-answer-text.correct {
                    color: #22543d;
                }

                .drs-answer-text.incorrect {
                    color: #742a2a;
                }

                .drs-feedback {
                    margin-top: 12px;
                    padding: 12px;
                    background: #edf2f7;
                    border-radius: 8px;
                    font-size: 14px;
                    color: #4a5568;
                }

                .drs-continue-btn {
                    width: 100%;
                    padding: 16px 32px;
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white;
                    border: none;
                    border-radius: 12px;
                    font-size: 18px;
                    font-weight: 600;
                    cursor: pointer;
                    transition: all 0.3s ease;
                    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
                }

                .drs-continue-btn:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
                }
            </style>
        `;

        return html;
    }

    _generateStepResult(result, stepNumber) {
        const isCorrect = result.isCorrect;
        const icon = isCorrect ? '✅' : '❌';
        const statusClass = isCorrect ? 'correct' : 'incorrect';

        return `
            <div class="drs-step-result ${statusClass}">
                <div class="drs-step-header">
                    <span class="drs-step-icon">${icon}</span>
                    <span class="drs-step-number">Question ${stepNumber}</span>
                </div>
                ${result.question ? `
                    <div class="drs-step-question">${result.question}</div>
                ` : ''}
                <div class="drs-answer-row">
                    <span class="drs-answer-label">Your answer:</span>
                    <span class="drs-answer-text ${statusClass}">${result.userAnswer || 'No answer'}</span>
                </div>
                ${result.expectedAnswer && !isCorrect ? `
                    <div class="drs-answer-row">
                        <span class="drs-answer-label">Expected:</span>
                        <span class="drs-answer-text correct">${result.expectedAnswer}</span>
                    </div>
                ` : ''}
                ${result.feedback ? `
                    <div class="drs-feedback">
                        <strong>${isCorrect ? '👍 Great!' : '💡 Tip:'}</strong> ${result.feedback}
                    </div>
                ` : ''}
                ${result.score !== undefined ? `
                    <div class="drs-answer-row">
                        <span class="drs-answer-label">AI Score:</span>
                        <span class="drs-answer-text">${result.score}/100</span>
                    </div>
                ` : ''}
            </div>
        `;
    }

    // ===== DEBUG & MONITORING METHODS =====

    /**
     * Get comprehensive debug information
     */
    getDebugInfo() {
        return {
            session: {
                duration: Date.now() - this._sessionStats.startTime,
                startTime: new Date(this._sessionStats.startTime).toISOString(),
                modulesCompleted: this._sessionStats.modulesCompleted,
                modulesFailed: this._sessionStats.modulesFailed,
                totalExercises: this._sessionStats.totalExercises,
                averageScore: this._sessionStats.averageScore,
                retryCount: this._sessionStats.retryCount
            },
            currentState: {
                activeModule: this._currentModule?.name || 'none',
                currentStep: this._currentStep,
                totalSteps: this._totalSteps,
                isActive: this._isActive
            },
            moduleQueue: {
                remaining: this._moduleQueue.length,
                completed: Array.from(this._completedModules),
                failed: Object.fromEntries(this._failedModules),
                workload: Object.fromEntries(this._moduleWorkload)
            },
            userProgress: { ...this._userProgress },
            failures: this._sessionStats.userFailures.slice(-10) // Last 10 failures
        };
    }

    /**
     * Log current DRS state for debugging
     */
    logDebugState() {
        const debugInfo = this.getDebugInfo();
        console.group('🔍 DRS Debug State');
        console.log('📊 Session:', debugInfo.session);
        console.log('🎯 Current:', debugInfo.currentState);
        console.log('📋 Queue:', debugInfo.moduleQueue);
        console.log('👤 User:', debugInfo.userProgress);
        console.log('⚠️ Recent Failures:', debugInfo.failures);
        console.groupEnd();
        return debugInfo;
    }

    /**
     * Track module completion
     */
    _trackModuleCompletion(moduleName, result) {
        const completionTime = Date.now();
        const startTime = this._sessionStats.timePerModule[moduleName]?.start || completionTime;
        const duration = completionTime - startTime;

        this._sessionStats.timePerModule[moduleName] = {
            start: startTime,
            end: completionTime,
            duration: duration,
            result: result
        };

        if (result.success) {
            this._completedModules.add(moduleName);
            this._sessionStats.modulesCompleted.push({
                name: moduleName,
                completedAt: new Date(completionTime).toISOString(),
                duration: duration,
                score: result.score || 0
            });
        } else {
            this._failedModules.set(moduleName, (this._failedModules.get(moduleName) || 0) + 1);
            this._sessionStats.modulesFailed.push({
                name: moduleName,
                failedAt: new Date(completionTime).toISOString(),
                reason: result.reason || 'unknown',
                attemptNumber: this._failedModules.get(moduleName)
            });
        }

        this._updateSessionStats();
        console.log(`📈 Module ${moduleName} ${result.success ? 'completed' : 'failed'} in ${duration}ms`);
    }

    /**
     * Track user failure
     */
    _trackUserFailure(exercise, userAnswer, expectedAnswer, attemptNumber = 1) {
        this._sessionStats.userFailures.push({
            timestamp: new Date().toISOString(),
            exercise: exercise.type || 'unknown',
            userAnswer: userAnswer,
            expectedAnswer: expectedAnswer,
            attemptNumber: attemptNumber,
            module: this._currentModule?.name || 'unknown'
        });

        // Update retry count if this is a retry
        if (attemptNumber > 1) {
            this._sessionStats.retryCount++;
        }

        console.log(`❌ User failure tracked: ${exercise.type} (attempt ${attemptNumber})`);
    }

    /**
     * Estimate workload for a module type
     */
    _estimateModuleWorkload(moduleType, contentData) {
        const workloadMap = {
            'vocabulary-flashcards': (data) => (data.vocabulary?.length || 5) * 0.5, // 30s per word
            'reading-comprehension': (data) => (data.content?.length || 1000) / 200, // ~200 words per minute
            'grammar-practice': (data) => (data.exercises?.length || 3) * 2, // 2 min per exercise
            'listening-comprehension': (data) => (data.audioDuration || 120) / 60 + 2, // audio + questions
            'translation': (data) => (data.sentences?.length || 5) * 1.5, // 1.5 min per sentence
            'default': () => 3 // 3 minutes default
        };

        const estimator = workloadMap[moduleType] || workloadMap.default;
        const workUnits = estimator(contentData);

        this._moduleWorkload.set(moduleType, workUnits);
        console.log(`📊 Estimated workload for ${moduleType}: ${workUnits.toFixed(1)} minutes`);

        return workUnits;
    }

    /**
     * Update session statistics
     */
    _updateSessionStats() {
        const completedCount = this._sessionStats.modulesCompleted.length;
        if (completedCount > 0) {
            const totalScore = this._sessionStats.modulesCompleted.reduce((sum, m) => sum + (m.score || 0), 0);
            this._sessionStats.averageScore = Math.round(totalScore / completedCount);
        }

        this._sessionStats.totalExercises = this._sessionStats.modulesCompleted.length + this._sessionStats.modulesFailed.length;
    }

    /**
     * Get progress summary for UI display
     */
    getProgressSummary() {
        const completed = this._completedModules.size;
        const failed = this._failedModules.size;
        const remaining = this._moduleQueue.length;
        const total = completed + failed + remaining;

        const totalWorkload = Array.from(this._moduleWorkload.values()).reduce((sum, w) => sum + w, 0);
        const completedWorkload = this._sessionStats.modulesCompleted.reduce((sum, m) => {
            return sum + (this._moduleWorkload.get(m.name) || 0);
        }, 0);

        return {
            modules: { completed, failed, remaining, total },
            workload: {
                completed: Math.round(completedWorkload),
                total: Math.round(totalWorkload),
                percentage: total > 0 ? Math.round((completedWorkload / totalWorkload) * 100) : 0
            },
            session: {
                duration: Date.now() - this._sessionStats.startTime,
                averageScore: this._sessionStats.averageScore,
                retryCount: this._sessionStats.retryCount
            }
        };
    }

    // ===== MODULE DECISION ALGORITHM =====

    /**
     * Decide next module based on user performance and content
     */
    decideNextModule(availableModules, userPerformance) {
        console.group('🧠 Deciding next module...');

        // Filter available modules
        const candidateModules = this._filterCandidateModules(availableModules);
        console.log('📋 Candidate modules:', candidateModules.map(m => m.type));

        if (candidateModules.length === 0) {
            console.log('⭐ No more modules available - session complete!');
            console.groupEnd();
            return null;
        }

        // Score each candidate module
        const scoredModules = candidateModules.map(module => ({
            ...module,
            score: this._scoreModule(module, userPerformance)
        }));

        // Sort by score (higher is better)
        scoredModules.sort((a, b) => b.score - a.score);

        const selected = scoredModules[0];
        console.log('🎯 Module scores:');
        scoredModules.forEach(m => console.log(`  ${m.type}: ${m.score.toFixed(2)}`));
        console.log(`✅ Selected: ${selected.type} (score: ${selected.score.toFixed(2)})`);
        console.groupEnd();

        // Track the decision
        this._trackDecision(selected, scoredModules, userPerformance);

        return selected;
    }

    /**
     * Filter modules that can be attempted
     */
    _filterCandidateModules(availableModules) {
        return availableModules.filter(module => {
            // Skip completed modules
            if (this._completedModules.has(module.type)) {
                return false;
            }

            // Skip modules that failed too many times (max 3 attempts)
            const failCount = this._failedModules.get(module.type) || 0;
            if (failCount >= 3) {
                console.log(`⚠️ Skipping ${module.type} - too many failures (${failCount})`);
                return false;
            }

            // Check prerequisites
            if (module.prerequisites && module.prerequisites.length > 0) {
                const missingPrereqs = module.prerequisites.filter(prereq =>
                    !this._completedModules.has(prereq)
                );
                if (missingPrereqs.length > 0) {
                    console.log(`⚠️ Skipping ${module.type} - missing prerequisites: ${missingPrereqs.join(', ')}`);
                    return false;
                }
            }

            return true;
        });
    }

    /**
     * Score a module based on various factors
     */
    _scoreModule(module, userPerformance) {
        let score = 100; // Base score

        // Factor 1: User performance in similar modules
        const similarPerformance = this._getSimilarModulePerformance(module.type);
        if (similarPerformance.count > 0) {
            const avgScore = similarPerformance.avgScore;
            if (avgScore < 60) {
                score += 30; // Boost modules where user struggles
            } else if (avgScore > 85) {
                score -= 15; // Reduce modules where user excels
            }
        }

        // Factor 2: Module difficulty vs user level
        const userLevel = this._estimateUserLevel();
        const difficultyPenalty = this._calculateDifficultyPenalty(module.difficulty, userLevel);
        score -= difficultyPenalty;

        // Factor 3: Failed attempts penalty
        const failCount = this._failedModules.get(module.type) || 0;
        score -= failCount * 20; // -20 points per previous failure

        // Factor 4: Content variety bonus
        const recentModuleTypes = this._sessionStats.modulesCompleted
            .slice(-3)
            .map(m => m.name.split('-')[0]); // Get module category
        const moduleCategory = module.type.split('-')[0];
        if (!recentModuleTypes.includes(moduleCategory)) {
            score += 15; // Bonus for variety
        }

        // Factor 5: Workload balancing
        const estimatedWorkload = this._estimateModuleWorkload(module.type, module.content);
        if (estimatedWorkload < 2) {
            score += 10; // Bonus for quick modules
        } else if (estimatedWorkload > 5) {
            score -= 10; // Penalty for long modules
        }

        // Factor 6: Learning path optimization
        if (module.isCore) {
            score += 25; // Prioritize core modules
        }

        return Math.max(0, score); // Never negative
    }

    /**
     * Get performance in similar module types
     */
    _getSimilarModulePerformance(moduleType) {
        const category = moduleType.split('-')[0]; // e.g., 'vocabulary' from 'vocabulary-flashcards'
        const similarModules = this._sessionStats.modulesCompleted.filter(m =>
            m.name.startsWith(category)
        );

        if (similarModules.length === 0) {
            return { count: 0, avgScore: 0 };
        }

        const avgScore = similarModules.reduce((sum, m) => sum + m.score, 0) / similarModules.length;
        return { count: similarModules.length, avgScore };
    }

    /**
     * Estimate user's current level
     */
    _estimateUserLevel() {
        if (this._sessionStats.averageScore >= 85) return 'advanced';
        if (this._sessionStats.averageScore >= 70) return 'intermediate';
        if (this._sessionStats.averageScore >= 50) return 'beginner';
        return 'novice';
    }

    /**
     * Calculate difficulty penalty
     */
    _calculateDifficultyPenalty(moduleDifficulty, userLevel) {
        const difficultyMap = { easy: 1, medium: 2, hard: 3, expert: 4 };
        const levelMap = { novice: 1, beginner: 2, intermediate: 3, advanced: 4 };

        const difficultyScore = difficultyMap[moduleDifficulty] || 2;
        const userScore = levelMap[userLevel] || 2;

        const gap = Math.abs(difficultyScore - userScore);
        return gap * 10; // 10 points penalty per level gap
    }

    /**
     * Track decision for analysis
     */
    _trackDecision(selectedModule, allCandidates, userPerformance) {
        if (!this._sessionStats.decisions) {
            this._sessionStats.decisions = [];
        }

        this._sessionStats.decisions.push({
            timestamp: new Date().toISOString(),
            selected: selectedModule.type,
            selectedScore: selectedModule.score,
            candidates: allCandidates.map(m => ({ type: m.type, score: m.score })),
            userLevel: this._estimateUserLevel(),
            sessionLength: this._sessionStats.modulesCompleted.length
        });
    }

    /**
     * Handle user failure with retry/skip options
     */
    handleUserFailure(exercise, userAnswer, expectedAnswer, attemptNumber = 1) {
        console.group('❌ Handling user failure...');

        // Track the failure
        this._trackUserFailure(exercise, userAnswer, expectedAnswer, attemptNumber);

        // Decide on next action
        const action = this._decideFailureAction(exercise, attemptNumber);
        console.log(`🎯 Failure action decided: ${action.type}`);
        console.groupEnd();

        return action;
    }

    /**
     * Decide what to do after user failure
     */
    _decideFailureAction(exercise, attemptNumber) {
        // Too many attempts on this specific exercise
        if (attemptNumber >= 3) {
            return {
                type: 'skip',
                reason: 'max_attempts_reached',
                message: 'Moving to next exercise after 3 attempts'
            };
        }

        // Easy exercises should be retried quickly
        if (exercise.difficulty === 'easy' && attemptNumber < 2) {
            return {
                type: 'retry',
                reason: 'easy_exercise',
                message: 'Let\'s try again - this should be manageable',
                showHint: true
            };
        }

        // Hard exercises get more chances with help
        if (exercise.difficulty === 'hard' || exercise.difficulty === 'expert') {
            return {
                type: 'retry',
                reason: 'challenging_content',
                message: 'This is challenging - here\'s some help',
                showHint: true,
                simplify: true
            };
        }

        // Default: offer choice
        return {
            type: 'choice',
            reason: 'standard_failure',
            message: 'Would you like to try again or skip this exercise?',
            options: ['retry', 'skip']
        };
    }

    // ===== COMPLETION SYSTEM =====

    /**
     * Complete current module and decide next action
     */
    completeCurrentModule(result) {
        console.group('🏁 Completing current module...');

        const moduleName = this._currentModule?.name || 'unknown';
        console.log(`📋 Module: ${moduleName}`);
        console.log(`📊 Result:`, result);

        // Track completion
        this._trackModuleCompletion(moduleName, result);

        // Generate completion summary
        const summary = this._generateCompletionSummary(result);
        console.log(`📈 Summary:`, summary);

        // Decide next action
        const nextAction = this._decideNextAction(result, summary);
        console.log(`🎯 Next action:`, nextAction);

        console.groupEnd();

        // Execute the decided action
        this._executeNextAction(nextAction, summary);

        return {
            completed: moduleName,
            summary: summary,
            nextAction: nextAction
        };
    }

    /**
     * Generate completion summary
     */
    _generateCompletionSummary(result) {
        const progress = this.getProgressSummary();

        return {
            moduleResult: result,
            sessionProgress: progress,
            userLevel: this._estimateUserLevel(),
            recommendations: this._generateRecommendations(result, progress),
            timeSpent: result.duration || 0,
            efficiency: this._calculateEfficiency(result)
        };
    }

    /**
     * Decide what to do next after module completion
     */
    _decideNextAction(result, summary) {
        // If session is complete
        if (summary.sessionProgress.modules.remaining === 0) {
            return {
                type: 'session_complete',
                message: 'Congratulations! You\'ve completed all available exercises.',
                showFinalReport: true
            };
        }

        // If user is struggling (low score + high failure rate)
        if (result.score < 50 && this._sessionStats.retryCount > 5) {
            return {
                type: 'break_suggested',
                message: 'Consider taking a break. You\'ve been working hard!',
                options: ['continue', 'break', 'easier_content']
            };
        }

        // If user is excelling
        if (result.score > 85 && summary.sessionProgress.modules.completed > 3) {
            return {
                type: 'advance_difficulty',
                message: 'Great performance! Ready for more challenging content?',
                options: ['continue', 'harder_content', 'skip_easy']
            };
        }

        // Standard progression
        return {
            type: 'continue',
            message: 'Ready for the next exercise?',
            autoAdvance: result.score > 70 // Auto-advance if doing well
        };
    }

    /**
     * Execute the decided next action
     */
    _executeNextAction(action, summary) {
        switch (action.type) {
            case 'continue':
                if (action.autoAdvance) {
                    setTimeout(() => this._loadNextModule(), 2000);
                } else {
                    this._showContinuePrompt(action.message);
                }
                break;

            case 'session_complete':
                this._showSessionCompleteScreen(summary);
                break;

            case 'break_suggested':
                this._showBreakSuggestion(action);
                break;

            case 'advance_difficulty':
                this._showDifficultyAdvancement(action);
                break;

            default:
                console.warn('Unknown action type:', action.type);
                this._showContinuePrompt('Ready to continue?');
        }
    }

    /**
     * Generate personalized recommendations
     */
    _generateRecommendations(result, progress) {
        const recommendations = [];

        // Performance-based recommendations
        if (result.score < 60) {
            recommendations.push({
                type: 'review',
                message: 'Consider reviewing this topic before moving on',
                priority: 'high'
            });
        }

        // Workload recommendations
        if (progress.session.duration > 1800000) { // 30 minutes
            recommendations.push({
                type: 'break',
                message: 'You\'ve been studying for a while. A short break might help',
                priority: 'medium'
            });
        }

        // Difficulty recommendations
        const userLevel = this._estimateUserLevel();
        if (userLevel === 'advanced' && result.score > 90) {
            recommendations.push({
                type: 'challenge',
                message: 'Try more challenging exercises to maximize learning',
                priority: 'low'
            });
        }

        return recommendations;
    }

    /**
     * Calculate learning efficiency
     */
    _calculateEfficiency(result) {
        const timeSpent = result.duration || 0;
        const score = result.score || 0;

        if (timeSpent === 0) return 0;

        // Efficiency = score per minute * 100
        const efficiency = (score / (timeSpent / 60000)) * 100;
        return Math.round(efficiency);
    }

    /**
     * Load next module in sequence
     */
    _loadNextModule() {
        // This would integrate with the main module loading system
        console.log('🔄 Loading next module...');

        // Emit event for module loader
        this._eventBus.emit('drs:requestNextModule', {
            currentProgress: this.getProgressSummary(),
            userLevel: this._estimateUserLevel()
        }, this.name);
    }

    /**
     * Get next content for dependency analysis
     * @param {Object} exerciseConfig - Configuration for the upcoming exercise
     * @returns {Promise<Object>} - Content object for analysis
     */
    async getNextContent(exerciseConfig) {
        try {
            console.log('🔍 Getting next content for dependency analysis:', exerciseConfig);

            const exerciseType = exerciseConfig.type || 'text';

            switch (exerciseType) {
                case 'text':
                case 'reading-comprehension':
                case 'reading-comprehension-AI':
                    return await this._getTextContent(exerciseConfig);

                case 'phrase':
                case 'phrase-practice':
                    return await this._getPhraseContent(exerciseConfig);

                case 'dialog':
                case 'listening-comprehension':
                case 'listening-comprehension-AI':
                    return await this._getDialogContent(exerciseConfig);

                case 'audio':
                    return await this._getAudioContent(exerciseConfig);

                default:
                    console.warn(`Unknown exercise type for content analysis: ${exerciseType}`);
                    return await this._getGenericContent(exerciseConfig);
            }

        } catch (error) {
            console.error('Failed to get next content:', error);
            return null;
        }
    }

    /**
     * Get text content for analysis
     */
    async _getTextContent(exerciseConfig) {
        const content = await this._contentLoader.loadExercise({
            type: 'exercise',
            subtype: 'reading-comprehension-AI',
            bookId: exerciseConfig.bookId,
            chapterId: exerciseConfig.chapterId,
            difficulty: exerciseConfig.difficulty || 'medium'
        });

        return {
            type: 'text',
            sentences: content.sentences || [],
            text: content.text || content.content || '',
            metadata: {
                bookId: exerciseConfig.bookId,
                chapterId: exerciseConfig.chapterId,
                difficulty: exerciseConfig.difficulty
            }
        };
    }

    /**
     * Get phrase content for analysis
     */
    async _getPhraseContent(exerciseConfig) {
        const content = await this._contentLoader.getContent(exerciseConfig.chapterId);

        return {
            type: 'phrase',
            phrases: content.phrases || [],
            text: content.phrases ? content.phrases.map(p => p.english || p.text || '').join(' ') : '',
            metadata: {
                bookId: exerciseConfig.bookId,
                chapterId: exerciseConfig.chapterId
            }
        };
    }

    /**
     * Get dialog content for analysis
     */
    async _getDialogContent(exerciseConfig) {
        const content = await this._contentLoader.getContent(exerciseConfig.chapterId);
        const dialogues = this._extractRealDialogues(content);

        return {
            type: 'dialog',
            lines: dialogues.map(d => d.text || d.line || ''),
            dialogs: dialogues,
            text: dialogues.map(d => d.text || d.line || '').join(' '),
            metadata: {
                bookId: exerciseConfig.bookId,
                chapterId: exerciseConfig.chapterId
            }
        };
    }

    /**
     * Get audio content for analysis
     */
    async _getAudioContent(exerciseConfig) {
        const content = await this._contentLoader.loadExercise({
            type: 'exercise',
            subtype: 'listening-comprehension-AI',
            bookId: exerciseConfig.bookId,
            chapterId: exerciseConfig.chapterId,
            difficulty: exerciseConfig.difficulty || 'medium'
        });

        return {
            type: 'audio',
            transcript: content.transcript || content.text || '',
            text: content.transcript || content.text || '',
            metadata: {
                bookId: exerciseConfig.bookId,
                chapterId: exerciseConfig.chapterId
            }
        };
    }

    /**
     * Get generic content for unknown types
     */
    async _getGenericContent(exerciseConfig) {
        try {
            const content = await this._contentLoader.getContent(exerciseConfig.chapterId);

            return {
                type: 'generic',
                text: this._extractAllText(content),
                content: content,
                metadata: {
                    bookId: exerciseConfig.bookId,
                    chapterId: exerciseConfig.chapterId
                }
            };
        } catch (error) {
            console.warn('Failed to get generic content:', error);
            return {
                type: 'generic',
                text: '',
                metadata: {
                    bookId: exerciseConfig.bookId,
                    chapterId: exerciseConfig.chapterId
                }
            };
        }
    }

    /**
     * Extract all text from content object
     */
    _extractAllText(content) {
        let allText = [];

        // Extract from various content types
        if (content.sentences) {
            allText.push(...content.sentences);
        }
        if (content.phrases) {
            allText.push(...content.phrases.map(p => p.english || p.text || ''));
        }
        if (content.dialogs) {
            allText.push(...content.dialogs.map(d => d.text || d.line || ''));
        }
        if (content.text) {
            allText.push(content.text);
        }
        if (content.content) {
            allText.push(content.content);
        }

        return allText.join(' ');
    }

    /**
     * Generic helper to load any exercise via ExerciseFactory
     * @param {string} exerciseType - Type of exercise to load
     * @param {Object} config - Exercise configuration
     * @param {Object} content - Exercise content
     * @returns {Promise<Object>} - Created module instance
     */
    async _loadExerciseViaFactory(exerciseType, config, content) {
        console.log(`🏭 Loading ${exerciseType} via factory...`);

        try {
            // Get dependencies
            const dependencies = await this._getDependencies(config);

            // Use factory to create and render module
            const module = await exerciseFactory.createAndRender(
                exerciseType,
                this._container,
                dependencies,
                config,
                content
            );

            // Store reference for cleanup
            this._currentModule = module;

            console.log(`✅ ${exerciseType} loaded successfully via factory`);
            return module;

        } catch (error) {
            console.error(`❌ Failed to load ${exerciseType}:`, error);
            throw error;
        }
    }

    /**
     * Get dependencies for exercise modules
     * @param {Object} config - Exercise configuration
     * @returns {Promise<Object>} - Dependencies object
     */
    async _getDependencies(config) {
        // Get shared services from orchestrator or create fallbacks
        let prerequisiteEngine = null;
        let contextMemory = null;
        let llmValidator = null;

        try {
            const moduleLoader = window.app.getCore().moduleLoader;
            const orchestrator = moduleLoader.getModule('smartPreviewOrchestrator');
            if (orchestrator && orchestrator.sharedServices) {
                prerequisiteEngine = orchestrator.sharedServices.prerequisiteEngine;
                contextMemory = orchestrator.sharedServices.contextMemory;
                llmValidator = orchestrator.sharedServices.llmValidator;
            }
        } catch (error) {
            console.log('Could not get shared services, will create fallbacks:', error);
        }

        // Create or reuse shared PrerequisiteEngine if not available from orchestrator
        if (!prerequisiteEngine) {
            // Check if we already have a shared instance
            if (this._sharedPrerequisiteEngine) {
                console.log('♻️ Reusing existing shared PrerequisiteEngine');
                prerequisiteEngine = this._sharedPrerequisiteEngine;
            } else {
                console.log('📚 Creating NEW shared PrerequisiteEngine (will be reused)');

                const PrerequisiteEngine = (await import('./services/PrerequisiteEngine.js')).default;
                prerequisiteEngine = new PrerequisiteEngine();

                // Initialize with persistent data for this chapter
                if (config.bookId && config.chapterId) {
                    await prerequisiteEngine.init(config.bookId, config.chapterId);
                }

                // STORE for reuse
                this._sharedPrerequisiteEngine = prerequisiteEngine;

                // Expose globally for getRealContentCoverage()
                if (typeof window !== 'undefined') {
                    window.sharedPrerequisiteEngine = prerequisiteEngine;
                }

                console.log('✅ Shared PrerequisiteEngine created, stored for reuse, and exposed globally');
            }
        }

        // Always update global reference to ensure getRealContentCoverage() has access
        if (prerequisiteEngine && typeof window !== 'undefined') {
            window.sharedPrerequisiteEngine = prerequisiteEngine;
        }

        // Create ContextMemory if not available
        if (!contextMemory) {
            console.log('📚 Creating fallback ContextMemory');
            contextMemory = {
                recordInteraction: (interaction) => {
                    console.log('📝 Interaction recorded (fallback):', interaction.type);
                }
            };
        }

        // LLMValidator is optional (only needed for AI modules)
        if (!llmValidator) {
            console.log('ℹ️ LLMValidator not available (optional for some modules)');
        }

        return {
            orchestrator: this, // UnifiedDRS acts as orchestrator
            prerequisiteEngine: prerequisiteEngine,
            contextMemory: contextMemory,
            llmValidator: llmValidator
        };
    }

    /**
     * Complete current exercise and let Smart Guide decide next one
     * Called by exercise modules when they finish
     */
    async completeExercise(results) {
        console.log('🏁 Exercise completed, transitioning to next...');
        console.log('📊 Results:', results);

        // Destroy current module
        if (this._currentModule && typeof this._currentModule.destroy === 'function') {
            await this._currentModule.destroy();
        }
        this._currentModule = null;

        // Refresh Vocabulary Knowledge modal if it's open
        if (typeof window.refreshVocabularyModalIfOpen === 'function') {
            window.refreshVocabularyModalIfOpen();
            console.log('🔄 Vocabulary modal refreshed with latest data');
        }

        // Force update progress bar with latest data
        if (typeof window.updateProgressBar === 'function') {
            setTimeout(() => {
                window.updateProgressBar();
                console.log('🔄 Progress bar refreshed with latest data');
            }, 500); // Small delay to ensure data is persisted
        }

        // Get Smart Guide components
        try {
            const moduleLoader = window.app.getCore().moduleLoader;
            const intelligentSequencer = moduleLoader.getModule('intelligentSequencer');

            if (!intelligentSequencer) {
                console.warn('⚠️ IntelligentSequencer not available');
                return;
            }

            console.log('🎯 Requesting next exercise from Smart Guide...');

            setTimeout(async () => {
                try {
                    const nextExercise = await intelligentSequencer.getNextExercise();

                    if (nextExercise) {
                        console.log('🎯 Next exercise recommended:', nextExercise);
                        window.updateGuideStatus?.('🔄 Preparing next exercise...');

                        // Use global startGuidedExercise if available
                        if (typeof window.startGuidedExercise === 'function') {
                            setTimeout(() => window.startGuidedExercise(nextExercise), 1500);
                        } else {
                            console.error('❌ startGuidedExercise function not found');
                        }
                    } else {
                        console.log('🎉 Session completed - no more exercises');
                        window.updateGuideStatus?.('🎉 Session Complete!');
                    }
                } catch (error) {
                    console.error('❌ Error loading next exercise:', error);
                    window.updateGuideStatus?.('❌ Error loading next exercise');
                }
            }, 1000);

        } catch (error) {
            console.error('❌ Error accessing Smart Guide:', error);
        }
    }

    /**
     * Clean up UI
     */
    _cleanupUI() {
        if (this._container) {
            this._container.innerHTML = '';
            this._container = null;
        }
        this._isActive = false;
    }
}

export default UnifiedDRS;