import lodash from "lodash";
import React, { useEffect, useRef, useState } from "react";
import { getStyles } from "../get-styles.js";
import {
  buildThemeCssVars,
  buildThemePortalCssVars
} from "../themeStrategy/build-theme-css-vars.js";
const StylesContext = React.createContext({
  styles: null,
  cssVars: {},
  portalCssVars: {},
  setEditorElement: null,
  stylePreset: null
});
function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}
const useForceUpdate = () => {
  const [_, setValue] = useState(0);
  return () => setValue((value) => value + 1);
};
const StylesContextProvider = ({
  children,
  documentStyle,
  theme,
  styles,
  environment,
  isMobile
}) => {
  const prevTheme = usePrevious(theme);
  const prevDocumentStyle = usePrevious(documentStyle);
  const forceUpdate = useForceUpdate();
  const cssVars = buildThemeCssVars(theme, documentStyle);
  const portalCssVars = buildThemePortalCssVars(theme);
  useEffect(() => {
    const documentStyleSubscription = styles.onDocumentStyleUpdate(forceUpdate);
    const themeSubscription = styles.onThemeUpdate(forceUpdate);
    styles.setTheme(theme).setDocumentStyle(documentStyle);
    return () => {
      documentStyleSubscription.cancel();
      themeSubscription.cancel();
    };
  }, []);
  useEffect(() => {
    if (prevTheme && !lodash.isEqual(prevTheme, theme)) {
      styles.setTheme(theme);
    }
    if (prevDocumentStyle && !lodash.isEqual(prevDocumentStyle, documentStyle)) {
      styles.setDocumentStyle(documentStyle);
    }
  }, [prevTheme, theme, prevDocumentStyle, documentStyle]);
  return /* @__PURE__ */ React.createElement(
    StylesContext.Provider,
    {
      value: {
        styles,
        cssVars,
        portalCssVars,
        setEditorElement: styles.setEditorElement,
        stylePreset: getStyles(environment, isMobile)
      }
    },
    children
  );
};
const StylesContextConsumer = ({ children }) => /* @__PURE__ */ React.createElement(StylesContext.Consumer, null, (value) => children(value));
function withStylesContext(Component) {
  return (props) => /* @__PURE__ */ React.createElement(StylesContextConsumer, null, (value) => /* @__PURE__ */ React.createElement(Component, { ...props, ...value }));
}
export {
  StylesContext,
  StylesContextProvider,
  withStylesContext
};
//# sourceMappingURL=styles-context.js.map
