import { autoUpdate, flip, limitShift, offset, shift, useFloating } from "@floating-ui/react-dom";
import React, { useContext, useEffect, useState } from "react";
import { RicosContext, ZIndexContext } from "./../../ricos-context/index.js";
import { useToolbarBoundary } from "./../../toolbars-v3/toolbar-boundary.js";
import { ClickOutside, UiComponentsProvider } from "./../../ui-components/index.js";
import { FLOATING_CONTAINER_AI_WIDGET } from "../data-hooks.js";
const FloatingContainer = ({
  children,
  modalConfig,
  onClickOutside
}) => {
  const { jsdomMode } = useContext(RicosContext);
  const zIndexService = useContext(ZIndexContext);
  const [modalElement, setModalElement] = useState(null);
  const referenceElement = modalConfig?.positioning?.referenceElement;
  const boundary = useToolbarBoundary();
  const {
    x,
    y,
    refs: { setReference, setFloating },
    strategy,
    middlewareData,
    placement
  } = useFloating({
    placement: modalConfig?.positioning?.placement,
    strategy: "fixed",
    middleware: [
      offset({ mainAxis: 2 }),
      flip({
        boundary: boundary || void 0
      }),
      shift({
        crossAxis: true,
        mainAxis: false,
        limiter: limitShift(),
        boundary: boundary || void 0
      })
    ],
    whileElementsMounted: (referenceEl, floatingEl, update) => autoUpdate(referenceEl, floatingEl, update, {
      animationFrame: true
    })
  });
  useEffect(() => {
    setReference(referenceElement);
  }, [setReference, referenceElement]);
  const isVisible = jsdomMode || Boolean(x || y);
  const escToClickOutside = (e) => {
    if (e.key === "Escape") {
      onClickOutside(e);
      return;
    }
  };
  return /* @__PURE__ */ React.createElement(
    ClickOutside,
    {
      onClickOutside,
      triggerOn: typeof modalConfig?.onClickOutside !== "function" ? modalConfig?.onClickOutside?.on : void 0
    },
    /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: (ref) => {
          setFloating(ref);
          setModalElement(ref);
        },
        onKeyDown: escToClickOutside,
        style: {
          width: referenceElement?.offsetWidth ? referenceElement.offsetWidth : "auto",
          position: strategy,
          top: y ?? "",
          left: x ?? "",
          zIndex: zIndexService.getZIndex("DIALOG"),
          display: "block",
          visibility: isVisible ? "visible" : "hidden"
        },
        "data-hook": FLOATING_CONTAINER_AI_WIDGET
      },
      modalElement && /* @__PURE__ */ React.createElement(UiComponentsProvider, { containerEl: modalElement }, children({ middlewareData, placement }))
    )
  );
};
export {
  FloatingContainer
};
//# sourceMappingURL=floating-container.js.map
