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