"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Dialog = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_1 = require("react");
const contains_1 = tslib_1.__importDefault(require("../utils/contains"));
const captureTabNavigation_1 = tslib_1.__importDefault(require("../utils/captureTabNavigation"));
const Modal_1 = require("../Modal");
const useIsOpen_1 = tslib_1.__importDefault(require("./useIsOpen"));
const useAutoFocus_1 = tslib_1.__importDefault(require("../utils/useAutoFocus"));
const icons_1 = require("../icons");
const WindowModal_1 = require("../WindowModal");
const Flex_1 = require("../Flex");
const clsx_1 = tslib_1.__importDefault(require("clsx"));
const twUtils_1 = require("../twUtils");
const baseClassName = 'ab-Dialog';
exports.Dialog = React.forwardRef((props, dialogRef) => {
    let { modal, fixed, focusOnBrowserVisible = false, autoFocus = true, className, children, modalProps, dismissOnClickOutside = false, onDismiss, windowModal, windowModalProps, showCloseButton = true, isOpen: _isOpenProp, ...boxProps } = props;
    modal = props.modal === undefined ? true : props.modal;
    fixed = props.fixed === undefined ? true : props.fixed;
    const [isOpen, setIsOpen] = (0, useIsOpen_1.default)(props);
    const boxRef = (0, react_1.useRef)(null);
    (0, useAutoFocus_1.default)({
        isOpen,
        autoFocus: props.autoFocus,
        previous: ({ autoFocus }) => autoFocus && isOpen,
        shouldFocus: ({ autoFocus }) => autoFocus && isOpen,
    }, boxRef);
    const onKeyDown = (e) => {
        if (props.onKeyDown) {
            props.onKeyDown(e);
        }
        (0, captureTabNavigation_1.default)(boxRef.current, e);
        if (e.key === 'Escape') {
            if (e.nativeEvent.anotherModalClosed) {
                return;
            }
            e.nativeEvent.anotherModalClosed = true;
            const activeElement = document.activeElement;
            const ignoreTags = {
                input: 1,
                a: 1,
                button: 1,
            };
            if (activeElement && !!ignoreTags[activeElement.tagName]) {
                return;
            }
            setIsOpen(false);
        }
        (0, captureTabNavigation_1.default)(boxRef.current, event);
    };
    (0, react_1.useEffect)(() => {
        if (dismissOnClickOutside && isOpen) {
            const dismissDialog = (e) => {
                requestAnimationFrame(() => {
                    if (e.preventDialogDismiss) {
                        return;
                    }
                    setIsOpen(false);
                });
            };
            document.documentElement.addEventListener('click', dismissDialog, {
                passive: true,
                capture: false,
            });
            return () => {
                document.documentElement.removeEventListener('click', dismissDialog);
            };
        }
    }, [isOpen, dismissOnClickOutside]);
    const bringToFront = React.useCallback(() => {
        if (boxRef.current &&
            boxRef.current.focus &&
            (!document.activeElement || !(0, contains_1.default)(boxRef.current, document.activeElement))) {
            boxRef.current.focus();
        }
    }, [boxRef]);
    React.useImperativeHandle(dialogRef, () => ({
        bringToFront,
    }));
    (0, react_1.useEffect)(() => {
        let listener;
        if (focusOnBrowserVisible) {
            listener = () => {
                if (document.visibilityState === 'visible' && autoFocus && focusOnBrowserVisible) {
                    bringToFront();
                }
            };
            document.addEventListener('visibilitychange', listener);
        }
        return () => {
            if (listener) {
                document.removeEventListener('visibilitychange', listener);
            }
        };
    }, [autoFocus, focusOnBrowserVisible]);
    if (!isOpen) {
        return null;
    }
    const closeButton = showCloseButton ? (React.createElement(Flex_1.Box, { title: "Close dialog", onClick: () => setIsOpen(false), className: (0, clsx_1.default)(`${baseClassName}__close-button twa:p-1`, 'twa:text-accentlight', 'twa:text-shadow-[0_1px_0_#fff]', `twa:text-3 twa:cursor-pointer twa:leading-none twa:font-bold`, 'twa:absolute twa:top-[6px] twa:right-[6px]') },
        React.createElement(icons_1.Icon, { size: 20, name: "close" }))) : null;
    const setPreventDismissFlag = (e) => {
        if (dismissOnClickOutside) {
            e.nativeEvent.preventDialogDismiss = true;
        }
    };
    const box = (React.createElement(Flex_1.Box, { ...boxProps, onClick: (e) => {
            setPreventDismissFlag(e);
            if (boxProps && boxProps.onClick) {
                boxProps.onClick(e);
            }
        }, onKeyDown: onKeyDown, className: (0, clsx_1.default)('twa:relative', 'twa:bg-defaultbackground', 'twa:text-text-on-defaultbackground', 'twa:fill-text-on-defaultbackground', 'twa:rounded-standard', 'twa:flex twa:flex-col', twUtils_1.targetOwn.focusOutline, twUtils_1.targetOwn.focusWithinOutline, baseClassName, modal ? `${baseClassName}--modal` : `${baseClassName}--not-modal`, className), ref: boxRef },
        children,
        closeButton));
    const content = fixed ? (React.createElement("div", { onClick: setPreventDismissFlag, className: (0, clsx_1.default)(`${baseClassName}-fixed-wrapper`, 'twa:fixed twa:inset-0', 'twa:m-auto', 'twa:flex twa:items-center twa:justify-center') }, box)) : (box);
    if (windowModal) {
        return React.createElement(WindowModal_1.WindowModal, { ...windowModalProps }, content);
    }
    if (modal) {
        return (React.createElement(Modal_1.Modal, { ...modalProps, isOpen: isOpen, onBringToFront: bringToFront }, box));
    }
    return content;
});
exports.default = exports.Dialog;
