// ====== Application Settings ======

class AppSettings {
    constructor() {
        this.settings = {
            debug: this.isDevelopment(),
            animationEnabled: true,
            soundEnabled: true,
            notifications: true,
            autoSave: true,
            theme: 'light'
        };
        
        this.loadFromStorage();
    }

    isDevelopment() {
        return window.location.hostname === 'localhost' || 
               window.location.hostname === '127.0.0.1';
    }

    loadFromStorage() {
        try {
            const stored = localStorage.getItem('app_settings');
            if (stored) {
                const parsed = JSON.parse(stored);
                this.settings = { ...this.settings, ...parsed };
            }
        } catch (error) {
            console.warn('Failed to load settings from storage:', error);
        }
    }

    saveToStorage() {
        try {
            localStorage.setItem('app_settings', JSON.stringify(this.settings));
        } catch (error) {
            console.warn('Failed to save settings to storage:', error);
        }
    }

    get(key) {
        return this.settings[key];
    }

    set(key, value) {
        this.settings[key] = value;
        this.saveToStorage();
        
        // Trigger setting change event
        this.onSettingChange(key, value);
    }

    onSettingChange(key, value) {
        // Dispatch custom event for other modules to listen to
        const event = new CustomEvent('appSettingChange', {
            detail: { key, value }
        });
        window.dispatchEvent(event);
    }

    // Theme management
    setTheme(theme) {
        this.set('theme', theme);
        document.documentElement.setAttribute('data-theme', theme);
    }

    toggleTheme() {
        const newTheme = this.get('theme') === 'light' ? 'dark' : 'light';
        this.setTheme(newTheme);
    }
}

// Create singleton instance
export const appSettings = new AppSettings();