/**
 * Customizer Panel Script
 * 
 * Handles two-way communication between the Customizer panel and preview:
 * 1. Receives focus requests from preview (when clicking edit icons)
 * 2. Scrolls preview directly when clicking section in panel
 *
 * @package Paws_And_Care
 * @since 3.0.1
 */

(function (wp, $) {
    'use strict';

    // Map of section IDs to their corresponding HTML section classes/IDs
    var sectionToElementMap = {
        'paws_and_care_slider': '.slider-section',
        'paws_and_care_about': '.about-section',
        'paws_and_care_services': '.services-section',
        'paws_and_care_portfolio': '.portfolio-section',
        'paws_and_care_testimonials': '.testimonials-section',
        'paws_and_care_pricing': '.pricing-section',
        'paws_and_care_team': '.team-section',
        'paws_and_care_cta': '.cta-section',
        'paws_and_care_clients': '.clients-section',
        'paws_and_care_blog': '.blog-section'
    };

    function scrollPreviewTo(elementSelector) {
        var previewWindow = wp.customize.previewer.targetWindow();

        if (previewWindow && previewWindow.jQuery) {
            var $target = previewWindow.jQuery(elementSelector);

            if ($target.length) {
                previewWindow.jQuery('html, body').animate({
                    scrollTop: $target.offset().top - 50
                }, 500);
            }
        }
    }

    // Wait for Customizer to be ready
    wp.customize.bind('ready', function () {

        // Listen for focus-section messages from preview (edit icon clicks)
        wp.customize.previewer.bind('focus-section', function (sectionId) {

            if (sectionId && wp.customize.section(sectionId)) {
                // Focus on the section (this expands the panel and scrolls to it)
                wp.customize.section(sectionId).focus();
            } else {
                // Try as a panel ID if section doesn't exist
                if (wp.customize.panel(sectionId)) {
                    wp.customize.panel(sectionId).focus();
                }
            }

        });

        // Listen for section expand events and scroll preview directly
        $.each(sectionToElementMap, function (sectionId, elementSelector) {
            var section = wp.customize.section(sectionId);
            if (section) {
                section.expanded.bind(function (isExpanded) {
                    if (isExpanded) {
                        // Small delay to ensure preview is ready
                        setTimeout(function () {
                            scrollPreviewTo(elementSelector);
                        }, 100);
                    }
                });
            }
        });

    });

})(wp, jQuery);


