import { useEffect, useState } from "react"; export type Theme = "light" | "dark"; export function useTheme(initial?: Theme) { const [theme, setTheme] = useState(initial ?? "light"); useEffect(() => { const stored = typeof window !== "undefined" && "localStorage" in window ? window.localStorage.getItem("theme") : null; if (stored === "light" || stored === "dark") { setTheme(stored); return; } if (typeof window !== "undefined" && "matchMedia" in window) { const media = window.matchMedia("(prefers-color-scheme: dark)"); setTheme(media.matches ? "dark" : "light"); const handler = (event: MediaQueryListEvent) => setTheme(event.matches ? "dark" : "light"); media.addEventListener("change", handler); return () => media.removeEventListener("change", handler); } setTheme("light"); }, []); useEffect(() => { if (typeof document === "undefined") return; document.documentElement.setAttribute("data-theme", theme); if ("localStorage" in window) { window.localStorage.setItem("theme", theme); } }, [theme]); const toggleTheme = () => setTheme((prev) => (prev === "light" ? "dark" : "light")); return { theme, setTheme, toggleTheme }; }