/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect } from "react";
import useModalStore from "../stores/useModalStore";
import "./ModalContainer.css";

interface ModalContainerProps {
  className?: string;
}

function ModalContainer({ className }: ModalContainerProps) {
  const [modal, setModal] = useModalStore((state) => [
    state.modal,
    state.setModal,
  ]);

  useEffect(() => {
    function handleKeyDown(e: KeyboardEvent) {
      if (e.code === "Escape") {
        setModal(null);
      }
    }

    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, []);

  if (modal) {
    return (
      <div
        onClick={() => setModal(null)}
        className={[
          "absolute w-full min-h-screen top-0 left-0 flex flex-col justify-center items-center p-8 bg-black bg-opacity-75 transition-opacity cursor-pointer z-10",
          className,
        ].join(" ")}
      >
        <div onClick={(e) => e.stopPropagation()} className="cursor-default">
          {modal}
        </div>
      </div>
    );
  }
}

export default ModalContainer;
