import _ from "lodash";
import React, { useContext, useEffect, useMemo, useRef } from "react";
import { flushSync } from "react-dom";
import { EditorContext, RicosContext } from "./../../ricos-context/index.js";
import { useSelection } from "./../../ricos-context/selection-context.js";
import { PluginContainerData_Alignment } from "./../../ricos-schema/next-schema/index.js";
import { isOnlyNodeSelected } from "./../../_shared/is-only-node-selected.js";
import { createResizeHandler } from "./create-resize-handler.js";
const getEnableMap = (disabled, verticallyResizable, alignment) => {
  if (disabled) {
    return {
      left: false,
      right: false,
      top: false,
      bottom: false,
      topRight: false,
      bottomRight: false,
      topLeft: false,
      bottomLeft: false
    };
  }
  switch (alignment) {
    case PluginContainerData_Alignment.LEFT:
      return {
        left: false,
        right: true,
        top: verticallyResizable,
        bottom: verticallyResizable,
        topRight: verticallyResizable,
        bottomRight: verticallyResizable,
        topLeft: false,
        bottomLeft: false
      };
    case PluginContainerData_Alignment.RIGHT:
      return {
        left: true,
        right: false,
        top: verticallyResizable,
        bottom: verticallyResizable,
        topRight: false,
        bottomRight: false,
        topLeft: verticallyResizable,
        bottomLeft: verticallyResizable
      };
    default:
      return {
        left: true,
        right: true,
        top: verticallyResizable,
        bottom: verticallyResizable,
        topRight: verticallyResizable,
        bottomRight: verticallyResizable,
        topLeft: verticallyResizable,
        bottomLeft: verticallyResizable
      };
  }
};
const useMaxContentWidth = (props, minWidth) => {
  const { editor, decorations } = props;
  const decorationKey = React.useMemo(() => {
    return decorations.map((decoration) => decoration.type?.attrs["data-breakout"] ?? "unknown").join(",");
  }, [decorations]);
  return React.useCallback(() => {
    const isBreakoutFullWidth = decorations.some(
      (decoration) => decoration.type?.attrs["data-breakout"] === "fullWidth"
    );
    if (isBreakoutFullWidth) {
      return editor.view.dom.clientWidth;
    }
    const nodeContainer = editor.view.dom.querySelector('[data-breakout="normal"]') ?? editor.view.dom.firstChild;
    const nodeContentStyles = window.getComputedStyle(nodeContainer);
    const paddingStart = parseInt(nodeContentStyles.paddingInlineStart) || 0;
    const paddingEnd = parseInt(nodeContentStyles.paddingInlineEnd) || 0;
    return Math.max(minWidth, nodeContainer.clientWidth - paddingStart - paddingEnd);
  }, [decorationKey]);
};
const defaultOptions = {
  minWidth: 15,
  verticallyResizable: false,
  lockAspectRatio: false,
  saveDimensions: false,
  expandToFullWidthOnOverdrag: false
};
const createResizerHoc = (options = defaultOptions) => (Component) => {
  return (props) => {
    const {
      minWidth = defaultOptions.minWidth,
      verticallyResizable = defaultOptions.verticallyResizable,
      lockAspectRatio = defaultOptions.lockAspectRatio,
      saveDimensions = defaultOptions.saveDimensions,
      expandToFullWidthOnOverdrag = defaultOptions.expandToFullWidthOnOverdrag
    } = options;
    const { isMobile } = useContext(RicosContext);
    const { updateAttributes, componentData } = props;
    const {
      adapter: { tiptapEditor: editor }
    } = React.useContext(EditorContext);
    const selection = useSelection();
    const selected = React.useMemo(
      () => componentData?.id ? isOnlyNodeSelected(editor.state, componentData.id) : false,
      [editor.state, componentData?.id, selection]
    );
    const getMinWidth = React.useCallback(() => minWidth, [minWidth]);
    const getMaxWidthLatest = useMaxContentWidth(props, minWidth);
    const getMaxWidthRef = useRef(getMaxWidthLatest);
    getMaxWidthRef.current = getMaxWidthLatest;
    const getMaxWidth = React.useCallback(() => getMaxWidthRef.current(), []);
    const alignment = componentData.containerData?.alignment ?? PluginContainerData_Alignment.CENTER;
    const enableMap = React.useMemo(
      () => getEnableMap(!selected, verticallyResizable, alignment),
      [selected, verticallyResizable, alignment]
    );
    const contentRef = useRef(null);
    const onResize = React.useCallback(
      (dimensions) => {
        const { width } = dimensions;
        const widthAttr = expandToFullWidthOnOverdrag && dimensions.isExceedingMaxWidth ? { size: "FULL_WIDTH" } : { custom: width };
        flushSync(() => {
          updateAttributes({
            containerData: {
              ...props.componentData.containerData,
              width: widthAttr
            }
          });
        });
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [updateAttributes, alignment, expandToFullWidthOnOverdrag]
    );
    const onResizeThrottle = useMemo(() => _.throttle(onResize, 16), [onResize]);
    const onResizeStop = React.useCallback(
      (dimensions) => {
        onResize(dimensions);
        if (saveDimensions && !dimensions.isExceedingMaxWidth) {
          flushSync(() => {
            updateAttributes({
              dimensions: {
                width: dimensions.width,
                height: dimensions.height
              }
            });
          });
        }
      },
      [onResize, saveDimensions, updateAttributes]
    );
    useEffect(() => {
      if (!contentRef.current) {
        return;
      }
      const cleanup = createResizeHandler({
        resizeElement: contentRef.current,
        isEnabled: selected && !isMobile,
        getMinWidth,
        getMaxWidth,
        enable: enableMap,
        lockAspectRatio,
        alignment,
        onResize: onResizeThrottle,
        onResizeStop
      });
      return cleanup;
    }, [
      selected,
      getMinWidth,
      getMaxWidth,
      enableMap,
      lockAspectRatio,
      alignment,
      onResizeThrottle,
      onResizeStop
    ]);
    return /* @__PURE__ */ React.createElement("div", { ref: contentRef, "data-resize-container": "" }, /* @__PURE__ */ React.createElement(Component, { ...props }));
  };
};
const ResizerHOC = createResizerHoc();
export {
  ResizerHOC,
  createResizerHoc
};
//# sourceMappingURL=react-resizer.js.map
