/**
 * Chess Podium admin: tab switching and form cp_tab hidden field.
 *
 * @package Chess_Podium
 */
(function() {
    var c = document.querySelector('.cp-admin-tabs');
    if (!c) return;
    var btns = c.querySelectorAll('.cp-tab-btn');
    var panels = c.querySelectorAll('.cp-tab-panel');
    btns.forEach(function(b) {
        b.addEventListener('click', function() {
            var t = this.getAttribute('data-tab');
            btns.forEach(function(x) { x.classList.remove('cp-tab-active'); });
            panels.forEach(function(p) {
                p.classList.toggle('cp-tab-active', p.getAttribute('data-panel') === t);
            });
            this.classList.add('cp-tab-active');
            if (window.history && window.history.replaceState) {
                var u = new URL(window.location.href);
                u.searchParams.set('cp_tab', t);
                window.history.replaceState({}, '', u.toString());
            }
        });
    });
    c.querySelectorAll('form').forEach(function(f) {
        f.addEventListener('submit', function() {
            var activeBtn = c.querySelector('.cp-tab-btn.cp-tab-active');
            var tab = activeBtn ? activeBtn.getAttribute('data-tab') : (new URL(window.location.href).searchParams.get('cp_tab') || 'overview');
            if (!f.querySelector('input[name="cp_tab"]')) {
                var inp = document.createElement('input');
                inp.type = 'hidden';
                inp.name = 'cp_tab';
                inp.value = tab;
                f.appendChild(inp);
            }
        });
    });
})();
