import { useMemo, useEffect, useRef } from "react";
import { serializeStyles } from "@emotion/serialize";
import {
  isNotNil,
  getBaseBreakpoint,
  getBreakpointMediaQuery
} from "@makeswift/controls";
import { useCache } from "../root-style-registry";
import { styleV1Css } from "../controls/style";
import { typographyCss } from "../controls/typography";
import { useBreakpoints } from "./use-breakpoints";
import { useCssId } from "./use-css-id";
import { useStyles, serializedStyleClassName } from "../use-style";
import { pollBoxModel } from "../poll-box-model";
function useStylesheetFactory() {
  const breakpoints = useBreakpoints();
  const cache = useCache();
  const componentUid = useCssId();
  const computedStyles = useRef({}).current;
  const boxModelCallbacks = useRef({}).current;
  return useMemo(() => {
    const getStylesheet = (styleSheetId) => ({
      breakpoints() {
        return breakpoints;
      },
      defineStyle(style, onBoxModelChange) {
        const serialized = serializeStyle(breakpoints, style, cache);
        const uid = `u-${componentUid}-${styleSheetId}`;
        computedStyles[uid] = serialized;
        const className = serializedStyleClassName(cache, serialized);
        if (!onBoxModelChange)
          return className;
        boxModelCallbacks[uid] = onBoxModelChange;
        return `${className} ${uid}`;
      },
      child(id) {
        return getStylesheet(`${styleSheetId}-${id}`);
      }
    });
    return {
      get(propName) {
        return getStylesheet(propName);
      },
      useDefinedStyles() {
        useStyles(cache, Object.values(computedStyles));
        useEffect(() => {
          const unsubscribes = Object.entries(boxModelCallbacks).map(
            ([uid, callback]) => callback != null ? pollBoxModel({
              element: document.querySelector(`.${uid}`),
              onBoxModelChange: callback
            }) : void 0
          ).filter(isNotNil);
          return () => unsubscribes.forEach((fn) => fn());
        }, [Object.keys(boxModelCallbacks).join(" ")]);
      }
    };
  }, [breakpoints, cache, componentUid]);
}
function isTypographyStyle(style) {
  return Array.isArray(style);
}
function isStyleV2(style) {
  return typeof style === "object" && "getStyle" in style && typeof style.getStyle === "function";
}
function styleV2Css(breakpoints, style) {
  return {
    ...style.getStyle(getBaseBreakpoint(breakpoints)),
    ...breakpoints.reduce(
      (styles, breakpoint) => ({
        ...styles,
        [getBreakpointMediaQuery(breakpoint)]: style.getStyle(breakpoint)
      }),
      {}
    )
  };
}
function resolvedStyleToCss(breakpoints, style) {
  if (isTypographyStyle(style)) {
    return typographyCss(breakpoints, style);
  }
  if (isStyleV2(style)) {
    return styleV2Css(breakpoints, style);
  }
  const { properties, styleData } = style;
  return styleV1Css(breakpoints, styleData, properties);
}
function serializeStyle(breakpoints, style, cache) {
  const css = resolvedStyleToCss(breakpoints, style);
  return serializeStyles([css], cache.registered);
}
export {
  useStylesheetFactory
};
//# sourceMappingURL=use-stylesheet-factory.js.map