import { createContext, useContext, useState, useEffect } from 'react'; const ThemeContext = createContext(); export const ThemeProvider = ({ children }) => { const [theme, setTheme] = useState('light'); // Initialize theme from localStorage or system preference useEffect(() => { // Check if we're in a browser environment if (typeof window !== 'undefined') { const savedTheme = localStorage.getItem('theme'); // Use saved theme or system preference if (savedTheme) { setTheme(savedTheme); document.documentElement.classList.toggle('dark', savedTheme === 'dark'); } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) { setTheme('dark'); document.documentElement.classList.add('dark'); } } }, []); // Update theme in localStorage and toggle dark class const updateTheme = (newTheme) => { if (typeof window !== 'undefined') { localStorage.setItem('theme', newTheme); document.documentElement.classList.toggle('dark', newTheme === 'dark'); setTheme(newTheme); } }; // Toggle between light and dark theme const toggleTheme = () => { const newTheme = theme === 'light' ? 'dark' : 'light'; updateTheme(newTheme); }; return ( {children} ); }; // Custom hook to use theme context export const useTheme = () => { const context = useContext(ThemeContext); if (!context) { throw new Error('useTheme must be used within a ThemeProvider'); } return context; };