"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import "./modal.css";
function PortalImpl({ onClose, children, title, closeOnClickOutside }) {
    const modalRef = useRef(null);
    useEffect(()=>{
        if (null !== modalRef.current) modalRef.current.focus();
    }, []);
    useEffect(()=>{
        let modalOverlayElement = null;
        const handler = (event)=>{
            if (27 === event.keyCode) onClose();
        };
        const clickOutsideHandler = (event)=>{
            const target = event.target;
            if (null !== modalRef.current && !modalRef.current.contains(target) && closeOnClickOutside) onClose();
        };
        const modelElement = modalRef.current;
        if (null !== modelElement) {
            modalOverlayElement = modelElement.parentElement;
            if (null !== modalOverlayElement) modalOverlayElement.addEventListener('click', clickOutsideHandler);
        }
        window.addEventListener('keydown', handler);
        return ()=>{
            window.removeEventListener('keydown', handler);
            if (null !== modalOverlayElement) modalOverlayElement?.removeEventListener('click', clickOutsideHandler);
        };
    }, [
        closeOnClickOutside,
        onClose
    ]);
    return /*#__PURE__*/ jsx("div", {
        className: "Modal__overlay",
        role: "dialog",
        children: /*#__PURE__*/ jsxs("div", {
            className: "Modal__modal",
            tabIndex: -1,
            ref: modalRef,
            children: [
                /*#__PURE__*/ jsx("h2", {
                    className: "Modal__title",
                    children: title
                }),
                /*#__PURE__*/ jsx("button", {
                    className: "Modal__closeButton",
                    "aria-label": "Close modal",
                    type: "button",
                    onClick: onClose,
                    children: "X"
                }),
                /*#__PURE__*/ jsx("div", {
                    className: "Modal__content",
                    children: children
                })
            ]
        })
    });
}
function Modal({ onClose, children, title, closeOnClickOutside = false }) {
    return /*#__PURE__*/ createPortal(/*#__PURE__*/ jsx(PortalImpl, {
        onClose: onClose,
        title: title,
        closeOnClickOutside: closeOnClickOutside,
        children: children
    }), document.body);
}
export default Modal;
