/**
 * 2026企业CMS - 默认模板JavaScript
 */

// 幻灯片轮播
document.addEventListener('DOMContentLoaded', function() {
    const slides = document.querySelectorAll('.slide-item');
    if (slides.length > 0) {
        let currentSlide = 0;
        slides[0].classList.add('active');
        
        setInterval(function() {
            slides[currentSlide].classList.remove('active');
            currentSlide = (currentSlide + 1) % slides.length;
            slides[currentSlide].classList.add('active');
        }, 5000);
    }
});

// 移动端菜单切换
document.addEventListener('DOMContentLoaded', function() {
    const menuToggle = document.querySelector('.menu-toggle');
    if (menuToggle) {
        menuToggle.addEventListener('click', function() {
            document.querySelector('.nav ul').classList.toggle('show');
        });
    }
    
    // 移动端多级菜单展开/收起
    const menuItemsWithChildren = document.querySelectorAll('.menu-item-has-children > a');
    if (window.innerWidth <= 768) {
        menuItemsWithChildren.forEach(function(item) {
            item.addEventListener('click', function(e) {
                e.preventDefault();
                const parentLi = this.parentElement;
                parentLi.classList.toggle('active');
                
                const subMenu = parentLi.querySelector('.sub-menu');
                if (subMenu) {
                    if (subMenu.style.display === 'block') {
                        subMenu.style.display = 'none';
                    } else {
                        subMenu.style.display = 'block';
                    }
                }
            });
        });
    }
});

// 返回顶部按钮显示/隐藏
window.addEventListener('scroll', function() {
    const backToTop = document.querySelector('.back-to-top');
    if (backToTop) {
        if (window.scrollY > 300) {
            backToTop.style.display = 'flex';
        } else {
            backToTop.style.display = 'none';
        }
    }
});

// 表单验证
function validateForm(formId) {
    const form = document.getElementById(formId);
    if (!form) return true;
    
    const requiredFields = form.querySelectorAll('[required]');
    let isValid = true;
    
    requiredFields.forEach(function(field) {
        if (!field.value.trim()) {
            field.style.borderColor = 'red';
            isValid = false;
        } else {
            field.style.borderColor = '#ddd';
        }
    });
    
    // 邮箱验证
    const emailField = form.querySelector('input[type="email"]');
    if (emailField && emailField.value) {
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailPattern.test(emailField.value)) {
            emailField.style.borderColor = 'red';
            isValid = false;
        }
    }
    
    // 手机号验证
    const phoneField = form.querySelector('input[name="phone"]');
    if (phoneField && phoneField.value) {
        const phonePattern = /^1[3-9]\d{9}$/;
        if (!phonePattern.test(phoneField.value)) {
            phoneField.style.borderColor = 'red';
            isValid = false;
        }
    }
    
    if (!isValid) {
        alert('请检查表单填写是否正确！');
    }
    
    return isValid;
}

// AJAX提交表单
function submitFormAjax(formId, url, successCallback) {
    const form = document.getElementById(formId);
    if (!form) return;
    
    const formData = new FormData(form);
    
    fetch(url, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (successCallback) successCallback(data);
        } else {
            alert(data.message || '操作失败！');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('网络错误，请稍后重试！');
    });
}

// 图片懒加载
document.addEventListener('DOMContentLoaded', function() {
    const lazyImages = document.querySelectorAll('img[data-lazy]');
    
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver(function(entries) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.lazy;
                    img.removeAttribute('data-lazy');
                    imageObserver.unobserve(img);
                }
            });
        });
        
        lazyImages.forEach(function(img) {
            imageObserver.observe(img);
        });
    } else {
        // 降级处理
        lazyImages.forEach(function(img) {
            img.src = img.dataset.lazy;
        });
    }
});

// 搜索自动完成
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.querySelector('.search-bar input[name="q"]');
    if (searchInput) {
        let timer;
        searchInput.addEventListener('input', function() {
            clearTimeout(timer);
            timer = setTimeout(function() {
                // 可实现AJAX搜索建议
            }, 300);
        });
    }
});
