/** @license MIT | @cube-dev/ui-kit v0.142.7 | Cube Dev Team */
import { DisplayTransition } from "../../helpers/DisplayTransition/DisplayTransition.js";
import { Provider, useProviderProps } from "../../../provider.js";
import { OpenTransitionContext } from "./OpenTransitionContext.js";
import { Children, cloneElement, forwardRef, useCallback, useState } from "react";
import { jsx } from "react/jsx-runtime";
import { createPortal } from "react-dom";

//#region src/components/overlays/Modal/Overlay.tsx
const EXIT_DURATION = 350;
function Overlay(props, ref) {
	let { children, isOpen, container = null, onEnter, onEntering, onEntered, onExit, onExiting, onExited, hideOnClose = false } = props;
	let [exited, setExited] = useState(!isOpen);
	if (isOpen && exited) setExited(false);
	let { root } = useProviderProps({});
	let handlePhaseChange = useCallback((phase) => {
		switch (phase) {
			case "enter":
				setExited(false);
				onEnter?.();
				onEntering?.();
				break;
			case "entered":
				onEntered?.();
				break;
			case "exit":
				onExit?.();
				onExiting?.();
				break;
			case "unmounted":
				setExited(true);
				onExited?.();
				break;
		}
	}, [
		onEnter,
		onEntering,
		onEntered,
		onExit,
		onExiting,
		onExited
	]);
	if (!(isOpen || !exited)) {
		if (!hideOnClose) return null;
	}
	return createPortal(/* @__PURE__ */ jsx(Provider, {
		ref,
		children: /* @__PURE__ */ jsx(DisplayTransition, {
			animateOnMount: true,
			isShown: !!isOpen,
			exposeUnmounted: hideOnClose,
			duration: EXIT_DURATION,
			onPhaseChange: handlePhaseChange,
			children: ({ phase, isShown }) => {
				return /* @__PURE__ */ jsx(OpenTransitionContext.Provider, {
					value: { transitionState: phase },
					children: Children.map(children, (child) => child && cloneElement(child, {
						isOpen: isShown,
						transitionState: phase
					}))
				});
			}
		})
	}), container || root || document.body);
}
let _Overlay = forwardRef(Overlay);
_Overlay.displayName = "Overlay";

//#endregion
export { _Overlay };
//# sourceMappingURL=Overlay.js.map