// #region Imports
import { fadeSlideIn, fadeSlideOut } from '../../../../Animations/Presets/Fade';
import { RendererServiceLocator } from '../../../../Dom/Renderer';
import { on, waitForEvent } from '@breadstone/mosaik-elements';
import { EID } from '../../../../Utilities/EId';
import { ToastPosition } from '../../../Types/ToastPosition';
import { Variant } from '../../../Types/Variant';
import { PortalElement } from '../../Primitives/Portal/PortalElement';
import { ToastElement } from './ToastElement';
/**
 * Represents the `Toast` constant.
 *
 * @public
 */
export var Toast;
(function (Toast) {
    let Timeout;
    (function (Timeout) {
        /**
         * The duration of a short (1500ms) toast message.
         *
         * @public
         * @readonly
         * @static
         */
        Timeout.SHORT = 1500;
        /**
         * The duration of a medium (3000ms) toast message.
         *
         * @public
         * @readonly
         * @static
         */
        Timeout.MEDIUM = 3000;
        /**
         * The duration of a long (6000ms) toast message.
         *
         * @public
         * @readonly
         * @static
         */
        Timeout.LONG = 6000;
    })(Timeout = Toast.Timeout || (Toast.Timeout = {}));
})(Toast || (Toast = {}));
/**
 * Represents the `TOAST_DEFAULT_OPTIONS` constant.
 *
 * @private
 */
const TOAST_DEFAULT_OPTIONS = {
    header: '',
    content: '',
    timeout: Toast.Timeout.MEDIUM,
    position: ToastPosition.Bottom,
    showProgress: false,
    hasBackdrop: false,
    isOpen: true,
    pressEscapeToClose: true,
    clickOutsideToClose: true,
    variant: Variant.Default,
    formatter: null,
    closeable: false,
    isBusy: false,
    enter: fadeSlideIn,
    exit: fadeSlideOut
};
/**
 * Service for managing the display and behavior of message box elements.
 * Provides methods to open and close message box elements within a portal structure.
 *
 * @public
 */
export class ToastService {
    // #region Fields
    _toastMap;
    // #endregion
    // #region Ctor
    /**
     * Constructs a new instance of the `ToastService` class.
     *
     * @public
     */
    constructor() {
        this._toastMap = new Map();
        on(window, 'popstate', () => {
            if (this._toastMap.size > 0) {
                for (const [key, value] of this._toastMap) {
                    if (value.options?.navigateToClose) {
                        void this.close(key);
                    }
                }
            }
        });
    }
    // #endregion
    // #region Methods
    /**
     * Opens a custom wrapper component containing a message box within a portal.
     *
     * @public
     * @template TResult - Expected return type of the resolved message box result.
     * @param {IToastOptions} options - Properties for portal and message box.
     * @returns {Promise<TResult>} A promise resolving with the message box result.
     */
    async open(options) {
        const toastId = options?.id ?? EID.next(ToastElement.is);
        let toastRef = this._toastMap.get(options?.id ?? EID.next(ToastElement.is));
        if (!toastRef) {
            const toastElement = RendererServiceLocator.current.createElement(ToastElement.is);
            RendererServiceLocator.current.setProperty(toastElement, 'id', toastId);
            const [portal, portalProjection] = await this.extendToPortal(toastElement, options);
            // eslint-disable-next-line require-atomic-updates
            this._toastMap.set(toastId, toastRef = {
                toastId: toastId,
                toastElement: toastElement,
                portalElement: portal,
                portalProjectionElement: portalProjection,
                options: options
            });
        }
        Object.assign(toastRef.toastElement, {
            ...TOAST_DEFAULT_OPTIONS,
            ...options
        });
        return new Promise((resolve) => {
            toastRef.resolve = resolve;
            void toastRef.toastElement.open();
            void waitForEvent(toastRef.toastElement, 'closed').then(() => {
                this._toastMap.delete(toastId);
                toastRef.toastElement.remove();
                toastRef.portalElement.remove();
                void toastRef.portalProjectionElement.close();
                toastRef.portalProjectionElement.remove();
                if (toastRef.resolve) {
                    toastRef.resolve();
                }
            });
        });
    }
    /**
     * Closes the message box in the wrapper component and optionally removes the wrapper from the DOM.
     *
     * @public
     * @template TResult - Type of result returned when the message box is closed.
     * @param {string} toastId - Unique identifier for the message box instance.
     * @param {TResult} [result] - Optional result returned when closing the message box.
     * @returns {Promise<void>} A promise resolving once the message box is fully closed.
     */
    async close(toastId, result) {
        return new Promise((resolve) => {
            const ref = this._toastMap.get(toastId);
            if (ref) {
                this._toastMap.delete(toastId);
                void waitForEvent(ref.toastElement, 'closed').then(() => {
                    void ref.portalProjectionElement.close();
                    ref.portalProjectionElement.remove();
                    if (ref.resolve) {
                        ref.resolve(result);
                    }
                    resolve();
                });
                void ref.toastElement.close();
            }
            else {
                console.error(`Wrapper with ID "${toastId}" not found.`);
                resolve(); // Resolve to avoid hanging promise if message box not found
            }
        });
    }
    configure(options) {
    }
    /**
     * Extends the message box component by placing it within a portal structure.
     *
     * @private
     * @param portalProps - Properties to set on the portal.
     * @param element - The element to place within the portal.
     * @returns The created PortalElement containing the message box.
     */
    extendToPortal(element, props) {
        const portal = this.createPortal(props);
        return new Promise((resolve) => {
            on(portal, 'portalAttached', (e) => {
                resolve([e.target, e.detail.projection]);
            });
            RendererServiceLocator.current.appendChild(portal, element);
        });
    }
    /**
     * Creates a new portal element and appends it to the document body.
     *
     * @private
     * @param props - Optional properties to set on the portal element.
     * @returns The created PortalElement.
     */
    createPortal(props) {
        const portal = RendererServiceLocator.current.createElement(PortalElement.is);
        Object.assign(portal, props);
        RendererServiceLocator.current.setAttribute(portal, 'id', EID.next(PortalElement.is));
        RendererServiceLocator.current.appendChild(document.body, portal);
        return portal;
    }
}
/**
 * The `ToastServiceLocator` class provides a locator service for the `ToastService` instance.
 *
 * @public
 */
export class ToastServiceLocator {
    // #region Fields
    static _current = null;
    // #endregion
    // #region Properties
    static get current() {
        if (!ToastServiceLocator.isSet()) {
            throw new Error('\'ToastService\' not set.');
        }
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        return ToastServiceLocator._current;
    }
    // #endregion
    // #region Methods
    static isSet() {
        return ToastServiceLocator._current !== null;
    }
    static set(current) {
        ToastServiceLocator._current = current;
    }
}
ToastServiceLocator.set(new ToastService());
//# sourceMappingURL=ToastService.js.map