/* eslint-disable @stylistic/type-annotation-spacing */
// #region Imports
import { fadeOut, fadeSlideIn } from '../../../../Animations/Presets/Fade';
import { RendererServiceLocator } from '../../../../Dom/Renderer';
import { on, waitForEvent } from '@breadstone/mosaik-elements';
import { EID } from '../../../../Utilities/EId';
import { Appearance } from '../../../Types/Appearance';
import { ElevationWeight } from '../../../Types/ElevationWeight';
import { PortalElement } from '../../Primitives/Portal/PortalElement';
import { DialogElement } from './DialogElement';
import { DIALOG_SERVICE_DEFAULT_CONFIG } from './IDialogServiceConfig';
/**
 * Represents the `DIALOG_DEFAULT_OPTIONS` constant.
 *
 * @private
 */
const DIALOG_DEFAULT_OPTIONS = {
    height: 'auto',
    width: 'auto',
    hasBackdrop: true,
    pressEscapeToClose: true,
    clickOutsideToClose: true,
    isDraggable: false,
    closeable: false,
    elevation: ElevationWeight.Bold,
    appearance: Appearance.Default,
    enter: fadeSlideIn,
    exit: fadeOut,
    isFullScreen: false
};
/**
 * Service for managing the display and behavior of dialog elements.
 * Provides methods to open and close dialog elements within a portal structure.
 * Supports extensible behavior pattern for customizing dialog interactions.
 *
 * @example
 * ```typescript
 * // Configure service globally before use
 * DialogService.configure({
 *     behaviors: [withDialogStackBehavior({ baseWidth: '80%', baseHeight: '60%' })],
 *     closeOnNavigation: true
 * });
 *
 * // Use the singleton instance
 * const result = await DialogService.instance.open('myDialog', MyDialogWrapper, options);
 * ```
 *
 * @public
 */
export class DialogService {
    // #region Fields
    static _instance = null;
    static _config = { ...DIALOG_SERVICE_DEFAULT_CONFIG };
    _dialogMap;
    _dialogStack;
    _behaviors;
    _portalElement;
    // #endregion
    // #region Ctor
    /**
     * Constructs a new instance of the `DialogService` class.
     * Use {@link DialogService.instance} to access the singleton instance.
     *
     * @private
     */
    constructor() {
        this._dialogMap = new Map();
        this._dialogStack = new Array();
        this._behaviors = DialogService._config.behaviors ?? [];
        // Configure all behaviors
        for (const behavior of this._behaviors) {
            behavior.configure({});
        }
        // Setup navigation listener if enabled
        if (DialogService._config.closeOnNavigation) {
            on(window, 'popstate', () => {
                if (this._dialogMap.size > 0) {
                    for (const [key, value] of this._dialogMap) {
                        if (value.options?.navigateToClose) {
                            void this.close(key);
                        }
                    }
                }
            });
        }
    }
    // #endregion
    // #region Properties
    /**
     * Returns the singleton instance of the DialogService.
     * Creates the instance on first access using the current configuration.
     *
     * @public
     * @readonly
     */
    static get instance() {
        DialogService._instance ??= new DialogService();
        return DialogService._instance;
    }
    /**
     * Returns the current number of open dialogs in the stack.
     *
     * @public
     * @readonly
     */
    get stackSize() {
        return this._dialogStack.length;
    }
    /**
     * Returns an array of all dialog references in stack order (oldest first).
     *
     * @public
     * @readonly
     */
    get stack() {
        return this._dialogStack
            .map((id) => this._dialogMap.get(id))
            .filter((ref) => ref !== undefined);
    }
    /**
     * Returns the registered behaviors for this service instance.
     *
     * @public
     * @readonly
     */
    get behaviors() {
        return this._behaviors;
    }
    // #endregion
    // #region Methods
    /**
     * Configures the dialog service globally.
     * Must be called before accessing the singleton instance.
     *
     * @public
     * @static
     * @param config - Configuration options for the dialog service.
     * @returns The DialogService class for chaining.
     * @throws Error if called after the instance has already been created.
     *
     * @example
     * ```typescript
     * DialogService.configure({
     *     behaviors: [withDialogStackBehavior({ baseWidth: '80%' })],
     *     closeOnNavigation: true
     * });
     * ```
     */
    static configure(config) {
        if (DialogService._instance !== null) {
            throw new Error('DialogService.configure() must be called before accessing DialogService.instance. ' +
                'The service has already been instantiated.');
        }
        DialogService._config = {
            ...DIALOG_SERVICE_DEFAULT_CONFIG,
            ...config
        };
        return DialogService;
    }
    /**
     * Opens a custom wrapper component containing a dialog within a portal.
     *
     * @public
     */
    async open(dialogId, wrapperClass, data, options) {
        // Let behaviors configure options before creating the ref
        for (const behavior of this._behaviors) {
            behavior.configure(options ?? {});
        }
        let ref = this._dialogMap.get(dialogId);
        ref ??= await this.createDialogRef(dialogId, wrapperClass, data, options);
        // Destructure to exclude isOpen from options - we control open state via dialogElement.open()
        // This ensures pressEscapeToClose and other properties are set before the escape listener is attached
        const { isOpen: _ignored, ...safeOptions } = options ?? {};
        Object.assign(ref.dialogElement, {
            ...DIALOG_DEFAULT_OPTIONS,
            ...safeOptions
        });
        // Let behaviors attach to the dialog
        for (const behavior of this._behaviors) {
            behavior.attach(ref);
        }
        return new Promise((resolve) => {
            ref.resolve = resolve;
            void ref.dialogElement.open();
        });
    }
    /**
     * Closes the dialog in the wrapper component and optionally removes the wrapper from the DOM.
     *
     * @public
     * @template TResult - Type of result returned when the dialog is closed.
     * @param dialogId - Unique identifier for the dialog instance.
     * @param result - Optional result returned when closing the dialog.
     * @returns A promise resolving once the dialog is fully closed.
     */
    async close(dialogId, result) {
        const ref = this._dialogMap.get(dialogId);
        if (!ref) {
            console.error(`Wrapper with ID "${dialogId}" not found.`);
            return;
        }
        // Let behaviors detach from the dialog
        for (const behavior of this._behaviors) {
            behavior.detach(ref);
        }
        // Remove from stack if it was a stacked dialog
        const stackIndex = this._dialogStack.indexOf(dialogId);
        if (stackIndex !== -1) {
            this._dialogStack.splice(stackIndex, 1);
        }
        // Delete from map before closing to prevent duplicate close calls
        this._dialogMap.delete(dialogId);
        // Set up the event listener BEFORE calling close() to ensure we catch the event.
        // DialogElement.close() plays the exit animation, then calls super.close() which
        // sets isOpen = false and fires the 'closed' event. By waiting for this event,
        // we ensure the entire close sequence (including animation) has completed.
        const closedPromise = waitForEvent(ref.dialogElement, 'closed');
        // Trigger the close (this starts the animation)
        void ref.dialogElement.close();
        // Wait for the 'closed' event which fires after the animation completes
        await closedPromise;
        // Remove portal projection after animation is done
        ref.portalProjectionElement.remove();
        // Resolve the promise from open() with the result
        if (ref.resolve) {
            ref.resolve(result);
        }
    }
    /**
     * Closes the topmost dialog in the stack.
     *
     * @public
     * @template TResult - Type of result returned when the dialog is closed.
     * @param result - Optional result returned when closing the dialog.
     * @returns A promise resolving once the dialog is fully closed.
     */
    async closeTop(result) {
        if (this._dialogStack.length === 0) {
            return Promise.resolve();
        }
        const topDialogId = this._dialogStack[this._dialogStack.length - 1];
        return this.close(topDialogId, result);
    }
    /**
     * Closes all open dialogs in the stack, from top to bottom.
     *
     * @public
     * @returns A promise resolving once all dialogs are closed.
     */
    async closeAll() {
        const dialogIds = [...this._dialogStack].reverse();
        for (const dialogId of dialogIds) {
            await this.close(dialogId);
        }
    }
    /**
     * Creates a new dialog reference.
     *
     * @private
     */
    async createDialogRef(dialogId, wrapperClass, data, options) {
        // Create the wrapper component containing the dialog
        const wrapperElement = new wrapperClass(data);
        RendererServiceLocator.current.setProperty(wrapperElement, 'id', dialogId);
        // Create and attach to portal
        const portalProjection = await this.extendToPortal(wrapperElement, options);
        const dialogElement = wrapperElement.shadowRoot?.querySelector(DialogElement.is);
        if (!dialogElement) {
            throw new Error(`Dialog element not found within wrapper for ID "${dialogId}".`);
        }
        // Calculate stack level from stack length
        const stackLevel = this._dialogStack.length;
        // Use default size or options size
        const defaultWidth = DIALOG_DEFAULT_OPTIONS.width.toString();
        const defaultHeight = DIALOG_DEFAULT_OPTIONS.height.toString();
        const computedWidth = options?.width?.toString() ?? defaultWidth;
        const computedHeight = options?.height?.toString() ?? defaultHeight;
        const dialogRef = {
            dialogId: dialogId,
            dialogElement: dialogElement,
            portalProjectionElement: portalProjection,
            wrapperElement: wrapperElement,
            stackLevel: stackLevel,
            computedWidth: computedWidth,
            computedHeight: computedHeight,
            options: options
        };
        this._dialogMap.set(dialogId, dialogRef);
        // Add to stack for tracking order
        this._dialogStack.push(dialogId);
        return dialogRef;
    }
    /**
     * Extends the dialog 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 PortalElement containing the dialog.
     */
    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=DialogService.js.map