// js/main.js - TPwallet主JavaScript文件

document.addEventListener('DOMContentLoaded', function() {
    // 设置当前年份
    document.getElementById('current-year').textContent = new Date().getFullYear();
    
    // 移动端导航菜单切换
    const hamburger = document.getElementById('hamburger');
    const navMenu = document.querySelector('.nav-menu');
    
    if (hamburger) {
        hamburger.addEventListener('click', function() {
            hamburger.classList.toggle('active');
            navMenu.classList.toggle('active');
            
            // 防止滚动
            document.body.style.overflow = navMenu.classList.contains('active') ? 'hidden' : '';
        });
    }
    
    // 关闭移动端菜单当点击链接时
    document.querySelectorAll('.nav-link').forEach(n => n.addEventListener('click', () => {
        hamburger.classList.remove('active');
        navMenu.classList.remove('active');
        document.body.style.overflow = '';
    }));
    
    // 移动端下拉菜单
    const dropdowns = document.querySelectorAll('.dropdown > .nav-link');
    dropdowns.forEach(dropdown => {
        dropdown.addEventListener('click', function(e) {
            if (window.innerWidth <= 768) {
                e.preventDefault();
                const parent = this.parentElement;
                parent.classList.toggle('active');
                
                // 关闭其他打开的dropdown
                dropdowns.forEach(other => {
                    if (other !== dropdown) {
                        other.parentElement.classList.remove('active');
                    }
                });
            }
        });
    });
    
    // 滚动时头部阴影效果
    window.addEventListener('scroll', function() {
        const header = document.querySelector('.header');
        if (window.scrollY > 50) {
            header.classList.add('scrolled');
        } else {
            header.classList.remove('scrolled');
        }
    });
    
    // 回到顶部按钮
    const backToTopButton = document.getElementById('backToTop');
    
    window.addEventListener('scroll', function() {
        if (window.scrollY > 300) {
            backToTopButton.classList.add('visible');
        } else {
            backToTopButton.classList.remove('visible');
        }
    });
    
    backToTopButton.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
    
    // Cookie同意提示
    const cookieConsent = document.getElementById('cookieConsent');
    const acceptCookies = document.getElementById('acceptCookies');
    
    // 检查是否已经同意过
    if (!localStorage.getItem('cookiesAccepted')) {
        setTimeout(() => {
            cookieConsent.style.display = 'block';
        }, 1000);
    }
    
    if (acceptCookies) {
        acceptCookies.addEventListener('click', function() {
            localStorage.setItem('cookiesAccepted', 'true');
            cookieConsent.style.display = 'none';
        });
    }
    
    // 图片懒加载
    const images = document.querySelectorAll('img[loading="lazy"]');
    
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src || img.src;
                    img.classList.add('loaded');
                    imageObserver.unobserve(img);
                }
            });
        });
        
        images.forEach(img => imageObserver.observe(img));
    }
    
    // 平滑滚动锚点链接
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            const href = this.getAttribute('href');
            
            if (href === '#') return;
            
            const targetElement = document.querySelector(href);
            
            if (targetElement) {
                e.preventDefault();
                
                window.scrollTo({
                    top: targetElement.offsetTop - 80,
                    behavior: 'smooth'
                });
                
                // 移动端关闭菜单
                if (window.innerWidth <= 768) {
                    hamburger.classList.remove('active');
                    navMenu.classList.remove('active');
                    document.body.style.overflow = '';
                }
            }
        });
    });
    
    // 统计数字动画
    const statNumbers = document.querySelectorAll('.stat-number');
    
    function animateStatNumbers() {
        statNumbers.forEach(stat => {
            const originalText = stat.textContent;
            const value = parseInt(originalText.replace(/[^0-9]/g, ''));
            const hasPlus = originalText.includes('+');
            const duration = 2000;
            const increment = value / (duration / 16);
            let current = 0;
            
            const timer = setInterval(() => {
                current += increment;
                if (current >= value) {
                    stat.textContent = value + (hasPlus ? '+' : '');
                    clearInterval(timer);
                } else {
                    stat.textContent = Math.floor(current) + (hasPlus ? '+' : '');
                }
            }, 16);
        });
    }
    
    // 当统计数字进入视窗时开始动画
    const statsSection = document.querySelector('.hero-stats');
    
    if (statsSection) {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    animateStatNumbers();
                    observer.unobserve(entry.target);
                }
            });
        }, { threshold: 0.5 });
        
        observer.observe(statsSection);
    }
    
    // 新闻订阅表单处理
    const newsletterForm = document.getElementById('newsletterForm');
    
    if (newsletterForm) {
        newsletterForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const email = document.getElementById('newsletterEmail').value;
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            
            // 显示加载状态
            submitBtn.textContent = '订阅中...';
            submitBtn.disabled = true;
            
            // 模拟API调用
            setTimeout(() => {
                // 这里应该发送到服务器
                // 暂时用模拟成功
                alert(`感谢订阅！我们将向 ${email} 发送最新资讯。`);
                newsletterForm.reset();
                
                // 恢复按钮状态
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            }, 1000);
        });
    }
    
    // 检测设备并添加相应类名
    function detectDevice() {
        const ua = navigator.userAgent;
        const body = document.body;
        
        if (/Android/i.test(ua)) {
            body.classList.add('android');
        } else if (/iPhone|iPad|iPod/i.test(ua)) {
            body.classList.add('ios');
        } else if (/Windows/i.test(ua)) {
            body.classList.add('windows');
        } else if (/Linux/i.test(ua)) {
            body.classList.add('linux');
        }
        
        // 添加触摸设备检测
        if ('ontouchstart' in window || navigator.maxTouchPoints) {
            body.classList.add('touch-device');
        } else {
            body.classList.add('no-touch-device');
        }
    }
    
    detectDevice();
    
    // 性能监控
    if ('performance' in window) {
        window.addEventListener('load', function() {
            const timing = performance.timing;
            const loadTime = timing.loadEventEnd - timing.navigationStart;
            
            // 如果页面加载时间超过3秒，记录警告
            if (loadTime > 3000) {
                console.warn(`页面加载时间较长: ${loadTime}ms`);
            }
        });
    }
    
    // 错误监控
    window.addEventListener('error', function(e) {
        console.error('页面错误:', e.message, e.filename, e.lineno);
        // 这里可以发送错误到服务器
    });
    
    // 离线检测
    window.addEventListener('offline', function() {
        console.warn('网络连接已断开');
    });
    
    window.addEventListener('online', function() {
        console.log('网络连接已恢复');
    });
});