/**
 * 自定义器预览功能
 * 实时预览关于我们时间轴设置的变化
 */

(function($) {
    'use strict';

    // 关于我们时间轴实时预览
    initAboutTimelinePreview();
    
    // 视频Banner实时预览
    initVideoBannerPreview();
    
    // 业务流程实时预览
    initBusinessProcessPreview();

    // 关于我们时间轴预览功能
    function initAboutTimelinePreview() {
        // 时间轴显示状态实时预览
        wp.customize('about_timeline_show', function(value) {
            value.bind(function(newval) {
                const timelineContainer = $('.about-timeline-block');
                if (newval) {
                    timelineContainer.show();
                } else {
                    timelineContainer.hide();
                }
            });
        });

        // 时间轴标题实时预览
        wp.customize('about_timeline_title', function(value) {
            value.bind(function(newval) {
                $('.about-timeline-block .timeline-title').text(newval);
            });
        });

        // 监听各个时间轴项目字段的变化
        for (let i = 1; i <= 5; i++) {
            // 监听启用状态变化
            wp.customize(`about_timeline_item_${i}_enabled`, function(value) {
                value.bind(function(newval) {
                    updateTimelineFromFields();
                });
            });
            
            // 监听年份变化
            wp.customize(`about_timeline_item_${i}_year`, function(value) {
                value.bind(function(newval) {
                    updateTimelineFromFields();
                });
            });
            
            // 监听标题变化
            wp.customize(`about_timeline_item_${i}_title`, function(value) {
                value.bind(function(newval) {
                    updateTimelineFromFields();
                });
            });
            
            // 监听描述变化
            wp.customize(`about_timeline_item_${i}_description`, function(value) {
                value.bind(function(newval) {
                    updateTimelineFromFields();
                });
            });
            
            // 监听图片变化
            wp.customize(`about_timeline_item_${i}_image`, function(value) {
                value.bind(function(newval) {
                    updateTimelineFromFields();
                });
            });
        }
    }

    // 从字段获取时间轴数据并更新预览
    function updateTimelineFromFields() {
        const timelineData = [];
        
        // 收集所有启用的时间轴项目数据
        for (let i = 1; i <= 5; i++) {
            const enabled = wp.customize(`about_timeline_item_${i}_enabled`).get();
            if (enabled) {
                const year = wp.customize(`about_timeline_item_${i}_year`).get();
                const title = wp.customize(`about_timeline_item_${i}_title`).get();
                const description = wp.customize(`about_timeline_item_${i}_description`).get();
                const image = wp.customize(`about_timeline_item_${i}_image`).get();
                
                // 只有当年份和标题都不为空时才添加
                if (year && title) {
                    timelineData.push({
                        year: year,
                        title: title,
                        description: description || '',
                        image: image || ''
                    });
                }
            }
        }
        
        if (timelineData.length > 0) {
            updateTimelinePreview(timelineData);
        }
    }
    
    // 更新时间轴预览内容
    function updateTimelinePreview(timelineData) {
        const timelineContainer = $('.timeline-container');
        const swiperContainer = $('.swiper-wrapper');
        
        if (timelineContainer.length === 0 || swiperContainer.length === 0) {
            return;
        }

        // 更新时间轴点
        let timelineHtml = '';
        timelineData.forEach((item, index) => {
            const activeClass = index === 0 ? ' active' : '';
            timelineHtml += `
                <div class="timeline-item${activeClass}" data-slide="${index}">
                    <div class="timeline-year">${item.year}</div>
                    <div class="timeline-dot"></div>
                </div>
            `;
        });
        timelineContainer.html(timelineHtml);

        // 更新Swiper幻灯片
        let swiperHtml = '';
        timelineData.forEach((item, index) => {
            swiperHtml += `
                <div class="swiper-slide">
                    <div class="slide-content">
                        <div class="slide-image">
                            <img src="${item.image}" alt="${item.title}" loading="lazy">
                        </div>
                        <div class="slide-text">
                            <h3>${item.title}</h3>
                            <p>${item.description}</p>
                        </div>
                    </div>
                </div>
            `;
        });
        swiperContainer.html(swiperHtml);

        // 重新初始化时间轴（如果存在）
        if (window.initTimelineBlocks) {
            // 销毁现有的实例
            $('.about-timeline-block').each(function() {
                const instance = $(this).data('timeline-instance');
                if (instance && typeof instance.destroy === 'function') {
                    instance.destroy();
                }
                $(this).removeData('timeline-instance');
                $(this).removeData('timeline-initialized');
            });
            
            // 重新初始化
            setTimeout(() => {
                window.initTimelineBlocks();
            }, 100);
        }
    }

    // 视频Banner预览功能
    function initVideoBannerPreview() {
        
        // 背景图片实时预览
        wp.customize('video_banner_bg_image', function(value) {
            value.bind(function(newval) {
                const bannerContainer = $('.video-banner-block');
                if (bannerContainer.length) {
                    if (newval) {
                        bannerContainer.css('background-image', 'url(' + newval + ')');
                    } else {
                        bannerContainer.css('background-image', 'none');
                    }
                }
            });
        });
        
        // 标题实时预览
        wp.customize('video_banner_content_title', function(value) {
            value.bind(function(newval) {
                $('.video-banner-content .banner-title').text(newval);
            });
        });
        
        // 副标题实时预览
        wp.customize('video_banner_content_subtitle', function(value) {
            value.bind(function(newval) {
                $('.video-banner-content .banner-subtitle').text(newval);
            });
        });
        
        // 描述实时预览
        wp.customize('video_banner_content_description', function(value) {
            value.bind(function(newval) {
                $('.video-banner-content .banner-description').text(newval);
            });
        });
        
        // 高度实时预览
        wp.customize('video_banner_height', function(value) {
            value.bind(function(newval) {
                const bannerContainer = $('.video-banner-block .video-banner-container');
                if (bannerContainer.length) {
                    bannerContainer.css('height', newval + 'px');
                }
            });
        });
        
        // 视频背景启用/禁用
        wp.customize('video_banner_video_bg_enabled', function(value) {
            value.bind(function(newval) {
                const videoBg = $('.video-banner-video-bg');
                if (videoBg.length) {
                    if (newval) {
                        videoBg.show();
                        initVideoBackground();
                    } else {
                        videoBg.hide();
                    }
                }
            });
        });
        
        // 视频背景URL实时预览
        wp.customize('video_banner_video_bg_url', function(value) {
            value.bind(function(newval) {
                const videoBg = $('.video-banner-video-bg video');
                if (videoBg.length && newval) {
                    videoBg.attr('src', newval);
                    // 重新加载视频
                    videoBg[0].load();
                }
            });
        });
        
        // 视频背景不透明度实时预览
        wp.customize('video_banner_video_bg_opacity', function(value) {
            value.bind(function(newval) {
                const videoBg = $('.video-banner-video-bg video');
                if (videoBg.length) {
                    videoBg.css('opacity', newval / 100);
                }
            });
        });
        
        // 区块ID实时预览
        wp.customize('video_banner_block_id', function(value) {
            value.bind(function(newval) {
                const bannerBlock = $('.video-banner-block');
                if (bannerBlock.length) {
                    bannerBlock.attr('id', newval);
                }
            });
        });
        
        // 区块类名实时预览
        wp.customize('video_banner_block_class', function(value) {
            value.bind(function(newval) {
                const bannerBlock = $('.video-banner-block');
                if (bannerBlock.length) {
                    // 移除之前的自定义类名（保留默认类名）
                    bannerBlock.removeClass(function(index, className) {
                        return (className.match(/(^|\s)custom-\S+/g) || []).join(' ');
                    });
                    
                    // 添加新的类名
                    if (newval) {
                        bannerBlock.addClass(newval);
                    }
                }
            });
        });
        
        // 初始化视频背景
        initVideoBackground();
    }
    
    // 初始化视频背景
    function initVideoBackground() {
        const videoBg = $('.video-banner-video-bg video');
        if (videoBg.length) {
            const video = videoBg[0];
            
            // 设置视频属性
            video.muted = true;
            video.loop = true;
            video.playsInline = true;
            
            // 尝试自动播放
            const playPromise = video.play();
            if (playPromise !== undefined) {
                playPromise.catch(function(error) {
                    console.log('视频自动播放失败:', error);
                    // 可以在这里添加用户交互后播放的逻辑
                });
            }
            
            // 视频加载完成后设置不透明度
            video.addEventListener('loadeddata', function() {
                const opacity = wp.customize('video_banner_video_bg_opacity')();
                videoBg.css('opacity', opacity / 100 || 1);
            });
            
            // 错误处理
            video.addEventListener('error', function(e) {

                videoBg.hide();
            });
        }
    }
    
    // 实时更新视频Banner样式
    function updateVideoBannerStyles() {
        const bannerContainer = $('.video-banner-block .video-banner-container');
        if (bannerContainer.length) {
            // 获取当前设置值
            const height = wp.customize('video_banner_height')();
            const bgImage = wp.customize('video_banner_bg_image')();
            
            // 应用样式
            if (height) {
                bannerContainer.css('height', height + 'px');
            }
            
            if (bgImage) {
                bannerContainer.css('background-image', 'url(' + bgImage + ')');
            }
        }
    }
    
    // 页面加载完成后初始化
    $(document).ready(function() {
        // 延迟执行以确保DOM完全加载
        setTimeout(function() {
            updateVideoBannerStyles();
            initVideoBackground();
        }, 500);
    });

    // 业务流程预览功能
    function initBusinessProcessPreview() {
        // 业务流程显示状态实时预览
        wp.customize('business_process_show', function(value) {
            value.bind(function(newval) {
                const processContainer = $('.business-process-block');
                if (newval) {
                    processContainer.show();
                } else {
                    processContainer.hide();
                }
            });
        });

        // 业务流程标题实时预览
        wp.customize('business_process_title', function(value) {
            value.bind(function(newval) {
                $('.business-process-block .process-title').text(newval);
            });
        });

        // 业务流程副标题实时预览
        wp.customize('business_process_subtitle', function(value) {
            value.bind(function(newval) {
                $('.business-process-block .process-subtitle').text(newval);
            });
        });

        // 监听各个tab的变化
        for (let i = 1; i <= 4; i++) {
            const tabNumber = i.toString().padStart(2, '0');
            
            // 监听tab标题变化
            wp.customize(`business_process_tab_${tabNumber}_title`, function(value) {
                value.bind(function(newval) {
                    $(`.business-process-tabs .tab-item[data-tab="${tabNumber}"] .tab-title`).text(newval);
                });
            });
            
            // 监听tab描述变化
            wp.customize(`business_process_tab_${tabNumber}_description`, function(value) {
                value.bind(function(newval) {
                    $(`.business-process-tabs .tab-item[data-tab="${tabNumber}"] .tab-description`).text(newval);
                });
            });
            
            // 监听tab图片变化
            wp.customize(`business_process_tab_${tabNumber}_image`, function(value) {
                value.bind(function(newval) {
                    const imageContainer = $('.business-process-image');
                    const currentActiveTab = $('.business-process-tabs .tab-item.active').data('tab');
                    
                    // 如果当前活动的tab是正在更改的tab，则更新图片
                    if (currentActiveTab === tabNumber) {
                        const img = imageContainer.find('img');
                        if (img.length && newval) {
                            img.attr('src', newval);
                        }
                    }
                    
                    // 更新数据属性以备后续切换使用
                    $(`.business-process-tabs .tab-item[data-tab="${tabNumber}"]`).attr('data-image', newval);
                });
            });
        }

        // 监听tab切换事件，更新图片预览
        $(document).on('click', '.business-process-tabs .tab-item', function() {
            const tabNumber = $(this).data('tab');
            const imageUrl = $(this).data('image');
            const imageContainer = $('.business-process-image');
            
            if (imageUrl && imageContainer.length) {
                const img = imageContainer.find('img');
                if (img.length) {
                    // 添加淡出效果
                    img.fadeOut(200, function() {
                        $(this).attr('src', imageUrl).fadeIn(200);
                    });
                }
            }
        });
    }

})(jQuery);