/**
 * Blog Over Customizer Controls - Dynamic Archive Redirect Handler
 * 
 * Listens for redirect messages from preview and navigates to:
 * - Archive Settings if Archive Override is ON
 * - Blog Settings if Archive Override is OFF
 */
(function ($) {
    'use strict';

    wp.customize.bind('ready', function () {

        // Listen for redirect messages from preview
        wp.customize.previewer.bind('blog-over-archive-redirect', function (data) {

            // Get the archive override setting value
            var archiveOverride = wp.customize('blog_over_archive_override').get();

            // Map blog partials to their archive equivalents
            var sectionMap = {
                'Blog_Over_entry_elements': {
                    archive: 'blog_over_archive_section',
                    blog: 'Blog_Over_section'
                },
                'Blog_Over_entry_meta': {
                    archive: 'blog_over_archive_section',
                    blog: 'Blog_Over_section'
                },
                'Blog_Over_style': {
                    archive: 'blog_over_archive_section',
                    blog: 'Blog_Over_section'
                },
                'Blog_Over_layout': {
                    archive: 'blog_over_archive_section',
                    blog: 'Blog_Over_section'
                }
            };

            var mapping = sectionMap[data.partial];
            if (!mapping) {
                return;
            }

            // Determine target section based on override state
            var targetSection = archiveOverride ? mapping.archive : mapping.blog;

            // Focus the appropriate section
            var section = wp.customize.section(targetSection);
            if (section) {
                section.expand();

                // If archive override is ON, also highlight the specific control
                if (archiveOverride) {
                    var controlMap = {
                        'Blog_Over_entry_elements': 'blog_over_archive_entry_elements',
                        'Blog_Over_entry_meta': 'blog_over_archive_entry_meta',
                        'Blog_Over_style': 'blog_over_archive_style',
                        'Blog_Over_layout': 'blog_over_archive_layout'
                    };

                    var targetControl = controlMap[data.partial];
                    if (targetControl) {
                        var control = wp.customize.control(targetControl);
                        if (control) {
                            control.focus();
                        }
                    }
                }
            }
        });
    });

})(jQuery);
