import { ReactNode, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

// https://github.com/tajo/react-portal/blob/master/src/utils.js
const canUseDOM = !!(
  typeof window !== "undefined" &&
  window.document &&
  window.document.createElement
);

export const SelectPortal = ({ children }: { children: ReactNode }) => {
  const node = useRef(document.createElement("ads-select-portal"));

  useEffect(() => {
    const currentNode = node.current;
    document.body.appendChild(currentNode);

    return () => {
      document.body.removeChild(currentNode);
    };
  }, []);

  if (!canUseDOM) return null;

  return ReactDOM.createPortal(children, node.current);
};
