'use client' import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react' import type { ReactNode } from 'react' export type Theme = 'light' | 'dark' const STORAGE_KEY = 'bo.theme' interface ThemeContextValue { theme: Theme setTheme: (theme: Theme) => void toggleTheme: () => void } const ThemeContext = createContext(null) function readStoredTheme(): Theme { try { return localStorage.getItem(STORAGE_KEY) === 'dark' ? 'dark' : 'light' } catch { // Private browsing or a blocked storage partition — light is the documented default. return 'light' } } /** * Applies the `.dark` class to , which is what the `dark:` variant in * src/index.css keys off. Light is the default per the design standard; dark is * opt-in and persisted per browser. */ export function ThemeProvider({ children }: { children: ReactNode }) { const [theme, setThemeState] = useState(readStoredTheme) useEffect(() => { document.documentElement.classList.toggle('dark', theme === 'dark') document.documentElement.style.colorScheme = theme }, [theme]) function persist(next: Theme) { try { localStorage.setItem(STORAGE_KEY, next) } catch { // Persisting is a nicety; the in-memory theme still applies for this session. } } const setTheme = useCallback((next: Theme) => { setThemeState(next) persist(next) }, []) // Derives from state, not storage — otherwise a blocked localStorage would // make every toggle read 'light' and flip to 'dark' forever. const toggleTheme = useCallback(() => { setThemeState(prev => { const next: Theme = prev === 'dark' ? 'light' : 'dark' persist(next) return next }) }, []) const value = useMemo(() => ({ theme, setTheme, toggleTheme }), [theme, setTheme, toggleTheme]) return {children} } export function useTheme(): ThemeContextValue { const ctx = useContext(ThemeContext) if (!ctx) { throw new Error('useTheme must be used within a ThemeProvider') } return ctx }