File size: 6,812 Bytes
bc2f725
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/**
 * Theme Manager - Dark/Light Mode Toggle
 * Crypto Monitor HF - Enterprise Edition
 */

class ThemeManager {
    constructor() {
        this.storageKey = 'crypto_monitor_theme';
        this.currentTheme = 'light';
        this.listeners = [];
    }

    /**
     * Initialize theme system
     */
    init() {
        // Load saved theme or detect system preference
        this.currentTheme = this.getSavedTheme() || this.getSystemPreference();

        // Apply theme
        this.applyTheme(this.currentTheme, false);

        // Set up theme toggle button
        this.setupToggleButton();

        // Listen for system theme changes
        this.listenToSystemChanges();

        console.log(`[ThemeManager] Initialized with theme: ${this.currentTheme}`);
    }

    /**
     * Get saved theme from localStorage
     */
    getSavedTheme() {
        try {
            return localStorage.getItem(this.storageKey);
        } catch (error) {
            console.warn('[ThemeManager] localStorage not available:', error);
            return null;
        }
    }

    /**
     * Save theme to localStorage
     */
    saveTheme(theme) {
        try {
            localStorage.setItem(this.storageKey, theme);
        } catch (error) {
            console.warn('[ThemeManager] Could not save theme:', error);
        }
    }

    /**
     * Get system theme preference
     */
    getSystemPreference() {
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            return 'dark';
        }
        return 'light';
    }

    /**
     * Apply theme to document
     */
    applyTheme(theme, save = true) {
        const body = document.body;

        // Remove existing theme classes
        body.classList.remove('theme-light', 'theme-dark');

        // Add new theme class
        body.classList.add(`theme-${theme}`);

        // Update current theme
        this.currentTheme = theme;

        // Save to localStorage
        if (save) {
            this.saveTheme(theme);
        }

        // Update toggle button
        this.updateToggleButton(theme);

        // Notify listeners
        this.notifyListeners(theme);

        // Announce to screen readers
        this.announceThemeChange(theme);

        console.log(`[ThemeManager] Applied theme: ${theme}`);
    }

    /**
     * Toggle between light and dark themes
     */
    toggleTheme() {
        const newTheme = this.currentTheme === 'light' ? 'dark' : 'light';
        this.applyTheme(newTheme);
    }

    /**
     * Set specific theme
     */
    setTheme(theme) {
        if (theme !== 'light' && theme !== 'dark') {
            console.warn(`[ThemeManager] Invalid theme: ${theme}`);
            return;
        }
        this.applyTheme(theme);
    }

    /**
     * Get current theme
     */
    getTheme() {
        return this.currentTheme;
    }

    /**
     * Set up theme toggle button
     */
    setupToggleButton() {
        const toggleBtn = document.getElementById('theme-toggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => {
                this.toggleTheme();
            });

            // Keyboard support
            toggleBtn.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    this.toggleTheme();
                }
            });

            // Initial state
            this.updateToggleButton(this.currentTheme);
        }
    }

    /**
     * Update toggle button appearance
     */
    updateToggleButton(theme) {
        const toggleBtn = document.getElementById('theme-toggle');
        const toggleIcon = document.getElementById('theme-toggle-icon');

        if (toggleBtn && toggleIcon) {
            if (theme === 'dark') {
                toggleIcon.textContent = '☀️';
                toggleBtn.setAttribute('aria-label', 'Switch to light mode');
                toggleBtn.setAttribute('title', 'Light Mode');
            } else {
                toggleIcon.textContent = '🌙';
                toggleBtn.setAttribute('aria-label', 'Switch to dark mode');
                toggleBtn.setAttribute('title', 'Dark Mode');
            }
        }
    }

    /**
     * Listen for system theme changes
     */
    listenToSystemChanges() {
        if (window.matchMedia) {
            const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)');

            // Modern browsers
            if (darkModeQuery.addEventListener) {
                darkModeQuery.addEventListener('change', (e) => {
                    // Only auto-change if user hasn't manually set a preference
                    if (!this.getSavedTheme()) {
                        const newTheme = e.matches ? 'dark' : 'light';
                        this.applyTheme(newTheme, false);
                    }
                });
            }
            // Older browsers
            else if (darkModeQuery.addListener) {
                darkModeQuery.addListener((e) => {
                    if (!this.getSavedTheme()) {
                        const newTheme = e.matches ? 'dark' : 'light';
                        this.applyTheme(newTheme, false);
                    }
                });
            }
        }
    }

    /**
     * Register change listener
     */
    onChange(callback) {
        this.listeners.push(callback);
        return () => {
            const index = this.listeners.indexOf(callback);
            if (index > -1) {
                this.listeners.splice(index, 1);
            }
        };
    }

    /**
     * Notify all listeners
     */
    notifyListeners(theme) {
        this.listeners.forEach(callback => {
            try {
                callback(theme);
            } catch (error) {
                console.error('[ThemeManager] Error in listener:', error);
            }
        });
    }

    /**
     * Announce theme change to screen readers
     */
    announceThemeChange(theme) {
        const liveRegion = document.getElementById('sr-live-region');
        if (liveRegion) {
            liveRegion.textContent = `Theme changed to ${theme} mode`;
        }
    }

    /**
     * Reset to system preference
     */
    resetToSystem() {
        try {
            localStorage.removeItem(this.storageKey);
        } catch (error) {
            console.warn('[ThemeManager] Could not remove saved theme:', error);
        }

        const systemTheme = this.getSystemPreference();
        this.applyTheme(systemTheme, false);
    }
}

// Create global instance
window.themeManager = new ThemeManager();

// Auto-initialize on DOMContentLoaded
document.addEventListener('DOMContentLoaded', () => {
    window.themeManager.init();
});

console.log('[ThemeManager] Module loaded');