// #region Imports
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var MenuItemElement_1;
import { Emit } from '../../../../Events/Decorators/EmitDecorator';
import { HTMLElementEventEmitter } from '@breadstone/mosaik-elements';
import { Disableable } from '../../../Behaviors/Disableable';
import { Focusable } from '../../../Behaviors/Focusable';
import { Labelable } from '../../../Behaviors/Labelable';
import { Slottable } from '../../../Behaviors/Slottable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Variantable } from '../../../Behaviors/Variantable';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Property } from '../../../Decorators/PropertyDecorator';
import { CustomElement } from '../../Abstracts/CustomElement';
import { ButtonElement } from '../../Buttons/Button/ButtonElement';
import { RippleElement } from '../../Effects/Ripple/RippleElement';
import { StackElement } from '../../Layouts/Stack/StackElement';
import { IconElement } from '../../Media/Icon/IconElement';
import { CheckmarkElement } from '../../Primitives/Checkmark/CheckmarkElement';
import { ExpandableElement } from '../../Primitives/Expandable/ExpandableElement';
import { FocusRingElement } from '../../Primitives/FocusRing/FocusRingElement';
import { TextElement } from '../../Primitives/Text/TextElement';
import { FloatingElement } from '../../Primitives/Floating/FloatingElement';
import { PortalElement } from '../../Primitives/Portal/PortalElement';
import { ProjectionController } from '../../Primitives/Portal/ProjectionController';
import { menuItemElementTemplate } from './MenuItemElementTemplate';
import { menuItemElementJoyStyle } from './Themes/MenuItemElement.Joy';
import { menuItemElementMemphisStyle } from './Themes/MenuItemElement.Memphis';
import { menuItemElementCosmopolitanStyle } from './Themes/MenuItemElement.Cosmopolitan';
import { Themeable } from '../../../Behaviors/Themeable';
import { TextOverflow } from '../../../Types/TextOverflow';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Key } from '../../../Types/Key';
import { SubMenuMode } from '../../../Types/SubMenuMode';
import { KeyboardController } from '../../../Controllers/KeyboardController';
// #endregion
/**
 * Menu Item - An individual option or choice within a menu.
 *
 * @element mosaik-menu-item
 *
 * @slot - The default slot for child menu items.
 * @slot start - The start slot.
 * @slot icon - The icon slot.
 * @slot label - The label slot.
 * @slot subLabel - The subLabel slot.
 * @slot end - The end slot.
 *
 * @fires activated - Called when the element is activated.
 *
 * @public
 */
let MenuItemElement = MenuItemElement_1 = class MenuItemElement extends Themeable(Disableable(Valueable(Variantable(Appearanceable(Focusable(Slottable(Labelable(CustomElement)))))))) {
    // #region Fields
    _keyboardController;
    _projectionController;
    _submenuProjectionController;
    _activated;
    _subLabel;
    _icon;
    _isActive;
    _isChecked;
    _hasChildren;
    _isExpanded;
    _textOverflow;
    _menuMode;
    _hoverCloseDelayId;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._subLabel = '';
        this._icon = '';
        this._isActive = false;
        this._isChecked = false;
        this._hasChildren = false;
        this._isExpanded = false;
        this._textOverflow = TextOverflow.Truncate;
        this._menuMode = SubMenuMode.Inline;
        this._hoverCloseDelayId = null;
        this._activated = new HTMLElementEventEmitter(this, 'activated');
        this._keyboardController = new KeyboardController(this);
        this._projectionController = null;
        this._submenuProjectionController = null;
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `{@link is}` property.
     * The `{@link is}` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-menu-item';
    }
    /**
     * Gets or sets the `subLabel` property.
     *
     * @public
     * @attr
     */
    get subLabel() {
        return this._subLabel;
    }
    set subLabel(value) {
        if (this._subLabel !== value) {
            this._subLabel = value;
            this.requestUpdate('subLabel');
        }
    }
    /**
     * Gets or sets the `icon` property.
     *
     * @public
     */
    get icon() {
        return this._icon;
    }
    set icon(value) {
        if (this._icon !== value) {
            this._icon = value;
            this.requestUpdate('icon');
        }
    }
    /**
     * Gets or sets the `isActive` property.
     *
     * @public
     * @attr
     */
    get isActive() {
        return this._isActive;
    }
    set isActive(value) {
        if (this._isActive !== value) {
            this._isActive = value;
            this.requestUpdate('isActive');
        }
    }
    /**
     * Gets or sets the `isChecked` property.
     *
     * @public
     * @attr
     */
    get isChecked() {
        return this._isChecked;
    }
    set isChecked(value) {
        if (this._isChecked !== value) {
            this._isChecked = value;
            this.requestUpdate('isChecked');
        }
    }
    /**
     * Gets or sets the `isExpanded` property.
     *
     * @public
     * @attr
     */
    get isExpanded() {
        return this._isExpanded;
    }
    set isExpanded(value) {
        if (this._isExpanded !== value) {
            this._isExpanded = value;
            this.requestUpdate('isExpanded');
        }
    }
    /**
     * The `hasChildren` property represents whether the element has children or not.
     *
     * @public
     * @readonly
     * @attr
     */
    get hasChildren() {
        return this._hasChildren;
    }
    set hasChildren(value) {
        if (this._hasChildren !== value) {
            this._hasChildren = value;
            this.requestUpdate('hasChildren');
        }
    }
    /**
     * Gets or sets the `textOverflow` property.
     *
     * @public
     * @attr
     */
    get textOverflow() {
        return this._textOverflow;
    }
    set textOverflow(value) {
        if (this._textOverflow !== value) {
            this._textOverflow = value;
            this.requestUpdate('textOverflow');
        }
    }
    /**
     * Determines how child menus are displayed.
     *
     * @public
     * @attr
     */
    get menuMode() {
        return this._menuMode;
    }
    set menuMode(value) {
        if (this._menuMode !== value) {
            this._menuMode = value;
            // Initialize projection controllers only when switching to Popover mode
            if (value === SubMenuMode.Popover && !this._projectionController) {
                // Detect children BEFORE projection removes them from slots
                this.hasChildren = this.hasSlotContent('submenu') || this.hasSlotContent('');
                this._projectionController = new ProjectionController(this, {
                    slotName: '',
                    targetSelector: '[part="projection"]',
                    projecting: (element) => {
                        element.setAttribute(`${MenuItemElement_1.is}-projection`, '');
                    }
                });
                this._submenuProjectionController = new ProjectionController(this, {
                    slotName: 'submenu',
                    targetSelector: '[part="projection"]',
                    projecting: (element) => {
                        element.setAttribute(`${MenuItemElement_1.is}-projection`, '');
                    }
                });
                // Trigger a re-render first, then initialize the controllers.
                // This ensures the template with Portal is rendered before we try to project.
                this.requestUpdate('menuMode');
                // If the element has already been updated (lazy controller creation),
                // we need to manually trigger the controller's first update lifecycle.
                // Wait for the next update cycle where the Portal will be rendered.
                if (this.hasUpdated) {
                    void this.updateComplete.then(() => {
                        // Trigger hostFirstUpdated manually for the lazy-created controllers
                        // by calling hostUpdated which will then call hostFirstUpdated
                        this._projectionController?.hostUpdated();
                        this._submenuProjectionController?.hostUpdated();
                    });
                }
            }
            else {
                this.requestUpdate('menuMode');
            }
        }
    }
    /**
     * Called when the element is activated.
     * Provides reference to `{@link IEventDetail}` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get activated() {
        return this._activated;
    }
    // #endregion
    // #region Methods
    /**
     * Expands the menu item.
     *
     * @public
     */
    expand() {
        if (this.disabled) {
            return;
        }
        if (!this.hasChildren) {
            return;
        }
        this.isExpanded = true;
    }
    /**
     * Collapses the menu item.
     *
     * @public
     */
    collapse() {
        if (this.disabled) {
            return;
        }
        if (!this.hasChildren) {
            return;
        }
        this.isExpanded = false;
    }
    /**
     * Toggles the expanded state of the menu item.
     *
     * @public
     */
    toggle() {
        if (this.disabled) {
            return;
        }
        if (!this.hasChildren) {
            return;
        }
        this.isExpanded = !this.isExpanded;
    }
    /**
     * @public
     * @override
     */
    connectedCallback() {
        super.connectedCallback();
        // Use pointer events for unified mouse/touch handling
        this.on('pointerenter', (event) => this.handlePointerEnter(event));
        this.on('pointerleave', (event) => this.handlePointerLeave(event));
        this.on('pointerdown', (event) => this.handlePointerDown(event));
        this.on('focusout', (event) => this.handleFocusOut(event));
        this._keyboardController
            .add([Key.RightArrow, Key.Enter, Key.Space], () => this.expand(), () => this.menuMode === SubMenuMode.Popover && this.hasChildren && !this.disabled, { preventDefault: true })
            .add([Key.LeftArrow, Key.Escape], () => this.collapse(), () => this.menuMode === SubMenuMode.Popover, { preventDefault: true });
    }
    /**
     * @public
     * @override
     */
    disconnectedCallback() {
        super.disconnectedCallback();
        this.clearHoverCloseDelay();
    }
    /**
     * @public
     * @overload
     */
    onSlotChanges(slotName) {
        // this is the slot to react on child menu changes
        if (slotName === '' || slotName === 'submenu') {
            // In popover mode, projection controller moves elements out of slots
            // So we check both slot content AND projected elements
            if (this._menuMode === SubMenuMode.Popover && this._projectionController) {
                const hasProjectedContent = this._projectionController.elements.length > 0 ||
                    (this._submenuProjectionController?.elements.length ?? 0) > 0;
                this.hasChildren = hasProjectedContent || this.hasSlotContent('submenu') || this.hasSlotContent('');
            }
            else {
                this.hasChildren = this.hasSlotContent('submenu') || this.hasSlotContent('');
            }
            if (!this.hasChildren && this.isExpanded) {
                this.isExpanded = false;
            }
        }
    }
    /**
     * Handles pointer leave from the floating submenu element.
     * This is called when the pointer leaves the Portal-projected floating element.
     * Only collapses on mouse leave (not touch).
     *
     * @private
     * @template
     */
    handleFloatingPointerLeave(event) {
        if (this.menuMode !== SubMenuMode.Popover) {
            return;
        }
        // Only hover-collapse for mouse pointer, not touch
        if (event.pointerType === 'touch') {
            return;
        }
        const relatedTarget = event.relatedTarget;
        // Check if the pointer moved back into the anchor (this menu item)
        // or into another element that belongs to this menu item
        if (relatedTarget && this.containsRelatedTarget(relatedTarget)) {
            return;
        }
        // Collapse with a small delay
        this.clearHoverCloseDelay();
        this._hoverCloseDelayId = window.setTimeout(() => {
            this._hoverCloseDelayId = null;
            this.collapse();
        }, 100);
    }
    /**
     * Emits the {@link activated} event.
     *
     * @protected
     */
    onActivated(args) {
        this._activated.emit(args);
    }
    /**
     * Clears the hover close delay timer.
     *
     * @private
     */
    clearHoverCloseDelay() {
        if (this._hoverCloseDelayId !== null) {
            window.clearTimeout(this._hoverCloseDelayId);
            this._hoverCloseDelayId = null;
        }
    }
    /**
     * Handles pointer enter for hover-based expansion.
     * Only expands on mouse hover (not touch), as touch devices use tap to toggle.
     *
     * @private
     */
    handlePointerEnter(event) {
        if (!(this.menuMode === SubMenuMode.Popover && this.hasChildren && !this.disabled)) {
            return;
        }
        // Only hover-expand for mouse pointer, not touch
        if (event.pointerType === 'touch') {
            return;
        }
        this.clearHoverCloseDelay();
        this.expand();
    }
    /**
     * Handles pointer leave for hover-based collapse.
     * Uses relatedTarget to determine if the pointer moved into a child element (floating submenu).
     * Only collapses on mouse leave (not touch), as touch devices use tap to toggle.
     *
     * @private
     */
    handlePointerLeave(event) {
        if (this.menuMode !== SubMenuMode.Popover) {
            return;
        }
        // Only hover-collapse for mouse pointer, not touch
        if (event.pointerType === 'touch') {
            return;
        }
        const relatedTarget = event.relatedTarget;
        // Check if the pointer moved into a child element (including the floating submenu)
        if (relatedTarget && this.containsRelatedTarget(relatedTarget)) {
            return;
        }
        // Use a small delay to allow the user to move the pointer into the floating submenu
        // This helps with cases where there is a small gap between the anchor and the floating element
        this.clearHoverCloseDelay();
        this._hoverCloseDelayId = window.setTimeout(() => {
            this._hoverCloseDelayId = null;
            this.collapse();
        }, 100);
    }
    /**
     * Handles pointer down for touch-based toggling.
     * On touch devices, toggle the expanded state on tap.
     *
     * @private
     */
    handlePointerDown(event) {
        if (!(this.menuMode === SubMenuMode.Popover && this.hasChildren && !this.disabled)) {
            return;
        }
        // Only toggle for touch pointer
        if (event.pointerType !== 'touch') {
            return;
        }
        // Prevent default to avoid triggering click events that might interfere
        event.preventDefault();
        this.toggle();
    }
    /**
     * Handles focus transitions to close the popover when focus leaves the item.
     *
     * @private
     */
    handleFocusOut(event) {
        if (this.menuMode !== SubMenuMode.Popover) {
            return;
        }
        const nextTarget = event.relatedTarget;
        if (!nextTarget || !this.containsRelatedTarget(nextTarget)) {
            this.collapse();
        }
    }
    /**
     * Checks whether the given target is contained within this element or its shadow DOM children.
     * This includes the floating submenu element projected via Portal to document.body.
     * Also checks nested submenus (3+ levels deep) by traversing child menu items.
     *
     * @private
     */
    containsRelatedTarget(target) {
        // Check if the target is contained within the light DOM
        if (this.contains(target)) {
            return true;
        }
        // Check if the target is contained within the shadow DOM
        if (this.shadowRoot?.contains(target)) {
            return true;
        }
        // Check if the target is contained within the Portal's projection element
        // (Portal projects content to document.body, so we need to check there)
        const portal = this.shadowRoot?.querySelector('mosaik-portal');
        if (portal?.projection?.contains(target)) {
            return true;
        }
        // Check if the target is within a nested child menu item's Portal projection
        // This handles 3+ level deep menus where child items have their own Portals
        // We must search in the Portal's projection, not in the light DOM (this.querySelectorAll),
        // because child menu items are projected there
        if (portal?.projection) {
            const childMenuItems = portal.projection.querySelectorAll('mosaik-menu-item');
            // eslint-disable-next-line @typescript-eslint/prefer-for-of
            for (let i = 0; i < childMenuItems.length; i++) {
                const childItem = childMenuItems[i];
                if (childItem.containsRelatedTarget(target)) {
                    return true;
                }
            }
        }
        // Traverse up the composed path to check if the target is in a slotted element
        // or within a floating element that belongs to this menu item
        let current = target;
        // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
        while (current) {
            if (current === this) {
                return true;
            }
            // Check for slot assignments (light DOM projected into shadow DOM)
            if (current instanceof HTMLElement) {
                const assignedSlot = current.assignedSlot;
                if (assignedSlot && this.shadowRoot?.contains(assignedSlot)) {
                    return true;
                }
            }
            // Move up the tree
            // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
            current = current.parentNode ?? current.host ?? null;
        }
        return false;
    }
};
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], MenuItemElement.prototype, "subLabel", null);
__decorate([
    Property({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], MenuItemElement.prototype, "icon", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], MenuItemElement.prototype, "isActive", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], MenuItemElement.prototype, "isChecked", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], MenuItemElement.prototype, "isExpanded", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], MenuItemElement.prototype, "hasChildren", null);
__decorate([
    Attribute({
        type: TextOverflow
    }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], MenuItemElement.prototype, "textOverflow", null);
__decorate([
    Attribute({
        type: String
    }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], MenuItemElement.prototype, "menuMode", null);
__decorate([
    Emit({ eventName: 'activated' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], MenuItemElement.prototype, "activated", null);
MenuItemElement = MenuItemElement_1 = __decorate([
    Component({
        selector: 'mosaik-menu-item',
        template: menuItemElementTemplate,
        themes: {
            joy: menuItemElementJoyStyle,
            memphis: menuItemElementMemphisStyle,
            cosmopolitan: menuItemElementCosmopolitanStyle
        },
        host: {
            tabIndex: '0'
        },
        imports: [
            IconElement,
            ButtonElement,
            TextElement,
            RippleElement,
            FocusRingElement,
            StackElement,
            CheckmarkElement,
            ExpandableElement,
            FloatingElement,
            PortalElement
        ]
    }),
    __metadata("design:paramtypes", [])
], MenuItemElement);
export { MenuItemElement };
//# sourceMappingURL=MenuItemElement.js.map