// The theme state: "system" follows the operating system, "light" and "dark" are the reader's choice.
// From https://auricartisan.com/integrations/react-tokens/ - CC0 1.0.
// The colors are never in JavaScript: this only sets data-theme on <html>, and tokens.css does the rest.
import { createContext, useContext, useEffect, useState } from "react";

const KEY = "theme";
const query = "(prefers-color-scheme: dark)";
const read = () => { try { return localStorage.getItem(KEY); } catch { return null; } };
const write = (v) => { try { if (v === "system") localStorage.removeItem(KEY); else localStorage.setItem(KEY, v); } catch { /* blocked */ } };

const ThemeContext = createContext({ choice: "system", theme: "light", setChoice: () => {} });

export function ThemeProvider({ children }) {
    const [choice, setChoice] = useState(() => (read() === "light" || read() === "dark" ? read() : "system"));
    const [system, setSystem] = useState(() => (window.matchMedia(query).matches ? "dark" : "light"));
    useEffect(() => {
        const mq = window.matchMedia(query);
        const follow = () => setSystem(mq.matches ? "dark" : "light");
        mq.addEventListener("change", follow);
        return () => mq.removeEventListener("change", follow);
    }, []);
    const theme = choice === "system" ? system : choice;
    useEffect(() => {
        document.documentElement.dataset.theme = theme;
        write(choice);
    }, [theme, choice]);
    return <ThemeContext.Provider value={{ choice, theme, setChoice }}>{children}</ThemeContext.Provider>;
}

export const useTheme = () => useContext(ThemeContext);
