import React, { createContext, useCallback, useContext, useEffect, useState } from 'react'; import { readPreference, writePreference } from '../lib/storage'; type Theme = 'light' | 'dark'; interface ThemeContextType { theme: Theme; toggleTheme: () => void; } const THEME_KEY = 'ca-theme'; const ThemeContext = createContext(undefined); // Light by default; the choice is saved and the system preference is not followed. const initialTheme = (): Theme => (readPreference(THEME_KEY) === 'dark' ? 'dark' : 'light'); export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [theme, setTheme] = useState(initialTheme); useEffect(() => { document.documentElement.classList.toggle('dark', theme === 'dark'); }, [theme]); const toggleTheme = useCallback(() => { setTheme((current) => { const next = current === 'dark' ? 'light' : 'dark'; writePreference(THEME_KEY, next); return next; }); }, []); return {children}; }; export const useTheme = () => { const context = useContext(ThemeContext); if (!context) throw new Error('useTheme must be used within ThemeProvider'); return context; };