import React, { useLayoutEffect, useMemo } from "react";
import { CssBaseline } from "@mui/material";
import { CssVarsProvider, useColorScheme } from "@mui/material/styles";

import { getTheme } from "./theme";
import { resolveEffectiveThemeMode, ThemeModePref } from "./themePrefs";

function ThemeModeSynchronizer({ mode }: { mode: "light" | "dark" }) {
  const { setMode } = useColorScheme();
  useLayoutEffect(() => { setMode(mode); }, [mode, setMode]);
  return null;
}

export default function JobTrackerThemeProvider({ preference, systemPrefersDark, children }: { preference: ThemeModePref; systemPrefersDark: boolean; children: React.ReactNode }) {
  const mode = resolveEffectiveThemeMode(preference, systemPrefersDark);
  const theme = useMemo(() => getTheme("light"), []);

  return (
    <CssVarsProvider theme={theme as any} defaultMode={mode} storageManager={null} disableTransitionOnChange>
      <ThemeModeSynchronizer mode={mode} />
      <CssBaseline enableColorScheme />
      {children}
    </CssVarsProvider>
  );
}
