import { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';

// TODO make this component stateless
export const Layer = ({ children }: { children: React.ReactNode }) => {
  const [mounted, setMounted] = useState(false);
  const portal = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (
      typeof document !== 'undefined' &&
      document.createElement &&
      document.body
    ) {
      const element = document.createElement('div');
      document.body.appendChild(element);
      portal.current = element;
      setMounted(true);
      return () => {
        if (document.body) {
          document.body.removeChild(element);
        }
      };
    }
  }, []);

  return mounted ? createPortal(children, portal.current!) : null;
};

export default Layer;
