import { __esDecorate, __runInitializers } from "tslib";
import { html } from 'lit';
import { property, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import UiListItem from '../../list/internals/ListItem.js';
import { findElementInShadowRoots } from '../../../lib/Dom.js';
import { nanoid } from 'nanoid';
import '@material/web/focus/md-focus-ring.js';
import '../../ripple/ui-ripple.js';
let UiMenuItem = (() => {
    let _classSuper = UiListItem;
    let _submenu_decorators;
    let _submenu_initializers = [];
    let _submenu_extraInitializers = [];
    let _subMenuOpen_decorators;
    let _subMenuOpen_initializers = [];
    let _subMenuOpen_extraInitializers = [];
    return class UiMenuItem extends _classSuper {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _submenu_decorators = [property({ type: String })];
            _subMenuOpen_decorators = [state()];
            __esDecorate(this, null, _submenu_decorators, { kind: "accessor", name: "submenu", static: false, private: false, access: { has: obj => "submenu" in obj, get: obj => obj.submenu, set: (obj, value) => { obj.submenu = value; } }, metadata: _metadata }, _submenu_initializers, _submenu_extraInitializers);
            __esDecorate(this, null, _subMenuOpen_decorators, { kind: "accessor", name: "subMenuOpen", static: false, private: false, access: { has: obj => "subMenuOpen" in obj, get: obj => obj.subMenuOpen, set: (obj, value) => { obj.subMenuOpen = value; } }, metadata: _metadata }, _subMenuOpen_initializers, _subMenuOpen_extraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #submenu_accessor_storage = __runInitializers(this, _submenu_initializers, void 0);
        /**
         * The ID of the associated submenu
         * @attribute
         */
        get submenu() { return this.#submenu_accessor_storage; }
        set submenu(value) { this.#submenu_accessor_storage = value; }
        /**
         * Whether the menu item has a sub-menu
         */
        get hasSubMenu() {
            return !!this.submenu && !!this.subMenuElement;
        }
        /**
         * Reference to the sub-menu element
         */
        get subMenuElement() {
            if (!this.submenu)
                return null;
            return findElementInShadowRoots(this.submenu, this);
        }
        #subMenuOpen_accessor_storage = (__runInitializers(this, _submenu_extraInitializers), __runInitializers(this, _subMenuOpen_initializers, false));
        /**
         * Whether the sub-menu is open
         */
        get subMenuOpen() { return this.#subMenuOpen_accessor_storage; }
        set subMenuOpen(value) { this.#subMenuOpen_accessor_storage = value; }
        constructor() {
            super();
            __runInitializers(this, _subMenuOpen_extraInitializers);
            this.addEventListener('mouseenter', this.handleMouseEnter.bind(this));
            this.addEventListener('mouseleave', this.handleMouseLeave.bind(this));
            this.addEventListener('click', this.handleMenuItemClick.bind(this));
        }
        connectedCallback() {
            super.connectedCallback();
            this.setAttribute('role', 'menuitem');
            // Generate ID if not present (needed for submenu anchoring)
            if (!this.id) {
                this.id = nanoid(6);
            }
        }
        updated(changedProperties) {
            super.updated(changedProperties);
            if (changedProperties.has('submenu')) {
                this.updateAccessibility();
                this.setupSubmenuConnection();
            }
        }
        /**
         * Sets up the connection between this menu item and its submenu
         */
        setupSubmenuConnection() {
            if (this.subMenuElement) {
                this.subMenuElement.anchor = this.id;
                // Find parent menu and set it on the submenu
                const parentMenu = this.closest('ui-menu, ui-sub-menu');
                if (parentMenu) {
                    this.subMenuElement.setParentMenu(parentMenu);
                }
            }
        }
        /**
         * Updates accessibility attributes
         */
        updateAccessibility() {
            if (this.hasSubMenu) {
                this.setAttribute('aria-haspopup', 'true');
                this.setAttribute('aria-expanded', String(this.subMenuOpen));
            }
            else {
                this.removeAttribute('aria-haspopup');
                this.removeAttribute('aria-expanded');
            }
        }
        /**
         * Handles mouse enter events
         */
        handleMouseEnter() {
            if (this.hasSubMenu && !this.subMenuOpen) {
                this.openSubMenu();
            }
        }
        /**
         * Handles mouse leave events
         */
        handleMouseLeave() {
            // Close sub-menu after a delay to allow moving to sub-menu
            setTimeout(() => {
                if (this.subMenuOpen && !this.matches(':hover') && !this.subMenuElement?.matches(':hover')) {
                    this.closeSubMenu();
                }
            }, 100);
        }
        /**
         * Handles click events
         */
        handleClick(e) {
            if (this.hasSubMenu) {
                e.preventDefault();
                e.stopPropagation();
                this.toggleSubMenu();
            }
            else {
                super.handleClick(e);
            }
        }
        /**
         * Handles menu item click events
         */
        handleMenuItemClick(e) {
            this.handleClick(e);
        }
        /**
         * Opens the sub-menu
         */
        openSubMenu() {
            if (!this.hasSubMenu || this.subMenuOpen)
                return;
            this.subMenuOpen = true;
            this.updateAccessibility();
            this.subMenuElement?.show();
            this.dispatchEvent(new CustomEvent('submenu-open', {
                detail: { subMenu: this.subMenuElement },
                bubbles: true,
                composed: true,
            }));
        }
        /**
         * Closes the sub-menu
         */
        closeSubMenu() {
            if (!this.subMenuOpen)
                return;
            this.subMenuOpen = false;
            this.updateAccessibility();
            this.subMenuElement?.hide();
        }
        /**
         * Toggles the sub-menu
         */
        toggleSubMenu() {
            if (this.subMenuOpen) {
                this.closeSubMenu();
            }
            else {
                this.openSubMenu();
            }
        }
        /**
         * Handles sub-menu item selection
         */
        handleSubMenuSelect(e) {
            // Bubble up the selection event
            this.dispatchEvent(new CustomEvent('select', {
                detail: e.detail,
                bubbles: true,
                composed: true,
            }));
        }
        render() {
            const classes = classMap({
                'surface': true,
                'menu-item': true,
                'menu-item-with-submenu': this.hasSubMenu,
                'submenu-open': this.subMenuOpen,
            });
            return html `
      ${this.renderFocusRing()} ${this.renderRipple()}
      <div class=${classes} role="menuitem">${this.renderStart()} ${this.renderBody()} ${this.renderEnd()}</div>
    `;
        }
        renderEnd() {
            return html `<div class="end">
      <slot name="end" @slotchange=${this.handleSlotChange}></slot>
      <span class="trailing-supporting-text"><slot name="end-text"></slot></span>
      ${this.hasSubMenu ? html `<ui-icon class="menu-item-arrow">arrow_right</ui-icon>` : ''}
    </div>`;
        }
    };
})();
/**
 * Material Design 3 Menu Item component.
 *
 * @slot - The menu item content (label, icon, etc.)
 * @fires select - Dispatched when the menu item is selected
 * @fires submenu-open - Dispatched when a sub-menu is opened
 */
export default UiMenuItem;
//# sourceMappingURL=MenuItem.js.map