/**
 * @fileoverview Settings management service
 * @version 1.0.0
 */

export interface AppSettings {
    ui: {
        hideDisabledNavButtons: boolean;
        hideAllNavButtons: boolean;
        autoAdvanceQuestions: boolean;
        clickToAdvance: boolean;
        showContinueButton: boolean;
        announceSelections: boolean;
        selectionFeedbackDuration: number;
        showQuestionNumbers: boolean;
        enableAnimations: boolean;
        defaultViewMode: 'single' | 'list';
        sidebarExpanded: boolean;
        theme: 'light' | 'dark' | 'auto';
        accessibilityMode: boolean;
    };
    quiz: {
        showHints: boolean;
        confirmBeforeSubmit: boolean;
        highlightAnsweredQuestions: boolean;
        timerEnabled: boolean;
        maxAttempts: number;
    };
    user: {
        role: 'guest' | 'user' | 'admin';
        permissions: string[];
        sessionTimeout: number;
        lastLoginTime: number;
    };
}

export class SettingsService {
    private static instance: SettingsService;
    private settings: AppSettings;
    private listeners: Set<(settings: AppSettings) => void> = new Set();
    private readonly STORAGE_KEY = 'quiz-app-settings';

    private constructor() {
        this.settings = this.getDefaultSettings();
        this.loadSettings();
    }

    static getInstance(): SettingsService {
        if (!SettingsService.instance) {
            SettingsService.instance = new SettingsService();
        }
        return SettingsService.instance;
    }

    private getDefaultSettings(): AppSettings {
        return {
            ui: {
                hideDisabledNavButtons: false,
                hideAllNavButtons: false,
                autoAdvanceQuestions: false,
                clickToAdvance: false,
                showContinueButton: true,
                announceSelections: true,
                selectionFeedbackDuration: 2000,
                showQuestionNumbers: true,
                enableAnimations: true,
                defaultViewMode: 'list',
                sidebarExpanded: true
            },
            quiz: {
                showHints: false,
                confirmBeforeSubmit: true,
                highlightAnsweredQuestions: true
            }
        };
    }

    getSettings(): AppSettings {
        return { ...this.settings };
    }

    updateSettings(updates: Partial<AppSettings>): void {
        this.settings = this.mergeDeep(this.settings, updates);
        this.saveSettings();
        this.notifyListeners();
    }

    updateUISettings(uiSettings: Partial<AppSettings['ui']>): void {
        this.updateSettings({ ui: { ...this.settings.ui, ...uiSettings } });
    }

    updateQuizSettings(quizSettings: Partial<AppSettings['quiz']>): void {
        this.updateSettings({ quiz: { ...this.settings.quiz, ...quizSettings } });
    }

    resetToDefaults(): void {
        this.settings = this.getDefaultSettings();
        this.saveSettings();
        this.notifyListeners();
    }

    subscribe(callback: (settings: AppSettings) => void): () => void {
        this.listeners.add(callback);
        return () => {
            this.listeners.delete(callback);
        };
    }

    private notifyListeners(): void {
        this.listeners.forEach(callback => callback(this.getSettings()));
    }

    private loadSettings(): void {
        try {
            const saved = localStorage.getItem(this.STORAGE_KEY);
            if (saved) {
                const parsed = JSON.parse(saved);
                this.settings = this.mergeDeep(this.getDefaultSettings(), parsed);
            }
        } catch (error) {
            console.warn('Failed to load settings from localStorage:', error);
            this.settings = this.getDefaultSettings();
        }
    }

    private saveSettings(): void {
        try {
            localStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.settings));
        } catch (error) {
            console.error('Failed to save settings to localStorage:', error);
        }
    }

    private mergeDeep(target: any, source: any): any {
        const result = { ...target };
        
        for (const key in source) {
            if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
                result[key] = this.mergeDeep(result[key] || {}, source[key]);
            } else {
                result[key] = source[key];
            }
        }
        
        return result;
    }

    // Specific getters for commonly used settings
    get hideDisabledNavButtons(): boolean {
        return this.settings.ui.hideDisabledNavButtons;
    }

    get autoAdvanceQuestions(): boolean {
        return this.settings.ui.autoAdvanceQuestions;
    }

    get enableAnimations(): boolean {
        return this.settings.ui.enableAnimations;
    }

    get defaultViewMode(): 'single' | 'list' {
        return this.settings.ui.defaultViewMode;
    }

    get showContinueButton(): boolean {
        return this.settings.ui.showContinueButton;
    }

    get announceSelections(): boolean {
        return this.settings.ui.announceSelections;
    }

    get selectionFeedbackDuration(): number {
        return this.settings.ui.selectionFeedbackDuration;
    }
}
