/**
 * Blog Over Customizer Tabs Control JavaScript
 * 
 * Handles switching between General and Design tabs within a Customizer section.
 */
(function ($) {
    'use strict';

    wp.customize.controlConstructor["blog-over-tabs"] = wp.customize.Control.extend({
        ready: function () {
            var control = this;
            var $container = control.container;
            var sectionId = control.section();

            // Get initial state from localStorage (persists across page loads)
            var storageKey = 'blog_over_tab_' + sectionId;
            var activeTab = localStorage.getItem(storageKey) || 'general';

            var $buttons = $container.find('.blog-over-tab-btn');

            // Apply initial state to buttons
            $buttons.removeClass('active');
            $buttons.filter('[data-tab="' + activeTab + '"]').addClass('active');

            // Apply initial state to section container
            // We need a slight delay to ensure the section container is fully initialized
            setTimeout(function() {
                control.toggleControls(activeTab);
            }, 100);

            // Handle tab clicks
            $buttons.on('click', function (e) {
                e.preventDefault();
                var $btn = $(this);
                
                if ($btn.hasClass('active')) {
                    return; // Already active
                }

                var tab = $btn.data('tab');
                
                // Update buttons
                $buttons.removeClass('active');
                $btn.addClass('active');

                // Save state
                localStorage.setItem(storageKey, tab);
                
                // Toggle section class
                control.toggleControls(tab);
            });
        },

        /**
         * Toggles the CSS class on the Customizer section container.
         * Actual showing/hiding is handled purely by CSS using !important to prevent 
         * conflicts with active_callbacks.
         */
        toggleControls: function (activeTab) {
            var control = this;
            
            // Find the closest UL which holds all controls in this section
            var $sectionContainer = control.container.closest('ul');
            
            if (!$sectionContainer.length) {
                return;
            }

            // Remove old states
            $sectionContainer.removeClass('blog-over-section-tab-general blog-over-section-tab-design');
            
            // Add new state
            $sectionContainer.addClass('blog-over-section-tab-' + activeTab);
        }
    });
})(jQuery);
