// 将地图相关的变量和函数提升到全局作用域
let map = null;
let marker = null;
let infoWindow = null;

// 地图数据配置
const mapData = {
    address: {
        zh: '广东省深圳市南山区粤海街道麻岭社区麻雀岭工业区M-6栋中钢大厦5A010',
        en: 'A010, 5th Floor, Zhonggang Building, Block M-6, Maqueling Industrial Zone, Maling Community, Yuehai Street, Nanshan District, Shenzhen, Guangdong Province, China'
    },
    companyName: {
        zh: '深圳汉晶电子信息有限公司',
        en: 'SZHJ Electronic Information Co., Ltd'
    },
    phone:{
        zh: '13420976989',
        en: '+86 13420976989'
    },
   
    contactInfo: {
        zh: {
            address: '地址',
            phone: '电话',
            email: '邮箱'
        },
        en: {
            address: 'Address',
            phone: 'Phone',
            email: 'Email'
        }
    }
};

// 创建信息窗体内容
function createInfoWindowContent(lang) {
    return `
        <div class="info-content" style="padding: 15px;">
            <h4 style="margin: 0 0 10px 0; color: #100B4E; font-size: 16px;">${mapData.companyName[lang]}</h4>
            <p style="margin: 0 0 8px 0; font-size: 13px;color: #100B4E;">
                <strong>${mapData.contactInfo[lang].address}：</strong>${mapData.address[lang]}
            </p>
            <p style="margin: 0 0 8px 0; font-size: 13px; color: #100B4E;">
                <strong>${mapData.contactInfo[lang].phone}：</strong>${mapData.phone[lang]}
            </p>
            <p style="margin: 0; font-size: 13px; color: #100B4E;">
                <strong>${mapData.contactInfo[lang].email}：</strong>fu.bin@hjsilicon.com
            </p>
        </div>
    `;
}

// 更新地图信息
function updateMapInfo(lang) {
    if (marker && infoWindow) {
        // 更新标记标题
        marker.setTitle(mapData.companyName[lang]);
        
        // 更新信息窗体内容
        infoWindow.setContent(createInfoWindowContent(lang));
        
        // 如果信息窗体是打开状态，重新打开以更新内容
        if (infoWindow.getIsOpen()) {
            infoWindow.open(map, marker.getPosition());
        }
    }
}

// 初始化地图
function initAMap() {
    try {
        // 获取当前语言
        const currentLang = window.currentLang || localStorage.getItem('siteLang') || "zh";
        
        // 先加载所需插件
        AMap.plugin(['AMap.Geocoder', 'AMap.ToolBar', 'AMap.Scale'], function() {
            const geocoder = new AMap.Geocoder({
                city: "深圳",
                radius: 1000
            });
            
            geocoder.getLocation(mapData.address.zh, function(status, result) {
                if (status === 'complete' && result.info === 'OK') {
                    const lnglat = result.geocodes[0].location;
                    
                    // 创建地图实例
                    map = new AMap.Map('mapContainer', {
                        zoom: 16,
                        center: [lnglat.lng, lnglat.lat],
                        viewMode: '3D',
                        resizeEnable: true,
                        pitch: 40,
                        mapStyle: 'amap://styles/normal'
                    });
                    
                    // 创建标记
                    marker = new AMap.Marker({
                        position: [lnglat.lng, lnglat.lat],
                        title: mapData.companyName[currentLang],
                        animation: 'AMAP_ANIMATION_DROP',
                        offset: new AMap.Pixel(-13, -30)
                    });
                    
                    map.add(marker);
                    
                    // 创建信息窗体
                    infoWindow = new AMap.InfoWindow({
                        content: createInfoWindowContent(currentLang),
                        offset: new AMap.Pixel(0, -30),
                        closeWhenClickMap: true
                    });
                    
                    // 地图加载完成后打开信息窗体
                    map.on('complete', function() {
                        infoWindow.open(map, [lnglat.lng, lnglat.lat]);
                    });
                    
                    // 点击标记时打开信息窗体
                    marker.on('click', function() {
                        infoWindow.open(map, marker.getPosition());
                    });
                    
                    // 添加控件
                    map.addControl(new AMap.ToolBar({
                        position: 'RB'
                    }));
                    
                    map.addControl(new AMap.Scale());
                    
                    // 确保标记点居中显示
                    map.setFitView([marker]);
                    
                    // 响应式处理
                    window.addEventListener('resize', function() {
                        map.resize();
                        map.setCenter([lnglat.lng, lnglat.lat]);
                    });
                } else {
                    console.error('地址解析失败:', result);
                    const mapContainer = document.getElementById('mapContainer');
                    if (mapContainer) {
                        mapContainer.innerHTML = 
                            '<div style="text-align:center;padding:20px;color:#f00;">地址定位失败，请刷新重试</div>';
                    }
                }
            });
        });
    } catch (error) {
        console.error('地图初始化失败:', error);
        const mapContainer = document.getElementById('mapContainer');
        if (mapContainer) {
            mapContainer.innerHTML = 
                '<div style="text-align:center;padding:20px;color:#f00;">地图加载失败，请刷新重试</div>';
        }
    }
}

// DOM加载完成时初始化
document.addEventListener('DOMContentLoaded', function() {
    const langData = {
        zh: {
            btn: "English",
            logo: "../imgs/svg/logo.svg",
            title: "深圳汉晶电子信息有限公司",
            // 顶部
            topBannerTitle: "公司介绍",
            topBannerDesc: "我们是一家专注于集成电路设计的高科技公司,致力于为客户提供从芯片设计到量产的全流程服务。我们的团队拥有丰富的行业经验，采用最先进的工具和技术，为客户提供高品质的芯片解决方案。我们始终坚持以客户为中心，以技术为驱动，致力于推动集成电路行业的创新与发展。",
            // 愿景/使命/价值观
            visionTitle: "我们的愿景",
            visionDesc: "聚焦高性能芯片设计，打造全球竞争力核心，以技术创新驱动产业升级，引领智能生态新未来。",
            missionTitle: "我们的使命",
            missionDesc: "通过在集成电路设计、应用解决方案和人工智能技术的持续创新,我们提供高可靠、智能的产品和服务，为客户创造价值，让人们的生活更加美好!",
            valueTitle: "我们的核心价值观",
            valueDesc: "客户至上、艰苦奋斗、创新卓越、合作共赢",
            emailLeftTitle: "我们准备好了",
            emailLeftText: "如果您有更多的需求，请联系我们",
            bannertopBG: "../imgs/us/corporateCultureConcept.svg",
        },
        en: {
            btn: "简体中文",
            logo: "../imgs/svg/logo_en.svg",
            title: "SZHJ Electronic Information Co., Ltd",
            // 顶部
            topBannerTitle: "Company Introduction",
            topBannerDesc: "We are a high-tech company focused on integrated circuit design, dedicated to providing customers with full-process services from chip design to mass production. Our team has extensive industry experience and uses the most advanced tools and technologies to provide customers with high-quality chip solutions. We always adhere to a customer-centric and technology-driven approach, committed to promoting innovation and development in the integrated circuit industry.",
            // 愿景/使命/价值观
            visionTitle: "Our Vision",
            visionDesc: "Focus on high-performance chip design, build globally competitive cores, drive industrial upgrading with technological innovation, and lead the new future of the intelligent ecosystem.",
            missionTitle: "Our Mission",
            missionDesc: "Through continuous innovation in integrated circuit design, application solutions, and artificial intelligence technology, we provide highly reliable and intelligent products and services, create value for customers, and make people's lives better!",
            valueTitle: "Our Core Values",
            valueDesc: "Customer First, Hard Work, Excellence in Innovation, Win-Win Cooperation",
            emailLeftTitle: "We're ready.",
            emailLeftText: "If you have more needs, please contact us!",
            bannertopBG: "../imgs/us/corporateCultureConcept_en.svg",
        }   
    };

    // 使用全局的 currentLang
    if (!window.currentLang) {
        window.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 logoImg = document.getElementById("logo-img");
        // if (logoImg) logoImg.src = data.logo;
        
        // const footerLogo = document.getElementById("footerLogo");
        // if (footerLogo) footerLogo.src = data.logo;

        // 页面标题
        document.title = data.title;
        
        const footerBoxRightTitle = document.querySelector(".footerBoxRightTitle");
        if (footerBoxRightTitle) footerBoxRightTitle.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 visionTitle = document.querySelector('.textOne .Right p:nth-child(1)');
        if (visionTitle) visionTitle.textContent = data.visionTitle;
        
        const visionDesc = document.querySelector('.textOne .Right p:nth-child(2)');
        if (visionDesc) visionDesc.textContent = data.visionDesc;

        // 使命
        const missionTitle = document.querySelector('.textTwo .Right p:nth-child(1)');
        if (missionTitle) missionTitle.textContent = data.missionTitle;
        
        const missionDesc = document.querySelector('.textTwo .Right p:nth-child(2)');
        if (missionDesc) missionDesc.textContent = data.missionDesc;

        // 价值观
        const valueTitle = document.querySelector('.textThree .Right p:nth-child(1)');
        if (valueTitle) valueTitle.textContent = data.valueTitle;
        
        const valueDesc = document.querySelector('.textThree .Right p:nth-child(2)');
        if (valueDesc) valueDesc.textContent = data.valueDesc;

        // 邮箱区
        const emailLeftTitle = document.querySelector(".emailLeftTitle");
        if (emailLeftTitle) emailLeftTitle.textContent = data.emailLeftTitle;
        
        const emailLeftText = document.querySelector(".emailLeftText");
        if (emailLeftText) emailLeftText.textContent = data.emailLeftText;

        // 背景图片
        const bannertop = document.querySelector('.bannertop');
        if (bannertop) bannertop.style.backgroundImage = `url(${data.bannertopBG})`;

        // 英文样式调整
        const visionPs = document.querySelectorAll('.textOne .Right p');
        const missionPs = document.querySelectorAll('.textTwo .Right p');
        const valuePs = document.querySelectorAll('.textThree .Right p');
        
        if (visionPs && missionPs && valuePs) {
            const allPs = [...visionPs, ...missionPs, ...valuePs];
        
            if (lang === 'en') {
                if (topBannerTitle) topBannerTitle.classList.add('en');
                if (topBannerDesc) topBannerDesc.classList.add('en');
                allPs.forEach(p => p.classList.add('en'));
            } else {
                if (topBannerTitle) topBannerTitle.classList.remove('en');
                if (topBannerDesc) topBannerDesc.classList.remove('en');
                allPs.forEach(p => p.classList.remove('en'));
            }
        }
        
        // 更新地图信息
        updateMapInfo(lang);
        
        // 更新语言显示
        updateLanguageDisplay(lang);
    }

    // 修正的handleLangToggle函数，正确接收lang参数
    function handleLangToggle(lang) {
        window.currentLang = lang;
        localStorage.setItem('siteLang', window.currentLang);
        applyLang(window.currentLang);
        updateLanguageDisplay(window.currentLang);
    }
    
    // 初始化语言和地图
    applyLang(window.currentLang);
    updateLanguageDisplay(window.currentLang);
    
    if (typeof AMap !== 'undefined') {
        initAMap();
    }

    // 获取语言切换相关的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 !== window.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();
    // });
});

// 回调函数
window.initMap = function() {
    if (typeof AMap !== 'undefined') {
        initAMap();
    }
};