/**
 * WordDiscoveryModule - Introduces new vocabulary words (10 at a time)
 * Shows word, pronunciation, meaning, and example before flashcard practice
 */

import DRSExerciseInterface from '../interfaces/DRSExerciseInterface.js';

class WordDiscoveryModule extends DRSExerciseInterface {
    constructor(orchestrator, llmValidator, prerequisiteEngine, contextMemory) {
        super('WordDiscoveryModule');
        this.orchestrator = orchestrator;
        this.llmValidator = llmValidator;
        this.prerequisiteEngine = prerequisiteEngine;
        this.contextMemory = contextMemory;

        this.config = {
            wordsPerSession: 10,
            showPronunciation: true,
            showExamples: true,
            autoAdvanceTime: 8000 // 8 seconds per word
        };

        this.currentWords = [];
        this.currentWordIndex = 0;
        this.discoveredWords = new Set();
        this.isActive = false;
    }

    /**
     * Check if module can run (when there are undiscovered words)
     */
    canRun(prerequisites, chapterContent) {
        const allWords = this._getAllWords(chapterContent);
        if (allWords.length === 0) return false;

        // Find words that haven't been discovered yet
        const undiscoveredWords = allWords.filter(wordObj => {
            return !this.prerequisiteEngine.isDiscovered(wordObj.word);
        });

        console.log(`📖 Found ${undiscoveredWords.length} undiscovered words`);
        return undiscoveredWords.length > 0;
    }

    /**
     * Get all words from letters and vocabulary sections
     * Letters (phonics) are loaded FIRST to prioritize them
     */
    _getAllWords(chapterContent) {
        const words = [];

        // Get words from letters section FIRST (phonics) - array format
        if (chapterContent?.letters) {
            for (const [letterKey, letterData] of Object.entries(chapterContent.letters)) {
                if (Array.isArray(letterData)) {
                    for (const wordEntry of letterData) {
                        words.push({
                            word: wordEntry.word,
                            data: {
                                user_language: wordEntry.translation,
                                translation: wordEntry.translation,
                                type: wordEntry.type,
                                pronunciation: wordEntry.pronunciation,
                                image: wordEntry.image,
                                letterGroup: letterKey
                            }
                        });
                    }
                }
            }
        }

        // Get words from vocabulary section
        if (chapterContent?.vocabulary) {
            for (const [word, data] of Object.entries(chapterContent.vocabulary)) {
                words.push({ word, data });
            }
        }

        return words;
    }

    /**
     * Present word discovery interface
     */
    async present(container, exerciseData) {
        this.container = container;
        this.isActive = true;

        // Get undiscovered words from chapter content (vocabulary + letters)
        const chapterContent = exerciseData.chapterContent || {};
        const allWords = this._getAllWords(chapterContent);

        this.undiscoveredWords = allWords.filter(wordObj => {
            return !this.prerequisiteEngine.isDiscovered(wordObj.word);
        });

        // Take next 10 undiscovered words
        this.currentWords = this.undiscoveredWords.slice(0, this.config.wordsPerSession);

        this.currentWordIndex = 0;

        console.log(`📚 Starting word discovery for ${this.currentWords.length} words`);

        this._createDiscoveryInterface();
        this._showCurrentWord();
    }

    /**
     * Create the discovery interface
     */
    _createDiscoveryInterface() {
        this.container.innerHTML = `
            <div class="word-discovery">
                <div class="discovery-header">
                    <h2>📖 Word Discovery</h2>
                    <div class="progress-info">
                        <span id="word-counter">Word 1 of ${this.currentWords.length}</span>
                        <div class="progress-bar">
                            <div class="progress-fill" id="discovery-progress" style="width: 0%"></div>
                        </div>
                    </div>
                </div>

                <div class="word-display" id="word-display">
                    <!-- Word content will be shown here -->
                </div>

                <div class="discovery-controls">
                    <button id="prev-word" class="btn btn-secondary" disabled>← Previous</button>
                    <button id="next-word" class="btn btn-primary">Next →</button>
                    <button id="complete-discovery" class="btn btn-success" style="display: none;">Complete Discovery</button>
                </div>

                <div class="discovery-info">
                    <p>Take your time to learn each word. Click "Next" when you're ready to continue.</p>
                </div>
            </div>
        `;

        this._attachEventListeners();
    }

    /**
     * Show current word with all details
     */
    async _showCurrentWord() {
        if (this.currentWordIndex >= this.currentWords.length) {
            await this._completeDiscovery();
            return;
        }

        const currentWord = this.currentWords[this.currentWordIndex];
        const wordData = currentWord.data;

        // DEBUG: Check image data
        console.log('🖼️ WordDiscovery showing word:', currentWord.word);
        console.log('🖼️ Word data:', wordData);
        console.log('🖼️ Has image?', wordData.image ? 'YES: ' + wordData.image : 'NO');

        // Build image HTML if image exists
        const imageHtml = wordData.image ? `
            <div class="word-image">
                <img src="content/${wordData.image}" alt="${currentWord.word}" onerror="console.error('Image failed to load:', 'content/${wordData.image}'); this.style.display='none'" onload="console.log('✓ Image loaded:', 'content/${wordData.image}')">
            </div>
        ` : '';

        const wordDisplay = document.getElementById('word-display');
        wordDisplay.innerHTML = `
            <div class="word-card ${wordData.image ? 'with-image' : ''}">
                ${imageHtml}
                <div class="word-main">
                    <h1 class="word-text">${currentWord.word}</h1>
                    ${this.config.showPronunciation && wordData.pronunciation ?
                        `<div class="word-pronunciation">${wordData.pronunciation}</div>` : ''
                    }
                </div>

                <div class="word-details">
                    <div class="word-meaning">
                        <h3>Meaning</h3>
                        <p>${wordData.user_language || wordData.translation || 'Definition not available'}</p>
                    </div>

                    ${wordData.type ? `
                        <div class="word-type">
                            <h3>Type</h3>
                            <span class="type-badge">${wordData.type}</span>
                        </div>
                    ` : ''}

                    ${this.config.showExamples ? `
                        <div class="word-example">
                            <h3>Example</h3>
                            <p>"${this._generateExample(currentWord.word)}"</p>
                        </div>
                    ` : ''}
                </div>
            </div>
        `;

        this._updateProgress();
        this._updateControls();
    }

    /**
     * Generate a simple example sentence
     */
    _generateExample(word) {
        const examples = {
            // Simple example patterns
            'default': `I need to learn the word "${word}".`
        };

        return examples.default;
    }

    /**
     * Update progress bar and counter
     */
    _updateProgress() {
        const progress = ((this.currentWordIndex + 1) / this.currentWords.length) * 100;
        const progressBar = document.getElementById('discovery-progress');
        const counter = document.getElementById('word-counter');

        if (progressBar) {
            progressBar.style.width = `${progress}%`;
        }

        if (counter) {
            counter.textContent = `Word ${this.currentWordIndex + 1} of ${this.currentWords.length}`;
        }
    }

    /**
     * Update control buttons
     */
    _updateControls() {
        const prevBtn = document.getElementById('prev-word');
        const nextBtn = document.getElementById('next-word');
        const completeBtn = document.getElementById('complete-discovery');

        if (prevBtn) {
            prevBtn.disabled = this.currentWordIndex === 0;
        }

        if (this.currentWordIndex === this.currentWords.length - 1) {
            if (nextBtn) nextBtn.style.display = 'none';
            if (completeBtn) completeBtn.style.display = 'inline-block';
        } else {
            if (nextBtn) nextBtn.style.display = 'inline-block';
            if (completeBtn) completeBtn.style.display = 'none';
        }
    }

    /**
     * Attach event listeners
     */
    _attachEventListeners() {
        const prevBtn = document.getElementById('prev-word');
        const nextBtn = document.getElementById('next-word');
        const completeBtn = document.getElementById('complete-discovery');

        if (prevBtn) {
            prevBtn.addEventListener('click', () => this._previousWord());
        }

        if (nextBtn) {
            nextBtn.addEventListener('click', () => this._nextWord());
        }

        if (completeBtn) {
            completeBtn.addEventListener('click', () => this._completeDiscovery());
        }

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

            switch(e.code) {
                case 'ArrowLeft':
                    e.preventDefault();
                    this._previousWord();
                    break;
                case 'ArrowRight':
                case 'Space':
                case 'Enter':
                    e.preventDefault();
                    this._nextWord();
                    break;
            }
        });
    }

    /**
     * Go to previous word
     */
    async _previousWord() {
        if (this.currentWordIndex > 0) {
            this.currentWordIndex--;
            await this._showCurrentWord();
        }
    }

    /**
     * Go to next word
     */
    async _nextWord() {
        if (this.currentWordIndex < this.currentWords.length - 1) {
            this.currentWordIndex++;
            await this._showCurrentWord();
        }
    }

    /**
     * Complete discovery session
     */
    async _completeDiscovery() {
        // Mark all current words as discovered (MUST await to ensure persistence)
        for (const wordObj of this.currentWords) {
            await this.prerequisiteEngine.markWordDiscovered(wordObj.word, {
                sessionId: Date.now(),
                moduleType: 'word-discovery',
                timestamp: new Date().toISOString()
            });
            this.discoveredWords.add(wordObj.word);
        }

        console.log(`✅ Discovery completed for ${this.currentWords.length} words`);

        // Show completion message with single "Continue" button
        this.container.innerHTML = `
            <div class="discovery-complete">
                <h2>🎉 Word Discovery Complete!</h2>
                <p>You've discovered ${this.currentWords.length} new words.</p>

                <div class="discovered-words">
                    ${this.currentWords.map(w => `<span class="discovered-word">${w.word}</span>`).join('')}
                </div>

                <button id="continue-btn" class="btn btn-primary">
                    Continue →
                </button>
            </div>
        `;

        // Attach event listener to Continue button
        document.getElementById('continue-btn')?.addEventListener('click', () => {
            // Complete exercise and let orchestrator decide next step
            if (this.orchestrator && this.orchestrator.completeExercise) {
                this.orchestrator.completeExercise({
                    moduleType: 'word-discovery',
                    wordsDiscovered: this.currentWords.length,
                    words: this.currentWords.map(w => w.word),
                    score: 100, // Discovery is always successful
                    completed: true
                });
            } else {
                console.log('✅ Word Discovery completed, orchestrator will decide next exercise');
            }
        });

        this.isActive = false;
    }

    /**
     * Validate method (not used for discovery)
     */
    async validate(userInput, context) {
        return { score: 1, feedback: 'Discovery completed', isCorrect: true };
    }

    /**
     * Get progress
     */
    getProgress() {
        return {
            type: 'word-discovery',
            wordsDiscovered: this.discoveredWords.size,
            currentSession: this.currentWords.length,
            progress: this.currentWordIndex / Math.max(this.currentWords.length, 1)
        };
    }

    /**
     * Cleanup
     */
    cleanup() {
        this.isActive = false;
        if (this.container) {
            this.container.innerHTML = '';
        }
    }

    /**
     * Get metadata
     */
    getMetadata() {
        return {
            name: 'Word Discovery',
            type: 'vocabulary-discovery',
            difficulty: 'beginner',
            estimatedTime: this.config.wordsPerSession * 30, // 30 seconds per word
            capabilities: ['vocabulary_introduction', 'word_learning'],
            prerequisites: []
        };
    }

    // ========================================
    // DRSExerciseInterface REQUIRED METHODS
    // ========================================

    async init(config = {}, content = {}) {
        this.config = { ...this.config, ...config };
        this.currentExerciseData = content;
        this.startTime = Date.now();
        this.initialized = true;
    }

    async render(container) {
        if (!this.initialized) throw new Error('WordDiscoveryModule must be initialized before rendering');
        await this.present(container, this.currentExerciseData);
    }

    async destroy() {
        this.cleanup?.();
        this.container = null;
        this.initialized = false;
    }

    getResults() {
        return {
            score: this.progress?.averageScore ? Math.round(this.progress.averageScore * 100) : 0,
            attempts: this.userResponses?.length || 0,
            timeSpent: this.startTime ? Date.now() - this.startTime : 0,
            completed: true,
            details: { progress: this.progress, responses: this.userResponses }
        };
    }

    handleUserInput(event, data) {
        if (event?.type === 'input') this._handleInputChange?.(event);
        if (event?.type === 'click' && event.target.id === 'submitButton') this._handleSubmit?.(event);
    }

    async markCompleted(results) {
        const { score, details } = results || this.getResults();
        if (this.contextMemory) {
            this.contextMemory.recordInteraction({
                type: 'word-discovery',
                subtype: 'completion',
                content: this.currentExerciseData,
                validation: { score },
                context: { moduleType: 'word-discovery' }
            });
        }
    }

    getExerciseType() {
        return 'word-discovery';
    }

    getExerciseConfig() {
        return {
            type: this.getExerciseType(),
            difficulty: this.currentExerciseData?.difficulty || 'medium',
            estimatedTime: 5,
            prerequisites: [],
            metadata: { ...this.config, requiresAI: false }
        };
    }

}

export default WordDiscoveryModule;