// #region Imports
import { RendererServiceLocator } from '../../../../Dom/Renderer';
import { on, waitForEvent } from '@breadstone/mosaik-elements';
import { EID } from '../../../../Utilities/EId';
import { Appearance } from '../../../Types/Appearance';
import { MessageBoxButtons } from '../../../Types/MessageBoxButtons';
import { Variant } from '../../../Types/Variant';
import { PortalElement } from '../../Primitives/Portal/PortalElement';
import { MessageBoxElement } from './MessageBoxElement';
import { MESSAGE_BOX_SERVICE_DEFAULT_CONFIG } from './IMessageBoxServiceConfig';
/**
 * Represents the `MESSAGE_BOX_DEFAULT_OPTIONS` constant.
 *
 * @private
 */
const MESSAGE_BOX_DEFAULT_OPTIONS = {
    header: '',
    subHeader: '',
    message: '',
    appearance: Appearance.Default,
    variant: Variant.Default,
    labels: {
        ok: 'OK',
        cancel: 'Cancel',
        yes: 'Yes',
        no: 'No'
    },
    clickOutsideToClose: false,
    pressEscapeToClose: false,
    closeable: false,
    hasBackdrop: true,
    buttons: MessageBoxButtons.OK,
    icon: ''
};
/**
 * Service for managing the display and behavior of message box elements.
 * Provides methods to open and close message box elements within a portal structure.
 *
 * Uses a singleton pattern with static configuration.
 *
 * @example
 * ```typescript
 * // Configure once at app startup
 * MessageBoxService.configure({
 *     closeOnNavigation: true,
 *     behaviors: []
 * });
 *
 * // Use throughout the app
 * const result = await MessageBoxService.instance.open('myMessageBox', {
 *     header: 'Confirm',
 *     message: 'Are you sure?',
 *     buttons: MessageBoxButtons.YesNo
 * });
 * ```
 *
 * @public
 */
export class MessageBoxService {
    // #region Fields
    static _instance = null;
    static _config = MESSAGE_BOX_SERVICE_DEFAULT_CONFIG;
    static _isConfigured = false;
    _messageBoxMap;
    _behaviors;
    _portalElement;
    // #endregion
    // #region Ctor
    /**
     * Constructs a new instance of the `MessageBoxService` class.
     * Use `MessageBoxService.configure()` and `MessageBoxService.instance` instead of direct instantiation.
     *
     * @private
     */
    constructor(config) {
        this._messageBoxMap = new Map();
        this._behaviors = config.behaviors ?? [];
        if (config.closeOnNavigation !== false) {
            on(window, 'popstate', () => {
                if (this._messageBoxMap.size > 0) {
                    for (const [key, value] of this._messageBoxMap) {
                        if (value.options?.navigateToClose) {
                            void this.close(key);
                        }
                    }
                }
            });
        }
    }
    // #endregion
    // #region Properties
    /**
     * Gets the singleton instance of `MessageBoxService`.
     * If not configured, uses default configuration.
     *
     * @public
     * @static
     */
    static get instance() {
        MessageBoxService._instance ??= new MessageBoxService(MessageBoxService._config);
        return MessageBoxService._instance;
    }
    // #endregion
    // #region Methods
    /**
     * Configures the `MessageBoxService` globally.
     * Must be called before accessing `instance` if custom configuration is needed.
     * Can only be called once; subsequent calls will throw an error.
     *
     * @public
     * @static
     * @param config - The configuration for the message box service.
     * @throws Error if already configured.
     *
     * @example
     * ```typescript
     * MessageBoxService.configure({
     *     closeOnNavigation: true,
     *     behaviors: [myCustomBehavior]
     * });
     * ```
     */
    static configure(config) {
        if (MessageBoxService._isConfigured) {
            throw new Error('MessageBoxService has already been configured. Configuration can only be set once.');
        }
        MessageBoxService._config = {
            ...MESSAGE_BOX_SERVICE_DEFAULT_CONFIG,
            ...config
        };
        MessageBoxService._isConfigured = true;
    }
    /**
     * Opens a message box within a portal.
     *
     * @public
     * @param messageBoxId - Unique identifier for the message box instance.
     * @param options - Properties for portal and message box.
     * @returns A promise resolving with the result of the message box.
     */
    async open(messageBoxId, options) {
        // Allow behaviors to configure options
        const mergedOptions = { ...options };
        for (const behavior of this._behaviors) {
            behavior.configure(mergedOptions);
        }
        let ref = this._messageBoxMap.get(messageBoxId);
        if (!ref) {
            const messageBoxElement = RendererServiceLocator.current.createElement(MessageBoxElement.is);
            RendererServiceLocator.current.setProperty(messageBoxElement, 'id', messageBoxId);
            const portalProjection = await this.extendToPortal(messageBoxElement, mergedOptions);
            this._messageBoxMap.set(messageBoxId, ref = {
                messageBoxId: messageBoxId,
                messageBoxElement: messageBoxElement,
                portalProjectionElement: portalProjection,
                options: mergedOptions
            });
        }
        // Destructure to exclude isOpen from options - we control open state via messageBoxElement.open()
        // This ensures pressEscapeToClose and other properties are set before the escape listener is attached
        const { isOpen: _ignored, ...safeOptions } = mergedOptions;
        Object.assign(ref.messageBoxElement, {
            ...MESSAGE_BOX_DEFAULT_OPTIONS,
            ...safeOptions
        });
        // Notify behaviors about attachment
        for (const behavior of this._behaviors) {
            behavior.attach(ref);
        }
        return new Promise((resolve) => {
            ref.resolve = resolve;
            void ref.messageBoxElement.open();
            void Promise.all([
                waitForEvent(ref.messageBoxElement, 'closed')
            ]).then(() => {
                // Notify behaviors about detachment
                for (const behavior of this._behaviors) {
                    behavior.detach(ref);
                }
                this._messageBoxMap.delete(messageBoxId);
                void ref.portalProjectionElement.close().then(() => {
                    ref.portalProjectionElement.remove();
                });
            });
        });
    }
    /**
     * Closes the message box and optionally removes it from the DOM.
     *
     * @public
     * @param messageBoxId - Unique identifier for the message box instance.
     * @returns A promise resolving once the message box is fully closed.
     */
    async close(messageBoxId) {
        return new Promise((resolve) => {
            const ref = this._messageBoxMap.get(messageBoxId);
            if (ref) {
                this._messageBoxMap.delete(messageBoxId);
                void waitForEvent(ref.messageBoxElement, 'dialogResult').then((event) => {
                    // Notify behaviors about detachment
                    for (const behavior of this._behaviors) {
                        behavior.detach(ref);
                    }
                    void ref.portalProjectionElement.close().then(() => {
                        ref.portalProjectionElement.remove();
                    });
                    if (ref.resolve) {
                        ref.resolve(event.detail.result);
                    }
                    resolve();
                });
                void ref.messageBoxElement.close();
            }
            else {
                console.error(`Wrapper with ID "${messageBoxId}" not found.`);
                resolve();
            }
        });
    }
    /**
     * Disposes of the service and cleans up resources.
     *
     * @public
     */
    dispose() {
        // Dispose all behaviors
        for (const behavior of this._behaviors) {
            behavior.dispose();
        }
        // Close all open message boxes
        for (const [id] of this._messageBoxMap) {
            void this.close(id);
        }
        this._messageBoxMap.clear();
        // Clean up portal
        if (this._portalElement) {
            this._portalElement.remove();
            this._portalElement = undefined;
        }
    }
    /**
     * Extends the message box component by placing it within a portal structure.
     *
     * @private
     * @param element - The element to place within the portal.
     * @param props - Properties to set on the portal.
     * @returns The created PortalProjectionElement containing the message box.
     */
    extendToPortal(element, props) {
        return new Promise((resolve) => {
            if (!this._portalElement) {
                this._portalElement = RendererServiceLocator.current.createElement(PortalElement.is);
                RendererServiceLocator.current.setAttribute(this._portalElement, 'id', EID.next(PortalElement.is));
                Object.assign(this._portalElement, props);
                RendererServiceLocator.current.appendChild(document.body, this._portalElement);
            }
            this._portalElement.addEventListener('portalAttached', (e) => {
                resolve(e.detail.projection);
            }, { once: true });
            RendererServiceLocator.current.appendChild(this._portalElement, element);
        });
    }
}
//# sourceMappingURL=MessageBoxService.js.map