/** @license MIT | @cube-dev/ui-kit v0.142.7 | Cube Dev Team */
import { mergeProps } from "../../../utils/react/mergeProps.js";
import { useEvent } from "../../../_internal/hooks/use-event.js";
import { DialogContainer } from "./DialogContainer.js";
import { useMemo, useRef, useState } from "react";
import { jsx } from "react/jsx-runtime";

//#region src/components/overlays/Dialog/use-dialog-container.tsx
/**
* Generic hook to manage a dialog component.
*
* @param Component - A React component that represents the dialog content. It must accept props of type P.
* @param defaultContainerProps - Default props to pass to the DialogContainer.
* @returns An object with `open` function to open the dialog with provided props and `rendered` JSX element to include in your component tree.
*/
function useDialogContainer(Component, defaultContainerProps) {
	const [isOpen, setIsOpen] = useState(false);
	const [componentProps, setComponentProps] = useState(null);
	const [containerProps, setContainerProps] = useState(null);
	const setupRef = useRef(false);
	function setupCheck() {
		if (!setupRef.current) throw new Error("useDialogContainer: DialogContainer must be rendered. Use `rendered` property to include it in your component tree.");
	}
	const open = useEvent((props, containerProps) => {
		setupCheck();
		setComponentProps(props);
		setContainerProps(containerProps ?? null);
		setIsOpen(true);
	});
	const update = useEvent((props, containerProps) => {
		setupCheck();
		setComponentProps(props);
		setContainerProps(containerProps ?? null);
	});
	const close = useEvent(() => {
		setIsOpen(false);
	});
	const renderedDialog = useMemo(() => {
		if (!componentProps) return null;
		return /* @__PURE__ */ jsx(DialogContainer, {
			isOpen,
			onDismiss: close,
			...mergeProps(defaultContainerProps, containerProps || void 0),
			children: /* @__PURE__ */ jsx(Component, { ...componentProps })
		});
	}, [
		componentProps,
		containerProps,
		isOpen,
		defaultContainerProps
	]);
	return {
		open,
		update,
		close,
		get rendered() {
			setupRef.current = true;
			return renderedDialog;
		}
	};
}

//#endregion
export { useDialogContainer };
//# sourceMappingURL=use-dialog-container.js.map