import { franc } from "franc-all";
import React, {
  ReactElement,
  ReactNode,
  useCallback,
  useEffect,
  useRef,
  useState,
} from "react";

function useModal() {
  const [achild, setChild] = useState<ReactNode>(null);
  return <Modal close={() => setChild(null)}>{achild}</Modal>;
}
export default useModal;

function Modal({
  children,
  height = "fit-content",
  width = "80%",
  close,
}: {
  children: ReactNode;
  close: () => void;
  width?: any;
  height?: any;
}) {
  function onKey(event: any) {
    if (event.key === "Escape") close();

    useEffect(() => {
      document.addEventListener("keyup", onKey);
      return () => {
        document.removeEventListener("keyup", onKey);
      };
    }, [children]);
  }

  function clickAway(e: React.MouseEvent) {
    e.stopPropagation();
    if (!modalRef.current || !modalRef.current.contains(e.target as any))
      close();
  }
  const modalRef = useRef<HTMLDivElement>(null);
  const style = { width, height };
  return (
    <div id="modal-bg" onClick={clickAway}>
      <div id="modal-fg" style={style} ref={modalRef}>
        {children}
      </div>
    </div>
  );
}
