import { jsx, jsxs } from 'react/jsx-runtime';
import { useId, useState, useEffect } from 'react';
import { cn } from '../../../utils/cn.js';
import { ModalContext } from '../Modal/Modal.js';
import { modalTheme, modalSizeVariants } from '../Modal/Modal.theme.js';
import { ArrowLeftIcon } from '@heroicons/react/24/outline';
import { modalStackTheme } from './ModalStack.theme.js';
import { Button } from '../Button/Button.js';

const ModalStackModal = ({ size = "md", variant = "default", showCloseButton = true, showBackButton = false, onClose, onBack, children, className, theme: themeOverrides, _stackOnClose, _isBackModal, }) => {
    var _a;
    const id = useId();
    const titleId = `${id}-title`;
    const subtitleId = `${id}-subtitle`;
    const [isBodyScrollable, setIsBodyScrollable] = useState(false);
    const closeHandler = onClose || _stackOnClose || (() => { });
    const backHandler = onBack || onClose || (() => { });
    // Reset scroll state when modal becomes hidden (back modal pushed back)
    useEffect(() => {
        if (_isBackModal) {
            setIsBodyScrollable(false);
        }
    }, [_isBackModal]);
    // Merge theme with overrides
    const theme = {
        ...modalTheme,
        ...(themeOverrides || {}),
        containerVariants: {
            ...modalTheme.containerVariants,
            ...((themeOverrides === null || themeOverrides === void 0 ? void 0 : themeOverrides.containerVariants) || {}),
        },
    };
    const contextValue = {
        isOpen: true,
        onClose: closeHandler,
        size,
        isSizeToken: ["sm", "md", "lg", "xl", "full"].includes(size),
        closeOnOverlayClick: true,
        closeOnEsc: true,
        showCloseButton,
        theme,
        isBodyScrollable,
        setIsBodyScrollable,
        titleId,
        subtitleId,
    };
    return (jsx(ModalContext.Provider, { value: contextValue, children: jsxs("div", { className: cn(theme.container, (_a = theme.containerVariants) === null || _a === void 0 ? void 0 : _a[variant], modalSizeVariants[size], className), role: "dialog", "aria-modal": "true", "aria-labelledby": titleId, "aria-describedby": subtitleId, children: [showBackButton && (jsx("div", { className: cn(modalStackTheme.backButton), children: jsxs(Button, { onClick: backHandler, "aria-label": "Go back", variant: "link", size: "sm", children: [jsx(ArrowLeftIcon, { className: "size-4" }), "Back"] }) })), children] }) }));
};
ModalStackModal.displayName = "ModalStack.Modal";

export { ModalStackModal };
