/**
 * 企业首页交互脚本
 * 包含导航、服务加载、表单处理等功能
 */

document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有功能
    initNavigation();
    initScrollEffects();
    loadServices();
    initContactForm();
});

/**
 * 导航栏功能
 * - 滚动时添加阴影
 * - 移动端菜单切换
 * - 平滑滚动到锚点
 */
function initNavigation() {
    const navbar = document.getElementById('navbar');
    const navToggle = document.getElementById('navToggle');
    const navMenu = document.getElementById('navMenu');
    const navLinks = document.querySelectorAll('.nav-link');

    // 滚动时添加阴影效果
    window.addEventListener('scroll', () => {
        if (window.scrollY > 50) {
            navbar.classList.add('scrolled');
        } else {
            navbar.classList.remove('scrolled');
        }
    });

    // 移动端菜单切换
    if (navToggle) {
        navToggle.addEventListener('click', () => {
            navMenu.classList.toggle('active');
            
            // 汉堡菜单动画
            const spans = navToggle.querySelectorAll('span');
            spans.forEach(span => span.classList.toggle('active'));
        });
    }

    // 导航链接点击事件
    navLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            
            // 移除所有活动状态
            navLinks.forEach(l => l.classList.remove('active'));
            // 添加当前活动状态
            link.classList.add('active');
            
            // 关闭移动端菜单
            if (navMenu.classList.contains('active')) {
                navMenu.classList.remove('active');
            }
            
            // 平滑滚动到目标区域
            const targetId = link.getAttribute('href');
            const targetSection = document.querySelector(targetId);
            if (targetSection) {
                const offsetTop = targetSection.offsetTop - 70; // 减去导航栏高度
                window.scrollTo({
                    top: offsetTop,
                    behavior: 'smooth'
                });
            }
        });
    });

    // 滚动时更新导航活动状态
    window.addEventListener('scroll', () => {
        let current = '';
        const sections = document.querySelectorAll('section');
        
        sections.forEach(section => {
            const sectionTop = section.offsetTop;
            const sectionHeight = section.clientHeight;
            if (scrollY >= sectionTop - 200) {
                current = section.getAttribute('id');
            }
        });

        navLinks.forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('href') === `#${current}`) {
                link.classList.add('active');
            }
        });
    });
}

/**
 * 滚动动画效果
 * 元素进入视口时添加动画
 */
function initScrollEffects() {
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate-in');
            }
        });
    }, observerOptions);

    // 观察所有需要动画的元素
    const animateElements = document.querySelectorAll(
        '.service-card, .stat-item, .contact-item, .about-text, .about-image'
    );
    
    animateElements.forEach(el => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(30px)';
        el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
        observer.observe(el);
    });

    // 添加动画样式
    const style = document.createElement('style');
    style.textContent = `
        .animate-in {
            opacity: 1 !important;
            transform: translateY(0) !important;
        }
    `;
    document.head.appendChild(style);
}

/**
 * 从服务器加载服务数据
 * 动态生成服务卡片
 */
async function loadServices() {
    const servicesGrid = document.getElementById('servicesGrid');
    
    if (!servicesGrid) return;

    try {
        // 显示加载状态
        servicesGrid.innerHTML = '<div class="loading">加载中...</div>';
        
        // 从 API 获取服务数据
        const response = await fetch('/api/services');
        
        if (!response.ok) {
            throw new Error('Failed to load services');
        }
        
        const services = await response.json();
        
        // 清空加载状态
        servicesGrid.innerHTML = '';
        
        // 生成服务卡片
        services.forEach((service, index) => {
            const card = createServiceCard(service);
            card.style.animationDelay = `${index * 0.1}s`;
            servicesGrid.appendChild(card);
        });
        
    } catch (error) {
        console.error('加载服务失败:', error);
        // 显示错误信息或使用默认数据
        servicesGrid.innerHTML = '<div class="error">加载失败，请刷新页面重试</div>';
        
        // 使用默认数据作为备用
        const defaultServices = [
            { icon: '💻', title: '软件开发', description: '提供企业级软件定制开发服务' },
            { icon: '☁️', title: '云计算服务', description: '安全可靠的云端解决方案' },
            { icon: '📊', title: '数据分析', description: '大数据分析与商业智能' },
            { icon: '💡', title: '技术咨询', description: '专业的技术架构咨询服务' }
        ];
        
        servicesGrid.innerHTML = '';
        defaultServices.forEach((service, index) => {
            const card = createServiceCard(service);
            card.style.animationDelay = `${index * 0.1}s`;
            servicesGrid.appendChild(card);
        });
    }
}

/**
 * 创建服务卡片元素
 */
function createServiceCard(service) {
    const card = document.createElement('div');
    card.className = 'service-card';
    card.innerHTML = `
        <div class="service-icon">${service.icon}</div>
        <h3 class="service-title">${service.title}</h3>
        <p class="service-description">${service.description}</p>
    `;
    return card;
}

/**
 * 联系表单处理
 * 表单验证和提交
 */
function initContactForm() {
    const form = document.getElementById('contactForm');
    
    if (!form) return;

    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        // 获取表单数据
        const formData = new FormData(form);
        const data = {
            name: formData.get('name'),
            email: formData.get('email'),
            message: formData.get('message')
        };
        
        // 简单验证
        if (!data.name || !data.email || !data.message) {
            showNotification('请填写所有必填项', 'error');
            return;
        }
        
        // 邮箱格式验证
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(data.email)) {
            showNotification('请输入有效的邮箱地址', 'error');
            return;
        }
        
        // 显示提交中状态
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.textContent = '发送中...';
        submitBtn.disabled = true;
        
        try {
            // 模拟提交（实际项目中应该发送到服务器）
            await simulateSubmit(data);
            
            showNotification('消息已发送，我们会尽快回复您！', 'success');
            form.reset();
            
        } catch (error) {
            console.error('提交失败:', error);
            showNotification('发送失败，请稍后重试', 'error');
        } finally {
            submitBtn.textContent = originalText;
            submitBtn.disabled = false;
        }
    });
}

/**
 * 模拟表单提交
 * 实际项目中应该替换为真实的 API 调用
 */
function simulateSubmit(data) {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('表单数据:', data);
            resolve({ success: true });
        }, 1500);
    });
}

/**
 * 显示通知消息
 */
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    // 添加样式
    notification.style.cssText = `
        position: fixed;
        top: 90px;
        right: 20px;
        padding: 15px 25px;
        border-radius: 10px;
        color: white;
        font-weight: 500;
        z-index: 9999;
        animation: slideIn 0.3s ease;
        max-width: 300px;
        word-wrap: break-word;
    `;
    
    // 根据类型设置颜色
    const colors = {
        success: '#10b981',
        error: '#ef4444',
        info: '#3b82f6',
        warning: '#f59e0b'
    };
    notification.style.backgroundColor = colors[type] || colors.info;
    
    // 添加动画样式
    const style = document.createElement('style');
    style.textContent = `
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        @keyframes slideOut {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }
    `;
    document.head.appendChild(style);
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 3秒后自动移除
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 3000);
}

/**
 * 数字动画效果
 * 用于统计数字的递增动画
 */
function animateNumber(element, target, duration = 2000) {
    const start = 0;
    const increment = target / (duration / 16);
    let current = start;
    
    const timer = setInterval(() => {
        current += increment;
        if (current >= target) {
            current = target;
            clearInterval(timer);
        }
        element.textContent = Math.floor(current) + '+';
    }, 16);
}

// 当关于我们区域进入视口时，启动数字动画
const statsObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const statNumbers = entry.target.querySelectorAll('.stat-number');
            statNumbers.forEach(stat => {
                const target = parseInt(stat.textContent);
                animateNumber(stat, target);
            });
            statsObserver.unobserve(entry.target);
        }
    });
}, { threshold: 0.5 });

// 观察统计区域
document.addEventListener('DOMContentLoaded', () => {
    const aboutSection = document.querySelector('.about-stats');
    if (aboutSection) {
        statsObserver.observe(aboutSection);
    }
});

// 导出函数供测试使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        createServiceCard,
        showNotification,
        animateNumber
    };
}
