// Main Application Entry Point
import './styles/main.scss';
import { VocabularyApp } from './modules/VocabularyApp.js';
import { VocabularyState } from './modules/VocabularyState.js';

class DramaLingApp {
    constructor() {
        console.log('🚀 Initializing Drama Ling App...');
        this.state = new VocabularyState();
        this.vocabulary = new VocabularyApp(this.state);
        this.init();
    }

    async init() {
        try {
            // Wait for DOM to be ready
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', () => this.setup());
            } else {
                await this.setup();
            }
        } catch (error) {
            console.error('App initialization failed:', error);
            this.showError('應用程式初始化失敗');
        }
    }

    async setup() {
        const app = document.getElementById('app');
        
        try {
            // Initialize vocabulary app
            await this.vocabulary.init();
            
            // Replace loading spinner with vocabulary app
            app.innerHTML = this.vocabulary.render();
            
            // Bind event listeners
            this.vocabulary.bindEvents();
            
            console.log('📚 Drama Ling 詞彙學習應用已載入');
        } catch (error) {
            console.error('Setup failed:', error);
            this.showError('載入詞彙學習功能失敗');
        }
    }

    showError(message) {
        const app = document.getElementById('app');
        app.innerHTML = `
            <div style="
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                text-align: center;
                color: var(--error-red);
                font-size: var(--text-lg);
            ">
                ❌ ${message}
                <br><br>
                <button onclick="location.reload()" style="
                    padding: var(--space-3) var(--space-6);
                    background: var(--primary-teal);
                    color: white;
                    border: none;
                    border-radius: var(--radius-lg);
                    cursor: pointer;
                ">重新載入</button>
            </div>
        `;
    }
}

// Initialize app
new DramaLingApp();