class Tabs {

    constructor(containerId) {
        this.container = document.getElementById(containerId);
        if (!this.container) {
            console.error(`Tabs container with ID "${containerId}" not found`);
            return;
        }

        this.tabButtons = this.container.querySelectorAll('.tab-button');
        this.tabPanels = this.container.querySelectorAll('.tab-panel');
        this.currentTab = 0;

        this.init();
    }

    init() {

        this.tabButtons.forEach((button, index) => {
            button.addEventListener('click', () => this.switchTab(index));

            button.addEventListener('keydown', (e) => this.handleKeyboard(e, index));
        });

        if (this.tabButtons.length > 0) {
            this.switchTab(0);
        }
    }

    switchTab(index) {
        if (index < 0 || index >= this.tabButtons.length) {
            return;
        }

        this.tabButtons.forEach(button => {
            button.classList.remove('active');
            button.setAttribute('aria-selected', 'false');
            button.setAttribute('tabindex', '-1');
        });

        this.tabPanels.forEach(panel => {
            panel.classList.remove('active');
        });

        this.tabButtons[index].classList.add('active');
        this.tabButtons[index].setAttribute('aria-selected', 'true');
        this.tabButtons[index].setAttribute('tabindex', '0');
        this.tabPanels[index].classList.add('active');

        this.currentTab = index;

        this.container.dispatchEvent(new CustomEvent('tabchange', {
            detail: { index, tabId: this.tabPanels[index].id }
        }));
    }

    handleKeyboard(e, currentIndex) {
        let newIndex = currentIndex;

        switch(e.key) {
            case 'ArrowLeft':
                newIndex = currentIndex > 0 ? currentIndex - 1 : this.tabButtons.length - 1;
                break;
            case 'ArrowRight':
                newIndex = currentIndex < this.tabButtons.length - 1 ? currentIndex + 1 : 0;
                break;
            case 'Home':
                newIndex = 0;
                break;
            case 'End':
                newIndex = this.tabButtons.length - 1;
                break;
            default:
                return;
        }

        e.preventDefault();
        this.switchTab(newIndex);
        this.tabButtons[newIndex].focus();
    }

    getCurrentTab() {
        return this.currentTab;
    }

    switchToTabById(tabId) {
        const index = Array.from(this.tabPanels).findIndex(panel => panel.id === tabId);
        if (index !== -1) {
            this.switchTab(index);
        }
    }
}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = Tabs;
}