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;
};
import { LitElement, html, nothing } from 'lit';
import { property } from 'lit/decorators.js';
import { EventEmitterMixin } from '../../util/EventEmitterMixin.js';
import { ReadyMixin } from '../../util/ReadyMixin.js';
import { RovingTabindexMixin } from '../../util/RovingTabindexMixin.js';
/**
 * A menu container component that provides keyboard navigation and ARIA menu semantics.
 *
 * Contains `btu-dropdown-item` children and manages roving tabindex, typeahead search,
 * and keyboard navigation following the WAI-ARIA Menu Button Pattern.
 *
 * @element btu-dropdown-menu
 *
 * @fires {CustomEvent} btu-dropdown-menu-ready - Fired after first render
 *
 * @slot - Menu items (`btu-dropdown-item` elements)
 *
 * @cssprop --dropdown-empty-color - Empty state text color (default: gray-400)
 *
 * @example
 * ```html
 * <btu-dropdown-menu name="Sort By" header checkbox>
 *   <btu-dropdown-item label="Name" selected></btu-dropdown-item>
 *   <btu-dropdown-item label="Date"></btu-dropdown-item>
 *   <btu-dropdown-item label="Size"></btu-dropdown-item>
 * </btu-dropdown-menu>
 * ```
 */
export default class DropdownMenu extends RovingTabindexMixin(EventEmitterMixin(ReadyMixin(LitElement))) {
    constructor() {
        super(...arguments);
        /**
         * Accessible name for the menu, displayed in header when header is true.
         * @attr
         */
        this.name = '';
        /**
         * Show header bar with menu name.
         * @attr
         */
        this.header = false;
        /**
         * Enable checkbox mode for items (menuitemcheckbox role).
         * @attr
         */
        this.checkbox = false;
        /**
         * Show icons before each item.
         * @attr
         */
        this.icon = false;
        /**
         * Fallback Lucide icon symbol for items without their own.
         * @attr
         */
        this.symbol = '';
        /**
         * Show favorite toggle on each item.
         * @attr
         */
        this.favorites = false;
        /**
         * Show keyboard shortcut text on each item.
         * @attr
         */
        this.shortcuts = false;
        /**
         * Message displayed when the menu has no focusable items.
         * @attr empty-message
         */
        this.emptyMessage = 'No items available';
        /** @internal */
        this._typeaheadBuffer = '';
        /** @internal */
        this._typeaheadTimeout = null;
        /** @internal */
        this._handleKeydown = (e) => {
            const focusable = this._getFocusableItems();
            if (focusable.length === 0)
                return;
            switch (e.key) {
                case 'ArrowDown': {
                    e.preventDefault();
                    this._rovingNext();
                    break;
                }
                case 'ArrowUp': {
                    e.preventDefault();
                    this._rovingPrev();
                    break;
                }
                case 'Home': {
                    e.preventDefault();
                    this._rovingFirst();
                    break;
                }
                case 'End': {
                    e.preventDefault();
                    this._rovingLast();
                    break;
                }
                case 'Enter': {
                    e.preventDefault();
                    const currentIndex = this._rovingCurrentIndex();
                    if (currentIndex >= 0) {
                        focusable[currentIndex].activate();
                    }
                    break;
                }
                case ' ': {
                    e.preventDefault();
                    const currentIndex = this._rovingCurrentIndex();
                    if (currentIndex >= 0) {
                        focusable[currentIndex].activate();
                    }
                    break;
                }
                case 'Escape': {
                    // Bubble up to Dropdown to handle close
                    break;
                }
                case 'Tab': {
                    // Bubble up to Dropdown to handle close + focus restore
                    break;
                }
                default: {
                    // Typeahead: printable characters
                    if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
                        this._handleTypeahead(e.key, focusable);
                    }
                    break;
                }
            }
        };
    }
    createRenderRoot() {
        this.renderOptions.renderBefore ??= this.firstChild;
        return this;
    }
    /** @internal Override: return menuitem elements from focusable items */
    _getRovingTargets() {
        return this._getFocusableItems()
            .map(item => item.querySelector('[role="menuitem"], [role="menuitemcheckbox"]'))
            .filter(Boolean);
    }
    connectedCallback() {
        super.connectedCallback();
        this.setAttribute('role', 'menu');
        if (this.name) {
            this.setAttribute('aria-label', this.name);
        }
        this.addEventListener('keydown', this._handleKeydown);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.removeEventListener('keydown', this._handleKeydown);
        if (this._typeaheadTimeout) {
            clearTimeout(this._typeaheadTimeout);
        }
    }
    firstUpdated() {
        this._configureItems();
        this.emit('btu-dropdown-menu-ready');
    }
    updated() {
        this._configureItems();
        if (this.name) {
            this.setAttribute('aria-label', this.name);
        }
        else {
            this.removeAttribute('aria-label');
        }
    }
    /** Configure all child items with menu-level settings */
    _configureItems() {
        const items = this._getAllItems();
        items.forEach(item => {
            item._configure({
                checkbox: this.checkbox,
                icon: this.icon,
                symbol: this.symbol,
                favorites: this.favorites,
                shortcuts: this.shortcuts,
            });
        });
    }
    /** Get all btu-dropdown-item children */
    _getAllItems() {
        return Array.from(this.querySelectorAll('btu-dropdown-item'));
    }
    /** Get only focusable items (default type, skip dividers/subheads) */
    _getFocusableItems() {
        return this._getAllItems().filter(item => item.focusable);
    }
    /** @internal Focus a specific item by updating tabindex */
    focusItem(item) {
        const index = this._getFocusableItems().indexOf(item);
        if (index >= 0)
            this._rovingFocus(index);
    }
    /** @internal Focus the first non-disabled focusable item (or first checked in checkbox mode) */
    focusFirst() {
        const items = this._getFocusableItems();
        if (this.checkbox) {
            const checked = items.find(i => i.selected && !i.disabled);
            if (checked) {
                this.focusItem(checked);
                return;
            }
        }
        const first = items.find(i => !i.disabled) || items[0];
        if (first)
            this.focusItem(first);
    }
    /** @internal Focus the last non-disabled focusable item */
    focusLast() {
        const items = this._getFocusableItems();
        const last = [...items].reverse().find(i => !i.disabled) || items[items.length - 1];
        if (last)
            this.focusItem(last);
    }
    /** Typeahead character matching with 500ms accumulation */
    _handleTypeahead(char, focusable) {
        this._typeaheadBuffer += char.toLowerCase();
        if (this._typeaheadTimeout) {
            clearTimeout(this._typeaheadTimeout);
        }
        this._typeaheadTimeout = setTimeout(() => {
            this._typeaheadBuffer = '';
        }, 500);
        const match = focusable.find(item => item.label.toLowerCase().startsWith(this._typeaheadBuffer));
        if (match) {
            this.focusItem(match);
        }
    }
    /** Check whether the menu has zero focusable items */
    get _isEmpty() {
        return this._getFocusableItems().length === 0;
    }
    render() {
        return html `${this.header && this.name ? html `<div class="btu-dropdown-header">${this.name}</div>` : nothing}${this
            ._isEmpty
            ? html `<div class="btu-dropdown-empty" role="status">${this.emptyMessage}</div>`
            : nothing}`;
    }
}
__decorate([
    property({ type: String })
], DropdownMenu.prototype, "name", void 0);
__decorate([
    property({ type: Boolean })
], DropdownMenu.prototype, "header", void 0);
__decorate([
    property({ type: Boolean })
], DropdownMenu.prototype, "checkbox", void 0);
__decorate([
    property({ type: Boolean })
], DropdownMenu.prototype, "icon", void 0);
__decorate([
    property({ type: String })
], DropdownMenu.prototype, "symbol", void 0);
__decorate([
    property({ type: Boolean })
], DropdownMenu.prototype, "favorites", void 0);
__decorate([
    property({ type: Boolean })
], DropdownMenu.prototype, "shortcuts", void 0);
__decorate([
    property({ type: String, attribute: 'empty-message' })
], DropdownMenu.prototype, "emptyMessage", void 0);
if (!customElements.get('btu-dropdown-menu')) {
    customElements.define('btu-dropdown-menu', DropdownMenu);
}
//# sourceMappingURL=DropdownMenu.js.map