"use client";
import * as React from 'react';
import { jsx } from 'react/jsx-runtime';

var THEME_STORAGE_KEY = "sm2-theme";
var DARK_CLASS_NAME = "dark";
var AppThemeContext = React.createContext(null);
function readStoredTheme() {
  if (typeof window === "undefined") {
    return void 0;
  }
  try {
    const raw = window.localStorage.getItem(THEME_STORAGE_KEY);
    return raw === "light" || raw === "dark" ? raw : void 0;
  } catch (e) {
    return void 0;
  }
}
function applyThemeToDocument(theme) {
  const root = document.documentElement;
  root.classList.toggle(DARK_CLASS_NAME, theme === "dark");
  root.style.colorScheme = theme;
}
function AppThemeProvider({
  children
}) {
  const [theme, setThemeState] = React.useState(
    () => {
      var _a;
      return (_a = readStoredTheme()) != null ? _a : "light";
    }
  );
  React.useLayoutEffect(() => {
    applyThemeToDocument(theme);
  }, [theme]);
  React.useEffect(() => {
    try {
      window.localStorage.setItem(THEME_STORAGE_KEY, theme);
    } catch (e) {
    }
  }, [theme]);
  React.useEffect(() => {
    const handleStorage = (event) => {
      if (event.key !== THEME_STORAGE_KEY) {
        return;
      }
      const nextTheme = event.newValue === "light" || event.newValue === "dark" ? event.newValue : "light";
      setThemeState(nextTheme);
      applyThemeToDocument(nextTheme);
    };
    window.addEventListener("storage", handleStorage);
    return () => window.removeEventListener("storage", handleStorage);
  }, []);
  const setTheme = React.useCallback((nextTheme) => {
    setThemeState(nextTheme);
  }, []);
  const value = React.useMemo(
    () => ({
      theme,
      resolvedTheme: theme,
      setTheme
    }),
    [theme, setTheme]
  );
  return /* @__PURE__ */ jsx(AppThemeContext.Provider, { value, children });
}
function useTheme() {
  const context = React.useContext(AppThemeContext);
  if (context == null) {
    throw new Error("useTheme must be used within AppThemeProvider");
  }
  return context;
}

export { AppThemeProvider, THEME_STORAGE_KEY, useTheme };
//# sourceMappingURL=app-theme-provider.js.map
//# sourceMappingURL=app-theme-provider.js.map