import { useEffect, useRef, useCallback } from 'react';
import ReactDom from 'react-dom';

import classes from './style.module.scss';

export const CustomModal = ({ children, closeEvent }) => {
  const modal = useRef();

  const handleClickOutside = useCallback(
    (event) => {
      if (modal.current) {
        if (event.target && !modal.current.contains(event.target)) closeEvent();
      }
    },
    [closeEvent],
  );

  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside)

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [handleClickOutside])


  return ReactDom.createPortal(<div className={classes.wrapper}>
    <div className={classes.modal} ref={modal}>
      {/* <div>header <button>x</button></div> */}
      {children}
    </div>
  </div>, document.body)
} 