/**
 * User Preferences Module
 * Manages user preferences and settings persistence
 */

(function() {
    'use strict';

    const STORAGE_KEY = 'aniworld_preferences';

    /**
     * Initialize user preferences
     */
    function initUserPreferences() {
        loadPreferences();
        console.log('[User Preferences] Initialized');
    }

    /**
     * Load preferences from localStorage
     */
    function loadPreferences() {
        try {
            const stored = localStorage.getItem(STORAGE_KEY);
            if (stored) {
                const preferences = JSON.parse(stored);
                applyPreferences(preferences);
            }
        } catch (error) {
            console.error('[User Preferences] Error loading:', error);
        }
    }

    /**
     * Save preferences to localStorage
     */
    function savePreferences(preferences) {
        try {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(preferences));
        } catch (error) {
            console.error('[User Preferences] Error saving:', error);
        }
    }

    /**
     * Apply preferences to the application
     */
    function applyPreferences(preferences) {
        if (preferences.theme) {
            document.documentElement.setAttribute('data-theme', preferences.theme);
        }
        if (preferences.language) {
            // Language preference would be applied here
        }
    }

    /**
     * Get current preferences
     */
    function getPreferences() {
        try {
            const stored = localStorage.getItem(STORAGE_KEY);
            return stored ? JSON.parse(stored) : {};
        } catch (error) {
            console.error('[User Preferences] Error getting preferences:', error);
            return {};
        }
    }

    /**
     * Update specific preference
     */
    function updatePreference(key, value) {
        const preferences = getPreferences();
        preferences[key] = value;
        savePreferences(preferences);
    }

    // Export functions
    window.UserPreferences = {
        load: loadPreferences,
        save: savePreferences,
        get: getPreferences,
        update: updatePreference
    };

    // Initialize on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initUserPreferences);
    } else {
        initUserPreferences();
    }

})();
