"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Modal;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_1 = require("react");
const react_dom_1 = require("react-dom");
function PortalImpl({ children, closeOnClickOutside, onClose, title, }) {
    const modalRef = (0, react_1.useRef)(null);
    (0, react_1.useEffect)(() => {
        if (modalRef.current !== null) {
            modalRef.current.focus();
        }
    }, []);
    (0, react_1.useEffect)(() => {
        let modalOverlayElement = null;
        const handler = (event) => {
            if (event.key === 'Escape') {
                onClose();
            }
        };
        const clickOutsideHandler = (event) => {
            const target = event.target;
            if (modalRef.current !== null && !modalRef.current.contains(target) && closeOnClickOutside) {
                onClose();
            }
        };
        const modelElement = modalRef.current;
        if (modelElement !== null) {
            modalOverlayElement = modelElement.parentElement;
            if (modalOverlayElement !== null) {
                modalOverlayElement.addEventListener('click', clickOutsideHandler);
            }
        }
        window.addEventListener('keydown', handler);
        return () => {
            window.removeEventListener('keydown', handler);
            if (modalOverlayElement !== null) {
                modalOverlayElement === null || modalOverlayElement === void 0 ? void 0 : modalOverlayElement.removeEventListener('click', clickOutsideHandler);
            }
        };
    }, [closeOnClickOutside, onClose]);
    return (React.createElement("div", { className: 'Modal__overlay', role: 'dialog' },
        React.createElement("div", { ref: modalRef, className: 'Modal__modal', tabIndex: -1 },
            React.createElement("h2", { className: 'Modal__title' }, title),
            React.createElement("button", { "aria-label": 'Close modal', className: 'Modal__closeButton', onClick: onClose, type: 'button' }, "X"),
            React.createElement("div", { className: 'Modal__content' }, children))));
}
function Modal({ children, closeOnClickOutside = false, onClose, title, }) {
    return (0, react_dom_1.createPortal)(React.createElement(PortalImpl, { closeOnClickOutside: closeOnClickOutside, onClose: onClose, title: title }, children), document.body);
}
//# sourceMappingURL=Modal.js.map