import React from 'react';
import { createPortal } from 'react-dom';

import type { PropsWithChildren } from 'react';

import { IS_BROWSER } from '@redocly/theme/core/utils';

export type PortalProps = {
  mountId?: string;
};

export function Portal({
  children,
  mountId = 'root',
}: PropsWithChildren<PortalProps>): React.ReactPortal | JSX.Element {
  const mount = IS_BROWSER ? document.getElementById(mountId) || document.body : null;

  if (!mount) {
    return <>{children}</>;
  }

  return createPortal(children, mount);
}
