import React, { useEffect, useState } from "react";
import { renderPortal } from "../../renderReactRoot";

const Portal = ({ children, container }) => {
  const [portalContent, setPortalContent] = useState(null);

  useEffect(() => {
    let isMounted = true;

    if (container) {
      renderPortal(children, container).then((portal) => {
        if (isMounted) {
          setPortalContent(portal);
        }
      });
    } else {
      setPortalContent(null);
    }

    return () => {
      isMounted = false;
    };
  }, [children, container]);

  // If no container, return null immediately
  if (!container) return null;

  return portalContent;
};

export default Portal;
