class SubNav {

    constructor(config) {
        this.containerId = config.containerId;
        this.sections = config.sections || [];
        this.defaultSection = config.defaultSection || (this.sections[0]?.id);
        this.activeSection = this.defaultSection;

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

        this.render();
        this.init();
    }

    render() {
        const activeSectionIndex = this.sections.findIndex(s => s.id === this.activeSection);
        const sectionCount = this.sections.length;
        const sectionNumber = activeSectionIndex + 1;

        this.container.innerHTML = `
            <div class="subnav-wrapper">
                <!-- Side Navigation -->
                <nav class="subnav-sidebar" role="navigation" aria-label="Section navigation">
                    <ul class="subnav-list">
                        ${this.sections.map(section => `
                            <li class="subnav-item">
                                <button
                                    class="subnav-link ${section.id === this.activeSection ? 'active' : ''}"
                                    data-section="${section.id}"
                                    role="tab"
                                    aria-selected="${section.id === this.activeSection}"
                                    aria-controls="subnav-content-${section.id}"
                                    title="${section.title}">
                                    ${section.icon ? `<span class="subnav-icon">${section.icon}</span>` : ''}
                                    <span class="subnav-text">${section.title}</span>
                                </button>
                            </li>
                        `).join('')}
                    </ul>
                </nav>

                <!-- Content Panel -->
                <div class="subnav-content-panel">
                    <!-- Section Indicator (visible on small screens) -->
                    <div class="subnav-section-indicator">
                        <span class="subnav-section-number">${sectionNumber}/${sectionCount}</span>
                        <span class="subnav-section-title">${this.sections[activeSectionIndex].title}</span>
                    </div>

                    ${this.sections.map(section => `
                        <div
                            id="subnav-content-${section.id}"
                            class="subnav-content ${section.id === this.activeSection ? 'active' : ''} ${section.noPadding ? 'no-padding' : ''}"
                            role="tabpanel"
                            aria-labelledby="subnav-link-${section.id}">
                            ${section.hideTitle ? '' : `<h2 class="subnav-content-title">${section.title}</h2>`}
                            <div class="subnav-content-body ${section.noPadding ? 'no-padding' : ''}">
                                ${typeof section.content === 'function' ? section.content() : section.content}
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
    }

    init() {

        const sideNavLinks = this.container.querySelectorAll('.subnav-link');
        sideNavLinks.forEach(link => {
            link.addEventListener('click', (e) => {
                const sectionId = e.currentTarget.dataset.section;
                this.switchSection(sectionId);
            });
        });

        this.setupKeyboardNavigation();
    }

    switchSection(sectionId) {
        if (this.activeSection === sectionId) return;

        const sideNavLinks = this.container.querySelectorAll('.subnav-link');
        sideNavLinks.forEach(link => {
            const isActive = link.dataset.section === sectionId;
            link.classList.toggle('active', isActive);
            link.setAttribute('aria-selected', isActive);
        });

        const contentPanels = this.container.querySelectorAll('.subnav-content');
        contentPanels.forEach(panel => {
            const isActive = panel.id === `subnav-content-${sectionId}`;
            panel.classList.toggle('active', isActive);
        });

        this.activeSection = sectionId;

        this.container.dispatchEvent(new CustomEvent('sectionchange', {
            detail: { sectionId }
        }));
    }

    setupKeyboardNavigation() {
        const sideNavLinks = this.container.querySelectorAll('.subnav-link');

        sideNavLinks.forEach((link, index) => {
            link.addEventListener('keydown', (e) => {
                let targetIndex = index;

                switch(e.key) {
                    case 'ArrowUp':
                        targetIndex = index > 0 ? index - 1 : sideNavLinks.length - 1;
                        e.preventDefault();
                        break;
                    case 'ArrowDown':
                        targetIndex = index < sideNavLinks.length - 1 ? index + 1 : 0;
                        e.preventDefault();
                        break;
                    case 'Home':
                        targetIndex = 0;
                        e.preventDefault();
                        break;
                    case 'End':
                        targetIndex = sideNavLinks.length - 1;
                        e.preventDefault();
                        break;
                    default:
                        return;
                }

                sideNavLinks[targetIndex].focus();
                this.switchSection(sideNavLinks[targetIndex].dataset.section);
            });
        });
    }

    getActiveSection() {
        return this.activeSection;
    }

    setActiveSection(sectionId) {
        this.switchSection(sectionId);
    }

    nextSection() {
        const currentIndex = this.sections.findIndex(s => s.id === this.activeSection);
        if (currentIndex < this.sections.length - 1) {
            this.switchSection(this.sections[currentIndex + 1].id);
            this.render();
            this.init();
            return true;
        }
        return false;
    }

    previousSection() {
        const currentIndex = this.sections.findIndex(s => s.id === this.activeSection);
        if (currentIndex > 0) {
            this.switchSection(this.sections[currentIndex - 1].id);
            this.render();
            this.init();
            return true;
        }
        return false;
    }

    getCurrentSectionIndex() {
        return this.sections.findIndex(s => s.id === this.activeSection);
    }

    getSectionCount() {
        return this.sections.length;
    }
}

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