// #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 { HTMLElementEventEmitter } from '@breadstone/mosaik-elements';
import { Emit } from '../../../../events/Decorators/EmitDecorator';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Disableable } from '../../../Behaviors/Disableable';
import { Focusable } from '../../../Behaviors/Focusable';
import { Labelable } from '../../../Behaviors/Labelable';
import { Rippleable } from '../../../Behaviors/Rippleable';
import { Slottable } from '../../../Behaviors/Slottable';
import { Themeable } from '../../../Behaviors/Themeable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Variantable } from '../../../Behaviors/Variantable';
import { addInheritanceConsumerController } from '../../../Controllers/InheritanceConsumerController';
import { KeyboardController } from '../../../Controllers/KeyboardController';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Property } from '../../../Decorators/PropertyDecorator';
import { Key } from '../../../Types/Key';
import { SubMenuMode } from '../../../Types/SubMenuMode';
import { TextOverflow } from '../../../Types/TextOverflow';
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 { FloatingElement } from '../../Primitives/Floating/FloatingElement';
import { FocusRingElement } from '../../Primitives/FocusRing/FocusRingElement';
import { PortalElement } from '../../Primitives/Portal/PortalElement';
import { ProjectionController } from '../../Primitives/Portal/ProjectionController';
import { TextElement } from '../../Primitives/Text/TextElement';
import { MENU_INHERITANCE_CONTEXT } from './MenuInheritanceContext';
import { menuItemElementTemplate } from './MenuItemElementTemplate';
import { menuItemElementCosmopolitanStyle } from './Themes/MenuItemElement.Cosmopolitan';
import { menuItemElementJoyStyle } from './Themes/MenuItemElement.Joy';
import { menuItemElementMemphisStyle } from './Themes/MenuItemElement.Memphis';
// #endregion
/**
 * Menu Item - An interactive menu option supporting hierarchical submenus and multiple display modes.
 *
 * @description
 * The Menu Item component represents an actionable option within a menu or submenu structure.
 * It supports nested hierarchical menus with both inline and popover submenu modes, icons, labels,
 * sublabels, checkmarks for selection states, and comprehensive keyboard navigation. The component
 * can expand to reveal child menu items, display active/checked states, and includes interactive
 * features like ripple effects and focus indicators. It supports both mouse hover and touch
 * interactions for submenu expansion.
 *
 * @name Menu Item
 * @element mosaik-menu-item
 * @category Selectors
 *
 * @slot  - The default slot.
 * @slot end - Content displayed at the end (after label)
 * @slot icon - The icon displayed for this menu item
 * @slot label - The primary label text
 * @slot start - Content displayed at the start (before icon)
 * @slot subLabel - Secondary descriptive text below the label
 * @slot - The default slot for child menu items (creates a submenu)
 *
 * @csspart caret - The expand/collapse indicator icon for items with children
 * @csspart checkmark - The selection checkmark indicator when isChecked is true
 * @csspart expandable - The expandable container for inline mode
 * @csspart focusRing - The focus indicator ring for keyboard navigation
 * @csspart popover - The floating popover container for submenu
 * @csspart portal - The portal element for popover projection
 * @csspart projection - The projection target for popover mode
 * @csspart ripple - The ripple effect container for interaction feedback
 * @csspart root - The root menu item container
 * @csspart submenu - The submenu content wrapper
 * @csspart submenu-container - Hidden container for submenu content (used in popover mode)
 * @csspart text - The label and sublabel text container
 *
 * @cssprop {String} --menu-item-background-color - The background fill color
 * @cssprop {String} --menu-item-border-color - The border color
 * @cssprop {String} --menu-item-border-radius - The corner rounding radius
 * @cssprop {String} --menu-item-border-style - The border line style
 * @cssprop {String} --menu-item-border-width - The border thickness
 * @cssprop {String} --menu-item-focus-ring-active-width - The item focus ring active width CSS custom property.
 * @cssprop {String} --menu-item-focus-ring-color - The item focus ring color CSS custom property.
 * @cssprop {String} --menu-item-focus-ring-inward-offset - The item focus ring inward offset CSS custom property.
 * @cssprop {String} --menu-item-focus-ring-outward-offset - The item focus ring outward offset CSS custom property.
 * @cssprop {String} --menu-item-font-family - The font family for menu item text
 * @cssprop {String} --menu-item-font-letter-spacing - The letter spacing for menu item text
 * @cssprop {String} --menu-item-font-line-height - The line height for menu item text
 * @cssprop {String} --menu-item-font-size - The font size for menu item text
 * @cssprop {String} --menu-item-font-text-decoration - The text decoration style
 * @cssprop {String} --menu-item-font-text-transform - The text transformation style
 * @cssprop {String} --menu-item-font-weight - The font weight for menu item text
 * @cssprop {String} --menu-item-foreground-color - The text and icon color
 * @cssprop {String} --menu-item-gap - The spacing between icon and label elements
 * @cssprop {String} --menu-item-height - The minimum height of the menu item
 * @cssprop {String} --menu-item-indent-color - The color of the indent indicator
 * @cssprop {String} --menu-item-indent-offset - The offset for the indent indicator
 * @cssprop {String} --menu-item-indent-size - The width of the indent indicator
 * @cssprop {String} --menu-item-padding-bottom - The bottom padding inside the menu item
 * @cssprop {String} --menu-item-padding-left - The left padding inside the menu item
 * @cssprop {String} --menu-item-padding-right - The right padding inside the menu item
 * @cssprop {String} --menu-item-padding-top - The top padding inside the menu item
 * @cssprop {Color} --menu-item-ripple-color - The item ripple color CSS custom property.
 * @cssprop {String} --menu-item-ripple-duration - The item ripple duration CSS custom property.
 * @cssprop {String} --menu-item-shadow - The drop shadow or elevation effect
 * @cssprop {String} --menu-item-shadow-blur - The item shadow blur CSS custom property.
 * @cssprop {String} --menu-item-shadow-color - The item shadow color CSS custom property.
 * @cssprop {String} --menu-item-shadow-offset-x - The item shadow offset x CSS custom property.
 * @cssprop {String} --menu-item-shadow-offset-y - The item shadow offset y CSS custom property.
 * @cssprop {String} --menu-item-shadow-spread - The item shadow spread CSS custom property.
 * @cssprop {String} --menu-item-transition-duration - The duration of hover/focus transitions
 * @cssprop {String} --menu-item-transition-mode - The timing function for transitions
 * @cssprop {String} --menu-item-transition-property - The CSS properties to transition
 * @cssprop {String} --menu-item-translate - The item translate CSS custom property.
 *
 * @fires activated {ActivatedEvent} - Fired when the menu item is clicked or activated
 * @fires connected {ConnectedEvent} - Fired when connected to the DOM
 * @fires changed {PropertyChangedEvent} - Fired when properties change
 *
 * @dependency mosaik-button - The Button element.
 * @dependency mosaik-checkmark - The Checkmark element.
 * @dependency mosaik-expandable - The Expandable element.
 * @dependency mosaik-floating - The Floating element.
 * @dependency mosaik-focus-ring - The Focus Ring element.
 * @dependency mosaik-icon - The Icon element.
 * @dependency mosaik-portal - The Portal element.
 * @dependency mosaik-ripple - The Ripple element.
 * @dependency mosaik-stack - The Stack element.
 * @dependency mosaik-text - The Text element.
 *
 * @example
 * Basic menu item (label and icon set via JavaScript):
 * ```html
 * <mosaik-menu-item id="saveItem">Save</mosaik-menu-item>
 * ```
 *
 * @example
 * Menu item with submenu (inline mode):
 * ```html
 * <mosaik-menu-item menu-mode="inline">
 *   File
 *   <mosaik-menu-item slot="submenu">New</mosaik-menu-item>
 *   <mosaik-menu-item slot="submenu">Open</mosaik-menu-item>
 *   <mosaik-menu-item slot="submenu">Save</mosaik-menu-item>
 * </mosaik-menu-item>
 * ```
 *
 * @example
 * Menu item with popover submenu:
 * ```html
 * <mosaik-menu-item menu-mode="popover">
 *   Edit
 *   <mosaik-menu-item slot="submenu">Cut</mosaik-menu-item>
 *   <mosaik-menu-item slot="submenu">Copy</mosaik-menu-item>
 *   <mosaik-menu-item slot="submenu">Paste</mosaik-menu-item>
 * </mosaik-menu-item>
 * ```
 *
 * @example
 * Checkable menu item:
 * ```html
 * <mosaik-menu-item is-checked>Show Toolbar</mosaik-menu-item>
 * ```
 *
 * @public
 */
let MenuItemElement = class MenuItemElement extends Themeable(Rippleable(Disableable(Valueable(Variantable(Appearanceable(Focusable(Slottable(Labelable(CustomElement))))))))) {
    static { MenuItemElement_1 = this; }
    // #region Fields
    /**
     * Delay in ms before a submenu opens on hover (Windows default is ~400ms).
     *
     * @private
     * @static
     * @readonly
     */
    static HOVER_OPEN_DELAY_MS = 250;
    /**
     * Delay in ms before a submenu closes after hover-out.
     *
     * @private
     * @static
     * @readonly
     */
    static HOVER_CLOSE_DELAY_MS = 100;
    _inheritance = addInheritanceConsumerController(this, {
        context: MENU_INHERITANCE_CONTEXT
    });
    _keyboardController;
    _projectionController;
    _submenuProjectionController;
    _activated;
    _subLabel;
    _icon;
    _isActive;
    _isChecked;
    _hasChildren;
    _isExpanded;
    _textOverflow;
    _menuMode;
    _hoverCloseDelayId;
    _hoverOpenDelayId;
    // #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._hoverOpenDelayId = null;
        this._activated = new HTMLElementEventEmitter(this, 'activated');
        this._keyboardController = new KeyboardController(this);
        this._projectionController = null;
        this._submenuProjectionController = null;
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `is` property.
     * The `is` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-menu-item';
    }
    /**
     * @inheritdoc
     * When used inside a Menu, inherits the menu's disabled state unless explicitly set.
     *
     * @public
     * @override
     */
    get disabled() {
        return this._inheritance.get('disabled', super.disabled);
    }
    set disabled(value) {
        this._inheritance.markExplicit('disabled');
        super.disabled = value;
    }
    /**
     * 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 `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('click', (event) => this.handleClick(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();
        this.clearHoverOpenDelay();
    }
    /**
     * @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 delay to allow the user to re-enter the submenu area
        this.clearHoverCloseDelay();
        this._hoverCloseDelayId = window.setTimeout(() => {
            this._hoverCloseDelayId = null;
            this.collapse();
        }, MenuItemElement_1.HOVER_CLOSE_DELAY_MS);
    }
    /**
     * Emits the `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;
        }
    }
    /**
     * Clears the hover open delay timer.
     *
     * @private
     */
    clearHoverOpenDelay() {
        if (this._hoverOpenDelayId !== null) {
            window.clearTimeout(this._hoverOpenDelayId);
            this._hoverOpenDelayId = null;
        }
    }
    /**
     * Cancels all pending hover timers (open and close).
     * Used by siblings to clean up when a different item is hovered.
     *
     * @private
     */
    cancelPendingTimers() {
        this.clearHoverOpenDelay();
        this.clearHoverCloseDelay();
    }
    /**
     * Collapses sibling menu items that have open popover submenus.
     * Ensures only one submenu is visible at a time, matching native Windows menu behavior.
     *
     * @private
     */
    collapseSiblings() {
        const parent = this.parentElement;
        if (!parent) {
            return;
        }
        const siblings = parent.querySelectorAll(':scope > mosaik-menu-item');
        for (const sibling of Array.from(siblings)) {
            if (sibling !== this && sibling.isExpanded && sibling.menuMode === SubMenuMode.Popover) {
                sibling.cancelPendingTimers();
                sibling.collapse();
            }
        }
    }
    /**
     * Handles pointer enter for hover-based expansion.
     * Opens submenus on hover after a delay, matching Windows native menu behavior.
     * Also collapses any sibling submenus to ensure only one is visible at a time.
     * Only expands on mouse hover (not touch), as touch devices use tap to toggle.
     *
     * @private
     */
    handlePointerEnter(event) {
        // All hover-based submenu behavior is exclusive to popover mode.
        // Inline mode uses click-to-toggle and does not react to hover.
        if (this.menuMode !== SubMenuMode.Popover) {
            return;
        }
        // Only hover behavior for mouse pointer, not touch
        if (event.pointerType === 'touch') {
            return;
        }
        // Collapse sibling submenus when hovering over any item.
        // This ensures only one submenu is visible at a time (Windows behavior).
        this.collapseSiblings();
        if (!this.hasChildren || this.disabled) {
            return;
        }
        // Cancel any pending close timer for this item
        this.clearHoverCloseDelay();
        // Open submenu after a short delay (like Windows MenuShowDelay)
        this.clearHoverOpenDelay();
        this._hoverOpenDelayId = window.setTimeout(() => {
            this._hoverOpenDelayId = null;
            this.expand();
        }, MenuItemElement_1.HOVER_OPEN_DELAY_MS);
    }
    /**
     * Handles pointer leave for hover-based collapse.
     * Uses relatedTarget to determine if the pointer moved into a child element (floating submenu).
     * Cancels any pending hover-open timer and uses a forgiving close delay.
     * 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;
        }
        // Cancel pending open if the user leaves before the delay completes
        this.clearHoverOpenDelay();
        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 forgiving delay to allow the user to move the pointer into the floating submenu.
        // This helps with diagonal mouse movements and small gaps between elements.
        this.clearHoverCloseDelay();
        this._hoverCloseDelayId = window.setTimeout(() => {
            this._hoverCloseDelayId = null;
            this.collapse();
        }, MenuItemElement_1.HOVER_CLOSE_DELAY_MS);
    }
    /**
     * 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 mouse click on the menu item.
     * Only intercepts clicks that originate from this item directly (not from child menu items
     * bubbling up). For popover parent items: prevents propagation so the surrounding popup/dropdown
     * does not close, matching native Windows menu behavior. For leaf items: emits activated.
     *
     * @private
     */
    handleClick(event) {
        // Only intercept clicks in popover mode.
        // Inline mode relies on existing expandable/toggle behavior - do not interfere.
        if (this.menuMode !== SubMenuMode.Popover) {
            return;
        }
        if (this.disabled) {
            return;
        }
        // Ignore clicks that bubble up from nested child menu items.
        // Only react to clicks that originated from this menu item's own content.
        const composedPath = event.composedPath();
        for (const node of composedPath) {
            if (node === this) {
                break;
            }
            if (node instanceof HTMLElement && node.tagName === 'MOSAIK-MENU-ITEM' && node !== this) {
                // Click originated from a child menu item - let it propagate untouched
                return;
            }
        }
        if (this.hasChildren) {
            // Prevent the click from reaching parent popup/dropdown close handlers.
            // In native Windows menus, clicking a parent item never closes the menu.
            event.stopPropagation();
            this.expand();
            return;
        }
        // Leaf item in popover submenu: emit activated event.
        // Let the click propagate naturally so parent menus can close.
        this.onActivated({});
    }
    /**
     * 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