/**
 * 自定义器预览脚本
 * 用于在自定义器中实时预览Banner和Futures更改
 */

(function($) {
    'use strict';

    // 横幅图片更改预览
    for (let i = 1; i <= 5; i++) {
        wp.customize('banner_image_' + i, function(value) {
            value.bind(function(newval) {
                // 刷新页面以显示新的Banner图片
                wp.customize.preview.send('refresh');
            });
        });

        // 横幅内容更改预览
        wp.customize('banner_content_' + i, function(value) {
            value.bind(function(newval) {
                $('.nenghui-banner .banner-slide:nth-child(' + i + ') .banner-text-content').html(newval);
            });
        });

        // 横幅按钮文字更改预览
        wp.customize('banner_button_text_' + i, function(value) {
            value.bind(function(newval) {
                $('.nenghui-banner .banner-slide:nth-child(' + i + ') .banner-btn').text(newval);
            });
        });

        // 横幅按钮链接更改预览
        wp.customize('banner_button_url_' + i, function(value) {
            value.bind(function(newval) {
                $('.nenghui-banner .banner-slide:nth-child(' + i + ') .banner-btn').attr('href', newval);
            });
        });
    }

    // 横幅高度更改预览
    wp.customize('banner_height', function(value) {
        value.bind(function(newval) {
            // 处理高度值，确保包含单位
            var height = newval;
            if (/^\d+$/.test(newval)) {
                height = newval + 'px';
            }
            // 验证格式
            if (!/^\d+(\.\d+)?(px|vh)$/.test(height)) {
                height = '500px';
            }
            $('.nenghui-banner').css('height', height);
            $('.nenghui-banner .banner-slide').css('height', height);
        });
    });

    // 横幅自动播放设置更改预览
    wp.customize('banner_autoplay', function(value) {
        value.bind(function(newval) {
            // 刷新页面以应用新的自动播放设置
            wp.customize.preview.send('refresh');
        });
    });

    // 横幅自动播放间隔更改预览
    wp.customize('banner_autoplay_delay', function(value) {
        value.bind(function(newval) {
            // 刷新页面以应用新的播放间隔
            wp.customize.preview.send('refresh');
        });
    });

    // 横幅遮罩开关更改预览
    wp.customize('banner_overlay_enabled', function(value) {
        value.bind(function(newval) {
            if (newval) {
                // 显示遮罩
                $('.nenghui-banner .banner-overlay').show();
            } else {
                // 隐藏遮罩
                $('.nenghui-banner .banner-overlay').hide();
            }
        });
    });

    // 横幅纯图模式开关更改预览
    wp.customize('banner_image_only_mode', function(value) {
        value.bind(function(newval) {
            if (newval) {
                // 隐藏文字和按钮内容
                $('.nenghui-banner .banner-content').hide();
            } else {
                // 显示文字和按钮内容
                $('.nenghui-banner .banner-content').show();
            }
        });
    });

    // 横幅移动端显示控制更改预览
    wp.customize('banner_show_on_mobile', function(value) {
        value.bind(function(newval) {
            if (!newval) {
                // 移动端隐藏
                $('.nenghui-banner').addClass('hide-on-mobile');
            } else {
                // 移动端显示
                $('.nenghui-banner').removeClass('hide-on-mobile');
            }
        });
    });

    // 横幅左右切换按钮开关更改预览
    wp.customize('banner_navigation_enabled', function(value) {
        value.bind(function(newval) {
            if (newval) {
                // 显示切换按钮
                $('.nenghui-banner .banner-nav-prev, .nenghui-banner .banner-nav-next').show();
            } else {
                // 隐藏切换按钮
                $('.nenghui-banner .banner-nav-prev, .nenghui-banner .banner-nav-next').hide();
            }
        });
    });

    // 横幅数量更改预览
    wp.customize('banner_count', function(value) {
        value.bind(function(newval) {
            // 刷新页面以重新生成Banner结构
            wp.customize.preview.send('refresh');
        });
    });

    // ========== 特色功能区块预览功能 ==========
    
    // 特色功能主标题更改预览
    wp.customize('futures_title', function(value) {
        value.bind(function(newval) {
            $('.nenghui-futures .futures-title').text(newval);
        });
    });

    // 特色功能背景图片更改预览
    wp.customize('futures_bg_image', function(value) {
        value.bind(function(newval) {
            if (newval) {
                $('.nenghui-futures').css('background-image', 'url(' + newval + ')');
            } else {
                $('.nenghui-futures').css('background-image', 'none');
            }
        });
    });

    // 特色功能按钮文字更改预览
    wp.customize('futures_button_text', function(value) {
        value.bind(function(newval) {
            $('.nenghui-futures .futures-btn').text(newval);
        });
    });

    // 特色功能按钮链接更改预览
    wp.customize('futures_button_url', function(value) {
        value.bind(function(newval) {
            $('.nenghui-futures .futures-btn').attr('href', newval);
        });
    });

    // 特色功能项目预览
    for (let i = 1; i <= 5; i++) {
        // 功能图标更改预览
        wp.customize('futures_item_' + i + '_icon', function(value) {
            value.bind(function(newval) {
                if (newval) {
                    $('.nenghui-futures .futures-item:nth-child(' + i + ') .futures-icon img').attr('src', newval);
                    $('.nenghui-futures .futures-item:nth-child(' + i + ')').show();
                } else {
                    $('.nenghui-futures .futures-item:nth-child(' + i + ')').hide();
                }
            });
        });

        // 功能标题更改预览
        wp.customize('futures_item_' + i + '_title', function(value) {
            value.bind(function(newval) {
                $('.nenghui-futures .futures-item:nth-child(' + i + ') .futures-item-title').text(newval);
            });
        });


    }

    // ========== 页面标题横幅区块预览功能 ==========
    
    // 页面标题横幅主标题更改预览
    wp.customize('banner_title_main_title', function(value) {
        value.bind(function(newval) {
            $('.nenghui-banner-title .banner-title').text(newval);
        });
    });

    // 页面标题横幅描述更改预览
    wp.customize('banner_title_description', function(value) {
        value.bind(function(newval) {
            if (newval && newval.trim() !== '') {
                $('.nenghui-banner-title .banner-description').text(newval).show();
            } else {
                $('.nenghui-banner-title .banner-description').hide();
            }
        });
    });

    // 页面标题横幅背景图片更改预览
    wp.customize('banner_title_bg_image', function(value) {
        value.bind(function(newval) {
            const bannerElement = $('.nenghui-banner-title');
            const bannerImage = bannerElement.find('.banner-image');
            
            if (newval && newval.trim() !== '') {
                // 设置新的背景图片
                bannerImage.css('background-image', 'url(' + newval + ')');
                bannerElement.attr('data-bg-image', newval);
                bannerElement.removeClass('no-image');
                
                // 预加载图片以检测是否有效
                const img = new Image();
                img.onload = function() {
                    bannerElement.removeClass('no-image');
                };
                img.onerror = function() {
                    bannerElement.addClass('no-image');
                };
                img.src = newval;
            } else {
                // 使用默认背景图片
                const defaultImage = bannerElement.data('default-bg') || 
                    (typeof wp !== 'undefined' && wp.customize && wp.customize.settings && wp.customize.settings.theme && wp.customize.settings.theme.template_url ? 
                        wp.customize.settings.theme.template_url + '/assets/images/about-bg.webp' : 
                        '/wp-content/themes/nenghui-energy-theme-4/assets/images/about-bg.webp');
                
                bannerImage.css('background-image', 'url(' + defaultImage + ')');
                bannerElement.attr('data-bg-image', defaultImage);
                bannerElement.removeClass('no-image');
            }
        });
    });

    // 页面标题横幅遮罩透明度更改预览
    wp.customize('banner_title_overlay_opacity', function(value) {
        value.bind(function(newval) {
            $('.nenghui-banner-title .banner-overlay').css('opacity', newval);
        });
    });
    
    // 页面标题横幅高度更改预览
    wp.customize('banner_title_height', function(value) {
        value.bind(function(newval) {
            var height = newval;
            // 处理高度值，确保包含单位
            if (/^\d+$/.test(newval)) {
                height = newval + 'px';
            }
            // 验证格式
            if (!/^\d+(\.\d+)?(px|vh|%)$/.test(height)) {
                height = '60vh';
            }
            $('.nenghui-banner-title').css('height', height);
        });
    });

    // ========== 新闻区块预览功能 ==========
    
    // 新闻标题更改预览
    wp.customize('news_title', function(value) {
        value.bind(function(newval) {
            $('.news-container .news-title').text(newval);
        });
    });



    // 新闻分类更改预览 - 需要刷新页面
    wp.customize('news_category_id', function(value) {
        value.bind(function(newval) {
            wp.customize.preview.send('refresh');
        });
    });

    // 新闻排序字段更改预览
    wp.customize('news_order_by', function(value) {
        value.bind(function(newval) {
            wp.customize.preview.send('refresh');
        });
    });

    // 新闻排序方向更改预览
    wp.customize('news_order', function(value) {
        value.bind(function(newval) {
            wp.customize.preview.send('refresh');
        });
    });

    // 新闻文章数量更改预览
    wp.customize('news_posts_count', function(value) {
        value.bind(function(newval) {
            wp.customize.preview.send('refresh');
        });
    });

    // 新闻每页文章数量更改预览
    wp.customize('news_posts_per_page', function(value) {
        value.bind(function(newval) {
            wp.customize.preview.send('refresh');
        });
    });

    // 新闻分页开关更改预览
    wp.customize('news_enable_pagination', function(value) {
        value.bind(function(newval) {
            wp.customize.preview.send('refresh');
        });
    });

    // ========== 选项卡区块预览功能 ==========
    
    // 选项卡数量更改预览
    wp.customize('tabs_count', function(value) {
        value.bind(function(newval) {
            // 刷新页面以重新生成选项卡结构
            wp.customize.preview.send('refresh');
        });
    });

    // ========== 关于我们导航区块预览功能 ==========
    
    // 关于我们导航菜单更改预览
    wp.customize('about_nav_menu_id', function(value) {
        value.bind(function(newval) {
            // 刷新页面以重新生成导航菜单
            wp.customize.preview.send('refresh');
        });
    });
    
    // 关于我们导航背景色更改预览
    wp.customize('about_nav_bg_color', function(value) {
        value.bind(function(newval) {
            $('.nenghui-about-nav').css('background-color', newval);
        });
    });
    
    // 关于我们导航文字颜色更改预览
    wp.customize('about_nav_text_color', function(value) {
        value.bind(function(newval) {
            $('.nenghui-about-nav .about-nav-link').css('color', newval);
        });
    });
    
    // 关于我们导航激活状态颜色更改预览
    wp.customize('about_nav_active_color', function(value) {
        value.bind(function(newval) {
            $('.nenghui-about-nav .about-nav-item.active .about-nav-link').css({
                'color': newval,
                'border-bottom-color': newval
            });
            $('.nenghui-about-nav .about-nav-link:hover').css('color', newval);
        });
    });
    
    // 关于我们导航样式更改预览
    wp.customize('about_nav_style', function(value) {
        value.bind(function(newval) {
            const aboutNav = $('.nenghui-about-nav');
            const navMenu = aboutNav.find('.about-nav-menu');
            
            // 移除所有样式类
            aboutNav.removeClass('nav-horizontal nav-vertical nav-dropdown');
            
            // 添加新样式类
            aboutNav.addClass('nav-' + newval);
            
            // 根据样式调整布局
            if (newval === 'vertical') {
                navMenu.css({
                    'flex-direction': 'column',
                    'align-items': 'stretch'
                });
            } else {
                navMenu.css({
                    'flex-direction': 'row',
                    'align-items': 'center'
                });
            }
        });
    });
    
    // 关于我们导航位置更改预览
    wp.customize('about_nav_position', function(value) {
        value.bind(function(newval) {
            // 刷新页面以应用新的位置设置
            wp.customize.preview.send('refresh');
        });
    });

    // 选项卡项目预览（支持最多5个选项卡）
    for (let i = 1; i <= 5; i++) {
        // 选项卡标题更改预览
        wp.customize('tab_title_' + i, function(value) {
            value.bind(function(newval) {
                const tabElement = $('.nenghui-container .nenghui-tab[data-nenghui-tab="tab-' + i + '"]');
                if (newval && newval.trim() !== '') {
                    tabElement.text(newval).show();
                } else {
                    tabElement.hide();
                }
            });
        });

        // 选项卡ID更改预览
        wp.customize('tab_id_' + i, function(value) {
            value.bind(function(newval) {
                // 刷新页面以应用新的ID
                wp.customize.preview.send('refresh');
            });
        });

        // 选项卡主标题更改预览
        wp.customize('tab_main_title_' + i, function(value) {
            value.bind(function(newval) {
                // 如果当前选项卡是激活状态，更新主标题
                const tabId = wp.customize('tab_id_' + i).get() || 'tab-' + i;
                const activeTab = $('.nenghui-container .nenghui-tab.active[data-nenghui-tab="' + tabId + '"]');
                if (activeTab.length > 0) {
                    $('.nenghui-container .main-title').html(newval);
                }
            });
        });

        // 选项卡按钮文字更改预览
        wp.customize('tab_button_text_' + i, function(value) {
            value.bind(function(newval) {
                // 如果当前选项卡是激活状态，更新按钮文字
                const tabId = wp.customize('tab_id_' + i).get() || 'tab-' + i;
                const activeTab = $('.nenghui-container .nenghui-tab.active[data-nenghui-tab="' + tabId + '"]');
                if (activeTab.length > 0) {
                    const button = $('.nenghui-container .learn-more-btn');
                    const spanElement = button.find('span:not(.arrow)');
                    if (spanElement.length > 0) {
                        spanElement.text(newval);
                    } else {
                        // 如果没有span元素，直接更新按钮文字（保留箭头）
                        const arrowHtml = button.find('.arrow').length > 0 ? button.find('.arrow')[0].outerHTML : '';
                        button.html('<span>' + newval + '</span><span class="arrow">→</span>');
                    }
                }
            });
        });

        // 选项卡按钮链接更改预览
        wp.customize('tab_button_url_' + i, function(value) {
            value.bind(function(newval) {
                // 如果当前选项卡是激活状态，更新按钮链接
                const tabId = wp.customize('tab_id_' + i).get() || 'tab-' + i;
                const activeTab = $('.nenghui-container .nenghui-tab.active[data-nenghui-tab="' + tabId + '"]');
                if (activeTab.length > 0) {
                    $('.nenghui-container .learn-more-btn').attr('href', newval);
                }
            });
        });

        // 选项卡图片更改预览
        wp.customize('tab_image_' + i, function(value) {
            value.bind(function(newval) {
                // 如果当前选项卡是激活状态，更新图片
                const tabId = wp.customize('tab_id_' + i).get() || 'tab-' + i;
                const activeTab = $('.nenghui-container .nenghui-tab.active[data-nenghui-tab="' + tabId + '"]');
                if (activeTab.length > 0 && newval) {
                    $('.nenghui-container .tab-image img').attr('src', newval);
                }
            });
        });

        // 选项卡图片替代文字更改预览
        wp.customize('tab_image_alt_' + i, function(value) {
            value.bind(function(newval) {
                // 如果当前选项卡是激活状态，更新图片alt属性
                const tabId = wp.customize('tab_id_' + i).get() || 'tab-' + i;
                const activeTab = $('.nenghui-container .nenghui-tab.active[data-nenghui-tab="' + tabId + '"]');
                if (activeTab.length > 0) {
                    $('.nenghui-container .tab-image img').attr('alt', newval);
                }
            });
        });
    }

    // 监听选项卡切换事件，确保预览功能正常工作
    $(document).on('click', '.nenghui-container .nenghui-tab', function() {
        // 延迟一点时间确保DOM更新完成
        setTimeout(function() {
            // 触发当前激活选项卡的所有设置重新应用
            const activeTab = $('.nenghui-container .nenghui-tab.active');
            if (activeTab.length > 0) {
                const tabType = activeTab.attr('data-nenghui-tab');
                // 优化：减少循环范围，只检查实际存在的选项卡
                const maxTabs = wp.customize('tabs_count') ? wp.customize('tabs_count').get() : 5;
                for (let i = 1; i <= Math.min(maxTabs, 10); i++) {
                    const tabIdControl = wp.customize('tab_id_' + i);
                    if (!tabIdControl) continue; // 跳过不存在的控件
                    
                    const tabId = tabIdControl.get() || 'tab-' + i;
                    if (tabId === tabType) {
                        // 重新应用当前选项卡的设置
                        const mainTitleControl = wp.customize('tab_main_title_' + i);
                        const buttonTextControl = wp.customize('tab_button_text_' + i);
                        const buttonUrlControl = wp.customize('tab_button_url_' + i);
                        const imageControl = wp.customize('tab_image_' + i);
                        
                        const mainTitle = mainTitleControl ? mainTitleControl.get() : '';
                        const buttonText = buttonTextControl ? buttonTextControl.get() : '了解更多';
                        const buttonUrl = buttonUrlControl ? buttonUrlControl.get() : '#';
                        let image = imageControl ? imageControl.get() : '';
                        const imageAlt = wp.customize('tab_image_alt_' + i) ? wp.customize('tab_image_alt_' + i).get() : '';
                        
                        // 如果没有图片，使用默认占位图片
                        if (!image) {
                            image = '/wp-content/themes/nenghui-energy-theme-1.0/assets/images/NaN-img.png';
                        }
                        
                        // 更新内容
                        if (mainTitle) $('.nenghui-container .main-title').html(mainTitle);
                        if (buttonText) {
                            const button = $('.nenghui-container .learn-more-btn');
                            const spanElement = button.find('span:not(.arrow)');
                            if (spanElement.length > 0) {
                                spanElement.text(buttonText);
                            } else {
                                button.html('<span>' + buttonText + '</span><span class="arrow">→</span>');
                            }
                        }
                        if (buttonUrl) $('.nenghui-container .learn-more-btn').attr('href', buttonUrl);
                        if (image) $('.nenghui-container .tab-image img').attr('src', image);
                        if (imageAlt) $('.nenghui-container .tab-image img').attr('alt', imageAlt);
                        
                        break;
                    }
                }
            }
        }, 100);
    });

    // ========== 关于公司区块预览功能 ==========
    
    // 关于公司主标题更改预览
    wp.customize('about_company_title', function(value) {
        value.bind(function(newval) {
            $('.about-company-section .about-company-title').text(newval);
        });
    });

    // 关于公司描述更改预览
    wp.customize('about_company_description', function(value) {
        value.bind(function(newval) {
            $('.about-company-section .about-company-description p').html(newval);
        });
    });

    // 关于公司第二段描述更改预览
    wp.customize('about_company_description_2', function(value) {
        value.bind(function(newval) {
            $('.about-company-section .about-company-description-2 p').html(newval);
        });
    });

    // 关于公司右侧图片更改预览
    wp.customize('about_company_image', function(value) {
        value.bind(function(newval) {
            if (newval) {
                $('.about-company-section .about-company-image img').attr('src', newval);
            }
        });
    });

    // 关于公司统计项目预览
    for (let i = 1; i <= 4; i++) {
        // 统计数字更改预览
        wp.customize('about_company_stat_' + i + '_number', function(value) {
            value.bind(function(newval) {
                $('.about-company-section .stat-item:nth-child(' + i + ') .stat-number').text(newval);
            });
        });

        // 统计标签更改预览
        wp.customize('about_company_stat_' + i + '_label', function(value) {
            value.bind(function(newval) {
                $('.about-company-section .stat-item:nth-child(' + i + ') .stat-label').text(newval);
            });
        });

        // 统计图标更改预览
        wp.customize('about_company_stat_' + i + '_icon', function(value) {
            value.bind(function(newval) {
                if (newval) {
                    $('.about-company-section .stat-item:nth-child(' + i + ') .stat-icon img').attr('src', newval);
                }
            });
        });
    }

    // ========== 发展历程区块预览功能 ==========
    
    // 发展历程主标题更改预览
    wp.customize('development_history_title', function(value) {
        value.bind(function(newval) {
            $('.development-history-section .development-history-title').text(newval);
        });
    });

    // 发展历程背景图片更改预览
    wp.customize('development_history_bg_image', function(value) {
        value.bind(function(newval) {
            if (newval) {
                $('.development-history-section .development-history-bg').css('background-image', 'url(' + newval + ')');
            }
        });
    });

    // 发展历程年份数量更改预览
    wp.customize('development_history_items_count', function(value) {
        value.bind(function(newval) {
            // 年份数量变化时刷新页面以重新生成项目
            wp.customize.preview.send('refresh');
        });
    });

    // 发展历程各年份项目预览
    // 动态获取年份数量并为每个项目添加预览功能
    function addDevelopmentHistoryItemPreview(itemIndex) {
        // 年份更改预览
        wp.customize('development_history_item_' + itemIndex + '_year', function(value) {
            value.bind(function(newval) {
                const timelineItem = $('.development-history-section .timeline-item').eq(itemIndex - 1);
                if (timelineItem.length > 0) {
                    timelineItem.find('.timeline-year').text(newval);
                    timelineItem.attr('data-year', newval);
                    
                    // 如果这是当前激活的项目，也更新右侧显示
                    if (timelineItem.hasClass('active')) {
                        $('.development-history-section .display-year').text(newval);
                    }
                }
            });
        });

        // 描述更改预览
        wp.customize('development_history_item_' + itemIndex + '_description', function(value) {
            value.bind(function(newval) {
                const timelineItem = $('.development-history-section .timeline-item').eq(itemIndex - 1);
                if (timelineItem.length > 0) {
                    const descriptionElement = timelineItem.find('.timeline-description');
                    timelineItem.attr('data-description', newval);
                    
                    if (newval && newval.trim() !== '') {
                        if (descriptionElement.length === 0) {
                            timelineItem.find('.timeline-content').append('<div class="timeline-description">' + newval + '</div>');
                        } else {
                            descriptionElement.text(newval);
                        }
                    } else {
                        descriptionElement.remove();
                    }
                    
                    // 如果这是当前激活的项目，也更新右侧显示
                    if (timelineItem.hasClass('active')) {
                        const displayDescription = $('.development-history-section .display-description');
                        if (newval && newval.trim() !== '') {
                            if (displayDescription.length === 0) {
                                $('.development-history-section .development-history-display').append('<div class="display-description">' + newval + '</div>');
                            } else {
                                displayDescription.text(newval).show();
                            }
                        } else {
                            displayDescription.hide();
                        }
                    }
                }
            });
        });

        // 激活状态更改预览
        wp.customize('development_history_item_' + itemIndex + '_active', function(value) {
            value.bind(function(newval) {
                const timelineItem = $('.development-history-section .timeline-item').eq(itemIndex - 1);
                if (timelineItem.length > 0) {
                    if (newval) {
                        // 移除其他项目的激活状态
                        $('.development-history-section .timeline-item').removeClass('active');
                        // 激活当前项目
                        timelineItem.addClass('active');
                        
                        // 更新右侧显示
                        const year = timelineItem.attr('data-year') || '';
                        const description = timelineItem.attr('data-description') || '';
                        
                        $('.development-history-section .display-year').text(year);
                        
                        const displayDescription = $('.development-history-section .display-description');
                        if (description && description.trim() !== '') {
                            if (displayDescription.length === 0) {
                                $('.development-history-section .development-history-display').append('<div class="display-description">' + description + '</div>');
                            } else {
                                displayDescription.text(description).show();
                            }
                        } else {
                            displayDescription.hide();
                        }
                    } else {
                        timelineItem.removeClass('active');
                    }
                }
            });
        });
    }

    // 为最多20个年份项目添加预览功能
    for (let i = 1; i <= 20; i++) {
        addDevelopmentHistoryItemPreview(i);
    }

    // ========== 联系地图区块预览功能 ==========
    
    // 联系地图区块标题更改预览
    wp.customize('contact_map_title', function(value) {
        value.bind(function(newval) {
            $('.nenghui-contact-map .contact-map-title').text(newval);
            if (newval && newval.trim() !== '') {
                $('.nenghui-contact-map .contact-map-header').show();
            } else {
                $('.nenghui-contact-map .contact-map-header').hide();
            }
        });
    });

    // 办公地址更改预览
    wp.customize('contact_office_address', function(value) {
        value.bind(function(newval) {
            const addressItem = $('.nenghui-contact-map .contact-item').eq(0);
            if (newval && newval.trim() !== '') {
                addressItem.find('.contact-value').html(newval.replace(/\n/g, '<br>'));
                addressItem.show();
            } else {
                addressItem.hide();
            }
        });
    });

    // 电话/手机更改预览
    wp.customize('contact_phone', function(value) {
        value.bind(function(newval) {
            const phoneItem = $('.nenghui-contact-map .contact-item').eq(1);
            if (newval && newval.trim() !== '') {
                const cleanPhone = newval.replace(/[\s\-\(\)]/g, '');
                phoneItem.find('.contact-value a').attr('href', 'tel:' + cleanPhone).text(newval);
                phoneItem.show();
            } else {
                phoneItem.hide();
            }
        });
    });

    // 邮箱更改预览
    wp.customize('contact_email', function(value) {
        value.bind(function(newval) {
            const emailItem = $('.nenghui-contact-map .contact-item').eq(2);
            if (newval && newval.trim() !== '') {
                emailItem.find('.contact-value a').attr('href', 'mailto:' + newval).text(newval);
                emailItem.show();
            } else {
                emailItem.hide();
            }
        });
    });

    // 地图嵌入代码更改预览
    wp.customize('contact_map_embed_code', function(value) {
        value.bind(function(newval) {
            const mapContainer = $('.nenghui-contact-map .contact-map-container');
            if (newval && newval.trim() !== '') {
                mapContainer.html(newval);
            } else {
                mapContainer.html('<div class="map-placeholder" style="height: 100%; background-color: #e9ecef; display: flex; align-items: center; justify-content: center; border-radius: 8px;"><p style="color: #6c757d; text-align: center; margin: 0;">请在自定义器中设置地图嵌入代码<br><small>联系地图设置 → 地图设置 → 地图嵌入代码</small></p></div>');
            }
        });
    });

    // 地图高度更改预览
    wp.customize('contact_map_height', function(value) {
        value.bind(function(newval) {
            let height = newval;
            // 验证高度格式
            if (!/^\d+(\.\d+)?(px|vh|%)$/.test(height)) {
                height = '400px';
            }
            $('.nenghui-contact-map .contact-map-container').css('height', height);
        });
    });

    // 背景颜色更改预览
    wp.customize('contact_bg_color', function(value) {
        value.bind(function(newval) {
            $('.nenghui-contact-map').css('background-color', newval);
        });
    });

    // 文字颜色更改预览
    wp.customize('contact_text_color', function(value) {
        value.bind(function(newval) {
            $('.nenghui-contact-map').css('color', newval);
        });
    });

    // 图标颜色更改预览
    wp.customize('contact_icon_color', function(value) {
        value.bind(function(newval) {
            $('.nenghui-contact-map .contact-icon').css('color', newval);
        });
    });

    // 产品Banner预览功能
    // 产品数量更改预览
    wp.customize('products_banner_count', function(value) {
        value.bind(function(newval) {
            wp.customize.preview.send('refresh');
        });
    });

    // 自动播放设置更改预览
    wp.customize('products_banner_autoplay', function(value) {
        value.bind(function(newval) {
            var carousel = document.querySelector('.products-carousel');
            if (carousel) {
                carousel.setAttribute('data-autoplay', newval ? 'true' : 'false');
                // 重新初始化轮播
                wp.customize.preview.send('refresh');
            }
        });
    });

    // 自动播放延迟更改预览
    wp.customize('products_banner_autoplay_delay', function(value) {
        value.bind(function(newval) {
            var carousel = document.querySelector('.products-carousel');
            if (carousel) {
                carousel.setAttribute('data-delay', newval);
                // 重新初始化轮播
                wp.customize.preview.send('refresh');
            }
        });
    });

    // 为每个产品添加预览功能
    for (let i = 1; i <= 7; i++) {
        // 产品图片更改预览
        wp.customize('products_banner_image_' + i, function(value) {
            value.bind(function(newval) {
                wp.customize.preview.send('refresh');
            });
        });

        // 产品标题更改预览
        wp.customize('products_banner_title_' + i, function(value) {
            value.bind(function(newval) {
                var titleElement = $('.nenghui-products-banner .product-slide:nth-child(' + i + ') .product-title');
                if (titleElement.length) {
                    titleElement.text(newval);
                } else {
                    wp.customize.preview.send('refresh');
                }
            });
        });

        // 产品描述更改预览
        wp.customize('products_banner_description_' + i, function(value) {
            value.bind(function(newval) {
                var descElement = $('.nenghui-products-banner .product-slide:nth-child(' + i + ') .product-description');
                if (descElement.length) {
                    descElement.text(newval);
                } else {
                    wp.customize.preview.send('refresh');
                }
            });
        });

        // 产品链接更改预览
        wp.customize('products_banner_link_' + i, function(value) {
            value.bind(function(newval) {
                var linkElement = $('.nenghui-products-banner .product-slide:nth-child(' + i + ') .product-link');
                if (linkElement.length) {
                    linkElement.attr('href', newval);
                } else {
                    wp.customize.preview.send('refresh');
                }
            });
        });
    }

    // ===== Black Maps 地图设置实时预览 =====
    
    // 地图背景颜色更改预览
    wp.customize('black_maps_bg_color', function(value) {
        value.bind(function(newval) {
            $('.black-maps-wrapper').css('background-color', newval);
            // 同时更新ECharts配置中的背景色
            updateMapBackgroundColor(newval);
        });
    });
    
    // 地图标题更改预览
    wp.customize('black_maps_title', function(value) {
        value.bind(function(newval) {
            updateMapTitle(newval);
        });
    });
    
    // 地图副标题更改预览
    wp.customize('black_maps_subtitle', function(value) {
        value.bind(function(newval) {
            updateMapSubtitle(newval);
        });
    });
    
    // 地图高度更改预览
    wp.customize('black_maps_height', function(value) {
        value.bind(function(newval) {
            $('.black-maps-wrapper').css('height', newval);
            // 触发ECharts重新调整大小
            resizeAllMaps();
        });
    });
    
    // 中国区域颜色更改预览
    wp.customize('black_maps_china_color', function(value) {
        value.bind(function(newval) {
            updateMapChinaColor(newval);
        });
    });
    
    // 目标国家颜色更改预览
    wp.customize('black_maps_target_color', function(value) {
        value.bind(function(newval) {
            updateMapTargetColor(newval);
        });
    });
    
    // 连接线颜色更改预览
    wp.customize('black_maps_line_color', function(value) {
        value.bind(function(newval) {
            updateMapLineColor(newval);
        });
    });
    
    // 自定义国家数据更改预览
    wp.customize('black_maps_countries', function(value) {
        value.bind(function(newval) {
            updateMapCountries(newval);
        });
    });
    
    // 地图更新辅助函数
    function updateMapBackgroundColor(color) {
        // 查找所有地图实例并更新背景色
        $('.black-maps-container').each(function() {
            var chartInstance = echarts.getInstanceByDom(this);
            if (chartInstance) {
                var option = chartInstance.getOption();
                option.backgroundColor = color;
                chartInstance.setOption(option);
            }
        });
    }
    
    function updateMapTitle(title) {
        $('.black-maps-container').each(function() {
            var chartInstance = echarts.getInstanceByDom(this);
            if (chartInstance) {
                var option = chartInstance.getOption();
                if (option.title && option.title[0]) {
                    option.title[0].text = title;
                    chartInstance.setOption(option);
                }
            }
        });
    }
    
    function updateMapSubtitle(subtitle) {
        $('.black-maps-container').each(function() {
            var chartInstance = echarts.getInstanceByDom(this);
            if (chartInstance) {
                var option = chartInstance.getOption();
                if (option.title && option.title[0]) {
                    option.title[0].subtext = subtitle;
                    chartInstance.setOption(option);
                }
            }
        });
    }
    
    function updateMapChinaColor(color) {
        $('.black-maps-container').each(function() {
            var chartInstance = echarts.getInstanceByDom(this);
            if (chartInstance) {
                var option = chartInstance.getOption();
                if (option.geo && option.geo[0] && option.geo[0].regions) {
                    // 查找中国区域配置并更新颜色
                    option.geo[0].regions.forEach(function(region) {
                        if (region.name === 'China') {
                            region.itemStyle.normal.areaColor = color;
                            region.itemStyle.emphasis.areaColor = color;
                        }
                    });
                    chartInstance.setOption(option);
                }
            }
        });
    }
    
    function updateMapTargetColor(color) {
        $('.black-maps-container').each(function() {
            var chartInstance = echarts.getInstanceByDom(this);
            if (chartInstance) {
                var option = chartInstance.getOption();
                if (option.geo && option.geo[0] && option.geo[0].regions) {
                    // 更新所有目标国家的颜色（除了中国）
                    option.geo[0].regions.forEach(function(region) {
                        if (region.name !== 'China') {
                            region.itemStyle.normal.areaColor = color;
                            region.itemStyle.emphasis.areaColor = color;
                        }
                    });
                    chartInstance.setOption(option);
                }
            }
        });
    }
    
    function updateMapLineColor(color) {
        $('.black-maps-container').each(function() {
            var chartInstance = echarts.getInstanceByDom(this);
            if (chartInstance) {
                var option = chartInstance.getOption();
                if (option.series) {
                    // 更新所有线条系列的颜色
                    option.series.forEach(function(series) {
                        if (series.type === 'lines' && series.lineStyle) {
                            series.lineStyle.normal.color = color;
                        }
                    });
                    chartInstance.setOption(option);
                }
            }
        });
    }
    
    function updateMapCountries(countriesJson) {
        // 当国家数据更改时，重新加载整个地图
        // 这是最简单和最可靠的方法
        wp.customize.preview.send('refresh');
    }
    
    function resizeAllMaps() {
        // 调整所有地图实例的大小
        setTimeout(function() {
            $('.black-maps-container').each(function() {
                var chartInstance = echarts.getInstanceByDom(this);
                if (chartInstance) {
                    chartInstance.resize();
                }
            });
        }, 100);
    }

    // ========== 地图设置实时预览 ==========
    
    // 地图标题预览
    wp.customize('black_maps_title', function(value) {
        value.bind(function(newval) {
            // 如果页面上有ECharts实例，更新标题
            if (typeof echarts !== 'undefined') {
                $('.black-maps-wrapper').each(function() {
                    var mapId = $(this).find('[id^="echartsMap"]').attr('id');
                    if (mapId) {
                        var chartInstance = echarts.getInstanceByDom(document.getElementById(mapId));
                        if (chartInstance) {
                            chartInstance.setOption({
                                title: {
                                    text: newval
                                }
                            });
                        }
                    }
                });
            }
        });
    });

    // 地图副标题预览
    wp.customize('black_maps_subtitle', function(value) {
        value.bind(function(newval) {
            if (typeof echarts !== 'undefined') {
                $('.black-maps-wrapper').each(function() {
                    var mapId = $(this).find('[id^="echartsMap"]').attr('id');
                    if (mapId) {
                        var chartInstance = echarts.getInstanceByDom(document.getElementById(mapId));
                        if (chartInstance) {
                            chartInstance.setOption({
                                title: {
                                    subtext: newval
                                }
                            });
                        }
                    }
                });
            }
        });
    });

    // 地图高度预览
    wp.customize('black_maps_height', function(value) {
        value.bind(function(newval) {
            var height = newval;
            if (/^\d+$/.test(newval)) {
                height = newval + 'px';
            }
            $('.black-maps-wrapper, .black-maps-container, [id^="echartsMap"]').css('height', height);
            
            // 重新调整ECharts大小
            if (typeof echarts !== 'undefined') {
                setTimeout(function() {
                    $('.black-maps-wrapper').each(function() {
                        var mapId = $(this).find('[id^="echartsMap"]').attr('id');
                        if (mapId) {
                            var chartInstance = echarts.getInstanceByDom(document.getElementById(mapId));
                            if (chartInstance) {
                                chartInstance.resize();
                            }
                        }
                    });
                }, 100);
            }
        });
    });

    // 背景颜色预览
    wp.customize('black_maps_bg_color', function(value) {
        value.bind(function(newval) {
            $('.black-maps-wrapper').css('background-color', newval);
        });
    });

    // 图表背景颜色预览
    wp.customize('black_maps_chart_bg', function(value) {
        value.bind(function(newval) {
            if (typeof echarts !== 'undefined') {
                $('.black-maps-wrapper').each(function() {
                    var mapId = $(this).find('[id^="echartsMap"]').attr('id');
                    if (mapId) {
                        var chartInstance = echarts.getInstanceByDom(document.getElementById(mapId));
                        if (chartInstance) {
                            chartInstance.setOption({
                                backgroundColor: newval
                            });
                        }
                    }
                });
            }
        });
    });

    // 标题颜色预览
    wp.customize('black_maps_title_color', function(value) {
        value.bind(function(newval) {
            if (typeof echarts !== 'undefined') {
                $('.black-maps-wrapper').each(function() {
                    var mapId = $(this).find('[id^="echartsMap"]').attr('id');
                    if (mapId) {
                        var chartInstance = echarts.getInstanceByDom(document.getElementById(mapId));
                        if (chartInstance) {
                            chartInstance.setOption({
                                title: {
                                    textStyle: {
                                        color: newval
                                    }
                                }
                            });
                        }
                    }
                });
            }
        });
    });

    // 标题字体大小预览
    wp.customize('black_maps_title_size', function(value) {
        value.bind(function(newval) {
            if (typeof echarts !== 'undefined') {
                $('.black-maps-wrapper').each(function() {
                    var mapId = $(this).find('[id^="echartsMap"]').attr('id');
                    if (mapId) {
                        var chartInstance = echarts.getInstanceByDom(document.getElementById(mapId));
                        if (chartInstance) {
                            chartInstance.setOption({
                                title: {
                                    textStyle: {
                                        fontSize: parseInt(newval)
                                    }
                                }
                            });
                        }
                    }
                });
            }
        });
    });

    // 颜色相关设置预览（需要刷新页面以完全应用）
    var colorSettings = [
        'black_maps_china_color',
        'black_maps_target_color', 
        'black_maps_line_color',
        'black_maps_effect_color'
    ];

    colorSettings.forEach(function(setting) {
        wp.customize(setting, function(value) {
            value.bind(function(newval) {
                // 颜色变化需要重新初始化地图，所以刷新页面
                wp.customize.preview.send('refresh');
            });
        });
    });

    // 自定义国家数据预览
    wp.customize('black_maps_countries_json', function(value) {
        value.bind(function(newval) {
            // 国家数据变化需要重新初始化地图
            wp.customize.preview.send('refresh');
        });
    });

    // 显示参数预览
    var displaySettings = [
        'black_maps_enable_zoom',
        'black_maps_enable_drag',
        'black_maps_animation_speed'
    ];

    displaySettings.forEach(function(setting) {
        wp.customize(setting, function(value) {
            value.bind(function(newval) {
                // 显示参数变化需要重新初始化地图
                wp.customize.preview.send('refresh');
            });
        });
    });

    // 地图预览辅助函数
    function refreshMapPreview() {
        if (typeof echarts !== 'undefined') {
            setTimeout(function() {
                $('.black-maps-wrapper').each(function() {
                    var mapId = $(this).find('[id^="echartsMap"]').attr('id');
                    if (mapId) {
                        var chartInstance = echarts.getInstanceByDom(document.getElementById(mapId));
                        if (chartInstance) {
                            chartInstance.resize();
                        }
                    }
                });
            }, 200);
        }
    }

    // 监听窗口大小变化，调整地图大小
    $(window).on('resize', function() {
        refreshMapPreview();
    });

})(jQuery);