// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化AOS动画库
    AOS.init({
        duration: 800,
        easing: 'ease-in-out',
        once: true,
        offset: 100
    });

    // 页面加载动画
    setTimeout(function() {
        const loader = document.querySelector('.page-loader');
        if (loader) {
            loader.classList.add('hidden');
            
            // 动画完成后移除元素
            setTimeout(function() {
                loader.style.display = 'none';
            }, 500);
        }
    }, 1500);

    // 创建滚动进度条
    createScrollProgress();
    
    // 创建返回顶部按钮
    createBackToTopButton();
    
    // 添加滚动事件监听
    window.addEventListener('scroll', handleScroll);
    
    // 初始化页面交互
    initPageInteractions();
    
    // 初始化表单处理
    initForms();
});

// 创建滚动进度条
function createScrollProgress() {
    const progressBar = document.createElement('div');
    progressBar.className = 'scroll-progress';
    document.body.appendChild(progressBar);
}

// 创建返回顶部按钮
function createBackToTopButton() {
    const backToTopBtn = document.createElement('div');
    backToTopBtn.className = 'back-to-top';
    backToTopBtn.innerHTML = '<i class="fas fa-chevron-up"></i>';
    backToTopBtn.setAttribute('aria-label', '返回顶部');
    
    backToTopBtn.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
    
    document.body.appendChild(backToTopBtn);
}

// 处理滚动事件
function handleScroll() {
    updateScrollProgress();
    toggleBackToTopButton();
}

// 更新滚动进度条
function updateScrollProgress() {
    const progressBar = document.querySelector('.scroll-progress');
    if (progressBar) {
        const windowHeight = window.innerHeight;
        const documentHeight = document.documentElement.scrollHeight - windowHeight;
        const scrolled = (window.scrollY / documentHeight) * 100;
        progressBar.style.width = scrolled + '%';
    }
}

// 显示/隐藏返回顶部按钮
function toggleBackToTopButton() {
    const backToTopBtn = document.querySelector('.back-to-top');
    if (backToTopBtn) {
        if (window.scrollY > 300) {
            backToTopBtn.classList.add('visible');
        } else {
            backToTopBtn.classList.remove('visible');
        }
    }
}

// 初始化页面交互
function initPageInteractions() {
    // 导航菜单点击效果
    initNavigation();
    
    // 功能卡片悬停效果
    initFeatureCards();
    
    // 用户评价卡片交互
    initTestimonialCards();
    
    // 行动号召按钮点击效果
    initCallToAction();
}

// 导航菜单交互
function initNavigation() {
    const navLinks = document.querySelectorAll('.navbar-nav .nav-link');
    
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            // 移除所有active类
            navLinks.forEach(l => l.classList.remove('active'));
            
            // 添加当前active类
            this.classList.add('active');
            
            // 如果是锚点链接，平滑滚动
            const href = this.getAttribute('href');
            if (href && href.startsWith('#')) {
                e.preventDefault();
                const target = document.querySelector(href);
                if (target) {
                    target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            }
        });
    });
}

// 功能卡片交互
function initFeatureCards() {
    const featureCards = document.querySelectorAll('.feature-box');
    
    featureCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-10px)';
            this.style.boxShadow = '0 15px 30px rgba(0,0,0,0.15)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '0 5px 15px rgba(0,0,0,0.05)';
        });
    });
}

// 用户评价卡片交互
function initTestimonialCards() {
    const testimonialCards = document.querySelectorAll('.testimonial-card');
    
    testimonialCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px)';
            this.style.boxShadow = '0 10px 25px rgba(0,0,0,0.1)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '0 5px 15px rgba(0,0,0,0.05)';
        });
    });
}

// 行动号召按钮交互
function initCallToAction() {
    const ctaButtons = document.querySelectorAll('.cta-section .btn, .hero-section .btn');
    
    ctaButtons.forEach(btn => {
        btn.addEventListener('mouseenter', function() {
            this.style.transform = 'scale(1.05)';
            this.style.boxShadow = '0 8px 25px rgba(0,0,0,0.2)';
        });
        
        btn.addEventListener('mouseleave', function() {
            this.style.transform = 'scale(1)';
            this.style.boxShadow = 'none';
        });
        
        btn.addEventListener('click', function(e) {
            // 添加点击效果
            this.style.transform = 'scale(0.95)';
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 150);
            
            // 如果是演示按钮，阻止默认行为
            if (this.getAttribute('href') === '#') {
                e.preventDefault();
                alert('欢迎体验结伴客平台！此功能正在开发中，敬请期待。');
            }
        });
    });
}

// 表单处理功能
function initForms() {
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 表单验证
            if (this.checkValidity()) {
                // 显示提交成功消息
                showFormSuccess(this);
                // 重置表单
                this.reset();
            } else {
                // 显示验证错误
                this.reportValidity();
            }
        });
    });
}

// 显示表单提交成功消息
function showFormSuccess(form) {
    // 创建成功消息
    const successMessage = document.createElement('div');
    successMessage.className = 'alert alert-success alert-dismissible fade show';
    successMessage.innerHTML = `
        <i class="fa fa-check-circle me-2"></i>
        提交成功！我们会尽快与您联系。
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    // 插入到表单前面
    form.parentNode.insertBefore(successMessage, form);
    
    // 5秒后自动消失
    setTimeout(() => {
        if (successMessage.parentNode) {
            successMessage.remove();
        }
    }, 5000);
}

// 页面性能优化：图片懒加载
function initLazyLoading() {
    if ('IntersectionObserver' in window) {
        const lazyImages = document.querySelectorAll('img[data-src]');
        
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.getAttribute('data-src');
                    img.removeAttribute('data-src');
                    imageObserver.unobserve(img);
                }
            });
        });
        
        lazyImages.forEach(img => {
            imageObserver.observe(img);
        });
    }
}

// 页面可见性变化处理
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        console.log('页面被隐藏');
    } else {
        console.log('页面恢复显示');
    }
});

// 错误处理
window.addEventListener('error', function(e) {
    console.error('页面错误:', e.error);
});

// 页面卸载前清理
window.addEventListener('beforeunload', function() {
    // 清理操作
});