// AI产业链分析平台 - 主要JavaScript文件

// 全局变量
let currentFilter = 'all';
let marketChart, techBarrierChart, marketShareChart;

// 公司数据
const companiesData = {
    cambricon: {
        name: '寒武纪',
        category: 'upstream',
        moatScore: 9.2,
        marketShare: 15,
        patents: 2700,
        revenue: 2.3,
        growth: 65
    },
    huawei: {
        name: '华为昇腾',
        category: 'upstream',
        moatScore: 9.5,
        marketShare: 25,
        patents: 5000,
        revenue: 8.5,
        growth: 45
    },
    nvidia: {
        name: '英伟达',
        category: 'upstream',
        moatScore: 9.9,
        marketShare: 90,
        patents: 8000,
        revenue: 60.9,
        growth: 122
    },
    iflytek: {
        name: '科大讯飞',
        category: 'upstream',
        moatScore: 9.1,
        marketShare: 18,
        patents: 3200,
        revenue: 18.3,
        growth: 25
    },
    baidu: {
        name: '百度飞桨',
        category: 'midstream',
        moatScore: 9.0,
        marketShare: 35,
        developers: 2333,
        models: 110,
        growth: 40
    },
    hikvision: {
        name: '海康威视',
        category: 'downstream',
        moatScore: 8.8,
        marketShare: 28,
        revenue: 81.2,
        accuracy: 99,
        growth: 12
    }
};

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeAnimations();
    initializeCharts();
    initializeFilters();
    initializeScrollEffects();
});

// 初始化滚动动画
function initializeAnimations() {
    // 页面加载动画
    anime({
        targets: '.fade-in',
        opacity: [0, 1],
        translateY: [30, 0],
        delay: anime.stagger(200),
        duration: 800,
        easing: 'easeOutQuart'
    });

    // 公司卡片动画
    anime({
        targets: '.company-card',
        scale: [0.9, 1],
        opacity: [0, 1],
        delay: anime.stagger(100, {start: 500}),
        duration: 600,
        easing: 'easeOutBack'
    });
}

// 初始化图表
function initializeCharts() {
    // 市场规模分析图表
    const marketChartDom = document.getElementById('marketChart');
    marketChart = echarts.init(marketChartDom);
    
    const marketOption = {
        backgroundColor: 'transparent',
        title: {
            text: 'AI产业市场规模趋势',
            textStyle: { color: '#ffffff', fontSize: 18 },
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(30, 41, 59, 0.9)',
            borderColor: 'rgba(148, 163, 184, 0.2)',
            textStyle: { color: '#ffffff' }
        },
        legend: {
            data: ['中国AI市场', '全球AI市场', 'AI芯片市场'],
            textStyle: { color: '#cbd5e1' },
            bottom: 10
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['2020', '2021', '2022', '2023', '2024', '2025'],
            axisLine: { lineStyle: { color: '#475569' } },
            axisLabel: { color: '#94a3b8' }
        },
        yAxis: {
            type: 'value',
            axisLine: { lineStyle: { color: '#475569' } },
            axisLabel: { color: '#94a3b8' },
            splitLine: { lineStyle: { color: 'rgba(71, 85, 105, 0.3)' } }
        },
        series: [
            {
                name: '中国AI市场',
                type: 'line',
                smooth: true,
                data: [150, 220, 320, 450, 620, 850],
                lineStyle: { color: '#2563eb', width: 3 },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0, y: 0, x2: 0, y2: 1,
                        colorStops: [
                            { offset: 0, color: 'rgba(37, 99, 235, 0.3)' },
                            { offset: 1, color: 'rgba(37, 99, 235, 0.05)' }
                        ]
                    }
                }
            },
            {
                name: '全球AI市场',
                type: 'line',
                smooth: true,
                data: [1200, 1650, 2200, 2900, 3800, 4900],
                lineStyle: { color: '#0891b2', width: 3 },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0, y: 0, x2: 0, y2: 1,
                        colorStops: [
                            { offset: 0, color: 'rgba(8, 145, 178, 0.3)' },
                            { offset: 1, color: 'rgba(8, 145, 178, 0.05)' }
                        ]
                    }
                }
            },
            {
                name: 'AI芯片市场',
                type: 'line',
                smooth: true,
                data: [180, 280, 420, 650, 950, 1400],
                lineStyle: { color: '#059669', width: 3 },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0, y: 0, x2: 0, y2: 1,
                        colorStops: [
                            { offset: 0, color: 'rgba(5, 150, 105, 0.3)' },
                            { offset: 1, color: 'rgba(5, 150, 105, 0.05)' }
                        ]
                    }
                }
            }
        ]
    };
    
    marketChart.setOption(marketOption);

    // 技术壁垒分析图表
    const techChartDom = document.getElementById('techBarrierChart');
    techBarrierChart = echarts.init(techChartDom);
    
    const techOption = {
        backgroundColor: 'transparent',
        title: {
            text: '各公司技术壁垒评分',
            textStyle: { color: '#ffffff', fontSize: 16 },
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            backgroundColor: 'rgba(30, 41, 59, 0.9)',
            borderColor: 'rgba(148, 163, 184, 0.2)',
            textStyle: { color: '#ffffff' }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: ['寒武纪', '华为昇腾', '英伟达', '科大讯飞', '百度飞桨', '海康威视'],
            axisLine: { lineStyle: { color: '#475569' } },
            axisLabel: { color: '#94a3b8', rotate: 45 }
        },
        yAxis: {
            type: 'value',
            max: 10,
            axisLine: { lineStyle: { color: '#475569' } },
            axisLabel: { color: '#94a3b8' },
            splitLine: { lineStyle: { color: 'rgba(71, 85, 105, 0.3)' } }
        },
        series: [{
            type: 'bar',
            data: [9.2, 9.5, 9.9, 9.1, 9.0, 8.8],
            itemStyle: {
                color: {
                    type: 'linear',
                    x: 0, y: 0, x2: 0, y2: 1,
                    colorStops: [
                        { offset: 0, color: '#2563eb' },
                        { offset: 1, color: '#0891b2' }
                    ]
                },
                borderRadius: [4, 4, 0, 0]
            },
            emphasis: {
                itemStyle: { color: '#059669' }
            }
        }]
    };
    
    techBarrierChart.setOption(techOption);

    // 市场份额分析图表
    const shareChartDom = document.getElementById('marketShareChart');
    marketShareChart = echarts.init(shareChartDom);
    
    const shareOption = {
        backgroundColor: 'transparent',
        title: {
            text: 'AI芯片市场份额',
            textStyle: { color: '#ffffff', fontSize: 16 },
            left: 'center'
        },
        tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(30, 41, 59, 0.9)',
            borderColor: 'rgba(148, 163, 184, 0.2)',
            textStyle: { color: '#ffffff' }
        },
        legend: {
            orient: 'horizontal',
            bottom: '0%',
            textStyle: { color: '#94a3b8' }
        },
        series: [{
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '45%'],
            avoidLabelOverlap: false,
            label: {
                show: false,
                position: 'center'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: '18',
                    fontWeight: 'bold',
                    color: '#ffffff'
                }
            },
            labelLine: { show: false },
            data: [
                { value: 90, name: '英伟达', itemStyle: { color: '#2563eb' } },
                { value: 25, name: '华为昇腾', itemStyle: { color: '#0891b2' } },
                { value: 15, name: '寒武纪', itemStyle: { color: '#059669' } },
                { value: 8, name: '其他', itemStyle: { color: '#6b7280' } }
            ]
        }]
    };
    
    marketShareChart.setOption(shareOption);

    // 响应式处理
    window.addEventListener('resize', function() {
        marketChart.resize();
        techBarrierChart.resize();
        marketShareChart.resize();
    });
}

// 初始化筛选功能
function initializeFilters() {
    const filterButtons = document.querySelectorAll('.filter-btn');
    const companyCards = document.querySelectorAll('.company-card');

    filterButtons.forEach(button => {
        button.addEventListener('click', function() {
            // 更新按钮状态
            filterButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            
            const filter = this.getAttribute('data-filter');
            currentFilter = filter;
            
            // 筛选公司卡片
            companyCards.forEach(card => {
                const categories = card.getAttribute('data-category');
                
                if (filter === 'all' || categories.includes(filter)) {
                    card.style.display = 'block';
                    anime({
                        targets: card,
                        opacity: [0, 1],
                        scale: [0.8, 1],
                        duration: 400,
                        easing: 'easeOutBack'
                    });
                } else {
                    anime({
                        targets: card,
                        opacity: [1, 0],
                        scale: [1, 0.8],
                        duration: 300,
                        easing: 'easeInBack',
                        complete: function() {
                            card.style.display = 'none';
                        }
                    });
                }
            });
        });
    });

    // 公司卡片点击事件
    companyCards.forEach(card => {
        card.addEventListener('click', function() {
            const companyId = this.getAttribute('data-company');
            if (companyId) {
                showCompanyDetails(companyId);
            }
        });
    });
}

// 显示公司详情
function showCompanyDetails(companyId) {
    const company = companiesData[companyId];
    if (!company) return;
    
    // 创建模态框显示公司详情
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
    modal.innerHTML = `
        <div class="bg-gray-900 rounded-lg p-8 max-w-2xl w-full mx-4 max-h-96 overflow-y-auto">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-2xl font-bold">${company.name} - 详细分析</h3>
                <button onclick="this.parentElement.parentElement.parentElement.remove()" class="text-gray-400 hover:text-white">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </button>
            </div>
            <div class="grid md:grid-cols-2 gap-6">
                <div>
                    <h4 class="text-lg font-semibold mb-3 text-blue-400">基本指标</h4>
                    <div class="space-y-2">
                        <div class="flex justify-between">
                            <span>护城河评分:</span>
                            <span class="text-green-400">${company.moatScore}/10</span>
                        </div>
                        <div class="flex justify-between">
                            <span>市场份额:</span>
                            <span class="text-blue-400">${company.marketShare}%</span>
                        </div>
                        ${company.patents ? `<div class="flex justify-between"><span>专利数量:</span><span class="text-purple-400">${company.patents}+</span></div>` : ''}
                        ${company.developers ? `<div class="flex justify-between"><span>开发者数:</span><span class="text-cyan-400">${company.developers}万</span></div>` : ''}
                    </div>
                </div>
                <div>
                    <h4 class="text-lg font-semibold mb-3 text-purple-400">财务表现</h4>
                    <div class="space-y-2">
                        ${company.revenue ? `<div class="flex justify-between"><span>营收规模:</span><span class="text-yellow-400">${company.revenue}亿元</span></div>` : ''}
                        ${company.growth ? `<div class="flex justify-between"><span>同比增长:</span><span class="text-green-400">+${company.growth}%</span></div>` : ''}
                    </div>
                </div>
            </div>
            <div class="mt-6 text-center">
                <button onclick="window.location.href='company.html?company=${companyId}'" class="btn-primary">
                    查看完整分析报告
                </button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 添加动画
    anime({
        targets: modal.querySelector('div'),
        scale: [0.8, 1],
        opacity: [0, 1],
        duration: 300,
        easing: 'easeOutBack'
    });
}

// 初始化滚动效果
function initializeScrollEffects() {
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('visible');
                
                // 为图表添加动画
                if (entry.target.querySelector('.chart-container')) {
                    animateChart(entry.target);
                }
            }
        });
    }, observerOptions);

    // 观察所有需要动画的元素
    document.querySelectorAll('.fade-in').forEach(el => {
        observer.observe(el);
    });
}

// 图表动画
function animateChart(container) {
    const chartContainer = container.querySelector('.chart-container');
    if (!chartContainer) return;
    
    const chartId = chartContainer.id;
    
    // 根据图表类型添加不同的动画
    switch(chartId) {
        case 'marketChart':
            animateMarketChart();
            break;
        case 'techBarrierChart':
            animateTechBarrierChart();
            break;
        case 'marketShareChart':
            animateMarketShareChart();
            break;
    }
}

// 市场规模图表动画
function animateMarketChart() {
    if (!marketChart) return;
    
    const option = marketChart.getOption();
    const newOption = { ...option };
    
    // 重置数据为0
    newOption.series.forEach(series => {
        series.data = series.data.map(() => 0);
    });
    
    marketChart.setOption(newOption);
    
    // 动画显示数据
    setTimeout(() => {
        marketChart.setOption(option);
    }, 500);
}

// 技术壁垒图表动画
function animateTechBarrierChart() {
    if (!techBarrierChart) return;
    
    const option = techBarrierChart.getOption();
    const newOption = { ...option };
    
    // 重置数据为0
    newOption.series[0].data = newOption.series[0].data.map(() => 0);
    
    techBarrierChart.setOption(newOption);
    
    // 动画显示数据
    setTimeout(() => {
        techBarrierChart.setOption(option);
    }, 500);
}

// 市场份额图表动画
function animateMarketShareChart() {
    if (!marketShareChart) return;
    
    const option = marketShareChart.getOption();
    const newOption = { ...option };
    
    // 重置数据为0
    newOption.series[0].data.forEach(item => {
        item.value = 0;
    });
    
    marketShareChart.setOption(newOption);
    
    // 动画显示数据
    setTimeout(() => {
        marketShareChart.setOption(option);
    }, 500);
}

// 滚动到指定区域
function scrollToSection(sectionId) {
    const section = document.getElementById(sectionId);
    if (section) {
        section.scrollIntoView({ 
            behavior: 'smooth',
            block: 'start'
        });
    }
}

// 平滑滚动导航
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        const targetId = this.getAttribute('href').substring(1);
        scrollToSection(targetId);
    });
});

// 导航栏滚动效果
window.addEventListener('scroll', function() {
    const nav = document.querySelector('nav');
    if (window.scrollY > 100) {
        nav.style.background = 'rgba(30, 41, 59, 0.95)';
    } else {
        nav.style.background = 'rgba(30, 41, 59, 0.8)';
    }
});

// 添加鼠标移动视差效果
document.addEventListener('mousemove', function(e) {
    const mouseX = e.clientX / window.innerWidth;
    const mouseY = e.clientY / window.innerHeight;
    
    // 为hero背景添加微妙的视差效果
    const heroBg = document.querySelector('.hero-bg');
    if (heroBg) {
        const moveX = (mouseX - 0.5) * 20;
        const moveY = (mouseY - 0.5) * 20;
        heroBg.style.transform = `translate(${moveX}px, ${moveY}px)`;
    }
});

// 键盘快捷键支持
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + K 快速搜索
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        // 这里可以添加搜索功能
        console.log('快速搜索功能');
    }
    
    // ESC 关闭模态框
    if (e.key === 'Escape') {
        const modal = document.querySelector('.fixed.inset-0');
        if (modal) {
            modal.remove();
        }
    }
});

// 性能优化：防抖和节流
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    }
}

// 使用防抖优化窗口大小改变事件
const debouncedResize = debounce(function() {
    if (marketChart) marketChart.resize();
    if (techBarrierChart) techBarrierChart.resize();
    if (marketShareChart) marketShareChart.resize();
}, 250);

window.addEventListener('resize', debouncedResize);

// 使用节流优化滚动事件
const throttledScroll = throttle(function() {
    // 滚动相关的处理
}, 16);

window.addEventListener('scroll', throttledScroll);