import { useState, useEffect } from 'react' type Theme = 'light' | 'dark' // Initialize theme on script load (before React renders) function initializeTheme(): Theme { const stored = localStorage.getItem('theme') as Theme | null if (stored) { return stored } // Check system preference if (window.matchMedia('(prefers-color-scheme: dark)').matches) { return 'dark' } return 'light' } // Apply theme class to document root function applyTheme(theme: Theme) { const root = window.document.documentElement root.classList.remove('light', 'dark') root.classList.add(theme) } // Initialize theme immediately on module load const initialTheme = initializeTheme() applyTheme(initialTheme) export function useTheme() { const [theme, setTheme] = useState(initialTheme) useEffect(() => { // Apply theme whenever it changes applyTheme(theme) localStorage.setItem('theme', theme) }, [theme]) const toggleTheme = () => { setTheme((prev) => (prev === 'light' ? 'dark' : 'light')) } return { theme, toggleTheme } }