(function($){
    'use strict';

    $(document).ready(function(){
        var $nav = $('.ns-settings-tabs-nav');
        if ( !$nav.length ) return;

        $nav.on('click', '.ns-tab-button', function(){
            var $btn = $(this);
            var tab = $btn.data('tab');
            $nav.find('.ns-tab-button').removeClass('ns-tab-active').attr('aria-selected','false');
            $btn.addClass('ns-tab-active').attr('aria-selected','true');

            var $content = $btn.closest('.ns-settings-tabs').find('.ns-settings-tab-pane');
            $content.removeClass('ns-settings-tab-active').hide();
            $content.filter('[data-tab="' + tab + '"]').addClass('ns-settings-tab-active').fadeIn(160);
            // Update hidden inputs so server can preserve subtab after post
            // Update both the nearest form and any global hidden fields in header/forms
            var $form = $btn.closest('.ns-settings-tabs').closest('form');
            if ( $form.length ) {
                $form.find('input[name="newssync_current_tab"]').val('settings');
                $form.find('input[name="newssync_current_subtab"]').val(tab);
            }
            // Also update any global inputs (e.g. language/clear-cache forms in header)
            $('input[name="newssync_current_tab"]').val('settings');
            $('input[name="newssync_current_subtab"]').val(tab);
        });

        // Ensure initial state: only first pane visible
        $('.ns-settings-tabs').each(function(){
            var $wrap = $(this);
            var $panes = $wrap.find('.ns-settings-tab-pane');
            $panes.hide();
            $panes.filter('.ns-settings-tab-active').show();
            // Initialize hidden fields according to active pane (also update global inputs)
            var $form = $wrap.closest('form');
            var activeTab = 'default';
            if ( $form.length ) {
                var $active = $panes.filter('.ns-settings-tab-active');
                activeTab = $active.length ? $active.data('tab') : 'default';
                $form.find('input[name="newssync_current_tab"]').val('settings');
                $form.find('input[name="newssync_current_subtab"]').val(activeTab);
            }
            // Update global inputs as well (header forms)
            $('input[name="newssync_current_tab"]').val('settings');
            $('input[name="newssync_current_subtab"]').val(activeTab);
        });
    });
})(jQuery);