(function() {
    function activateTab(id) {
        const tabs = document.querySelectorAll('.iccb-tabs .nav-tab');
        const panels = document.querySelectorAll('.iccb-tab-panel');

        tabs.forEach((tab) => {
            const active = tab.getAttribute('href') === `#${id}`;
            tab.classList.toggle('nav-tab-active', active);
            tab.setAttribute('aria-selected', active ? 'true' : 'false');
        });

        panels.forEach((panel) => {
            if (panel.id === id) {
                panel.removeAttribute('hidden');
                panel.classList.add('is-active');
            } else {
                panel.setAttribute('hidden', 'hidden');
                panel.classList.remove('is-active');
            }
        });

        try {
            localStorage.setItem('iccbSettingsActiveTab', id);
        } catch (error) {}
    }

    document.addEventListener('click', (event) => {
        const tab = event.target.closest('.iccb-tabs .nav-tab');
        if (!tab) {
            return;
        }

        event.preventDefault();
        const id = tab.getAttribute('href').replace('#', '');
        activateTab(id);
        if (history.replaceState) {
            history.replaceState(null, '', `#${id}`);
        }
    });

    document.addEventListener('DOMContentLoaded', () => {
        const hash = (location.hash || '').replace('#', '');
        let saved = '';
        try {
            saved = localStorage.getItem('iccbSettingsActiveTab') || '';
        } catch (error) {}

        const first = document.querySelector('.iccb-tab-panel')?.id || 'tab-appearance';
        activateTab(hash || saved || first);
    });
})();
