import { createContext, useContext, useEffect, useMemo, useState } from "react";
import { syncSystemBars } from "../platform/system-bars.js";
import { readSavedTheme, resolveTheme, writeSavedTheme } from "./theme.js";

const ThemeContext = createContext({ theme: "system", setTheme: () => {} });

export function ThemeProvider({ children }) {
  const [theme, setThemeState] = useState(() => readSavedTheme() ?? "system");
  const [systemTheme, setSystemTheme] = useState(() => resolveTheme("system"));
  const resolvedTheme = resolveTheme(theme, { matches: systemTheme === "dark" });
  const setTheme = (nextTheme) => setThemeState(nextTheme);

  useEffect(() => {
    const media = globalThis.matchMedia?.("(prefers-color-scheme: dark)");
    if (!media) return undefined;
    const update = () => setSystemTheme(media.matches ? "dark" : "light");
    update();
    media.addEventListener?.("change", update);
    return () => media.removeEventListener?.("change", update);
  }, []);
  useEffect(() => {
    writeSavedTheme(undefined, theme);
    document.documentElement.dataset.theme = resolvedTheme;
    document.documentElement.style.colorScheme = resolvedTheme;
    document.querySelector('meta[name="theme-color"]')?.setAttribute("content", resolvedTheme === "dark" ? "#15171b" : "#f7f7f8");
    void syncSystemBars(resolvedTheme);
  }, [theme, resolvedTheme]);

  const value = useMemo(() => ({ theme, setTheme }), [theme]);
  return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}

export function useTheme() { return useContext(ThemeContext); }
