import { useEffect, useMemo, useState } from 'react'; import { usePreferencesStore, type ResolvedTheme, type ThemeMode } from '@/store/preferencesStore'; function readSystemTheme(): ResolvedTheme { if (typeof window === 'undefined' || !window.matchMedia) { return 'dark'; } return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'; } function resolveTheme(themeMode: ThemeMode, systemTheme: ResolvedTheme): ResolvedTheme { return themeMode === 'system' ? systemTheme : themeMode; } export function useThemeEffect(): ResolvedTheme { const themeMode = usePreferencesStore((state) => state.themeMode); const [systemTheme, setSystemTheme] = useState(() => readSystemTheme()); useEffect(() => { if (typeof window === 'undefined' || !window.matchMedia) { return undefined; } const media = window.matchMedia('(prefers-color-scheme: light)'); const update = () => setSystemTheme(media.matches ? 'light' : 'dark'); update(); if ('addEventListener' in media) { media.addEventListener('change', update); return () => media.removeEventListener('change', update); } media.addListener(update); return () => media.removeListener(update); }, []); const resolvedTheme = useMemo( () => resolveTheme(themeMode, systemTheme), [systemTheme, themeMode], ); useEffect(() => { document.documentElement.dataset.theme = resolvedTheme; document.documentElement.classList.toggle('dark', resolvedTheme === 'dark'); document.documentElement.style.colorScheme = resolvedTheme; const themeColor = resolvedTheme === 'dark' ? '#0B0E14' : '#F6F8FC'; let themeMeta = document.querySelector('meta[name="theme-color"]'); if (!themeMeta) { themeMeta = document.createElement('meta'); themeMeta.name = 'theme-color'; document.head.appendChild(themeMeta); } themeMeta.content = themeColor; }, [resolvedTheme]); return resolvedTheme; }