import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'; type Theme = 'light' | 'dark'; interface ThemeContextType { theme: Theme; toggleTheme: () => void; } const ThemeContext = createContext(undefined); export const ThemeProvider: React.FC<{ children: ReactNode }> = ({ children }) => { const [theme, setTheme] = useState(() => { const storedTheme = localStorage.getItem('theme'); if (storedTheme) { return storedTheme as Theme; } return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; }); useEffect(() => { const root = window.document.documentElement; root.classList.remove('light', 'dark'); root.classList.add(theme); localStorage.setItem('theme', theme); }, [theme]); const toggleTheme = () => { setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light')); }; return ( {children} ); }; export const useTheme = (): ThemeContextType => { const context = useContext(ThemeContext); if (!context) { throw new Error('useTheme must be used within a ThemeProvider'); } return context; };