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 { styleMap } from 'lit/directives/style-map.js';
import { announce } from '../../util/aria.js';
import { EventEmitterMixin } from '../../util/EventEmitterMixin.js';
import { ReadyMixin } from '../../util/ReadyMixin.js';
import { TooltipMixin } from '../../util/TooltipMixin.js';
import '../icon/Icon.js';
const PLACEMENT_AREA = {
    'bottom-start': 'block-end span-inline-end',
    'bottom-end': 'block-end span-inline-start',
    'top-start': 'block-start span-inline-end',
    'top-end': 'block-start span-inline-start',
};
/**
 * A dropdown component that renders a trigger button and manages a floating panel
 * containing a `btu-dropdown-menu`.
 *
 * Uses the native Popover API and CSS anchor positioning for panel management.
 * The trigger button is built with existing `btu-button-*` classes.
 *
 * **Trigger button styling:** Set `--button-*` CSS custom properties on `<btu-dropdown>`
 * or a parent element to customize the trigger via CSS inheritance (e.g.,
 * `--button-border-radius`, `--button-color-background`). See
 * `tailwind-plugin-button.ts` for available props.
 *
 * @element btu-dropdown
 *
 * @fires {CustomEvent} btu-dropdown-ready - Fired after first render and initialization
 * @fires {CustomEvent} btu-dropdown-show - Fired when the dropdown panel opens
 * @fires {CustomEvent} btu-dropdown-hide - Fired when the dropdown panel closes
 * @fires {CustomEvent<{label: string, value: string, selected: boolean}>} btu-dropdown-item-select - Fired when a menu item is activated (bubbles from btu-dropdown-item)
 * @fires {CustomEvent<{label: string, favorited: boolean}>} btu-dropdown-item-favorite - Fired when a menu item's favorite is toggled (bubbles from btu-dropdown-item)
 *
 * @slot - A `btu-dropdown-menu` element containing `btu-dropdown-item` children
 *
 * @example
 * ```html
 * <btu-dropdown label="Actions" variant="secondary">
 *   <btu-dropdown-menu>
 *     <btu-dropdown-item label="Edit"></btu-dropdown-item>
 *     <btu-dropdown-item label="Duplicate"></btu-dropdown-item>
 *     <btu-dropdown-item label="Delete" disabled></btu-dropdown-item>
 *   </btu-dropdown-menu>
 * </btu-dropdown>
 * ```
 *
 * @cssprop --dropdown-panel-background - Panel background color (default: white)
 * @cssprop --dropdown-panel-border-color - Panel border color (default: gray-200)
 * @cssprop --dropdown-panel-border-radius - Panel border radius (default: borderRadius.lg)
 * @cssprop --dropdown-panel-min-width - Panel minimum width (default: max(12rem, anchor-size(width)))
 * @cssprop --dropdown-item-background - Item background color (default: transparent)
 * @cssprop --dropdown-item-color - Item text color (default: gray-700)
 * @cssprop --dropdown-item-hover-background - Item hover background (default: gray-100)
 * @cssprop --dropdown-item-hover-color - Item hover text color (default: gray-900)
 * @cssprop --dropdown-item-selected-background - Selected item background (default: primary-50)
 * @cssprop --dropdown-item-selected-color - Selected item text color (default: primary-700)
 * @cssprop --dropdown-item-font-size - Item font size (default: fontSize.sm)
 * @cssprop --dropdown-divider-color - Divider line color (default: gray-200)
 * @cssprop --dropdown-empty-color - Empty state text color (default: gray-400)
 */
export default class Dropdown extends TooltipMixin(EventEmitterMixin(ReadyMixin(LitElement))) {
    constructor() {
        super(...arguments);
        /**
         * Trigger button text.
         * @attr
         */
        this.label = '';
        /**
         * Panel visibility state. Can be set programmatically (e.g., for tour UIs)
         * — syncs to `showPopover()`/`hidePopover()` in `updated()`.
         * @attr
         */
        this.open = false;
        /**
         * Panel placement: 'bottom-start', 'bottom-end', 'top-start', 'top-end'.
         * @attr
         */
        this.placement = 'bottom-start';
        /**
         * Button size: 'sm', 'md', 'lg'.
         * @attr
         */
        this.size = 'md';
        /**
         * Prevents opening.
         * @attr
         */
        this.disabled = false;
        /**
         * Button variant: 'primary', 'secondary', 'tertiary', 'primary-clear', 'secondary-clear', 'tertiary-clear'.
         * @attr
         */
        this.variant = 'secondary';
        /**
         * Lucide icon symbol for the trigger.
         * @attr
         */
        this.symbol = '';
        /**
         * Icon position: 'leading' or 'trailing'.
         * @attr icon-position
         */
        this.iconPosition = 'leading';
        /**
         * Hides label, shows icon only.
         * @attr icon-only
         */
        this.iconOnly = false;
        /**
         * Keeps panel open on item click.
         * @attr stay-open-on-select
         */
        this.stayOpenOnSelect = false;
        /**
         * Hides the chevron icon on the trigger button.
         * @attr no-chevron
         */
        this.noChevron = false;
        /** @internal */
        this._triggerAnchorName = `--dropdown-anchor-${crypto.randomUUID().slice(0, 8)}`;
        /** @internal */
        this._panelId = `dropdown-panel-${crypto.randomUUID().slice(0, 8)}`;
        /** @internal */
        this._panel = null;
        /** @internal */
        this._menu = null;
        /** @internal */
        this._triggerEl = null;
        /** @internal */
        this._panelVisible = false;
        /** @internal */
        this._boundToggle = this._handlePanelToggle.bind(this);
        /** @internal */
        this._boundItemSelect = this._handleItemSelect.bind(this);
        /** @internal */
        this._boundKeydown = this._handleTriggerKeydown.bind(this);
        /** @internal */
        this._boundPanelKeydown = this._handlePanelKeydown.bind(this);
        /** @internal */
        this._boundFocusin = (e) => e.stopPropagation();
    }
    createRenderRoot() {
        return this;
    }
    connectedCallback() {
        // Capture the menu child before Lit renders and replaces innerHTML.
        // Skip if already captured — prevents losing the reference when the element
        // is moved in the DOM (e.g., pseudo-slots) before firstUpdated runs.
        if (!this._menu) {
            this._menu = this.querySelector('btu-dropdown-menu');
            if (this._menu) {
                this._menu.remove();
            }
        }
        super.connectedCallback();
        // Re-attach listeners on reconnection (e.g., after pseudo-slot moves).
        // firstUpdated only fires once, so listeners lost in disconnectedCallback
        // must be restored here.
        if (this._panel) {
            this._panel.addEventListener('toggle', this._boundToggle);
            this._panel.addEventListener('keydown', this._boundPanelKeydown);
            this._panel.addEventListener('focusin', this._boundFocusin);
            this.addEventListener('btu-dropdown-item-select', this._boundItemSelect);
        }
    }
    firstUpdated() {
        this._triggerEl = this.querySelector('button');
        // Create panel
        this._panel = document.createElement('div');
        this._panel.id = this._panelId;
        this._panel.setAttribute('popover', 'auto');
        this._panel.className = 'btu-dropdown-panel';
        // Anchor positioning — set inline to avoid Tailwind/PostCSS issues
        // with newer CSS properties (position-area, position-try-fallbacks)
        const s = this._panel.style;
        s.setProperty('position', 'fixed');
        s.setProperty('inset', 'unset');
        s.setProperty('margin', '0');
        s.setProperty('position-anchor', this._triggerAnchorName);
        s.setProperty('position-area', PLACEMENT_AREA[this.placement]);
        s.setProperty('position-try-fallbacks', 'flip-block');
        s.setProperty('position-visibility', 'anchors-visible');
        s.setProperty('min-width', 'var(--dropdown-panel-min-width, max(12rem, anchor-size(width)))');
        // Move menu into panel
        if (this._menu) {
            this._panel.appendChild(this._menu);
        }
        // Append panel to host
        this.appendChild(this._panel);
        // Bind toggle event
        this._panel.addEventListener('toggle', this._boundToggle);
        this._panel.addEventListener('keydown', this._boundPanelKeydown);
        // Prevent focusin from panel items bubbling to host — stops TooltipMixin from re-showing
        this._panel.addEventListener('focusin', this._boundFocusin);
        // Listen for item select events
        this.addEventListener('btu-dropdown-item-select', this._boundItemSelect);
        this.emit('btu-dropdown-ready');
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        if (this._panel) {
            this._panel.removeEventListener('toggle', this._boundToggle);
            this._panel.removeEventListener('keydown', this._boundPanelKeydown);
            this._panel.removeEventListener('focusin', this._boundFocusin);
        }
        this.removeEventListener('btu-dropdown-item-select', this._boundItemSelect);
    }
    updated(changedProperties) {
        super.updated(changedProperties);
        // Sync placement when property changes
        if (changedProperties.has('placement') && this._panel) {
            this._panel.style.setProperty('position-area', PLACEMENT_AREA[this.placement]);
        }
        // Sync open property to native popover
        if (changedProperties.has('open') && this._panel) {
            if (this.open && !this._panelVisible) {
                try {
                    this._panel.showPopover();
                }
                catch (e) {
                    if (!(e instanceof DOMException && e.name === 'InvalidStateError'))
                        throw e;
                }
            }
            else if (!this.open && this._panelVisible) {
                try {
                    this._panel.hidePopover();
                }
                catch (e) {
                    if (!(e instanceof DOMException && e.name === 'InvalidStateError'))
                        throw e;
                }
            }
        }
    }
    /** Build the button class string based on variant and size */
    _getButtonClasses() {
        const sz = this.size;
        const classes = ['btu-button'];
        switch (this.variant) {
            case 'primary':
                classes.push('btu-button-primary', `btu-button-${sz}`);
                break;
            case 'secondary':
                classes.push('btu-button-gray', `btu-button-${sz}`, 'btu-button-outline');
                break;
            case 'tertiary':
                classes.push('btu-button-gray', `btu-button-${sz}`, 'btu-button-fill-none');
                break;
            case 'primary-clear':
                classes.push('btu-button-primary', `btu-button-${sz}`, 'btu-button-container-none');
                break;
            case 'secondary-clear':
                classes.push('btu-button-gray', `btu-button-${sz}`, 'btu-button-container-none');
                break;
            case 'tertiary-clear':
                classes.push('btu-button-gray', `btu-button-${sz}`, 'btu-button-container-none', 'btu-button-fill-none');
                break;
        }
        if (this.iconOnly) {
            classes.push('btu-button-text-hidden');
        }
        return classes.join(' ');
    }
    /** @internal */
    _handlePanelToggle(e) {
        const event = e;
        this._panelVisible = event.newState === 'open';
        this.open = this._panelVisible;
        if (this._panelVisible) {
            this.emit('btu-dropdown-show');
            announce(`${this.label || 'Dropdown'} menu expanded`);
            // Hide tooltip when dropdown opens
            const tip = this.querySelector('[data-tooltip-internal]');
            if (tip)
                try {
                    tip.hidePopover();
                }
                catch { }
            // Focus first item after panel opens
            requestAnimationFrame(() => {
                this._menu?.focusFirst();
            });
        }
        else {
            this.emit('btu-dropdown-hide');
            announce(`${this.label || 'Dropdown'} menu collapsed`);
            // Return focus to trigger without scrolling the page
            this._triggerEl?.focus({ preventScroll: true });
        }
    }
    /** @internal */
    _handleItemSelect() {
        const isCheckbox = this._menu?.checkbox ?? false;
        if (!this.stayOpenOnSelect && !isCheckbox) {
            this._hidePanel();
        }
    }
    /** @internal */
    _handleTriggerKeydown(e) {
        if (this.disabled)
            return;
        switch (e.key) {
            case 'ArrowDown': {
                e.preventDefault();
                this._showPanel();
                requestAnimationFrame(() => {
                    this._menu?.focusFirst();
                });
                break;
            }
            case 'ArrowUp': {
                e.preventDefault();
                this._showPanel();
                requestAnimationFrame(() => {
                    this._menu?.focusLast();
                });
                break;
            }
        }
    }
    /** @internal */
    _handlePanelKeydown(e) {
        if (e.key === 'Escape') {
            e.preventDefault();
            e.stopPropagation();
            this._hidePanel();
            this._triggerEl?.focus({ preventScroll: true });
        }
        if (e.key === 'Tab') {
            this._hidePanel();
            this._triggerEl?.focus({ preventScroll: true });
        }
    }
    /** Show the dropdown panel */
    _showPanel() {
        if (this._panel && !this._panelVisible) {
            this._panel.showPopover();
        }
    }
    /** Hide the dropdown panel */
    _hidePanel() {
        if (this._panel && this._panelVisible) {
            this._panel.hidePopover();
        }
    }
    render() {
        const buttonClasses = this._getButtonClasses();
        return html `<button
      type="button"
      class="${buttonClasses}"
      style=${styleMap({ 'anchor-name': this._triggerAnchorName })}
      ?disabled="${this.disabled}"
      aria-haspopup="menu"
      aria-expanded="${this.open}"
      aria-controls="${this._panelId}"
      aria-label="${this.iconOnly ? this.label : nothing}"
      popovertarget="${this._panelId}"
      @keydown="${this._boundKeydown}"
    >
      ${this.symbol && this.iconPosition === 'leading'
            ? html `<btu-icon symbol="${this.symbol}" size="sm"></btu-icon>`
            : nothing}
      ${this.iconOnly ? nothing : this.label}
      ${this.symbol && this.iconPosition === 'trailing'
            ? html `<btu-icon symbol="${this.symbol}" size="sm"></btu-icon>`
            : nothing}
      ${this.noChevron
            ? nothing
            : html `<btu-icon class="btu-dropdown-chevron" symbol="chevron-down" size="sm"></btu-icon>`}
    </button>`;
    }
}
__decorate([
    property({ type: String })
], Dropdown.prototype, "label", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], Dropdown.prototype, "open", void 0);
__decorate([
    property({ type: String })
], Dropdown.prototype, "placement", void 0);
__decorate([
    property({ type: String })
], Dropdown.prototype, "size", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], Dropdown.prototype, "disabled", void 0);
__decorate([
    property({ type: String })
], Dropdown.prototype, "variant", void 0);
__decorate([
    property({ type: String })
], Dropdown.prototype, "symbol", void 0);
__decorate([
    property({ type: String, attribute: 'icon-position' })
], Dropdown.prototype, "iconPosition", void 0);
__decorate([
    property({ type: Boolean, attribute: 'icon-only' })
], Dropdown.prototype, "iconOnly", void 0);
__decorate([
    property({ type: Boolean, attribute: 'stay-open-on-select' })
], Dropdown.prototype, "stayOpenOnSelect", void 0);
__decorate([
    property({ type: Boolean, attribute: 'no-chevron', reflect: true })
], Dropdown.prototype, "noChevron", void 0);
if (!customElements.get('btu-dropdown')) {
    customElements.define('btu-dropdown', Dropdown);
}
//# sourceMappingURL=Dropdown.js.map