import { jsx as _jsx } from "react/jsx-runtime";
import { useState } from 'react';
import { createRoot } from 'react-dom/client';
export const confirmable = (Component) => {
    const Confirmable = ({ dispose, reject, resolve, ...other }) => {
        const [show, setShow] = useState(true);
        const dismiss = () => {
            setShow(false);
            dispose();
        };
        const cancel = (value) => {
            setShow(false);
            reject(value);
        };
        const proceed = (value) => {
            setShow(false);
            resolve(value);
        };
        return _jsx(Component, { cancel: cancel, dismiss: dismiss, proceed: proceed, show: show, ...other });
    };
    return Confirmable;
};
const DEFAULT_UNMOUNT_DELAY_MS = 1000;
export const createConfirmation = (Component, unmountDelay = DEFAULT_UNMOUNT_DELAY_MS, mountingNode) => {
    return async (props) => {
        let record;
        const dispose = () => {
            setTimeout(() => {
                if (!record)
                    return;
                const { wrapper, root } = record;
                root.unmount();
                if (wrapper.parentNode) {
                    wrapper.parentNode.removeChild(wrapper);
                }
                record = undefined;
            }, unmountDelay);
        };
        const promise = new Promise((resolve, reject) => {
            const host = mountingNode ?? document.body;
            const wrapper = host.appendChild(document.createElement('div'));
            const root = createRoot(wrapper);
            record = { wrapper, root };
            root.render(_jsx(Component, { ...props, dispose: dispose, resolve: resolve, reject: reject }));
        });
        return promise.then((result) => {
            dispose();
            return result;
        }, async (error) => {
            dispose();
            return Promise.reject(error);
        });
    };
};
//# sourceMappingURL=imperative-confirm.js.map