'use client';
import React, { createContext, useCallback, useContext, useEffect, useState } from 'react';
const initialContext = {
    autoMode: true,
    setTheme: ()=>null,
    theme: 'light'
};
const Context = /*#__PURE__*/ createContext(initialContext);
const localStorageKey = 'payload-theme';
const getTheme = ()=>{
    let theme;
    const themeFromStorage = window.localStorage.getItem(localStorageKey);
    if (themeFromStorage === 'light' || themeFromStorage === 'dark') {
        theme = themeFromStorage;
    } else {
        theme = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    }
    document.documentElement.setAttribute('data-theme', theme);
    return {
        theme,
        themeFromStorage
    };
};
const defaultTheme = 'light';
export const ThemeProvider = ({ children })=>{
    const [theme, setThemeState] = useState(defaultTheme);
    const [autoMode, setAutoMode] = useState();
    useEffect(()=>{
        const { theme, themeFromStorage } = getTheme();
        setThemeState(theme);
        setAutoMode(!themeFromStorage);
    }, []);
    const setTheme = useCallback((themeToSet)=>{
        if (themeToSet === 'light' || themeToSet === 'dark') {
            setThemeState(themeToSet);
            setAutoMode(false);
            window.localStorage.setItem(localStorageKey, themeToSet);
            document.documentElement.setAttribute('data-theme', themeToSet);
        } else if (themeToSet === 'auto') {
            const existingThemeFromStorage = window.localStorage.getItem(localStorageKey);
            if (existingThemeFromStorage) window.localStorage.removeItem(localStorageKey);
            const themeFromOS = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
            document.documentElement.setAttribute('data-theme', themeFromOS);
            setAutoMode(true);
            setThemeState(themeFromOS);
        }
    }, []);
    return /*#__PURE__*/ React.createElement(Context.Provider, {
        value: {
            autoMode,
            setTheme,
            theme
        }
    }, children);
};
export const useTheme = ()=>useContext(Context);
export default Context;

//# sourceMappingURL=index.js.map