import {createRoot} from '@wordpress/element';
import Confirm from "../../components/popups/general/confirm";

export default function confirm(message) {
    return new Promise((resolve) => {
        const options = typeof message === 'object' && message !== null ? message : {title: message};
        const {title, description, confirmLabel, cancelLabel, style, beforeUnmount} = options;

        const container = document.createElement('div');
        document.body.appendChild(container);

        const root = createRoot(container);

        const handleConfirm = () => {
            cleanup(true);
            resolve(true);
        };

        const handleCancel = () => {
            cleanup(false);
            resolve(false);
        };

        /**
         * Cleanup
         *
         * @param {boolean} confirmed Confirmed
         */
        const cleanup = (confirmed) => {
            if (beforeUnmount) {
                beforeUnmount(confirmed);
            }
            root.unmount();
            container.remove();
        };

        root.render(
            <Confirm
                title={title}
                description={description}
                confirmLabel={confirmLabel}
                cancelLabel={cancelLabel}
                style={style}
                onConfirm={handleConfirm}
                onCancel={handleCancel}
            />
        )
    });
}