'use client';

// src/base/Portal/Portal.tsx
import { forwardRef, useRef, useState } from "react";
import { useIsomorphicEffect } from "@paalan/react-hooks";
import { assignRef } from "@paalan/react-shared/utils";
import { createPortal } from "react-dom";
import { Fragment, jsx } from "react/jsx-runtime";
var createPortalNode = (props) => {
  const node = document.createElement("div");
  node.setAttribute("data-portal", "true");
  if (typeof props.className === "string") {
    node.classList.add(...props.className.split(" "));
  }
  if (typeof props.style === "object") {
    Object.assign(node.style, props.style);
  }
  if (typeof props.id === "string") {
    node.setAttribute("id", props.id);
  }
  return node;
};
var defaultProps = {};
var Portal = forwardRef((props, ref) => {
  const { children, target, ...others } = { ...defaultProps, ...props };
  const [mounted, setMounted] = useState(false);
  const nodeRef = useRef(null);
  useIsomorphicEffect(() => {
    setMounted(true);
    nodeRef.current = !target ? createPortalNode(others) : typeof target === "string" ? document.querySelector(target) : target;
    if (!nodeRef.current) return;
    assignRef(ref, nodeRef.current);
    if (!target && nodeRef.current) {
      document.body.appendChild(nodeRef.current);
    }
    return () => {
      if (!target && nodeRef.current) {
        document.body.removeChild(nodeRef.current);
      }
    };
  }, [target]);
  if (!mounted || !nodeRef.current) {
    return null;
  }
  return createPortal(/* @__PURE__ */ jsx(Fragment, { children }), nodeRef.current);
});
Portal.displayName = "Portal";
export {
  Portal
};
