import { useRef, useEffect } from "react";
const createRootElement = (id) => {
  const rootContainer = document.createElement("div");
  rootContainer.setAttribute("id", id);
  return rootContainer;
};
const addRootElement = (rootElement) => {
  document.body.insertBefore(
    rootElement,
    document.body.lastElementChild.nextElementSibling
  );
};
const usePortal = (id) => {
  const rootElementRef = useRef(null);
  useEffect(() => {
    const existingParent = document.getElementById(id);
    const parentElem = existingParent || createRootElement(id);
    if (!existingParent) {
      addRootElement(parentElem);
    }
    parentElem.appendChild(rootElementRef.current);
    return function removeElement() {
      rootElementRef.current.remove();
      if (!parentElem.childElementCount) {
        parentElem.remove();
      }
    };
  }, [id]);
  const getRootElemement = () => {
    if (!rootElementRef.current) {
      rootElementRef.current = document.createElement("div");
    }
    return rootElementRef.current;
  };
  return getRootElemement();
};
export {
  usePortal
};
