document.addEventListener('DOMContentLoaded', function() {
    var wrap = document.querySelector('.ciboost-admin-wrap');
    var header = document.querySelector('.ciboost-admin-header');
    var notices = document.querySelector('.ciboost-admin-notices');
    var content = document.querySelector('#wpbody-content');

    if (!header || !notices) {
        return;
    }

    header.querySelectorAll('.notice, .updated, .error').forEach(function(notice) {
        notices.appendChild(notice);
    });

    if (wrap && content) {
        Array.prototype.slice.call(content.children).forEach(function(element) {
            if (element === wrap) {
                return;
            }

            if (
                wrap.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_PRECEDING &&
                element.matches &&
                element.matches('.notice, .updated, .error')
            ) {
                notices.appendChild(element);
            }
        });
    }

    if (!notices.children.length) {
        notices.style.display = 'none';
    }

    var tabs = document.querySelectorAll('.ciboost-tab');
    var panels = document.querySelectorAll('.ciboost-tab-panel');
    var compressionPanel = document.querySelector('.ciboost-compression-panel');
    var submitBtn = document.querySelector('.ciboost-settings-card .submit');
    var isFreeUser = !!(window.ciboostAdmin && window.ciboostAdmin.isFreeUser);

    function activateTab(tabName) {
        tabs.forEach(function(tab) {
            tab.classList.toggle('active', tab.getAttribute('data-tab') === tabName);
        });

        panels.forEach(function(panel) {
            panel.classList.toggle('active', panel.getAttribute('data-panel') === tabName);
        });

        if (compressionPanel) {
            compressionPanel.classList.toggle('active', tabName === 'pro');
        }

        if (submitBtn && isFreeUser) {
            submitBtn.style.display = (tabName === 'pro') ? 'none' : '';
        }
    }

    tabs.forEach(function(tab) {
        tab.addEventListener('click', function() {
            var tabName = this.getAttribute('data-tab');
            activateTab(tabName);
            history.replaceState(null, '', '#' + tabName);

            try {
                localStorage.setItem('ciboost_active_tab', tabName);
            } catch (error) {}
        });
    });

    var hash = window.location.hash.replace('#', '');
    var savedTab = '';

    try {
        savedTab = localStorage.getItem('ciboost_active_tab') || '';
    } catch (error) {}

    var restoreTab = hash || savedTab;

    if (restoreTab && document.querySelector('.ciboost-tab[data-tab="' + restoreTab + '"]')) {
        activateTab(restoreTab);
    }
});
