import { jsx as _jsx } from "@emotion/react/jsx-runtime";
import { useState, useEffect } from 'react';
import { persistentStorage } from '../../../persistent-storage';
import { ConfigProvider } from './config-provider';
import { ThemeTokenProvider } from './theme-token-provider';
import { ThemeContext } from './contexts';
const DARK_THEME_QUERY = '(prefers-color-scheme: dark)';
const getSystemThemeMode = () => window.matchMedia(DARK_THEME_QUERY).matches ? 'dark' : 'light';
const getThemeMode = (preference) => preference === 'system' ? getSystemThemeMode() : preference;
export const ThemeProvider = ({ children }) => {
    const [preference, setPreference] = useState(() => persistentStorage.get('themePreference', 'system'));
    const [mode, setMode] = useState(() => getThemeMode(preference));
    useEffect(() => {
        window.electron.updateMenuState('themePreference', preference);
    }, []);
    useEffect(() => {
        document.body.classList.toggle('editor-theme_dark', mode === 'dark');
    }, [mode]);
    useEffect(() => {
        setMode(getThemeMode(preference));
    }, [preference]);
    useEffect(() => {
        const themeQuery = window.matchMedia(DARK_THEME_QUERY);
        const handleSystemThemeChange = () => {
            setMode((currentMode) => preference === 'system' ? getSystemThemeMode() : currentMode);
        };
        themeQuery.addEventListener('change', handleSystemThemeChange);
        return () => {
            themeQuery.removeEventListener('change', handleSystemThemeChange);
        };
    }, [preference]);
    useEffect(() => {
        const handleSwitchTheme = (themePreference) => {
            setPreference(themePreference);
            persistentStorage.set('themePreference', themePreference);
        };
        const unsubscribe = window.electron.onSwitchTheme(handleSwitchTheme);
        return () => unsubscribe();
    }, []);
    return (_jsx(ThemeContext.Provider, { value: mode, children: _jsx(ConfigProvider, { children: _jsx(ThemeTokenProvider, { children: children }) }) }));
};
