/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable require-atomic-updates */
// #region Imports
import { RendererServiceLocator } from '../../../../Dom/Renderer';
import { on, waitForEvent } from '@breadstone/mosaik-elements';
import { EID } from '../../../../Utilities/EId';
import { PortalElement } from '../../Primitives/Portal/PortalElement';
import { BottomSheetElement } from './BottomSheetElement';
/**
 * Represents the `BOTTOM_SHEET_DEFAULT_OPTIONS` constant.
 *
 * @private
 */
const BOTTOM_SHEET_DEFAULT_OPTIONS = {
    content: '',
    header: '',
    heigth: 'auto',
    icon: ''
};
/**
 * Service for managing the display and behavior of bottom sheet elements.
 * Provides methods to open and close bottom sheets within a portal structure.
 *
 * @public
 */
export class BottomSheetService {
    // #region Fields
    _bottomSheetMap;
    _portalElement;
    // #endregion
    // #region Ctor
    /**
     * Constructs a new instance of the `BottomSheetService` class.
     *
     * @public
     */
    constructor() {
        this._bottomSheetMap = new Map();
        on(window, 'popstate', () => {
            if (this._bottomSheetMap.size > 0) {
                for (const [key, value] of this._bottomSheetMap) {
                    if (value.options?.navigateToClose) {
                        void this.close(key);
                    }
                }
            }
        });
    }
    // #endregion
    // #region Methods
    /**
     * Opens a custom wrapper component containing a bottom sheet within a portal.
     *
     * @public
     * @template T - Type of the wrapper component extending HTMLElement.
     * @template TData - Type of data provided to the wrapper component.
     * @template TResult - Expected return type of the resolved bottom sheet result.
     * @param {string} bottomSheetId - Unique identifier for the bottom sheet instance.
     * @param {new (args?: TData) => T} wrapperClass - Class of the wrapper component containing the bottom sheet.
     * @param {IBottomSheetOptions} options - Properties for portal and bottom sheet.
     * @param {TData} [data] - Optional data passed to the wrapper component.
     * @returns {Promise<TResult>} A promise resolving with the bottom sheet result.
     */
    async open(bottomSheetId, wrapperClass, options, data) {
        let ref = this._bottomSheetMap.get(bottomSheetId);
        if (!ref) {
            const wrapperElement = new wrapperClass(data);
            RendererServiceLocator.current.setProperty(wrapperElement, 'id', bottomSheetId);
            const portalProjection = await this.extendToPortal(wrapperElement, options);
            const bottomSheetElement = wrapperElement.shadowRoot?.querySelector(BottomSheetElement.is);
            if (!bottomSheetElement) {
                throw new Error(`Bottom sheet element not found within wrapper for ID "${bottomSheetId}".`);
            }
            ref = {
                bottomSheetId,
                bottomSheetElement,
                portalProjectionElement: portalProjection,
                wrapperElement,
                options
            };
            this._bottomSheetMap.set(bottomSheetId, ref);
        }
        Object.assign(ref.bottomSheetElement, {
            ...BOTTOM_SHEET_DEFAULT_OPTIONS,
            ...options
        });
        return new Promise((resolve) => {
            ref.resolve = resolve;
            ref.bottomSheetElement.open();
            void waitForEvent(ref.bottomSheetElement, 'closed').then(() => {
                this._bottomSheetMap.delete(bottomSheetId);
                ref.portalProjectionElement.close();
                ref.portalProjectionElement.remove();
            });
        });
    }
    /**
     * Closes the bottom sheet in the wrapper component and optionally removes the wrapper from the DOM.
     *
     * @public
     * @template TResult - Type of result returned when the bottom sheet is closed.
     * @param {string} bottomSheetId - Unique identifier for the bottom sheet instance.
     * @param {TResult} [result] - Optional result returned when closing the bottom sheet.
     * @returns {Promise<void>} A promise resolving once the bottom sheet is fully closed.
     */
    async close(bottomSheetId, result) {
        return new Promise((resolve) => {
            const ref = this._bottomSheetMap.get(bottomSheetId);
            if (ref) {
                this._bottomSheetMap.delete(bottomSheetId);
                void waitForEvent(ref.bottomSheetElement, 'closed').then(() => {
                    ref.portalProjectionElement.close();
                    ref.portalProjectionElement.remove();
                    if (ref.resolve) {
                        ref.resolve(result);
                    }
                    resolve();
                });
                ref.bottomSheetElement.close();
            }
            else {
                console.error(`Wrapper with ID "${bottomSheetId}" not found.`);
                resolve();
            }
        });
    }
    /**
     * Extends the bottom sheet 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 bottom sheet.
     */
    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);
                this._portalElement.addEventListener('portalAttached', (e) => {
                    resolve(e.detail.projection);
                });
                RendererServiceLocator.current.appendChild(document.body, this._portalElement);
            }
            RendererServiceLocator.current.appendChild(this._portalElement, element);
        });
    }
}
/**
 * @public
 */
export class BottomSheetServiceLocator {
    static _current = null;
    static get current() {
        if (!BottomSheetServiceLocator.isSet()) {
            throw new Error('\'BottomSheetService\' not set.');
        }
        return BottomSheetServiceLocator._current;
    }
    static isSet() {
        return BottomSheetServiceLocator._current !== null;
    }
    static set(current) {
        BottomSheetServiceLocator._current = current;
    }
}
BottomSheetServiceLocator.set(new BottomSheetService());
//# sourceMappingURL=BottomSheetService.js.map