'use client' import { createContext, useContext, useEffect, useState } from 'react' import * as React from 'react' type Theme = 'light' | 'dark' interface ThemeContextType { theme: Theme toggleTheme: () => void } const ThemeContext = createContext(undefined) export function ThemeProvider({ children }: { children: React.ReactNode }) { const [theme, setTheme] = useState('light') const [mounted, setMounted] = useState(false) useEffect(() => { setMounted(true) // Check localStorage for saved theme preference const savedTheme = localStorage.getItem('theme') as Theme | null if (savedTheme) { setTheme(savedTheme) document.documentElement.classList.toggle('dark', savedTheme === 'dark') } else { // Check system preference const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches const initialTheme = prefersDark ? 'dark' : 'light' setTheme(initialTheme) document.documentElement.classList.toggle('dark', initialTheme === 'dark') } }, []) const toggleTheme = () => { const newTheme = theme === 'light' ? 'dark' : 'light' setTheme(newTheme) localStorage.setItem('theme', newTheme) document.documentElement.classList.toggle('dark', newTheme === 'dark') } // Always provide the context, even before mounting // This prevents the "useTheme must be used within a ThemeProvider" error return ( {children} ) } export function useTheme() { const context = useContext(ThemeContext) if (context === undefined) { throw new Error('useTheme must be used within a ThemeProvider') } return context }