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 } 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';
import '../dropdown/Dropdown.js';
import '../dropdown/DropdownItem.js';
import '../dropdown/DropdownMenu.js';
import './ActionItem.js';
/** @internal Variant priority for sort and overflow ordering */
const VARIANT_PRIORITY = {
    tertiary: 0,
    secondary: 1,
    primary: 2,
    destructive: 0,
};
/**
 * A persistent container for primary, secondary, tertiary, and destructive actions
 * within an interface, typically anchored to the bottom of a view.
 *
 * Uses a two-zone layout: destructive actions on the left (start zone),
 * main actions on the right (end zone). Both zones maintain their position
 * even when the other zone is empty (BSP-18087).
 *
 * **Positioning:** Uses `margin-top: auto` to push to bottom of flex/grid parents.
 * In block layout parents, the bar sits after content (a console warning is emitted).
 *
 * **Overflow:** When items don't fit, the least important overflow into a "More" dropdown.
 * Items are auto-sorted by variant priority (tertiary → secondary → primary).
 * With `compact`, compactable items progressively hide labels one-by-one before overflowing.
 *
 * @element btu-action-bar
 *
 * @fires {CustomEvent} btu-action-bar-ready - Fired after first render and initialization
 * @fires {CustomEvent<{label: string}>} btu-action-item-click - Fired when an action item is clicked (bubbles from btu-action-item)
 *
 * @slot - One or more `btu-action-item` elements
 *
 * @cssprop --action-bar-gap - Gap between items (default: 0.75rem)
 * @cssprop --action-bar-padding - Bar padding (default: 1.5rem)
 * @cssprop --action-bar-background - Background color (default: white)
 * @cssprop --action-bar-border-color - Border color (default: gray-200)
 * @cssprop --action-bar-z-index - Z-index (default: 100)
 *
 * @example
 * ```html
 * <!-- Basic: destructive left, actions right -->
 * <btu-action-bar label="Content actions">
 *   <btu-action-item zone="start" variant="destructive" label="Delete" symbol="trash-2"></btu-action-item>
 *   <btu-action-item zone="end" variant="secondary" label="Cancel"></btu-action-item>
 *   <btu-action-item zone="end" variant="primary" label="Save Changes"></btu-action-item>
 * </btu-action-bar>
 * ```
 *
 * @example
 * ```html
 * <!-- Parent must be flex/grid for bottom-anchoring -->
 * <div style="display: flex; flex-direction: column; min-height: 100vh;">
 *   <main>Content here</main>
 *   <btu-action-bar label="Page actions">
 *     <btu-action-item variant="primary" label="Save"></btu-action-item>
 *   </btu-action-bar>
 * </div>
 * ```
 */
export default class ActionBar extends RovingTabindexMixin(EventEmitterMixin(ReadyMixin(LitElement))) {
    constructor() {
        super(...arguments);
        /**
         * Bar position: 'top' or 'bottom' (default).
         * @attr
         */
        this.position = 'bottom';
        /**
         * Enables CSS sticky positioning. When combined with position='top',
         * the bar sticks to the top of the scroll container. With position='bottom'
         * (default), it sticks to the bottom.
         * @attr
         */
        this.sticky = false;
        /**
         * Content alignment: 'default' (two-zone), 'start', 'center', 'end'.
         * Non-default alignments disable two-zone layout.
         * @attr item-alignment
         */
        this.alignment = 'default';
        /**
         * Adds a box-shadow to the bar.
         * @attr
         */
        this.shadow = false;
        /**
         * Accessible label for the toolbar region.
         * @attr
         */
        this.label = '';
        /**
         * Enables progressive label compacting. When space shrinks, items marked
         * `compactable` (with icons) have their labels hidden one-by-one
         * from least to most important before items overflow into "More".
         * @attr
         */
        this.compact = false;
        /** @internal */
        this.initialClasses = [];
        /** @internal */
        this._items = [];
        /** @internal */
        this._startZone = null;
        /** @internal */
        this._endZone = null;
        /** @internal */
        this._moreDropdown = null;
        /** @internal */
        this._ro = null;
        /** @internal */
        this._rafId = null;
        /** @internal - Cached expanded widths per item */
        this._expandedWidths = new Map();
        /** @internal - Cached compacted widths per item */
        this._compactedWidths = new Map();
        /** @internal */
        this._hasOverflow = false;
        /** @internal - Tracks which individual items are currently compacted */
        this._compactedItems = new Set();
        /** @internal */
        this._boundKeydown = this._handleKeydown.bind(this);
    }
    createRenderRoot() {
        return this;
    }
    /** @internal Override: return visible item buttons + More dropdown button in visual order */
    _getRovingTargets() {
        const targets = [];
        // Start-zone items
        if (this._startZone) {
            for (const item of this._startZone.querySelectorAll('btu-action-item')) {
                if (item.style.display !== 'none') {
                    const button = item.querySelector('button');
                    if (button)
                        targets.push(button);
                }
            }
        }
        // More button (DOM-first in end zone, visually left of action items)
        if (this._moreDropdown && this._moreDropdown.style.display !== 'none') {
            const moreButton = this._moreDropdown.querySelector('button');
            if (moreButton)
                targets.push(moreButton);
        }
        // End-zone items
        for (const item of this._getEndZoneItems()) {
            if (item.style.display !== 'none') {
                const button = item.querySelector('button');
                if (button)
                    targets.push(button);
            }
        }
        return targets;
    }
    connectedCallback() {
        // Capture initial classes from backend HTML
        if (this.className) {
            this.initialClasses = this.className.split(' ').filter(c => c.trim());
        }
        // Capture action-item children before Lit renders
        this._items = Array.from(this.querySelectorAll('btu-action-item'));
        this._items.forEach(item => item.remove());
        // Host element IS the toolbar — no wrapper div
        this.setAttribute('role', 'toolbar');
        this.setAttribute('aria-orientation', 'horizontal');
        super.connectedCallback();
        this.addEventListener('keydown', this._boundKeydown);
    }
    willUpdate() {
        const classes = [...this.initialClasses, 'btu-action-bar'];
        this.className = classes.filter(Boolean).join(' ');
        if (this.label) {
            this.setAttribute('aria-label', this.label);
        }
        else {
            this.removeAttribute('aria-label');
        }
    }
    firstUpdated() {
        this._startZone = this.querySelector('.btu-action-bar-start');
        this._endZone = this.querySelector('.btu-action-bar-end');
        if (!this._startZone || !this._endZone)
            return;
        // Distribute items into zones
        for (const item of this._items) {
            const zone = this._getItemZone(item);
            (zone === 'start' ? this._startZone : this._endZone).appendChild(item);
        }
        // Sort end-zone items by variant importance
        this._sortEndZoneItems();
        // Create overflow dropdown (after sort so it's appended last)
        this._createOverflowDropdown(this._endZone);
        // Cache widths (always cache both maps)
        this._cacheWidths(this._expandedWidths, false);
        this._cacheWidths(this._compactedWidths, true);
        // Setup overflow detection
        this._setupOverflowDetection();
        // Initial tabindex
        this._updateTabindex(0);
        this.emit('btu-action-bar-ready');
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.removeEventListener('keydown', this._boundKeydown);
        if (this._ro) {
            this._ro.disconnect();
            this._ro = null;
        }
        if (this._rafId) {
            cancelAnimationFrame(this._rafId);
            this._rafId = null;
        }
    }
    /** @internal Determine which zone an item belongs to */
    _getItemZone(item) {
        if (item.zone === 'start' || item.zone === 'end')
            return item.zone;
        // Fallback: destructive → start, others → end
        return item.variant === 'destructive' ? 'start' : 'end';
    }
    /** @internal Get all visible (non-overflow) items in order */
    _getVisibleItems() {
        const items = [];
        if (this._startZone) {
            items.push(...Array.from(this._startZone.querySelectorAll('btu-action-item')));
        }
        if (this._endZone) {
            items.push(...Array.from(this._endZone.querySelectorAll(':scope > btu-action-item')));
        }
        return items.filter(item => item.style.display !== 'none');
    }
    /** @internal Get end-zone items only */
    _getEndZoneItems() {
        if (!this._endZone)
            return [];
        return Array.from(this._endZone.querySelectorAll(':scope > btu-action-item'));
    }
    /** @internal Sort end-zone items by variant importance */
    _sortEndZoneItems() {
        if (!this._endZone)
            return;
        const endItems = this._getEndZoneItems();
        const descending = this.alignment === 'start';
        endItems.sort((a, b) => {
            const pa = VARIANT_PRIORITY[a.variant] ?? 0;
            const pb = VARIANT_PRIORITY[b.variant] ?? 0;
            return descending ? pb - pa : pa - pb;
        });
        for (const item of endItems) {
            this._endZone.appendChild(item);
        }
    }
    /** @internal Cache item widths, optionally in compacted (icon-only) state */
    _cacheWidths(target, compacted) {
        target.clear();
        for (const item of this._getEndZoneItems()) {
            const canCompact = compacted && item.compactable && item.symbol && !item.iconOnly;
            const button = canCompact ? item.querySelector('button') : null;
            if (button)
                button.classList.add('btu-button-text-hidden');
            target.set(item, item.getBoundingClientRect().width);
            if (button)
                button.classList.remove('btu-button-text-hidden');
        }
    }
    /** @internal Sum widths of visible items using per-item compact state */
    _calcTotalWidth(items) {
        const gap = parseFloat(getComputedStyle(this._endZone).gap) || 12;
        let total = 0;
        for (const item of items) {
            if (item.style.display === 'none')
                continue;
            const map = this._compactedItems.has(item) ? this._compactedWidths : this._expandedWidths;
            const w = map.get(item) || item.getBoundingClientRect().width;
            if (total > 0)
                total += gap;
            total += w;
        }
        return total;
    }
    /** @internal Set up ResizeObserver for overflow detection */
    _setupOverflowDetection() {
        this._ro = new ResizeObserver(() => this._scheduleRecalc());
        this._ro.observe(this);
    }
    /** @internal rAF-debounced recalculation */
    _scheduleRecalc() {
        if (this._rafId)
            return;
        this._rafId = requestAnimationFrame(() => {
            this._rafId = null;
            this._recalculateOverflow();
        });
    }
    /** @internal Recalculate which items overflow */
    _recalculateOverflow() {
        if (!this._endZone)
            return;
        const endItems = this._getEndZoneItems();
        const containerWidth = this._endZone.clientWidth;
        const moreWidth = 40; // approximate "More" button width
        const gap = parseFloat(getComputedStyle(this._endZone).gap) || 12;
        // Phase 0: Reset — show all items, clear compact states
        endItems.forEach(item => (item.style.display = ''));
        this._compactedItems.clear();
        // Phase 1: Check if everything fits expanded
        if (this._calcTotalWidth(endItems) <= containerWidth) {
            this._hasOverflow = false;
            this._updateOverflowDropdown([]);
            this._updateTabindex(Math.min(this._rovingIndex, this._getVisibleItems().length - 1));
            return;
        }
        // Build priority-sorted list: least important first (stable sort)
        const byPriority = [...endItems].sort((a, b) => (VARIANT_PRIORITY[a.variant] ?? 0) - (VARIANT_PRIORITY[b.variant] ?? 0));
        // Phase 2: Progressive compacting (if enabled)
        if (this.compact) {
            for (const item of byPriority) {
                if (!item.compactable || !item.symbol || item.iconOnly)
                    continue;
                this._compactedItems.add(item);
                if (this._calcTotalWidth(endItems) <= containerWidth) {
                    this._hasOverflow = false;
                    this._updateOverflowDropdown([]);
                    this._updateTabindex(Math.min(this._rovingIndex, this._getVisibleItems().length - 1));
                    return;
                }
            }
        }
        // Phase 3: Overflow least-important-first
        const overflow = [];
        for (const item of byPriority) {
            const visible = endItems.filter(i => !overflow.includes(i));
            const visibleWidth = this._calcTotalWidth(visible);
            if (visibleWidth + moreWidth + gap <= containerWidth) {
                break;
            }
            overflow.push(item);
            item.style.display = 'none';
        }
        this._hasOverflow = overflow.length > 0;
        this._updateOverflowDropdown(overflow);
        this._updateTabindex(Math.min(this._rovingIndex, Math.max(0, this._getVisibleItems().length - 1)));
    }
    /** @internal Create the overflow "More" dropdown */
    _createOverflowDropdown(endZone) {
        this._moreDropdown = document.createElement('btu-dropdown');
        this._moreDropdown.setAttribute('symbol', 'ellipsis');
        this._moreDropdown.setAttribute('icon-only', '');
        this._moreDropdown.setAttribute('variant', 'tertiary');
        this._moreDropdown.setAttribute('size', 'sm');
        this._moreDropdown.setAttribute('no-chevron', '');
        this._moreDropdown.setAttribute('aria-label', 'More actions');
        this._moreDropdown.style.display = 'none';
        const menu = document.createElement('btu-dropdown-menu');
        this._moreDropdown.appendChild(menu);
        endZone.prepend(this._moreDropdown);
        this._moreDropdown.addEventListener('btu-dropdown-item-select', this._handleOverflowSelect.bind(this));
    }
    /** @internal Populate overflow dropdown menu */
    _updateOverflowDropdown(overflowItems) {
        if (!this._moreDropdown)
            return;
        const menu = this._moreDropdown.querySelector('btu-dropdown-menu');
        if (!menu)
            return;
        if (overflowItems.length === 0) {
            this._moreDropdown.style.display = 'none';
            menu.innerHTML = '';
            return;
        }
        this._moreDropdown.style.display = '';
        menu.innerHTML = '';
        // Reverse: most important overflowed items at top of dropdown
        const menuItems = [...overflowItems].reverse();
        for (const item of menuItems) {
            const menuItem = document.createElement('btu-dropdown-item');
            menuItem.setAttribute('label', item.label);
            menuItem.dataset.itemIndex = String(this._items.indexOf(item));
            if (item.symbol)
                menuItem.setAttribute('symbol', item.symbol);
            if (item.disabled)
                menuItem.setAttribute('disabled', '');
            menu.appendChild(menuItem);
        }
    }
    /** @internal Handle click on overflow dropdown item */
    _handleOverflowSelect(e) {
        const menuItem = e.target;
        const index = parseInt(menuItem.dataset.itemIndex || '-1', 10);
        const original = this._items[index];
        if (original && !original.disabled && !original.loading) {
            original.emit('btu-action-item-click', { label: original.label });
        }
    }
    /** @internal Update roving tabindex and configure compact state on visible items */
    _updateTabindex(activeIndex) {
        this._rovingFocus(activeIndex, false);
        const targets = this._getRovingTargets();
        const activeTarget = targets[this._rovingIndex];
        const visible = this._getVisibleItems();
        visible.forEach(item => {
            const button = item.querySelector('button');
            item._configure({
                tabindex: button === activeTarget ? 0 : -1,
                collapsed: this._compactedItems.has(item),
            });
        });
    }
    /** @internal Reactive recalculation when properties change */
    updated(changedProperties) {
        if (changedProperties.has('compact') || changedProperties.has('alignment')) {
            this._scheduleRecalc();
        }
    }
    /** @internal Keyboard handler for toolbar navigation */
    _handleKeydown(e) {
        const isRtl = getComputedStyle(this).direction === 'rtl';
        const nextKey = isRtl ? 'ArrowLeft' : 'ArrowRight';
        const prevKey = isRtl ? 'ArrowRight' : 'ArrowLeft';
        switch (e.key) {
            case nextKey:
                e.preventDefault();
                this._rovingNext();
                break;
            case prevKey:
                e.preventDefault();
                this._rovingPrev();
                break;
            case 'Home':
                e.preventDefault();
                this._rovingFirst();
                break;
            case 'End':
                e.preventDefault();
                this._rovingLast();
                break;
        }
    }
    render() {
        return html `
      <div class="btu-action-bar-start"></div>
      <div class="btu-action-bar-end"></div>
    `;
    }
}
__decorate([
    property({ type: String, reflect: true })
], ActionBar.prototype, "position", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], ActionBar.prototype, "sticky", void 0);
__decorate([
    property({ type: String, reflect: true, attribute: 'item-alignment' })
], ActionBar.prototype, "alignment", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], ActionBar.prototype, "shadow", void 0);
__decorate([
    property({ type: String })
], ActionBar.prototype, "label", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], ActionBar.prototype, "compact", void 0);
if (!customElements.get('btu-action-bar')) {
    customElements.define('btu-action-bar', ActionBar);
}
//# sourceMappingURL=ActionBar.js.map