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 '../badge/Badge.js';
import '../dropdown/Dropdown.js';
import '../dropdown/DropdownItem.js';
import '../dropdown/DropdownMenu.js';
import '../icon/Icon.js';
/**
 * A container component for managing a group of tabs.
 *
 * Provides selection state management, size propagation to child tabs,
 * and keyboard navigation following the WAI-ARIA Tabs pattern.
 *
 * When a tab becomes active, direct sibling elements that share the same
 * `name` value are shown; other siblings with a `name` attribute are
 * hidden. Only direct siblings are managed — nested tab groups control their
 * own panels independently.
 *
 * @element btu-tabs
 *
 * @fires {CustomEvent} btu-tabs-ready - Fired after first render and initialization
 * @fires {CustomEvent<{name: string}>} btu-tabs-show - Fired when a tab becomes active
 * @fires {CustomEvent<{name: string}>} btu-tabs-hide - Fired when a tab is deactivated
 * @fires {CustomEvent<{name: string}>} btu-tab-change - Fired when a tab is selected (bubbles from btu-tab)
 * @fires {CustomEvent} btu-tab-ready - Fired when a child tab finishes initialization (bubbles from btu-tab)
 *
 * @cssprop --tabs-active-color - Text and icon color of the active tab (default: gray-700)
 * @cssprop --tabs-active-indicator-color - Color of the active tab underline indicator (default: primary-500 → primary-700 → primary-900 gradient)
 * @cssprop --tabs-border-color - Color of the bottom border divider (default: gray-200)
 * @cssprop --tabs-color - Text and icon color for all tabs (default: gray-500; active/hover tabs use gray-700)
 * @cssprop --tabs-background - Background color for all tab buttons (default: transparent)
 * @cssprop --tabs-container-background - Background color of the tabs container (default: theme white)
 * @cssprop --tabs-hover-background - Background color of a tab on hover (default: gray-100)
 * @cssprop --tabs-hover-color - Text and icon color of a tab on hover (default: gray-700)
 * @cssprop --tabs-gap - Spacing between tabs (default: 1rem)
 *
 * @example
 * ```html
 * <div>
 *   <btu-tabs size="md" active-tab="main">
 *     <btu-tab name="main" label="Main"></btu-tab>
 *     <btu-tab name="seo" label="SEO"></btu-tab>
 *     <btu-tab name="overrides" label="Overrides"></btu-tab>
 *   </btu-tabs>
 *   <div name="main" role="tabpanel">Main content</div>
 *   <div name="seo" role="tabpanel">SEO content</div>
 *   <div name="overrides" role="tabpanel">Overrides content</div>
 * </div>
 * ```
 */
export default class Tabs extends RovingTabindexMixin(EventEmitterMixin(ReadyMixin(LitElement))) {
    constructor() {
        super(...arguments);
        /**
         * Size variant applied to all child tabs.
         * @attr
         */
        this.size = 'md';
        /**
         * Layout variant.
         * - 'full': tabs scroll horizontally when they overflow (default)
         * - 'menu': all tabs are hidden; the active tab label and a chevron dropdown are shown instead
         * @attr
         */
        this.variant = 'full';
        /** @internal */
        this.initialClasses = [];
        /** @internal Bound event handler for cleanup */
        this.boundHandleTabChange = this.handleTabChange.bind(this);
        /** @internal Bound event handler for cleanup */
        this.boundHandleKeyDown = this.handleKeyDown.bind(this);
        /** @internal Menu variant state */
        this.rafId = null;
        this.menuWrapper = null;
        this.menuDropdown = null;
        this.menuLabel = null;
        this.menuIcon = null;
        this.menuErrorBadge = null;
    }
    static get tagName() {
        return 'BTU-TABS';
    }
    /** @internal */
    _getRovingTargets() {
        const buttons = [];
        for (const tab of this.getTabs()) {
            if (tab.style.display === 'none')
                continue;
            const btn = tab.querySelector('button');
            if (btn)
                buttons.push(btn);
        }
        return buttons;
    }
    // Dropdown doesn't accept 'xs'; floor the tabs 'xs' size to 'sm' when forwarding.
    get _dropdownSize() {
        return this.size === 'xs' ? 'sm' : this.size;
    }
    // Menu-variant icon is always small relative to the tab label, regardless of tabs size.
    get _menuIconSize() {
        return this.size === 'lg' ? 'md' : 'sm';
    }
    connectedCallback() {
        super.connectedCallback();
        if (this.className) {
            this.initialClasses = this.className.split(' ').filter(c => c.trim());
        }
        this.setAttribute('role', 'tablist');
        this.addEventListener('btu-tab-change', this.boundHandleTabChange);
        this.addEventListener('keydown', this.boundHandleKeyDown);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        if (this.rafId) {
            cancelAnimationFrame(this.rafId);
            this.rafId = null;
        }
        this.removeEventListener('btu-tab-change', this.boundHandleTabChange);
        this.removeEventListener('keydown', this.boundHandleKeyDown);
    }
    createRenderRoot() {
        return this;
    }
    willUpdate() {
        this.className = [
            ...this.initialClasses,
            'btu-tabs',
            `btu-tabs-${this.size}`,
            this.variant === 'menu' ? 'btu-tabs-menu-mode' : '',
        ]
            .filter(Boolean)
            .join(' ');
    }
    firstUpdated() {
        if (!this.activeTab) {
            const firstEnabled = this.getTabs().find(t => !t.disabled);
            if (firstEnabled)
                this.activeTab = firstEnabled.name;
        }
        this.syncTabs();
        this.syncPanels();
        if (this.variant === 'menu') {
            this.initMenu();
        }
        else {
            this.emit('btu-tabs-ready');
        }
    }
    updated(changedProperties) {
        if (changedProperties.has('activeTab') && !this.activeTab) {
            const firstEnabled = this.getTabs().find(t => !t.disabled);
            if (firstEnabled)
                this.activeTab = firstEnabled.name;
        }
        if (changedProperties.has('activeTab') || changedProperties.has('size')) {
            this.syncTabs();
        }
        if (changedProperties.has('activeTab')) {
            this.syncPanels();
        }
        if (changedProperties.has('size') && this.menuDropdown) {
            this.menuDropdown.size = this._dropdownSize;
        }
        if (changedProperties.has('variant') && changedProperties.get('variant') !== undefined) {
            this.teardownVariant(changedProperties.get('variant'));
            if (this.variant === 'menu')
                this.initMenu();
        }
    }
    /** @internal Tear down a variant's DOM and state before switching to another */
    teardownVariant(previous) {
        if (previous === 'menu') {
            this.menuWrapper?.remove();
            this.menuWrapper = null;
            this.menuDropdown = null;
            this.menuLabel = null;
            this.menuIcon = null;
            this.menuErrorBadge = null;
            this.getTabs().forEach(tab => tab.style.removeProperty('display'));
        }
    }
    /** @internal */
    syncTabs() {
        this.getTabs().forEach(tab => {
            tab.size = this.size;
            tab._active = tab.name === this.activeTab;
            tab._tabindex = tab.name === this.activeTab ? 0 : -1;
            tab.requestUpdate();
        });
        if (this.variant === 'menu') {
            this.syncMenuState();
        }
    }
    /** @internal Show/hide panel elements that are direct siblings with a matching name value */
    syncPanels() {
        if (!this.activeTab || !this.parentElement)
            return;
        Array.from(this.parentElement.children).forEach(child => {
            if (child === this || !(child instanceof HTMLElement))
                return;
            // data-tab is a deprecated fallback for compat — use name instead
            const panelName = child.getAttribute('name') ?? child.dataset.tab;
            if (!panelName)
                return;
            child.hidden = panelName !== this.activeTab;
        });
    }
    /** @internal */
    getTabs() {
        return Array.from(this.querySelectorAll('btu-tab'));
    }
    /** @internal */
    activateTab(name) {
        const newTab = this.getTabs().find(t => t.name === name);
        if (!newTab || newTab.disabled) {
            const available = this.getTabs()
                .map(t => t.name)
                .filter(Boolean);
            console.warn(`[btu-tabs] Tab "${name}" not found or is disabled. Available tabs: ${available.join(', ')}`);
            return;
        }
        if (name === this.activeTab)
            return;
        const oldName = this.activeTab;
        if (oldName) {
            this.emit('btu-tabs-hide', { name: oldName });
        }
        this.activeTab = name;
        this.emit('btu-tabs-show', { name });
        this.syncTabs();
        this.syncPanels();
    }
    /** @internal */
    handleTabChange(event) {
        this.activateTab(event.detail.name);
    }
    /** @internal Keyboard navigation following WAI-ARIA Tabs pattern */
    handleKeyDown(event) {
        switch (event.key) {
            case 'ArrowRight':
                event.preventDefault();
                this._rovingNext();
                break;
            case 'ArrowLeft':
                event.preventDefault();
                this._rovingPrev();
                break;
            case 'Home':
                event.preventDefault();
                this._rovingFirst();
                break;
            case 'End':
                event.preventDefault();
                this._rovingLast();
                break;
        }
    }
    // ─── Menu variant ────────────────────────────────────────────────────────────
    /** @internal */
    initMenu() {
        // Hide all tab buttons — they're only accessible via the dropdown
        this.getTabs().forEach(tab => (tab.style.display = 'none'));
        const activeTab = this.getTabs().find(t => t.name === this.activeTab);
        this.menuWrapper = document.createElement('div');
        const wrapper = this.menuWrapper;
        wrapper.className = 'btu-tab-menu-wrapper';
        this.menuIcon = document.createElement('btu-icon');
        this.menuIcon.setAttribute('size', this._menuIconSize);
        this.menuIcon.setAttribute('symbol', activeTab?.symbol ?? '');
        this.menuIcon.hidden = !activeTab?.symbol;
        this.menuLabel = document.createElement('span');
        this.menuLabel.className = 'btu-tab-menu-label';
        this.menuLabel.textContent = activeTab?.label ?? '';
        if (activeTab?.iconPosition === 'trailing') {
            wrapper.appendChild(this.menuLabel);
            wrapper.appendChild(this.menuIcon);
        }
        else {
            wrapper.appendChild(this.menuIcon);
            wrapper.appendChild(this.menuLabel);
        }
        this.menuErrorBadge = document.createElement('btu-badge');
        this.menuErrorBadge.setAttribute('size', 'sm');
        this.menuErrorBadge.setAttribute('variant', 'error');
        this.menuErrorBadge.textContent = '!';
        this.menuErrorBadge.hidden = !activeTab?.error;
        wrapper.appendChild(this.menuErrorBadge);
        const dropdownMenu = document.createElement('btu-dropdown-menu');
        this.menuDropdown = document.createElement('btu-dropdown');
        this.menuDropdown.label = 'Tabs';
        this.menuDropdown.iconOnly = true;
        this.menuDropdown.noChevron = false;
        this.menuDropdown.variant = 'tertiary';
        this.menuDropdown.placement = 'bottom-start';
        this.menuDropdown.size = this._dropdownSize;
        this.menuDropdown.appendChild(dropdownMenu);
        this.menuDropdown.addEventListener('btu-dropdown-item-select', (e) => {
            e.stopPropagation();
            const item = e.target.closest('btu-dropdown-item');
            const name = item?.dataset.name;
            if (name)
                this.activateTab(name);
        });
        wrapper.appendChild(this.menuDropdown);
        this.appendChild(wrapper);
        // Defer population to allow btu-dropdown to finish its firstUpdated lifecycle
        this.rafId = requestAnimationFrame(() => {
            this.rafId = null;
            this.updateMenuItems();
            this.emit('btu-tabs-ready');
        });
    }
    /** @internal */
    updateMenuItems() {
        if (!this.isConnected)
            return;
        const menu = this.menuDropdown?.querySelector('btu-dropdown-menu');
        if (!menu)
            return;
        menu.innerHTML = '';
        const tabs = this.getTabs();
        const hasIcons = tabs.some(t => !!t.symbol);
        tabs.forEach(tab => {
            const item = document.createElement('btu-dropdown-item');
            item.dataset.name = tab.name ?? '';
            item.label = tab.label ?? tab.name ?? '';
            item.selected = tab.name === this.activeTab;
            item.disabled = tab.disabled;
            item.error = tab.error;
            if (tab.symbol)
                item.symbol = tab.symbol;
            menu.appendChild(item);
            item._configure({ checkbox: false, icon: hasIcons, symbol: '', favorites: false, shortcuts: false });
        });
    }
    /** @internal */
    syncMenuState() {
        const activeTab = this.getTabs().find(t => t.name === this.activeTab);
        if (this.menuLabel) {
            this.menuLabel.textContent = activeTab?.label ?? '';
        }
        if (this.menuIcon) {
            const symbol = activeTab?.symbol ?? '';
            this.menuIcon.setAttribute('symbol', symbol);
            this.menuIcon.setAttribute('size', this._menuIconSize);
            this.menuIcon.hidden = !symbol;
            // Reposition if icon-position changed
            const wrapper = this.menuIcon.parentElement;
            if (wrapper && this.menuLabel) {
                if (activeTab?.iconPosition === 'trailing') {
                    wrapper.insertBefore(this.menuIcon, this.menuErrorBadge);
                }
                else {
                    wrapper.insertBefore(this.menuIcon, this.menuLabel);
                }
            }
        }
        if (this.menuErrorBadge) {
            this.menuErrorBadge.hidden = !activeTab?.error;
        }
        this.menuDropdown?.querySelectorAll('btu-dropdown-item').forEach(item => {
            item.selected = item.dataset.name === this.activeTab;
        });
    }
    render() {
        return html ``;
    }
}
__decorate([
    property({ type: String })
], Tabs.prototype, "size", void 0);
__decorate([
    property({ type: String, attribute: 'active-tab' })
], Tabs.prototype, "activeTab", void 0);
__decorate([
    property({ type: String })
], Tabs.prototype, "variant", void 0);
if (!customElements.get('btu-tabs')) {
    customElements.define('btu-tabs', Tabs);
}
//# sourceMappingURL=Tabs.js.map