// #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';
import { BOTTOM_SHEET_SERVICE_DEFAULT_CONFIG } from './IBottomSheetServiceConfig';
/**
 * Represents the `BOTTOM_SHEET_DEFAULT_OPTIONS` constant.
 *
 * @private
 */
const BOTTOM_SHEET_DEFAULT_OPTIONS = {
    content: '',
    header: '',
    height: '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.
 *
 * Uses a singleton pattern with static configuration.
 *
 * @example
 * ```typescript
 * // Configure once at app startup
 * BottomSheetService.configure({
 *     closeOnNavigation: true,
 *     behaviors: []
 * });
 *
 * // Use throughout the app
 * const result = await BottomSheetService.instance.open('mySheet', MyBottomSheetWrapper);
 * ```
 *
 * @public
 */
export class BottomSheetService {
    // #region Fields
    static _instance = null;
    static _config = BOTTOM_SHEET_SERVICE_DEFAULT_CONFIG;
    static _isConfigured = false;
    _bottomSheetMap;
    _behaviors;
    _portalElement;
    // #endregion
    // #region Ctor
    /**
     * Constructs a new instance of the `BottomSheetService` class.
     * Use `BottomSheetService.configure()` and `BottomSheetService.instance` instead of direct instantiation.
     *
     * @private
     */
    constructor(config) {
        this._bottomSheetMap = new Map();
        this._behaviors = config.behaviors ?? [];
        if (config.closeOnNavigation !== false) {
            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 Properties
    /**
     * Gets the singleton instance of `BottomSheetService`.
     * If not configured, uses default configuration.
     *
     * @public
     * @static
     */
    static get instance() {
        BottomSheetService._instance ??= new BottomSheetService(BottomSheetService._config);
        return BottomSheetService._instance;
    }
    // #endregion
    // #region Methods
    /**
     * Configures the `BottomSheetService` 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 bottom sheet service.
     * @throws Error if already configured.
     *
     * @example
     * ```typescript
     * BottomSheetService.configure({
     *     closeOnNavigation: true,
     *     behaviors: [myCustomBehavior]
     * });
     * ```
     */
    static configure(config) {
        if (BottomSheetService._isConfigured) {
            throw new Error('BottomSheetService has already been configured. Configuration can only be set once.');
        }
        BottomSheetService._config = {
            ...BOTTOM_SHEET_SERVICE_DEFAULT_CONFIG,
            ...config
        };
        BottomSheetService._isConfigured = true;
    }
    /**
     * 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 bottomSheetId - Unique identifier for the bottom sheet instance.
     * @param wrapperClass - Class of the wrapper component containing the bottom sheet.
     * @param options - Properties for portal and bottom sheet.
     * @param data - Optional data passed to the wrapper component.
     * @returns A promise resolving with the bottom sheet result.
     */
    async open(bottomSheetId, wrapperClass, options, data) {
        // Allow behaviors to configure options
        const mergedOptions = { ...options };
        for (const behavior of this._behaviors) {
            behavior.configure(mergedOptions);
        }
        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, mergedOptions);
            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: mergedOptions
            };
            this._bottomSheetMap.set(bottomSheetId, ref);
        }
        Object.assign(ref.bottomSheetElement, {
            ...BOTTOM_SHEET_DEFAULT_OPTIONS,
            ...mergedOptions
        });
        // Notify behaviors about attachment
        for (const behavior of this._behaviors) {
            behavior.attach(ref);
        }
        return new Promise((resolve) => {
            ref.resolve = resolve;
            void ref.bottomSheetElement.open();
            void waitForEvent(ref.bottomSheetElement, 'closed').then(() => {
                // Notify behaviors about detachment
                for (const behavior of this._behaviors) {
                    behavior.detach(ref);
                }
                this._bottomSheetMap.delete(bottomSheetId);
                void 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 bottomSheetId - Unique identifier for the bottom sheet instance.
     * @param result - Optional result returned when closing the bottom sheet.
     * @returns 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(() => {
                    // Notify behaviors about detachment
                    for (const behavior of this._behaviors) {
                        behavior.detach(ref);
                    }
                    void ref.portalProjectionElement.close();
                    ref.portalProjectionElement.remove();
                    if (ref.resolve) {
                        ref.resolve(result);
                    }
                    resolve();
                });
                void ref.bottomSheetElement.close();
            }
            else {
                console.error(`Wrapper with ID "${bottomSheetId}" 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 bottom sheets
        for (const [id] of this._bottomSheetMap) {
            void this.close(id);
        }
        this._bottomSheetMap.clear();
        // Clean up portal
        if (this._portalElement) {
            this._portalElement.remove();
            this._portalElement = undefined;
        }
    }
    /**
     * Extends the bottom sheet 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 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);
                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=BottomSheetService.js.map