import { createContext, useContext, useEffect, useMemo, useState, type ReactNode, } from "react"; export type Theme = "light" | "dark"; interface ThemeContextValue { theme: Theme; setTheme: (theme: Theme) => void; toggle: () => void; } const ThemeContext = createContext(null); const STORAGE_KEY = "stirling.portal.theme"; function readInitialTheme(): Theme { if (typeof window === "undefined") return "light"; const stored = window.localStorage.getItem(STORAGE_KEY); if (stored === "light" || stored === "dark") return stored; return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; } export function ThemeProvider({ children }: { children: ReactNode }) { const [theme, setTheme] = useState(readInitialTheme); useEffect(() => { document.documentElement.setAttribute("data-theme", theme); window.localStorage.setItem(STORAGE_KEY, theme); }, [theme]); const value = useMemo( () => ({ theme, setTheme, toggle: () => setTheme((t) => (t === "light" ? "dark" : "light")), }), [theme], ); return ( {children} ); } export function useTheme(): ThemeContextValue { const v = useContext(ThemeContext); if (!v) throw new Error("useTheme must be used inside "); return v; }