document.addEventListener('DOMContentLoaded', function () {
    const accordionItems = document.querySelectorAll('.accordion-item');

    // 为每个手风琴项添加点击事件
    accordionItems.forEach((item, index) => {
        const header = item.querySelector('.accordion-header');

        header.addEventListener('click', () => {
            // 获取当前是否激活
            const isActive = item.classList.contains('active');

            // 关闭所有项
            accordionItems.forEach(item => {
                item.classList.remove('active');
            });

            // 如果点击的不是当前激活项，则展开它
            if (!isActive) {
                item.classList.add('active');
            }
        });

        // 默认展开第一项
        if (index === 0) {
            item.classList.add('active');
        }
    });


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

    const langData = {
        zh: {
            btn: "English",
            logo: "../imgs/svg/logo.svg",       
   
            title: "深圳汉晶电子信息有限公司",
            emailLeftTitle:"我们准备好了",
            emailLeftText:"如果您有更多的需求，请联系我们",
            // 顶部
            topBannerTitle: "芯片设计技术服务",
            topBannerDesc: "我们公司提供全方位的芯片设计技术服务，涵盖从需求讨论、  系统设计、  逻辑设计、 FPGA原型验证到最终的芯片制造、测试与验证等各个环节。我们采用行业领先的工具和技术,确保芯片的性能、功耗、稳定性都能满足客户需求。",
            // 手风琴
            accordion: [
                { title: "1.需求分析与规划", content: "根据客户的应用场景，进行深度调研，分析产品需求，输出系统方案。" },
                { title: "2.芯片架构设计", content: "从芯片框架设计到芯片核心模块设计，包括接口定义等，确保基于此架构就可以正常进行逻辑设计。" },
                { title: "3.逻辑设计与验证", content: "使用先进的设计工具（如 Verilog）进行芯片逻辑设计，并通过仿真与验证工具（如 systemverilog）确保功能和性能的正确性。通过后仿确定芯片功耗、面积符合客户需求。" },
                { title: "4.硬件设计与原理图", content: "在芯片封装设计时充分考虑到PCB板设计，不仅仅是考虑芯片本身，在芯片设计时就考虑产品的可靠性和稳定性。" },
                { title: "5.制程与工艺", content: "团队与先进半导体制造厂有着长期的合作，对工艺细节了解充分，确保芯片生产过程中的质量控制与工艺优化，工艺良率达到业界领先水平。" },
                { title: "6.测试与验证", content: "针对刚出厂的芯片，能对应设计开发测试板，提供包括功能测试、性能测试、功耗测试、热测试等全面的验证服务，保证客户收到的芯片都是合格产品。" },
                { title: "7.量产与交付", content: "根据客户需求，我们提供从小批量试产到大规模量产的全程技术支持，并确保交付时效与质量。" }
            ],
            // 优势列表
            bannerBottomList: [
                {
                    title: "全流程技术服务",
                    desc: "从芯从客户需求沟通到量产交付，提供端到端的技术服务，确保客户需求得到全方位满足。"
                },
                {
                    title: "行业经验",
                    desc: "我们的团队拥有多年芯片前后端设计经验，所设计的芯片均流片成功，能够应对复杂的设计挑战，提供个性化解决方案，在低功耗方面有独到的设计方法学。"
                },
                {
                    title: "技术工具",
                    desc: "在采用标准 EDA 工具链的基础上，我们开发了定制化自动脚本，提升设计效率与验证覆盖率。"
                },
                {
                    title: "稳定的芯片制造商合作关系",
                    desc: "团队与SMIC、GF等芯片制造商有着良好的合作关系,在12nm、22nm等先进制程上均有流片并都是一版流片成功。"
                }
            ],
            bannertopBG: "../imgs/main/content.svg",
            bannerBottomBG: "../imgs/main/advantage.svg",
        },
        en: {
            btn: "简体中文",
            logo: "../imgs/svg/logo_en.svg",
    
            title: "SZHJ Electronic Information Co., Ltd",
            emailLeftTitle:"We're ready.",
            emailLeftText:"If you have more needs, please contact us!",
            // 顶部
            topBannerTitle: "Chip Design Technology Services",
            topBannerDesc: "Our company provides comprehensive 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 chip's performance, power consumption, and stability meet customer requirements.",
            // 手风琴
            accordion: [
                { title: "1. Requirement Analysis & Planning", content: "Conduct in-depth research based on customer application scenarios, analyze product requirements, and deliver system solutions." },
                { title: "2. Chip Architecture Design", content: "From chip framework design to core module design, including interface definitions, ensuring that logic design can proceed smoothly based on this architecture." },
                { title: "3. Logic Design & Verification", content: "Use advanced design tools (such as Verilog) for chip logic design, and ensure functional and performance correctness through simulation and verification tools (such as SystemVerilog). Post-simulation ensures that chip power and area meet customer requirements." },
                { title: "4. Hardware Design & Schematics", content: "Fully consider PCB design during chip packaging, not only focusing on the chip itself, but also considering product reliability and stability during chip design." },
                { title: "5. Process & Technology", content: "The team has long-term cooperation with advanced semiconductor manufacturers, is fully familiar with process details, and ensures quality control and process optimization during chip production, achieving industry-leading yield." },
                { title: "6. Testing & Verification", content: "For newly manufactured chips, we can design and develop test boards, providing comprehensive verification services including functional, performance, power, and thermal tests to ensure all delivered chips are qualified." },
                { title: "7. Mass Production & Delivery", content: "According to customer needs, we provide full technical support from small batch trial production to large-scale mass production, ensuring delivery timeliness and quality." }
            ],
            // 优势列表
            bannerBottomList: [
                {
                    title: "Full-process Technical Service",
                    desc: "From customer requirement communication to mass production and delivery, we provide end-to-end technical services to ensure all customer needs are fully met."
                },
                {
                    title: "Industry Experience",
                    desc: "Our team has many years of experience in front-end and back-end chip design. All designed chips have been successfully taped out, capable of handling complex design challenges, providing personalized solutions, and having unique methodologies in low-power design."
                },
                {
                    title: "Technical Tools",
                    desc: "Based on standard EDA toolchains, we have developed customized automation scripts to improve design efficiency and verification coverage."
                },
                {
                    title: "Stable Partnerships with Chip Manufacturers",
                    desc: "The team has good cooperation with SMIC, GF and other chip manufacturers, and has successfully taped out chips in advanced processes such as 12nm and 22nm in one go."
                }
            ],
            bannertopBG: "../imgs/main/content_en.svg",
            bannerBottomBG: "../imgs/main/advantage_en.svg",
        }
    };


    let currentLang = localStorage.getItem('siteLang') || "zh";
    
    // 语言显示更新函数
    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 = '简体中文';
            }
        }
    }
    
    function applyLang(lang) {
        const data = langData[lang];

        // logo
        // const footerLogo = document.getElementById("footerLogo");
        // if (footerLogo) footerLogo.src = data.logo;

        // 页面内容
        const titleElement = document.getElementById("title");
        if (titleElement) titleElement.textContent = data.title;
        
        // 顶部标题和描述
        const topBannerTitle = document.querySelector('.topBannerLeftTitle p:nth-child(1)');
        if (topBannerTitle) topBannerTitle.textContent = data.topBannerTitle;
        
        const topBannerDesc = document.querySelector('.topBannerLeftTitle p:nth-child(2)');
        if (topBannerDesc) topBannerDesc.textContent = data.topBannerDesc;

        // 手风琴
        const accordionItems = document.querySelectorAll('.accordion-item');
        data.accordion.forEach((item, idx) => {
            if (accordionItems[idx]) {
                const header = accordionItems[idx].querySelector('.accordion-header h3');
                if (header) header.textContent = item.title;
                
                const content = accordionItems[idx].querySelector('.accordion-content p');
                if (content) content.textContent = item.content;
            }
        });

        // 优势列表
        const bannerBottomList = document.querySelectorAll('.bannerBottomList li');
        data.bannerBottomList.forEach((item, idx) => {
            if (bannerBottomList[idx]) {
                // 第一个p是标题，第二个p是描述
                const ps = bannerBottomList[idx].querySelectorAll('p');
                if (ps[0]) ps[0].textContent = item.title;
                if (ps[1]) ps[1].textContent = item.desc;
            }
        });

        // 优势列表样式切换
        bannerBottomList.forEach(li => {
            if (lang === 'en') {
                li.classList.add('en');
            } else {
                li.classList.remove('en');
            }
        });

        // 页脚和其他内容
        const emailLeftTitle = document.querySelector(".emailLeftTitle");
        if (emailLeftTitle) emailLeftTitle.textContent = data.emailLeftTitle;
        
        const emailLeftText = document.querySelector(".emailLeftText");
        if (emailLeftText) emailLeftText.textContent = data.emailLeftText;
        
        const footerBoxRightTitle = document.querySelector('.footerBoxRightTitle');
        if (footerBoxRightTitle) footerBoxRightTitle.textContent = data.title;
        
        // 背景图
        const bannertop = document.querySelector('.bannertop');
        if (bannertop) bannertop.style.backgroundImage = `url(${data.bannertopBG})`;
        
        const bannerBottom = document.querySelector('.bannerBottom');
        if (bannerBottom) bannerBottom.style.backgroundImage = `url(${data.bannerBottomBG})`;

        // 切换样式
        const topBannerLeftTitle = document.querySelector('.topBannerLeftTitle');
        const topBannerLeft = document.querySelector('.topBannerLeft');
        
        if (lang === 'en') {        
            if (topBannerTitle) topBannerTitle.classList.add('en');
            if (topBannerDesc) topBannerDesc.classList.add('en');
            if (topBannerLeft) topBannerLeft.classList.add('en');
        } else {
            if (topBannerTitle) topBannerTitle.classList.remove('en');
            if (topBannerDesc) topBannerDesc.classList.remove('en');
            if (topBannerLeft) topBannerLeft.classList.remove('en');
        }

        // 更新下拉菜单显示
        updateLanguageDisplay(lang);
    }

    // 修正的handleLangToggle函数，正确接收lang参数
    function handleLangToggle(lang) {
        currentLang = lang;
        localStorage.setItem('siteLang', currentLang);
        applyLang(currentLang);
        updateLanguageDisplay(currentLang);
    }
    
    // 初始化
    applyLang(currentLang);
    updateLanguageDisplay(currentLang);

    // 获取语言切换相关的DOM元素
    const langBtn = document.getElementById('lang-btn');
    const langDropdown = document.getElementById('lang-dropdown');
    const langItems = document.querySelectorAll('.lang-item');
 
    // 切换下拉菜单显示/隐藏
    if (langBtn) {
        langBtn.addEventListener('click', function(e) {
            console.log(`点击切换语言`);
            e.stopPropagation(); // 阻止事件冒泡
            
            // 直接修改样式，而不是依赖 CSS 类
            if (langDropdown.style.display === 'block') {
                langDropdown.style.display = 'none';
            } else {
                langDropdown.style.display = 'block';
                // 确保绝对定位和 z-index 正确设置
                langDropdown.style.position = 'absolute';
                langDropdown.style.top = '100%';
                langDropdown.style.right = '0';
                langDropdown.style.zIndex = '1000';
            }
            
            console.log('修改后显示状态:', langDropdown.style.display);
            
            // 旋转箭头
            const arrow = langBtn.querySelector('.arrow');
            if (arrow) {
                arrow.style.transform = langDropdown.style.display === 'block' ? 'rotate(180deg)' : 'rotate(0)';
            }
        });
    }
// 点击其他区域关闭下拉菜单
document.addEventListener('click', function(event) {
    if (!event.target.closest('.lang-dropdown') && langDropdown) {
        langDropdown.style.display = 'none';
        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)';
            }
        });
    });

    // 注释掉旧的事件绑定代码
    // document.getElementById("lang-toggle").addEventListener("click", handleLangToggle);
    // document.getElementById("lang-toggle").addEventListener("keydown", e => {
    //     if (e.key === "Enter" || e.key === " ") handleLangToggle();
    // });
});