import { createContext, useContext, useState, useCallback, useMemo, useEffect } from 'react'; export type Theme = 'dark' | 'light'; interface ThemeContextType { theme: Theme; toggleTheme: () => void; setTheme: (theme: Theme) => void; isDark: boolean; isLight: boolean; } const ThemeContext = createContext(null); function getInitialTheme(): Theme { if (typeof window === 'undefined') return 'dark'; const stored = localStorage.getItem('dg-theme') as Theme | null; if (stored === 'dark' || stored === 'light') return stored; return 'dark'; } function applyTheme(theme: Theme) { document.documentElement.setAttribute('data-theme', theme); } export function ThemeProvider({ children }: { children: React.ReactNode }) { const [theme, setThemeState] = useState(getInitialTheme); useEffect(() => { applyTheme(theme); }, [theme]); const toggleTheme = useCallback(() => { setThemeState(prev => { const next = prev === 'dark' ? 'light' : 'dark'; localStorage.setItem('dg-theme', next); return next; }); }, []); const setTheme = useCallback((t: Theme) => { localStorage.setItem('dg-theme', t); setThemeState(t); }, []); const value = useMemo(() => ({ theme, toggleTheme, setTheme, isDark: theme === 'dark', isLight: theme === 'light', }), [theme, toggleTheme, setTheme]); return {children}; } export function useTheme(): ThemeContextType { const ctx = useContext(ThemeContext); if (!ctx) throw new Error('useTheme must be used within ThemeProvider'); return ctx; }