import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2020-2026 GoodData Corporation
import { memo, useCallback } from "react";
import cx from "classnames";
import { UiFocusManager } from "../@ui/UiFocusManager/UiFocusManager.js";
import { defaultFocusCheckFn } from "../@ui/UiFocusManager/utils.js";
import { ScreenReaderToast } from "../Messages/toasts/ToastsCenter.js";
import { isElementSubmitButton, isElementTextInput } from "../utils/domUtilities.js";
import { DialogCloseButton } from "./DialogCloseButton.js";
const checkKeyHandler = (event, key, handler) => {
    if (event.key !== key || !handler) {
        return;
    }
    event.preventDefault();
    event.stopPropagation();
    handler();
};
/**
 * @internal
 */
export const DialogBase = memo(function DialogBase({ submitOnEnterKey, onCancel, onSubmit, displayCloseButton, onClose, accessibilityConfig, className, dataTestId, autofocusOnOpen = true, refocusKey, children, CloseButton = DialogCloseButton, initialFocus, returnFocusTo, shouldCloseOnEscape = false, returnFocusAfterClose = false, isModal = true, focusCheckFn = defaultFocusCheckFn, }) {
    const handleKeyDown = useCallback((event) => {
        // don't call onSubmit when pressing enter key on input fields
        const isEnterKeyDownOnInputField = event.key === "Enter" && isElementTextInput(event.target);
        if (submitOnEnterKey === false && isEnterKeyDownOnInputField) {
            return;
        }
        if (event.key === "Enter" && !isElementSubmitButton(event) && !isElementTextInput(event.target)) {
            return;
        }
        checkKeyHandler(event, "Enter", onSubmit);
        checkKeyHandler(event, "Escape", shouldCloseOnEscape ? onClose : onCancel);
    }, [onCancel, onSubmit, onClose, submitOnEnterKey, shouldCloseOnEscape]);
    const dialogClasses = cx("overlay", "gd-dialog", className);
    return (_jsx(UiFocusManager, { enableFocusTrap: isModal, enableAutofocus: autofocusOnOpen ? { initialFocus, refocusKey } : false, enableReturnFocusOnUnmount: returnFocusAfterClose ? { returnFocusTo } : false, focusCheckFn: focusCheckFn, children: _jsxs("div", { id: accessibilityConfig?.dialogId, onKeyDown: handleKeyDown, "data-testid": dataTestId, role: "dialog", "aria-modal": accessibilityConfig?.isModal, "aria-label": accessibilityConfig?.title, "aria-labelledby": accessibilityConfig?.titleElementId, "aria-describedby": accessibilityConfig?.descriptionElementId, children: [
                _jsx(ScreenReaderToast, {}), _jsxs("div", { className: dialogClasses, children: [displayCloseButton ? (_jsx(CloseButton, { onClose: onClose ?? onCancel, accessibilityConfig: accessibilityConfig })) : null, children] })
            ] }) }));
});
