import { writable } from 'svelte/store'; import { browser } from '$app/environment'; type Theme = 'light' | 'dark' | 'system'; const themeStore = writable('system'); let currentTheme: Theme = 'system'; function setTheme(theme: Theme) { currentTheme = theme; themeStore.set(theme); if (browser) { localStorage.setItem('theme', theme); updateDocumentTheme(theme); } } function updateDocumentTheme(theme: Theme) { if (!browser) return; const root = document.documentElement; if (theme === 'system') { const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; root.classList.toggle('dark', systemTheme === 'dark'); } else { root.classList.toggle('dark', theme === 'dark'); } } function initTheme() { if (!browser) return; // Get saved theme from localStorage const savedTheme = localStorage.getItem('theme') as Theme | null; const initialTheme = savedTheme || 'system'; setTheme(initialTheme); // Listen for system theme changes window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { if (currentTheme === 'system') { updateDocumentTheme('system'); } }); } export { themeStore, setTheme, initTheme };