import * as React from "react";
import { webLightTheme, webDarkTheme, Theme } from "@fluentui/react-components";

type ColorScheme = "light" | "dark";
const STORAGE_KEY = "color-scheme";

export function useFluentColorScheme(): {
    colorScheme: ColorScheme;
    setColorScheme: (value: ColorScheme) => void;
    theme: Theme;
} {
    const [colorScheme, setColorSchemeState] = React.useState<ColorScheme>(() => {
        if (typeof window !== "undefined") {
            const saved = localStorage.getItem(STORAGE_KEY) as ColorScheme | null;
            if (saved === "light" || saved === "dark") return saved;
            const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
            return prefersDark ? "dark" : "light";
        }
        return "light";
    });

    const setColorScheme = React.useCallback((value: ColorScheme) => {
        setColorSchemeState(value);
        localStorage.setItem(STORAGE_KEY, value);
    }, []);

    const theme = colorScheme === "dark" ? webDarkTheme : webLightTheme;

    return { colorScheme, setColorScheme, theme };
}
