"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var floating_exports = {};
__export(floating_exports, {
  Floating: () => Floating
});
module.exports = __toCommonJS(floating_exports);
var import_react_dom = require("@floating-ui/react-dom");
var import_react = __toESM(require("react"));
var import_ricos_context = require("./../../ricos-context/index.js");
var import_use_draggable_modal = require("./../hooks/use-draggable-modal.js");
var import_focus_manager = require("./../../_shared/focus-manager/focus-manager.js");
var import_ui_components = require("./../../ui-components/index.js");
const Floating = ({ children, modalConfig, closeModal }) => {
  const { jsdomMode, environment } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  const zIndexService = (0, import_react.useContext)(import_ricos_context.ZIndexContext);
  const [modalElement, setModalElement] = (0, import_react.useState)(null);
  const [clampedY, setClampedY] = (0, import_react.useState)(null);
  const { autoFocus = true, initialFocus, positioning } = modalConfig || {};
  let placement = positioning?.placement;
  const referenceElement = positioning?.referenceElement;
  if (environment === "wixel" && (placement === "right-start" || placement === "bottom")) {
    placement = "bottom-start";
  }
  const middlewares = placement === "right" || placement === "right-start--custom-offset" ? [(0, import_react_dom.offset)({ mainAxis: 8 })] : placement === "right-start" ? [(0, import_react_dom.offset)({ mainAxis: 32, crossAxis: -78 })] : placement === "bottom" || placement === "bottom-start" || placement === "bottom-end" ? [(0, import_react_dom.offset)({ mainAxis: 8 }), (0, import_react_dom.flip)()] : placement === "left" || placement === "left-start" || placement === "left-end" ? [(0, import_react_dom.offset)({ mainAxis: 8 }), (0, import_react_dom.flip)()] : placement === "right-end" ? [(0, import_react_dom.offset)({ mainAxis: 20 }), (0, import_react_dom.flip)()] : [];
  const {
    x,
    y,
    isPositioned,
    refs: { setReference, setFloating },
    strategy
  } = (0, import_react_dom.useFloating)({
    placement: toFloatingPlacement(placement),
    strategy: "fixed",
    middleware: [
      ...middlewares,
      (0, import_react_dom.shift)({
        crossAxis: true
      })
    ],
    ...modalConfig?.sticky && {
      whileElementsMounted: (referenceEl, floatingEl, update) => {
        return (0, import_react_dom.autoUpdate)(referenceEl, floatingEl, update, {
          animationFrame: true
        });
      }
    }
  });
  (0, import_react.useEffect)(() => {
    setReference(referenceElement);
  }, [setReference, referenceElement]);
  const coords = (0, import_use_draggable_modal.useDraggableModal)({
    modalElement,
    dragHandleSelector: modalConfig.enableDrag ? modalConfig.dragHandleSelector : "[data-drag-handle]"
  });
  (0, import_react.useEffect)(() => {
    setClampedY(null);
  }, [coords]);
  (0, import_react.useEffect)(() => {
    if (!modalElement) {
      return;
    }
    let prevHeight = modalElement.getBoundingClientRect().height;
    const observer = new ResizeObserver(() => {
      const currentHeight = modalElement.getBoundingClientRect().height;
      const grew = currentHeight > prevHeight;
      prevHeight = currentHeight;
      if (!grew) {
        return;
      }
      const rect = modalElement.getBoundingClientRect();
      const overflow = rect.bottom - window.innerHeight;
      if (overflow > 0) {
        setClampedY(Math.max(0, rect.top - overflow));
      }
    });
    observer.observe(modalElement);
    return () => observer.disconnect();
  }, [modalElement]);
  const isVisible = jsdomMode || isPositioned;
  const content = /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      ref: (ref) => {
        setFloating(ref);
        setModalElement(ref);
      },
      style: {
        top: clampedY ?? coords?.y ?? y ?? "",
        left: coords?.x ?? x ?? "",
        position: strategy,
        zIndex: zIndexService.getZIndex("DIALOG"),
        display: "block",
        visibility: isVisible ? "visible" : "hidden"
      }
    },
    modalElement && /* @__PURE__ */ import_react.default.createElement(import_ui_components.UiComponentsProvider, { containerEl: modalElement }, children)
  );
  const onClickOutside = (event) => {
    const clickOutsideHandler = typeof modalConfig.onClickOutside === "function" ? modalConfig.onClickOutside : modalConfig.onClickOutside?.handler;
    if (clickOutsideHandler) {
      clickOutsideHandler(event);
    } else if (referenceElement instanceof HTMLElement && !referenceElement?.contains(event.target)) {
      closeModal();
    }
  };
  return /* @__PURE__ */ import_react.default.createElement(
    import_ui_components.ClickOutside,
    {
      onClickOutside,
      triggerOn: typeof modalConfig.onClickOutside !== "function" ? modalConfig.onClickOutside?.on : void 0
    },
    autoFocus ? /* @__PURE__ */ import_react.default.createElement(
      import_focus_manager.FocusManager,
      {
        focusTrapOptions: {
          returnFocusOnDeactivate: false,
          fallbackFocus: document.activeElement,
          ...initialFocus !== void 0 && { initialFocus }
        },
        jsdomMode,
        active: isVisible,
        preventScroll: true
      },
      content
    ) : content
  );
};
const toFloatingPlacement = (placement) => {
  if (placement === "right-start--custom-offset") {
    return "right-start";
  }
  if (placement === "overlay") {
    return "bottom-start";
  }
  return placement;
};
//# sourceMappingURL=floating.js.map
