'use strict';

var React = require('react');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefault(React);

// src/theme/OsdkThemeProvider.tsx
var OsdkThemeContext = /* @__PURE__ */ React.createContext(null);
var DARK_QUERY = "(prefers-color-scheme: dark)";
function subscribe(callback) {
  if (typeof window === "undefined" || typeof window.matchMedia !== "function") {
    return () => {
    };
  }
  const mql = window.matchMedia(DARK_QUERY);
  mql.addEventListener("change", callback);
  return () => mql.removeEventListener("change", callback);
}
function getSnapshot() {
  if (typeof window === "undefined" || typeof window.matchMedia !== "function") {
    return "light";
  }
  return window.matchMedia(DARK_QUERY).matches ? "dark" : "light";
}
function getServerSnapshot() {
  return "light";
}
function useSystemTheme() {
  return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}

// src/theme/OsdkThemeProvider.tsx
var DATA_THEME_ATTR = "data-bp-color-scheme";
function OsdkThemeProvider({
  theme: controlledTheme,
  defaultTheme = "system",
  onThemeChanged,
  target,
  children
}) {
  const [internalTheme, setInternalTheme] = React__default.default.useState(defaultTheme);
  const theme = controlledTheme ?? internalTheme;
  const systemTheme = useSystemTheme();
  const resolvedTheme = theme === "system" ? systemTheme : theme;
  React__default.default.useLayoutEffect(() => {
    const element = target ?? (typeof document !== "undefined" ? document.documentElement : null);
    if (element == null) return;
    const previous = element.getAttribute(DATA_THEME_ATTR);
    element.setAttribute(DATA_THEME_ATTR, resolvedTheme);
    return () => {
      if (previous == null) {
        element.removeAttribute(DATA_THEME_ATTR);
      } else {
        element.setAttribute(DATA_THEME_ATTR, previous);
      }
    };
  }, [resolvedTheme, target]);
  const setTheme = React__default.default.useCallback((next) => {
    if (controlledTheme === void 0) {
      setInternalTheme(next);
    }
    onThemeChanged?.(next);
  }, [controlledTheme, onThemeChanged]);
  const value = React__default.default.useMemo(() => ({
    theme,
    resolvedTheme,
    setTheme
  }), [theme, resolvedTheme, setTheme]);
  return /* @__PURE__ */ React__default.default.createElement(OsdkThemeContext.Provider, {
    value
  }, children);
}
function useOsdkTheme() {
  const ctx = React.useContext(OsdkThemeContext);
  if (ctx == null) {
    throw new Error("useOsdkTheme must be used within an <OsdkThemeProvider>.");
  }
  return ctx;
}

exports.OsdkThemeProvider = OsdkThemeProvider;
exports.useOsdkTheme = useOsdkTheme;
//# sourceMappingURL=chunk-2YA74OKB.cjs.map
//# sourceMappingURL=chunk-2YA74OKB.cjs.map