document.addEventListener('DOMContentLoaded', function() {
    // 获取URL参数中的产品ID
    const urlParams = new URLSearchParams(window.location.search);
    const productId = urlParams.get('product');

    // 显示产品的函数
    function showProduct(productId, shouldScroll = false) { // 默认不滚动
        console.log('Showing product:', productId);

        // 移除所有产品项的active类
        const productItems = document.querySelectorAll('.product-item');
        productItems.forEach(p => {
            p.classList.remove('active');
        });
        
        // 找到对应的产品项并添加active类
        const targetItem = document.querySelector(`[data-product="${productId}"]`);
        if (targetItem) {
            targetItem.classList.add('active');
            
            // 确保产品所在的分类是展开的
            const category = targetItem.closest('.category-content');
            if (category) {
                // 先移除所有分类的show类
                document.querySelectorAll('.category-content').forEach(c => {
                    c.classList.remove('show');
                });
                document.querySelectorAll('.category-header').forEach(h => {
                    h.classList.remove('active');
                });

                // 展开当前分类
                category.classList.add('show');
                const categoryHeader = category.previousElementSibling;
                if (categoryHeader) {
                    categoryHeader.classList.add('active');
                }
            }

            // 隐藏所有详情内容
            document.querySelectorAll('.detail-content').forEach(content => {
                if (content) {
                    content.style.display = 'none';
                }
            });
            
            // 显示目标产品详情
            const targetContent = document.getElementById(productId);
            if (targetContent) {
                targetContent.style.display = 'block';
            }

            // 只在指定需要滚动时才滚动
            if (shouldScroll) {
                setTimeout(() => {
                    targetItem.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }, 100);
            }
        }
    }

    // 初始化：根据URL参数决定行为
    if (productId) {
        // 如果有产品ID参数，则显示对应产品并滚动
        showProduct(productId, true); // 有参数时滚动
    } else {
        // 没有参数时，显示第一个产品但不滚动
        const firstProduct = document.querySelector('.product-item');
        if (firstProduct) {
            showProduct(firstProduct.dataset.product, false); // 无参数时不滚动
        }
    }

    // 产品项点击处理
    const productItems = document.querySelectorAll('.product-item');
    productItems.forEach(item => {
        item.addEventListener('click', function() {
            const productId = this.dataset.product;
            // 点击产品项时需要滚动
            showProduct(productId, true);
            updateURL(productId);
        });
    });

    // 更新URL函数
    function updateURL(productId) {
        const newURL = new URL(window.location.href);
        newURL.searchParams.set('product', productId);
        window.history.pushState({ productId }, '', newURL);
    }

    // 处理浏览器后退/前进
    window.addEventListener('popstate', function(event) {
        if (event.state && event.state.productId) {
            showProduct(event.state.productId, true);
        }
    });


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


    const langData = {
        zh: {
           
            btn: "English",
            logo: "../imgs/svg/logo.svg",       
   
            title: "深圳汉晶电子信息有限公司",
            topBannerLeftTitle1:"成功的工艺",
            topBannerLeftTitle2:"与产品案例",
            topBannerBthSpan:"联系我们",
            product_item_titleY100:"Y100 服务器芯片",
            product_item_titleS6PRO:"S6PRO 运算加速芯片",
            product_item_titleFX100:"FX100 MCU芯片",
            product_item_titleGSEC8:"GSEC8 安全加密芯片",
            product_item_titleS1PRO:"S1PRO 运算加速芯片",
            product_item_titleVV10:"VV10 信息安全芯片",
            OtherProducts:"其他产品",
            detail_info_textY1001:"解决方案：我们通过对客户需求的深度研究，设计了一款集成了高速计算、信号处理单元和数据传输功能的芯片。",
            detail_info_textY1002:"技术亮点：采用了定制化的22nm工艺，低功耗设计。",
            detail_info_textS6PRO1:"解决方案：在S1PRO芯片的架构基础上进一步优化细节，缩减逻辑资源，节省面积。",
            detail_info_textS6PRO2:"技术亮点：使用了定制化的12nm工艺，集成了多个核心模块，并通过自研算法加速模块，提升了运算能力。",
            detail_info_textS1PRO1:"解决方案：我们根据客户的需求设计了一个集成soc和特定加速模块的系统级芯片。通过先进的架构和特定的低功耗设计，确保芯片在性能和功耗上的平衡。",
            detail_info_textS1PRO2:"技术亮点：使用了定制化的22nm工艺，集成了多个核心模块，并通过自研算法加速模块，提升了运算能力。",
            detail_info_textVV101:"解决方案：我们根据客户的需求设计了一个由CPU核心处理器连接外部存储并通过私有总线扩展外设接口，内部包含两个RAM，具备ITCM和DTCM用于指令和数据存储。",
            detail_info_textVV102:"技术亮点：EAI协处理器接口和AES算法核支持高效加解密运算，RSA算法核由控制、模乘和寄存器堆组成，实现高效RSA算法运算。",
            detail_info_textFX1001:"解决方案：我们根据客户的需求设计了一个由两个Master和三个Slave组成，其中，两个Master分别是CPU内核和DMA控制器，三个Slave为内部SRAM，NVM和外设。",
            detail_info_textFX1002:"技术亮点：FX100采用超低功耗休眠模式（μA级别），使得搭载该芯片的医疗器械在外部断电时依然可以通过内置电池继续工作。",
            detail_info_textGSEC81:"解决方案：集成 RSA/ECC 加速器，支持安全启动与防物理攻击。",
            detail_info_textGSEC82:"技术亮点：支持国密算法，具备 CC EAL5+ 认证与 TRNG。",
            emailLeftTitle:"我们准备好了",
            emailLeftText:"如果您有更多的需求，请联系我们",
            chipProducts:"芯片产品",

        },
        en: {
           
            btn: "简体中文",
            logo: "../imgs/svg/logo_en.svg",
    
            title: "SZHJ Electronic Information Co., Ltd",
            topBannerLeftTitle1:"Successful Processes",
            topBannerLeftTitle2:"With product examples",
            topBannerBthSpan:"Contact Us",
            product_item_titleY100:"Y100 Server Chips",
            product_item_titleS6PRO:"S6PRO computing accelerator chip",
            product_item_titleFX100:"FX100 MCU chip",
            product_item_titleGSEC8:"GSEC8 Secure encryption chip",
            product_item_titleS1PRO:"S1PRO computing accelerator chip",
            product_item_titleVV10:"VV10 Information Security Chip",
            OtherProducts:"Other Products",
            detail_info_textY1001:"Solution: We designed a chip that integrates high-speed computing, signal processing unit and data transmission functions through an in-depth study of customer requirements.",
            detail_info_textY1002:"Technical highlight: Adopting customized 22nm process and low-power design.",
            detail_info_textS6PRO1:"Solution: Further optimize the details based on the architecture of the S1PRO chip, reduce logic resources and save area.",
            detail_info_textS6PRO2:"Technical highlights: Customized 12nm process is used, multiple core modules are integrated, and self-developed algorithm acceleration modules are used to enhance computing power.",
            detail_info_textS1PRO1:"Solution: We designed a system-on-chip with integrated soc and specific acceleration modules according to the customer's requirements. The advanced architecture and specific low-power design ensure that the chip is balanced in terms of performance and power consumption.",
            detail_info_textS1PRO2:"Technical highlights: Customized 12nm process is used, multiple core modules are integrated, and self-developed algorithm acceleration modules are used to enhance computing power.",
            detail_info_textVV101:"Solution: According to the customer's requirements, we designed a CPU core processor to connect to external storage and extend the peripheral interface through a private bus, which contains two internal RAMs with ITCM and DTCM for instruction and data storage.",
            detail_info_textVV102:"Technology highlights: EAI coprocessor interface and AES algorithm core support efficient encryption and decryption operations, RSA algorithm core consists of control, modulo multiplication and register stacks to realize efficient RSA algorithm operations.",
            detail_info_textFX1001:"Solution: According to the customer's requirements, we designed a system consisting of two Masters and three Slaves, where the two Masters are the CPU core and the DMA controller, and the three Slaves are the internal SRAM, NVM and peripherals.",
            detail_info_textFX1002:"Technical highlights: The FX100 utilizes an ultra-low power sleep mode (μA level), which allows medical devices equipped with the chip to continue to operate with the built-in battery even when external power is lost.",
            detail_info_textGSEC81:"Solution: Integrated RSA/ECC gas pedal supports secure boot and physical attack prevention.",
            detail_info_textGSEC82:"Technical Highlights: Supports state secret algorithms with CC EAL5+ certification and TRNG.",
            emailLeftTitle:"We're ready.",
            emailLeftText:"If you have more needs, please contact us!",
            chipProducts:"Chip products",
        }
    };

    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 topBannerLeftTitle1 = document.getElementById("topBannerLeftTitle1");
        if (topBannerLeftTitle1) topBannerLeftTitle1.textContent = data.topBannerLeftTitle1;
        
        const topBannerLeftTitle2 = document.getElementById("topBannerLeftTitle2");
        if (topBannerLeftTitle2) topBannerLeftTitle2.textContent = data.topBannerLeftTitle2;
        
        const topBannerBthSpan = document.querySelector(".topBannerBthSpan");
        if (topBannerBthSpan) topBannerBthSpan.textContent = data.topBannerBthSpan;

        // 使用querySelectorAll获取所有元素并检查每个元素
        document.querySelectorAll('.product_item_titleY100').forEach(el => {
            if (el) el.textContent = data.product_item_titleY100;
        });
        
        document.querySelectorAll('.product_item_titleS6PRO').forEach(el => {
            if (el) el.textContent = data.product_item_titleS6PRO;
        });
        
        document.querySelectorAll('.product_item_titleFX100').forEach(el => {
            if (el) el.textContent = data.product_item_titleFX100;
        });
        
        document.querySelectorAll('.product_item_titleGSEC8').forEach(el => {
            if (el) el.textContent = data.product_item_titleGSEC8;
        });
        
        document.querySelectorAll('.product_item_titleS1PRO').forEach(el => {
            if (el) el.textContent = data.product_item_titleS1PRO;
        }); 
        
        document.querySelectorAll('.product_item_titleVV10').forEach(el => {
            if (el) el.textContent = data.product_item_titleVV10;
        });  

        document.querySelectorAll('.category-header-title').forEach(el => {
            if (el) el.textContent = data.chipProducts;
        });  

        const otherProducts = document.querySelector(".OtherProducts");
        if (otherProducts) otherProducts.textContent = data.OtherProducts;
        
        // 解决方案和技术亮点文本
        const elements = {
            ".detail_info_textY1001": data.detail_info_textY1001,
            ".detail_info_textY1002": data.detail_info_textY1002,
            ".detail_info_textS6PRO1": data.detail_info_textS6PRO1,
            ".detail_info_textS6PRO2": data.detail_info_textS6PRO2,
            ".detail_info_textS1PRO1": data.detail_info_textS1PRO1,
            ".detail_info_textS1PRO2": data.detail_info_textS1PRO2,
            ".detail_info_textVV101": data.detail_info_textVV101,
            ".detail_info_textVV102": data.detail_info_textVV102,
            ".detail_info_textFX1001": data.detail_info_textFX1001,
            ".detail_info_textFX1002": data.detail_info_textFX1002,
            ".detail_info_textGSEC81": data.detail_info_textGSEC81,
            ".detail_info_textGSEC82": data.detail_info_textGSEC82,
            ".emailLeftTitle": data.emailLeftTitle,
            ".emailLeftText": data.emailLeftText,
        };

        // 遍历并应用文本
        for (const [selector, text] of Object.entries(elements)) {
            const element = document.querySelector(selector);
            if (element) element.textContent = text;
        }
        
        const footerBoxRightTitle = document.querySelector('.footerBoxRightTitle');
        if (footerBoxRightTitle) footerBoxRightTitle.textContent = data.title;

        // 切换样式
        if (lang === 'en') {
            if (topBannerLeftTitle1) topBannerLeftTitle1.classList.add('en');
            if (topBannerLeftTitle2) topBannerLeftTitle2.classList.add('en');
        } else {
            if (topBannerLeftTitle1) topBannerLeftTitle1.classList.remove('en');
            if (topBannerLeftTitle2) topBannerLeftTitle2.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';
            }
            
            // 旋转箭头
            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)';
            }
        }
    });
 
    // 语言选择事件
    if (langItems) {
        langItems.forEach(item => {
            item.addEventListener('click', function() {
                const lang = this.getAttribute('data-lang');
                if (lang !== currentLang) {
                    handleLangToggle(lang);
                }
                if (langDropdown) langDropdown.style.display = 'none';
                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();
    // });
});