// Lite tabs
const initTabs = () => {
    const tabContainers = document.querySelectorAll('.tabs');

    for (const tabs of tabContainers) {
        const settings = {
            borders: false,
            boxed: false,
            height: 'auto',
            hideHash: true,
            hashTag: true,
            selectedTab: 1,
            width: 500
        };

        // define key variables
        const tabLinks = tabs.querySelectorAll('.tab-nav__link');
        const tabContents = tabs.querySelectorAll('.tab-content .tab');

        if (!(tabLinks.length && tabContents.length)) return;

        for (const tabLink of tabLinks) {
            const selectedContent = document.querySelector(tabLink.getAttribute('href'));
            if (!selectedContent) return;

            tabLink.addEventListener('click', (e) => {
                const currentLink = tabLink;

                for (const tabContent of tabContents) {
                    tabContent.classList.remove('tab--selected');
                    selectedContent.classList.add('tab--selected');
                }

                // defaults: add selected class to tab
                for (const tabLink of tabLinks) {
                    tabLink.classList.remove('tab-nav__link--selected');
                    currentLink.classList.add('tab-nav__link--selected');
                }

                // option: hide hash change
                if (settings.hideHash) {
                    e.preventDefault();
                }
            });
        }

        // If hash tag..
        const hash = window.location.hash.substring(1);
        if (hash) {
            const link = document.querySelector('[href="#' + hash + '"]');
            if (link) {
                link.dispatchEvent(new Event('click'));
            }
        } else if (tabLinks.length) {
            tabs.querySelector('.tab-content .tab').classList.add('tab--selected');
        }

        // switch tabs on hash change
        window.addEventListener('hashchange', (e) => {
            const hash = window.location.hash.substring(1);
            if (hash) {
                const link = document.querySelector('[href="#' + hash + '"]');
                if (link) {
                    link.dispatchEvent(new Event('click'));
                }
            }
        });
    };
}

export { initTabs };
