document.addEventListener('DOMContentLoaded', () => {
    const elements = document.querySelectorAll('.perCent2');
    
    const animatePercentage = (element) => {
        // 添加可见类,触发CSS过渡效果
        element.classList.add('visible');
        
        let current = 1;
        const target = parseInt(element.getAttribute('data-target'));
        
        // 重置为初始值
        element.textContent = '1%';
        
        const timer = setInterval(() => {
            current += 1;
            element.textContent = `${current}%`;
            
            if (current >= target) {
                clearInterval(timer);
            }
        }, 30);
    };

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                animatePercentage(entry.target);
            } else {
                // 当元素离开视口时
                entry.target.classList.remove('visible');
                entry.target.textContent = '1%';  // 重置为初始值
            }
        });
    }, {
        threshold: 0.5,
        rootMargin: '0px'
    });

    elements.forEach(element => {
        // 初始状态设置
        element.classList.remove('visible');
        element.textContent = '1%';
        observer.observe(element);
    });

    // ------------------------------
    // 获取所需的DOM元素
    const container = document.querySelector('.carousel-container');
    const list = document.querySelector('.carousel-list');
    const items = document.querySelectorAll('.carousel-item');
    const prevBtn = document.querySelector('.carousel-arrow-left');
    const nextBtn = document.querySelector('.carousel-arrow-right');
    const indicators = document.querySelectorAll('.indicator');

    // 如果元素不存在,直接返回
    if (!container || !list || !items.length) {
        console.error('轮播图元素不存在,初始化失败');
        return;
    }

    // 克隆第一个和最后一个项目
    const firstClone = items[0].cloneNode(true);
    const lastClone = items[items.length - 1].cloneNode(true);

    // 将克隆的元素添加到列表中
    list.appendChild(firstClone);
    list.insertBefore(lastClone, list.firstChild);

    // 设置初始位置,因为添加了一个项目在前面,所以从1开始
    let currentIndex = 1;
    let interval = null;
    let isTransitioning = false;

    // 初始化位置
    updatePosition(false);

    // 更新位置的函数
    function updatePosition(withTransition = true) {
        // 如果需要过渡动画
        if (withTransition) {
            list.style.transition = 'transform 0.5s ease';
        } else {
            list.style.transition = 'none';
        }
        
        // 计算位置并应用变换
        const position = -currentIndex * 100;
        list.style.transform = `translateX(${position}%)`;
        
        // 更新指示器状态,注意要减去1因为我们添加了克隆项目
        updateIndicators();
    }

    // 更新指示器状态
    function updateIndicators() {
        // 考虑循环,将currentIndex转换回真实索引
        const realIndex = currentIndex - 1;
        // 使用模运算确保索引在有效范围内
        const activeIndex = (realIndex + items.length) % items.length;
        
        indicators.forEach((indicator, i) => {
            indicator.classList.toggle('active', i === activeIndex);
        });
    }

    // 自动播放函数
    function startAutoPlay() {
        if (interval) clearInterval(interval);
        interval = setInterval(nextSlide, 3000);
    }

    // 暂停自动播放
    function stopAutoPlay() {
        clearInterval(interval);
    }

    // 下一张函数
    function nextSlide() {
        if (isTransitioning) return;
        isTransitioning = true;
        
        currentIndex++;
        updatePosition();
    }

    // 上一张函数
    function prevSlide() {
        if (isTransitioning) return;
        isTransitioning = true;
        
        currentIndex--;
        updatePosition();
    }

    // 处理过渡结束事件
    list.addEventListener('transitionend', () => {
        isTransitioning = false;
        
        // 如果到达了最后一个克隆项
        if (currentIndex >= items.length + 1) {
            currentIndex = 1;
            updatePosition(false);
        }
        
        // 如果到达了第一个克隆项
        if (currentIndex <= 0) {
            currentIndex = items.length;
            updatePosition(false);
        }
    });

    // 绑定指示器点击事件
    indicators.forEach((indicator, index) => {
        indicator.addEventListener('click', () => {
            currentIndex = index + 1; // +1因为我们添加了克隆项目
            updatePosition();
            stopAutoPlay();
            startAutoPlay();
        });
    });

    // 鼠标悬停暂停
    container.addEventListener('mouseenter', stopAutoPlay);
    container.addEventListener('mouseleave', startAutoPlay);

    // 添加触摸滑动支持
    let touchStartX = 0;
    let touchEndX = 0;

    container.addEventListener('touchstart', (e) => {
        touchStartX = e.touches[0].clientX;
        stopAutoPlay();
    });

    container.addEventListener('touchend', (e) => {
        touchEndX = e.changedTouches[0].clientX;
        const difference = touchStartX - touchEndX;
        
        if (Math.abs(difference) > 50) {
            if (difference > 0) {
                nextSlide();
            } else {
                prevSlide();
            }
        }
        
        startAutoPlay();
    });

    // 开始自动播放
    startAutoPlay();

    // --------------------------------

    const langData = {
        zh: {
            nav: {
                home: "首页",
                business: "主营业务",
                products: "产品案例",
                support: "技术支持",
                future: "展望未来",
                about: "关于我们"
            },
            btn: "English",
            logo: "./imgs/svg/logo.svg",
            bannerBg: "../imgs/svg/背景纹(大).svg",
            bannerListImgs: [
                "../imgs/home/mainBusiness.png",
                "../imgs/home/aboutUs.png",
            ],
            CarouselImgs: [
                "./imgs/home/Y100.jpg",
                "./imgs/home/S6PRO.jpg",
            ],
            carouselText: "产品详情",
            title: "深圳汉晶电子信息有限公司",
            bannerBottom2Title: "为什么选择汉晶?",
            bannerBottomListOneTitle: "IC设计全生命周期一站式覆盖",
            bannerBottomListTwoTitle: "独特的低功耗设计,让芯片更有竞争力",
            bannerBottomListThreeTitle: "有稳定的芯片制造商合作关系",
            bannerBottomListFourTitle: "流片均一版成功,即流片成功率100%,助力客户赢得市场",
            bannertopTitle: "芯片设计技术服务",
            bannertopText: "我们公司提供全方位的芯片设计技术服务,涵盖从需求讨论、系统设计、逻辑设计、FPGA原型验证到最终的芯片制造、测试与验证等各个环节。我们采用行业领先的工具和技术,确保芯片的性能、功耗、稳定性都能满足客户需求。",
            bannerletfTextTitle: "Y100 服务器芯片",
            bannerletfTextTitle2: "S6PRO 运算加速芯片",
            bannerBottomTextTitle: "我们的目标",
            bannerBottomTextText: "汇聚人才,共同创造突破性技术,为更加智能、更加安全、更有保障的科技世界保驾护航。",
            newBottomTitle: "研发团队",
            newBottomText: "研究生学历",
            emailLeftTitle: "我们准备好了",
            emailLeftText: "如果您有更多的需求,请联系我们",
        },
        en: {
            nav: {
                home: "Home",
                business: "Business",
                products: "Products",
                support: "Support",
                future: "Future",
                about: "About Us"
            },
            btn: "简体中文",
            logo: "./imgs/svg/logo_en.svg",
            bannerBg: "../imgs/svg/bg_en.svg",
            bannerListImgs: [
                "../imgs/home/mainBusiness_en.png",
                "../imgs/home/aboutUs_en.png",
            ],
            CarouselImgs: [
                "./imgs/home/Y100_en.jpg",
                "./imgs/home/S6PRO_en.jpg",
            ],
            carouselText: "Product Details",
            title: "SZHJ Electronic Information Co., Ltd",
            bannerBottom2Title: "Why Hanjing?",
            bannerBottomListOneTitle: "One-stop coverage of the entire IC design life cycle",
            bannerBottomListTwoTitle: "Unique low-power design makes the chip more competitive",
            bannerBottomListThreeTitle: "Stable relationships with chip makers",
            bannerBottomListFourTitle: "Successful flow of the first version of the film, i.e., 100% success rate of the flow of the film, to help customers win the market",
            bannertopTitle: "Chip Design Technology Services",
            bannertopText: "Our company provides a full range of chip design technology services, covering all aspects from requirements discussion, system design, logic design, FPGA prototyping, to final chip manufacturing, testing and verification. We use industry-leading tools and technologies to ensure that the performance, power consumption, and stability of the chip meets customer requirements.",
            bannerletfTextTitle: "Y100 Server Chips",
            bannerletfTextTitle2: "S6PRO computing accelerator chip",
            bannerBottomTextTitle: "Our Goals",
            bannerBottomTextText: "Bringing together talents to create breakthrough technologies for a smarter, safer and more secure technological world.",
            newBottomTitle: "R&D Team",
            newBottomText: "postgraduate education",
            emailLeftTitle: "We're ready.",
            emailLeftText: "If you have more needs, please contact us!",
        }
    };

    // 语言显示更新函数 - 移到外部作为独立函数
    function updateLanguageDisplay(lang) {
        const currentFlag = document.getElementById('current-flag');
        const currentLangText = document.getElementById('current-lang');
        
        if (currentFlag && currentLangText) {
            if (lang === 'en') {
                currentFlag.src = './imgs/flags/en.svg';
                currentLangText.textContent = 'English';
            } else {
                currentFlag.src = './imgs/flags/zh.svg';
                currentLangText.textContent = '简体中文';
            }
        }
    }

    let currentLang = localStorage.getItem('siteLang') || "zh";

    function applyLang(lang) {
        try {
            const data = langData[lang];
    
            // 导航文本 - 使用常规的条件检查而不是可选链
            const navHome = document.getElementById("nav-home");
            if (navHome) navHome.textContent = data.nav.home;
            
            const navBusiness = document.getElementById("nav-business");
            if (navBusiness) navBusiness.textContent = data.nav.business;
            
            const navProducts = document.getElementById("nav-products");
            if (navProducts) navProducts.textContent = data.nav.products;
            
            const navSupport = document.getElementById("nav-support");
            if (navSupport) navSupport.textContent = data.nav.support;
            
            const navFuture = document.getElementById("nav-future");
            if (navFuture) navFuture.textContent = data.nav.future;
            
            const navAbout = document.getElementById("nav-about");
            if (navAbout) navAbout.textContent = data.nav.about;
            
            // logo
            // const logoImg = document.getElementById("logo-img");
            // if (logoImg) logoImg.src = data.logo;
            
            // const footerLogo = document.getElementById("footerLogo");
            // if (footerLogo) footerLogo.src = data.logo;
    
            // 轮播图图片全部替换(包括克隆节点)
            document.querySelectorAll('img[alt="S6PRO"]').forEach(img => {
                img.src = data.CarouselImgs[1];
            });
            document.querySelectorAll('img[alt="Y100"]').forEach(img => {
                img.src = data.CarouselImgs[0];
            });
    
            // 轮播图详情按钮文本全部切换
            document.querySelectorAll('.carouselText').forEach(span => {
                span.textContent = data.carouselText;
            });
    
            // 其它页面内容 - 单独处理每个元素
            const bannerBottom2Title = document.querySelector('.bannerBottom2Title');
            if (bannerBottom2Title) bannerBottom2Title.textContent = data.bannerBottom2Title;
            
            const bannerBottomListOneTitle = document.querySelector('.bannerBottomListOneTitle');
            if (bannerBottomListOneTitle) bannerBottomListOneTitle.textContent = data.bannerBottomListOneTitle;
            
            const bannerBottomListTwoTitle = document.querySelector('.bannerBottomListTwoTitle');
            if (bannerBottomListTwoTitle) bannerBottomListTwoTitle.textContent = data.bannerBottomListTwoTitle;
            
            const bannerBottomListThreeTitle = document.querySelector('.bannerBottomListThreeTitle');
            if (bannerBottomListThreeTitle) bannerBottomListThreeTitle.textContent = data.bannerBottomListThreeTitle;
            
            const bannerBottomListFourTitle = document.querySelector('.bannerBottomListFourTitle');
            if (bannerBottomListFourTitle) bannerBottomListFourTitle.textContent = data.bannerBottomListFourTitle;
            
            const bannertopTitle = document.querySelector('.bannertopTitle');
            if (bannertopTitle) bannertopTitle.textContent = data.bannertopTitle;
            
            const bannertopText = document.querySelector('.bannertopText');
            if (bannertopText) bannertopText.textContent = data.bannertopText;
            
            const bannerletfTextTitle = document.querySelector('.bannerletfTextTitle');
            if (bannerletfTextTitle) bannerletfTextTitle.textContent = data.bannerletfTextTitle;
            
            const bannerBottomTextTitle = document.querySelector('.bannerBottomTextTitle');
            if (bannerBottomTextTitle) bannerBottomTextTitle.textContent = data.bannerBottomTextTitle;
            
            const bannerBottomTextText = document.querySelector('.bannerBottomTextText');
            if (bannerBottomTextText) bannerBottomTextText.textContent = data.bannerBottomTextText;
            
            const newBottomTitle = document.querySelector('.newBottomTitle');
            if (newBottomTitle) newBottomTitle.textContent = data.newBottomTitle;
            
            const newBottomText = document.querySelector('.newBottomText');
            if (newBottomText) newBottomText.textContent = data.newBottomText;
            
            const emailLeftTitle = document.querySelector('.emailLeftTitle');
            if (emailLeftTitle) emailLeftTitle.textContent = data.emailLeftTitle;
            
            const emailLeftText = document.querySelector('.emailLeftText');
            if (emailLeftText) emailLeftText.textContent = data.emailLeftText;
            
            // 页面标题
            document.title = data.title;
            
            const footerTitle = document.querySelector('.footerBoxRightTitle');
            if (footerTitle) footerTitle.textContent = data.title;
            
            const titleElement = document.querySelector('.title');
            if (titleElement) titleElement.textContent = data.title;
            
            const bannerletfTextTitle2 = document.getElementById("bannerletfTextTitle2");
            if (bannerletfTextTitle2) bannerletfTextTitle2.textContent = data.bannerletfTextTitle2;
    
            // 特定类的添加/移除
            const textBox = document.querySelector('.textBox');
            if (textBox) {
                if (lang === 'en') {
                    textBox.classList.add('en');
                } else {
                    textBox.classList.remove('en');
                }
            }
    
            // bannerBottomList 背景图片
            const bannerTop = document.querySelector(".bannertop");
            if (bannerTop && data.bannerListImgs[0]) {
                bannerTop.style.backgroundImage = `url(${data.bannerListImgs[0]})`;
            }
            
            const bannerBottom = document.querySelector(".bannerBottom");
            if (bannerBottom && data.bannerListImgs[1]) {
                bannerBottom.style.backgroundImage = `url(${data.bannerListImgs[1]})`;
            }
        } catch (error) {
            console.error("语言切换出错:", error);
        }
    }

    function handleLangToggle(lang) {
        currentLang = lang;
        localStorage.setItem('siteLang', currentLang);
        applyLang(currentLang);
        updateLanguageDisplay(currentLang);
        
        // 如果在aboutUs页面,还需要更新地图信息
        if (typeof updateMapInfo === 'function') {
            updateMapInfo(currentLang);
        }
    }

    // 初始化语言
    applyLang(currentLang);
    updateLanguageDisplay(currentLang);

    // 获取语言切换相关的DOM元素
    const langBtn = document.getElementById('lang-btn');
    const langDropdown = document.getElementById('lang-dropdown');
    const langItems = document.querySelectorAll('.lang-item');

    // 切换下拉菜单显示/隐藏
    langBtn?.addEventListener('click', function(e) {
        e.stopPropagation(); // 阻止事件冒泡
        langDropdown.classList.toggle('show');
        const arrow = langBtn.querySelector('.arrow');
        if (arrow) {
            arrow.style.transform = langDropdown.classList.contains('show') ? 'rotate(180deg)' : 'rotate(0)';
        }
    });

    // 点击其他区域关闭下拉菜单
    document.addEventListener('click', function(event) {
        if (!event.target.closest('.lang-dropdown') && langDropdown) {
            langDropdown.classList.remove('show');
            const arrow = langBtn?.querySelector('.arrow');
            if (arrow) {
                arrow.style.transform = 'rotate(0)';
            }
        }
    });

    // 语言选择事件
    langItems?.forEach(item => {
        item.addEventListener('click', function() {
            const lang = this.getAttribute('data-lang');
            if (lang !== currentLang) {
                handleLangToggle(lang);
            }
            langDropdown.classList.remove('show');
            const arrow = langBtn.querySelector('.arrow');
            if (arrow) {
                arrow.style.transform = 'rotate(0)';
            }
        });
    });
});