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

import { useHiveUIContext } from '../../core/contexts/HiveUIContext';
import { assertEmptyObject } from '../../utils/assertEmptyObject';

/** Props for {@link Portal} */
export interface PortalProps {
  children: ReactNode;
}

/**
 * It renders children at the root of HiveUI and, as a result, protects children from external styles of the CSS context.
 * A typical use case for portals is when a parent component has an `overflow: hidden` or `z-index` style.
 *
 * ```tsx
 * <Portal>
 *   some content
 * </Portal>
 * ```
 */
export function Portal(props: PortalProps) {
  const { children, ...restProps } = props;
  assertEmptyObject(restProps);

  const { rootElement } = useHiveUIContext();

  if (!rootElement) {
    return null;
  }

  return createPortal(children, rootElement);
}
