import { useAuth } from "@/contexts/auth-context";
import { useMantineColorScheme } from "@mantine/core";
import { useEffect } from "react";
import { CHROME_COLORS, setThemeColorMeta } from "./theme-colors";

const ColorSchemeProvider = ({ children }: { children: React.ReactNode }) => {
  const {
    metadata: { colorScheme },
  } = useAuth();
  const { setColorScheme } = useMantineColorScheme();

  useEffect(() => {
    if (!colorScheme) return;

    setColorScheme(colorScheme);

    const media = window.matchMedia("(prefers-color-scheme: dark)");
    const applyThemeColor = () => {
      const resolved =
        colorScheme === "auto"
          ? media.matches
            ? "dark"
            : "light"
          : colorScheme;
      setThemeColorMeta(CHROME_COLORS[resolved].base);
    };

    applyThemeColor();

    if (colorScheme === "auto") {
      media.addEventListener("change", applyThemeColor);
      return () => media.removeEventListener("change", applyThemeColor);
    }
  }, [colorScheme, setColorScheme]);

  return children;
};

export default ColorSchemeProvider;
