// @warp-css;
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 { classNames } from '@chbphone55/classnames';
import { html, LitElement } from 'lit';
import { property, query } from 'lit/decorators.js';
import { reset } from '../styles.js';
import { styles } from './styles.js';
const ccTabs = {
    wrapper: 'inline-block border-b s-border mb-32',
    base: 'inline-grid relative -mb-1',
    selectionIndicator: 'absolute s-border-selected -bottom-0 border-b-4 transition-all',
};
const ccGridLayout = {
    cols1: 'grid-cols-1',
    cols2: 'grid-cols-2',
    cols3: 'grid-cols-3',
    cols4: 'grid-cols-4',
    cols5: 'grid-cols-5',
    cols6: 'grid-cols-6',
    cols7: 'grid-cols-7',
    cols8: 'grid-cols-8',
    cols9: 'grid-cols-9',
};
// Simple debounce utility
function debounce(func, wait = 200, immediate = false) {
    let timeout;
    return ((...args) => {
        const later = () => {
            timeout = null;
            if (!immediate)
                func(...args);
        };
        const callNow = immediate && !timeout;
        if (timeout)
            clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow)
            func(...args);
    });
}
/**
 * Tabs are used to organize content by grouping similar information on the same page.
 *
 * [See Storybook for usage examples](https://warp-ds.github.io/elements/?path=/docs/tabs--docs)
 */
export class WarpTabs extends LitElement {
    static { this.styles = [reset, styles]; }
    constructor() {
        super();
        this.active = '';
        this.tabClass = '';
        this._activeTab = '';
        this._updateSelectionIndicatorDebounced = debounce(this.updateSelectionIndicator.bind(this), 100);
        this._handleTabClick = (event) => {
            const newActiveTab = event.detail.name;
            if (newActiveTab !== this._activeTab) {
                this.active = newActiveTab;
                this._activeTab = newActiveTab;
                this.updateSelectionIndicator();
                this.updatePanels();
                this._notifyTabChange();
            }
        };
        this._handleKeyDown = (event) => {
            if (event.altKey ||
                event.ctrlKey ||
                event.shiftKey ||
                !['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) {
                return;
            }
            const tabs = Array.from(this.querySelectorAll('w-tab'));
            const currentIndex = tabs.findIndex((tab) => tab.getAttribute('name') === this._activeTab);
            if (currentIndex === -1)
                return;
            let nextIndex = currentIndex;
            switch (event.key) {
                case 'Home':
                    nextIndex = 0;
                    break;
                case 'End':
                    nextIndex = tabs.length - 1;
                    break;
                case 'ArrowLeft':
                    nextIndex = Math.max(0, currentIndex - 1);
                    break;
                case 'ArrowRight':
                    nextIndex = Math.min(tabs.length - 1, currentIndex + 1);
                    break;
            }
            if (nextIndex !== currentIndex) {
                event.preventDefault();
                const nextTab = tabs[nextIndex];
                const nextTabName = nextTab.getAttribute('name');
                if (nextTabName) {
                    this.active = nextTabName;
                    this._activeTab = nextTabName;
                    this.updateSelectionIndicator();
                    this.updatePanels();
                    this._notifyTabChange();
                    // Focus the next tab
                    const el = nextTab;
                    el.tabIndex = 0; // All tabs are initially -1
                    el.focus();
                    tabs.forEach((t) => {
                        t.tabIndex = t === el ? 0 : -1;
                    });
                }
            }
        };
        this.addEventListener('tab-click', this._handleTabClick);
    }
    connectedCallback() {
        super.connectedCallback();
        // Set up resize observer for selection indicator updates
        if (typeof ResizeObserver !== 'undefined') {
            this._resizeObserver = new ResizeObserver(() => {
                this._updateSelectionIndicatorDebounced();
            });
            this._resizeObserver.observe(this);
        }
        // Fallback for older browsers
        window.addEventListener('resize', this._updateSelectionIndicatorDebounced);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        if (this._resizeObserver) {
            this._resizeObserver.disconnect();
        }
        window.removeEventListener('resize', this._updateSelectionIndicatorDebounced);
        this.removeEventListener('tab-click', this._handleTabClick);
    }
    firstUpdated() {
        this._initializeActiveTab();
        this.updateSelectionIndicator();
        this.updatePanels();
    }
    updated(changedProperties) {
        if (changedProperties.has('active') && this.active !== this._activeTab) {
            this._activeTab = this.active;
            this.updateSelectionIndicator();
            this.updatePanels();
            this._notifyTabChange();
        }
    }
    get tabs() {
        const slot = this.shadowRoot?.querySelector('slot');
        // Get the slotted elements
        const slottedElements = slot.assignedElements({ flatten: true });
        // Filter only w-tab elements
        return slottedElements.filter((el) => el.tagName.toLowerCase() === 'w-tab');
    }
    get activeTab() {
        const activeTabs = this.tabs.filter((tab) => tab.name === this._activeTab);
        return activeTabs[0];
    }
    _initializeActiveTab() {
        if (this.activeTab) {
            this._activeTab = this.activeTab.getAttribute('name') || '';
        }
        else if (this.tabs.length > 0) {
            this._activeTab = this.tabs[0].getAttribute('name') || '';
        }
        if (this._activeTab) {
            this.active = this._activeTab;
        }
    }
    _notifyTabChange() {
        this.dispatchEvent(new CustomEvent('change', {
            detail: { name: this._activeTab },
            bubbles: true,
            composed: true,
        }));
    }
    updateSelectionIndicator() {
        requestAnimationFrame(() => {
            if (!this.tabList || !this.selectionIndicator)
                return;
            if (!this.activeTab)
                return;
            const tabListRect = this.tabList.getBoundingClientRect();
            const activeTabRect = this.activeTab.getBoundingClientRect();
            const left = activeTabRect.left - tabListRect.left;
            const width = activeTabRect.width;
            this.selectionIndicator.style.left = `${left}px`;
            this.selectionIndicator.style.width = `${width}px`;
        });
    }
    updatePanels() {
        // Update tab panels visibility
        const panels = document.querySelectorAll('w-tab-panel');
        panels.forEach((panel) => {
            if (panel.name === this._activeTab) {
                panel.removeAttribute('hidden');
                // Also explicitly set hidden property to false for web components
                panel.hidden = false;
            }
            else {
                panel.setAttribute('hidden', '');
                panel.hidden = true;
            }
        });
        // Update tab active states
        const tabs = this.querySelectorAll('w-tab');
        tabs.forEach((tab) => {
            const tabName = tab.getAttribute('name');
            if (tabName === this._activeTab) {
                tab.setAttribute('active', '');
                tab.tabIndex = 0;
            }
            else {
                tab.removeAttribute('active');
                tab.tabIndex = -1;
            }
        });
    }
    get _tabCount() {
        return this.querySelectorAll('w-tab').length;
    }
    get _gridClass() {
        const count = Math.min(this._tabCount, 9);
        return ccGridLayout[`cols${count}`] || ccGridLayout.cols1;
    }
    render() {
        const navClasses = classNames(this.tabClass, ccTabs.wrapper);
        const divClasses = classNames([ccTabs.base, this._gridClass]);
        return html `
      <div class="${navClasses}">
        <div role="tablist" class="${divClasses}" @keydown="${this._handleKeyDown}">
          <slot></slot>
          <span class="selection-indicator ${ccTabs.selectionIndicator}" data-testid="selection-indicator"></span>
        </div>
      </div>
    `;
    }
}
__decorate([
    property({ reflect: true })
], WarpTabs.prototype, "active", void 0);
__decorate([
    property({ attribute: 'tab-class', reflect: true })
], WarpTabs.prototype, "tabClass", void 0);
__decorate([
    query('[role="tablist"]')
], WarpTabs.prototype, "tabList", void 0);
__decorate([
    query('.selection-indicator')
], WarpTabs.prototype, "selectionIndicator", void 0);
if (!customElements.get('w-tabs')) {
    customElements.define('w-tabs', WarpTabs);
}
