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

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

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

        this._eventBus = dependencies.eventBus;
        this._content = dependencies.content;
        this._config = {
            container: null,
            difficulty: 'medium',
            maxElements: 6,
            timeLimit: 180,
            ...config
        };

        this._score = 0;
        this._currentStory = [];
        this._availableElements = [];
        this._storyTarget = null;
        this._gameMode = 'vocabulary';
        this._vocabulary = [];
        this._wordsByType = {};
        this._timeLeft = this._config.timeLimit;
        this._isRunning = false;
        this._gameTimer = null;
        this._gameContainer = null;
        this._draggedElement = null;

        Object.seal(this);
    }

    static getMetadata() {
        return {
            id: 'story-builder',
            name: 'Story Builder',
            description: 'Build coherent stories by dragging and arranging words',
            version: '2.0.0',
            author: 'Class Generator',
            category: 'creative',
            tags: ['story', 'building', 'vocabulary', 'creativity'],
            difficulty: {
                min: 1,
                max: 4,
                default: 2
            },
            estimatedDuration: 10,
            requiredContent: ['vocabulary']
        };
    }

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

        let score = 40;

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

            const hasTypes = Object.values(content.vocabulary).some(word =>
                typeof word === 'object' && word.type
            );
            if (hasTypes) score += 5;
        }

        return Math.min(score, 100);
    }

    async init() {
        this._validateNotDestroyed();

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

        this._eventBus.on('game:start', this._handleGameStart.bind(this), this.name);
        this._eventBus.on('game:stop', this._handleGameStop.bind(this), this.name);
        this._eventBus.on('navigation:change', this._handleNavigationChange.bind(this), this.name);

        this._injectCSS();

        // Start game immediately
        try {
            this._gameContainer = this._config.container;
            const content = this._content;

            if (!content) {
                throw new Error('No content available - please select a book or chapter first');
            }

            this._extractVocabulary(content);

            if (!this._vocabulary || this._vocabulary.length < 6) {
                const vocabCount = this._vocabulary ? this._vocabulary.length : 0;
                throw new Error(`Not enough vocabulary for Story Builder (found ${vocabCount}, minimum 6 required). Please select content with more vocabulary words.`);
            }

            this._createGameBoard();
            this._setupEventListeners();
            this._loadStoryContent();

            // Emit game ready event
            this._eventBus.emit('game:ready', {
                gameId: 'story-builder',
                instanceId: this.name,
                vocabulary: this._vocabulary.length
            }, this.name);

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

        this._setInitialized();
    }

    async destroy() {
        this._validateNotDestroyed();

        this._cleanup();
        this._removeCSS();
        this._eventBus.off('game:start', this.name);
        this._eventBus.off('game:stop', this.name);
        this._eventBus.off('navigation:change', this.name);

        this._setDestroyed();
    }

    _handleGameStart(event) {
        this._validateInitialized();
        if (event.gameId === 'story-builder') {
            this._startGame();
        }
    }

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

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

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

            const content = await this._content.getCurrentContent();
            if (!content) {
                throw new Error('No content available');
            }

            this._extractVocabulary(content);

            if (this._vocabulary.length < 6) {
                throw new Error('Not enough vocabulary for Story Builder (minimum 6 words required)');
            }

            this._createGameBoard();
            this._setupEventListeners();
            this._loadStoryContent();

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

    _stopGame() {
        this._cleanup();
    }

    _cleanup() {
        this._isRunning = false;
        if (this._gameTimer) {
            clearInterval(this._gameTimer);
            this._gameTimer = null;
        }
        if (this._gameContainer) {
            this._gameContainer.innerHTML = '';
        }
    }

    _showInitError(message) {
        this._gameContainer.innerHTML = `
            <div class="game-error">
                <h3>❌ Loading Error</h3>
                <p>${message}</p>
                <p>The game requires vocabulary with word types (noun, verb, adjective, etc.).</p>
                <button onclick="window.app.getCore().router.navigate('/games')" class="back-btn">← Back to Games</button>
            </div>
        `;
    }

    _extractVocabulary(content) {
        this._vocabulary = [];

        console.log('StoryBuilder: Extracting vocabulary from content:', content);

        if (!content) {
            console.warn('StoryBuilder: No content provided to _extractVocabulary');
            return;
        }

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

        this._vocabulary = this._vocabulary.filter(item =>
            item &&
            typeof item.original === 'string' &&
            typeof item.translation === 'string' &&
            item.original.trim() !== '' &&
            item.translation.trim() !== ''
        );

        if (!content.vocabulary) {
            console.warn('StoryBuilder: Content has no vocabulary property');
        } else if (Object.keys(content.vocabulary).length === 0) {
            console.warn('StoryBuilder: Content vocabulary is empty');
        } else {
            console.log('StoryBuilder: Content vocabulary keys:', Object.keys(content.vocabulary));
        }

        this._wordsByType = this._groupVocabularyByType(this._vocabulary);
        console.log(`StoryBuilder: ${this._vocabulary.length} words loaded`, this._vocabulary.slice(0, 3));
    }

    _groupVocabularyByType(vocabulary) {
        const grouped = {};

        vocabulary.forEach(word => {
            const type = word.type || 'general';
            if (!grouped[type]) {
                grouped[type] = [];
            }
            grouped[type].push(word);
        });

        return grouped;
    }

    _createGameBoard() {
        this._gameContainer.innerHTML = `
            <div class="story-builder-wrapper">
                <div class="mode-selector">
                    <button class="mode-btn active" data-mode="vocabulary">
                        📚 Vocabulary Story
                    </button>
                    <button class="mode-btn" data-mode="sequence">
                        📝 Sequence
                    </button>
                    <button class="mode-btn" data-mode="dialogue">
                        💬 Dialogue
                    </button>
                    <button class="mode-btn" data-mode="scenario">
                        🎭 Scenario
                    </button>
                </div>

                <div class="game-info">
                    <div class="story-objective" id="story-objective">
                        <h3>Objective:</h3>
                        <p id="objective-text">Choose a mode and let's start!</p>
                    </div>
                    <div class="game-stats">
                        <div class="stat-item">
                            <span class="stat-value" id="time-left">${this._timeLeft}</span>
                            <span class="stat-label">Time</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-value" id="story-progress">0/${this._config.maxElements}</span>
                            <span class="stat-label">Progress</span>
                        </div>
                    </div>
                </div>

                <div class="story-construction">
                    <div class="story-target" id="story-target">
                        <!-- Story to build -->
                    </div>

                    <div class="drop-zone" id="drop-zone">
                        <div class="drop-hint">Drag elements here to build your story</div>
                    </div>
                </div>

                <div class="elements-bank" id="elements-bank">
                    <!-- Available elements -->
                </div>

                <div class="game-controls">
                    <button class="control-btn" id="start-btn">🎮 Start</button>
                    <button class="control-btn" id="check-btn" disabled>✅ Check</button>
                    <button class="control-btn" id="hint-btn" disabled>💡 Hint</button>
                    <button class="control-btn" id="restart-btn">🔄 Restart</button>
                </div>

                <div class="feedback-area" id="feedback-area">
                    <div class="instruction">
                        Select a mode to start building stories!
                    </div>
                </div>
            </div>
        `;
    }

    _setupEventListeners() {
        document.querySelectorAll('.mode-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                if (this._isRunning) return;

                document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                this._gameMode = btn.dataset.mode;

                this._loadStoryContent();
            });
        });

        document.getElementById('start-btn').addEventListener('click', () => this._start());
        document.getElementById('check-btn').addEventListener('click', () => this._checkStory());
        document.getElementById('hint-btn').addEventListener('click', () => this._showHint());
        document.getElementById('restart-btn').addEventListener('click', () => this._restart());

        this._setupDragAndDrop();
    }

    _loadStoryContent() {
        switch (this._gameMode) {
            case 'vocabulary':
                this._setupVocabularyMode();
                break;
            case 'sequence':
                this._setupSequenceMode();
                break;
            case 'dialogue':
                this._setupDialogueMode();
                break;
            case 'scenario':
                this._setupScenarioMode();
                break;
            default:
                this._setupVocabularyMode();
        }
    }

    _setupVocabularyMode() {
        if (Object.keys(this._wordsByType).length === 0) {
            this._setupFallbackContent();
            return;
        }

        this._storyTarget = this._createStoryTemplate();
        this._availableElements = this._selectWordsForStory();

        document.getElementById('objective-text').textContent =
            'Build a coherent story using these words! Use different types: nouns, verbs, adjectives...';
    }

    _createStoryTemplate() {
        const types = Object.keys(this._wordsByType);

        const templates = [
            { pattern: ['noun', 'verb', 'adjective', 'noun'], name: 'Simple Story' },
            { pattern: ['adjective', 'noun', 'verb', 'noun'], name: 'Descriptive Story' },
            { pattern: ['noun', 'verb', 'adjective', 'noun', 'verb'], name: 'Action Story' },
            { pattern: ['article', 'adjective', 'noun', 'verb', 'adverb'], name: 'Rich Story' }
        ];

        const availableTemplate = templates.find(template =>
            template.pattern.every(type =>
                types.includes(type) && this._wordsByType[type].length > 0
            )
        );

        if (availableTemplate) {
            return {
                template: availableTemplate,
                requiredTypes: availableTemplate.pattern
            };
        }

        return {
            template: { pattern: types.slice(0, 4), name: 'Custom Story' },
            requiredTypes: types.slice(0, 4)
        };
    }

    _selectWordsForStory() {
        const words = [];

        if (this._storyTarget && this._storyTarget.requiredTypes) {
            this._storyTarget.requiredTypes.forEach(type => {
                if (this._wordsByType[type] && this._wordsByType[type].length > 0) {
                    const typeWords = this._shuffleArray([...this._wordsByType[type]]).slice(0, 3);
                    words.push(...typeWords);
                }
            });
        }

        const allTypes = Object.keys(this._wordsByType);
        allTypes.forEach(type => {
            if (this._wordsByType[type] && this._wordsByType[type].length > 0) {
                const extraWords = this._shuffleArray([...this._wordsByType[type]]).slice(0, 1);
                words.push(...extraWords);
            }
        });

        const uniqueWords = words.filter((word, index, self) =>
            self.findIndex(w => w.original === word.original) === index
        );

        return this._shuffleArray(uniqueWords).slice(0, this._config.maxElements);
    }

    _setupSequenceMode() {
        const actionWords = this._wordsByType.verb || [];
        const objectWords = this._wordsByType.noun || [];

        if (actionWords.length >= 2 && objectWords.length >= 2) {
            this._storyTarget = {
                type: 'sequence',
                steps: [
                    { order: 1, text: `First: ${actionWords[0].original}`, word: actionWords[0] },
                    { order: 2, text: `Then: ${actionWords[1].original}`, word: actionWords[1] },
                    { order: 3, text: `With: ${objectWords[0].original}`, word: objectWords[0] },
                    { order: 4, text: `Finally: ${objectWords[1].original}`, word: objectWords[1] }
                ]
            };

            this._availableElements = this._shuffleArray([...this._storyTarget.steps]);
            document.getElementById('objective-text').textContent =
                'Put these actions in logical order!';
        } else {
            this._setupVocabularyMode();
        }
    }

    _setupDialogueMode() {
        const greetings = this._wordsByType.greeting || [];
        const nouns = this._wordsByType.noun || [];
        const verbs = this._wordsByType.verb || [];

        if (greetings.length >= 1 && (nouns.length >= 2 || verbs.length >= 2)) {
            const dialogue = [
                { speaker: 'A', text: greetings[0].original, word: greetings[0] },
                { speaker: 'B', text: greetings[0].translation, word: greetings[0] }
            ];

            if (verbs.length >= 1) {
                dialogue.push({ speaker: 'A', text: verbs[0].original, word: verbs[0] });
            }
            if (nouns.length >= 1) {
                dialogue.push({ speaker: 'B', text: nouns[0].original, word: nouns[0] });
            }

            this._storyTarget = { type: 'dialogue', conversation: dialogue };
            this._availableElements = this._shuffleArray([...dialogue]);

            document.getElementById('objective-text').textContent =
                'Reconstruct this dialogue in the right order!';
        } else {
            this._setupVocabularyMode();
        }
    }

    _setupScenarioMode() {
        const allWords = Object.values(this._wordsByType).flat();

        if (allWords.length >= 4) {
            const scenario = {
                context: 'Daily Life',
                elements: this._shuffleArray(allWords).slice(0, 6)
            };

            this._storyTarget = { type: 'scenario', scenario };
            this._availableElements = [...scenario.elements];

            document.getElementById('objective-text').textContent =
                `Create a story about: "${scenario.context}" using these words!`;
        } else {
            this._setupVocabularyMode();
        }
    }

    _setupFallbackContent() {
        if (this._vocabulary.length >= 4) {
            this._availableElements = this._shuffleArray([...this._vocabulary]).slice(0, 6);
            this._gameMode = 'vocabulary';

            document.getElementById('objective-text').textContent =
                'Build a story with these words!';
        } else {
            document.getElementById('objective-text').textContent =
                'Not enough vocabulary available. Please select different content.';
        }
    }

    _start() {
        if (this._isRunning || this._availableElements.length === 0) return;

        this._isRunning = true;
        this._score = 0;
        this._currentStory = [];
        this._timeLeft = this._config.timeLimit;

        this._renderElements();
        this._startTimer();
        this._updateUI();

        document.getElementById('start-btn').disabled = true;
        document.getElementById('check-btn').disabled = false;
        document.getElementById('hint-btn').disabled = false;

        this._showFeedback('Drag the elements in order to build your story!', 'info');
    }

    _renderElements() {
        const elementsBank = document.getElementById('elements-bank');
        elementsBank.innerHTML = '<h4>Available elements:</h4>';

        this._availableElements.forEach((element, index) => {
            const elementDiv = this._createElement(element, index);
            elementsBank.appendChild(elementDiv);
        });
    }

    _createElement(element, index) {
        const div = document.createElement('div');
        div.className = 'story-element';
        div.draggable = true;
        div.dataset.index = index;

        if (element.original && element.translation) {
            div.innerHTML = `
                <div class="element-content">
                    <div class="original">${element.original}</div>
                    <div class="translation">${element.translation}</div>
                    ${element.type ? `<div class="word-type">${element.type}</div>` : ''}
                </div>
            `;
        } else if (element.text || element.original) {
            div.innerHTML = `
                <div class="element-content">
                    <div class="original">${element.text || element.original}</div>
                    ${element.translation ? `<div class="translation">${element.translation}</div>` : ''}
                    ${element.speaker ? `<div class="speaker">${element.speaker}:</div>` : ''}
                </div>
            `;
        } else if (element.word) {
            div.innerHTML = `
                <div class="element-content">
                    <div class="original">${element.word.original}</div>
                    <div class="translation">${element.word.translation}</div>
                    ${element.word.type ? `<div class="word-type">${element.word.type}</div>` : ''}
                </div>
            `;
        } else if (typeof element === 'string') {
            div.innerHTML = `<div class="element-content">${element}</div>`;
        }

        if (element.type) {
            div.classList.add(`type-${element.type}`);
        }

        return div;
    }

    _setupDragAndDrop() {
        document.addEventListener('dragstart', (e) => {
            if (e.target.classList.contains('story-element')) {
                this._draggedElement = e.target;
                e.target.style.opacity = '0.5';
            }
        });

        document.addEventListener('dragend', (e) => {
            if (e.target.classList.contains('story-element')) {
                e.target.style.opacity = '1';
                this._draggedElement = null;
            }
        });

        const dropZone = document.getElementById('drop-zone');

        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.add('drag-over');
        });

        dropZone.addEventListener('dragleave', () => {
            dropZone.classList.remove('drag-over');
        });

        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('drag-over');

            if (this._draggedElement && this._isRunning) {
                this._addToStory(this._draggedElement);
            }
        });
    }

    _addToStory(elementDiv) {
        const index = parseInt(elementDiv.dataset.index);
        const element = this._availableElements[index];

        this._currentStory.push({ element, originalIndex: index });

        const storyElement = elementDiv.cloneNode(true);
        storyElement.classList.add('in-story');
        storyElement.draggable = false;

        const removeBtn = document.createElement('button');
        removeBtn.className = 'remove-element';
        removeBtn.innerHTML = '×';
        removeBtn.onclick = () => this._removeFromStory(storyElement, element);
        storyElement.appendChild(removeBtn);

        document.getElementById('drop-zone').appendChild(storyElement);
        elementDiv.style.display = 'none';

        this._updateProgress();
    }

    _removeFromStory(storyElement, element) {
        this._currentStory = this._currentStory.filter(item => item.element !== element);
        storyElement.remove();

        const originalElement = document.querySelector(`[data-index="${this._availableElements.indexOf(element)}"]`);
        if (originalElement) {
            originalElement.style.display = 'block';
        }

        this._updateProgress();
    }

    _checkStory() {
        if (this._currentStory.length === 0) {
            this._showFeedback('Add at least one element to your story!', 'error');
            return;
        }

        const isCorrect = this._validateStory();

        if (isCorrect) {
            this._score += this._currentStory.length * 10;
            this._showFeedback('Bravo! Perfect story! 🎉', 'success');

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

            setTimeout(() => {
                this._nextChallenge();
            }, 2000);
        } else {
            this._score = Math.max(0, this._score - 5);
            this._showFeedback('Almost! Check the order of your story 🤔', 'warning');

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

    _validateStory() {
        switch (this._gameMode) {
            case 'vocabulary':
                return this._validateVocabularyStory();
            case 'sequence':
                return this._validateSequence();
            case 'dialogue':
                return this._validateDialogue();
            case 'scenario':
                return this._validateScenario();
            default:
                return true;
        }
    }

    _validateVocabularyStory() {
        if (this._currentStory.length < 3) return false;

        const typesUsed = new Set();
        this._currentStory.forEach(item => {
            const element = item.element;
            if (element.type) {
                typesUsed.add(element.type);
            }
        });

        return typesUsed.size >= 2;
    }

    _validateSequence() {
        if (!this._storyTarget?.steps) return true;

        const expectedOrder = this._storyTarget.steps.sort((a, b) => a.order - b.order);

        if (this._currentStory.length !== expectedOrder.length) return false;

        return this._currentStory.every((item, index) => {
            const expected = expectedOrder[index];
            return item.element.order === expected.order;
        });
    }

    _validateDialogue() {
        return this._currentStory.length >= 2;
    }

    _validateScenario() {
        return this._currentStory.length >= 3;
    }

    _showHint() {
        switch (this._gameMode) {
            case 'vocabulary':
                const typesAvailable = Object.keys(this._wordsByType);
                this._showFeedback(`Tip: Try using different word types: ${typesAvailable.join(', ')}`, 'info');
                break;
            case 'sequence':
                if (this._storyTarget?.steps) {
                    const nextStep = this._storyTarget.steps.find(step =>
                        !this._currentStory.some(item => item.element.order === step.order)
                    );
                    if (nextStep) {
                        this._showFeedback(`Next step: "${nextStep.text}"`, 'info');
                    }
                }
                break;
            case 'dialogue':
                this._showFeedback('Think about the natural order of a conversation!', 'info');
                break;
            case 'scenario':
                this._showFeedback('Create a coherent story in this context!', 'info');
                break;
            default:
                this._showFeedback('Tip: Think about the logical order of events!', 'info');
        }
    }

    _nextChallenge() {
        this._loadStoryContent();
        this._currentStory = [];
        document.getElementById('drop-zone').innerHTML = '<div class="drop-hint">Drag elements here to build your story</div>';
        this._renderElements();
        this._updateProgress();
    }

    _startTimer() {
        this._gameTimer = setInterval(() => {
            this._timeLeft--;
            this._updateUI();

            if (this._timeLeft <= 0) {
                this._endGame();
            }
        }, 1000);
    }

    _endGame() {
        this._isRunning = false;
        if (this._gameTimer) {
            clearInterval(this._gameTimer);
            this._gameTimer = null;
        }

        document.getElementById('start-btn').disabled = false;
        document.getElementById('check-btn').disabled = true;
        document.getElementById('hint-btn').disabled = true;

        this._eventBus.emit('game:end', {
            gameId: 'story-builder',
            score: this._score,
            module: this.name
        });
    }

    _restart() {
        this._endGame();
        this._score = 0;
        this._currentStory = [];
        this._timeLeft = this._config.timeLimit;

        document.getElementById('drop-zone').innerHTML = '<div class="drop-hint">Drag elements here to build your story</div>';
        this._loadStoryContent();
        this._updateUI();
    }

    _updateProgress() {
        document.getElementById('story-progress').textContent =
            `${this._currentStory.length}/${this._config.maxElements}`;
    }

    _updateUI() {
        document.getElementById('time-left').textContent = this._timeLeft;
    }

    _showFeedback(message, type = 'info') {
        const feedbackArea = document.getElementById('feedback-area');
        feedbackArea.innerHTML = `<div class="instruction ${type}">${message}</div>`;
    }

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

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

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

            .mode-selector {
                display: flex;
                gap: 10px;
                margin-bottom: 20px;
                justify-content: center;
                flex-wrap: wrap;
            }

            .mode-btn {
                padding: 10px 20px;
                border: 2px solid #e5e7eb;
                border-radius: 25px;
                background: white;
                cursor: pointer;
                transition: all 0.3s ease;
                font-weight: 500;
            }

            .mode-btn.active {
                background: linear-gradient(135deg, #3b82f6, #1d4ed8);
                color: white;
                border-color: #3b82f6;
            }

            .mode-btn:hover:not(.active) {
                border-color: #3b82f6;
                background: #f0f9ff;
            }

            .game-info {
                display: grid;
                grid-template-columns: 2fr 1fr;
                gap: 20px;
                margin-bottom: 25px;
            }

            .story-objective {
                background: linear-gradient(135deg, #f0f9ff, #dbeafe);
                border-radius: 12px;
                padding: 20px;
                border-left: 4px solid #3b82f6;
            }

            .story-objective h3 {
                color: #3b82f6;
                margin: 0 0 8px 0;
            }

            .story-objective p {
                margin: 0;
                color: #374151;
            }

            .game-stats {
                display: flex;
                justify-content: space-around;
                align-items: center;
                background: white;
                border-radius: 12px;
                padding: 20px;
                border: 2px solid #e5e7eb;
            }

            .stat-item {
                text-align: center;
            }

            .stat-value {
                font-size: 1.5em;
                font-weight: bold;
                display: block;
                color: #3b82f6;
            }

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

            .story-construction {
                background: #f8f9fa;
                border-radius: 12px;
                padding: 20px;
                margin: 20px 0;
            }

            .story-target {
                background: white;
                border-radius: 8px;
                padding: 15px;
                margin-bottom: 15px;
                border-left: 4px solid #3b82f6;
            }

            .drop-zone {
                min-height: 120px;
                border: 3px dashed #ddd;
                border-radius: 12px;
                padding: 20px;
                text-align: center;
                display: flex;
                flex-wrap: wrap;
                gap: 10px;
                align-items: center;
                justify-content: center;
                transition: all 0.3s ease;
            }

            .drop-zone.drag-over {
                border-color: #3b82f6;
                background: rgba(59, 130, 246, 0.1);
            }

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

            .elements-bank {
                background: white;
                border-radius: 12px;
                padding: 20px;
                margin: 20px 0;
                border: 2px solid #e5e7eb;
            }

            .elements-bank h4 {
                margin-bottom: 15px;
                color: #3b82f6;
            }

            .story-element {
                display: inline-block;
                background: white;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                padding: 12px;
                margin: 8px;
                cursor: grab;
                transition: all 0.3s ease;
                position: relative;
                min-width: 150px;
            }

            .story-element:hover {
                border-color: #3b82f6;
                transform: translateY(-2px);
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            }

            .story-element:active {
                cursor: grabbing;
            }

            .story-element.in-story {
                background: #10b981;
                color: white;
                border-color: #10b981;
                cursor: default;
                margin: 5px;
            }

            .element-content {
                text-align: center;
            }

            .original {
                font-weight: 600;
                margin-bottom: 4px;
            }

            .translation {
                font-size: 0.9rem;
                color: #6b7280;
            }

            .word-type {
                font-size: 0.8rem;
                color: #9ca3af;
                font-style: italic;
                margin-top: 2px;
            }

            .speaker {
                font-size: 0.8rem;
                color: #ef4444;
                font-weight: bold;
                margin-bottom: 2px;
            }

            .story-element.in-story .translation {
                color: rgba(255,255,255,0.8);
            }

            .story-element.in-story .word-type {
                color: rgba(255,255,255,0.6);
            }

            .story-element.type-noun {
                border-left: 4px solid #3b82f6;
            }

            .story-element.type-verb {
                border-left: 4px solid #10b981;
            }

            .story-element.type-adjective {
                border-left: 4px solid #f59e0b;
            }

            .story-element.type-adverb {
                border-left: 4px solid #8b5cf6;
            }

            .story-element.type-greeting {
                border-left: 4px solid #ef4444;
            }

            .remove-element {
                position: absolute;
                top: -5px;
                right: -5px;
                width: 20px;
                height: 20px;
                background: #ef4444;
                color: white;
                border: none;
                border-radius: 50%;
                font-size: 12px;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
            }

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

            .control-btn {
                padding: 12px 25px;
                border: none;
                border-radius: 25px;
                font-size: 1.1em;
                font-weight: bold;
                cursor: pointer;
                transition: all 0.3s ease;
                background: linear-gradient(135deg, #3b82f6, #1d4ed8);
                color: white;
            }

            .control-btn:hover:not(:disabled) {
                transform: translateY(-2px);
                box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4);
            }

            .control-btn:disabled {
                opacity: 0.6;
                cursor: not-allowed;
                transform: none;
            }

            .feedback-area {
                background: #f3f4f6;
                border-radius: 12px;
                padding: 20px;
                text-align: center;
                min-height: 60px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .instruction {
                font-size: 1.1em;
                font-weight: 500;
                color: #374151;
            }

            .instruction.success {
                color: #10b981;
                font-weight: bold;
            }

            .instruction.error {
                color: #ef4444;
                font-weight: bold;
            }

            .instruction.warning {
                color: #f59e0b;
                font-weight: bold;
            }

            .instruction.info {
                color: #3b82f6;
                font-weight: bold;
            }

            .game-error {
                background: rgba(239, 68, 68, 0.1);
                border: 2px solid #ef4444;
                border-radius: 15px;
                padding: 30px;
                text-align: center;
                color: #374151;
            }

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

            .back-btn {
                background: linear-gradient(135deg, #6b7280, #4b5563);
                color: white;
                border: none;
                padding: 12px 25px;
                border-radius: 25px;
                font-size: 1.1em;
                font-weight: bold;
                cursor: pointer;
                margin-top: 20px;
                transition: all 0.3s ease;
            }

            .back-btn:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 15px rgba(107, 114, 128, 0.4);
            }

            @media (max-width: 768px) {
                .story-builder-wrapper {
                    padding: 15px;
                }

                .game-info {
                    grid-template-columns: 1fr;
                    gap: 15px;
                }

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

                .story-element {
                    min-width: 120px;
                    padding: 8px;
                    margin: 5px;
                }

                .drop-zone {
                    min-height: 100px;
                    padding: 15px;
                }

                .elements-bank {
                    padding: 15px;
                }

                .game-controls {
                    flex-direction: column;
                    align-items: center;
                }

                .control-btn {
                    width: 100%;
                    max-width: 200px;
                }
            }
        `;

        document.head.appendChild(style);
    }

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

export default StoryBuilder;