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

interface LayerProps {
  children: React.ReactNode;
}

const Layer = ({ children }: LayerProps) => {
  const [mounted, setMounted] = useState(false);
  const portal = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (
      typeof document !== 'undefined' &&
      document.createElement &&
      document.body
    ) {
      const div = document.createElement('div');
      document.body.appendChild(div);
      portal.current = div;
      setMounted(true);

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

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

export default Layer;
