// 实时行情数据更新功能
document.addEventListener('DOMContentLoaded', function() {
    const tickerContent = document.querySelector('.ticker-content');
    if (!tickerContent) return;

    // 初始占位符数据
    const initialData = [
        { symbol: 'HSI', price: '16,842.23', change: '+1.2%', direction: 'positive' },
        { symbol: 'AAPL', price: '173.45', change: '+0.8%', direction: 'positive' },
        { symbol: 'TSLA', price: '245.67', change: '-0.5%', direction: 'negative' },
        { symbol: 'BTC/USD', price: '61,234.56', change: '+2.1%', direction: 'positive' }
    ];

    // 初始化行情显示器
    function initializeTicker() {
        tickerContent.innerHTML = '';
        initialData.forEach(item => {
            const tickerItem = createTickerItem(item);
            tickerContent.appendChild(tickerItem);
        });
    }

    // 创建行情项元素
    function createTickerItem(data) {
        const item = document.createElement('div');
        item.className = 'ticker-item';
        item.innerHTML = `
            <span class="symbol">${data.symbol}</span>
            <span class="price">${formatPrice(data.price)}</span>
            <span class="change ${data.direction}">${data.change}</span>
        `;
        return item;
    }

    // 格式化价格显示
    function formatPrice(price) {
        if (typeof price === 'number') {
            // 对于数字，添加千位分隔符
            return price.toLocaleString('en-US', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        }
        return price;
    }

    // 获取实时市场数据
    async function fetchMarketData() {
        try {
            const response = await fetch('/api/market-data');
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            const data = await response.json();
            
            if (data.status === 'success') {
                updateTicker(data.data);
            } else {
                console.error('获取市场数据失败:', data.message);
            }
        } catch (error) {
            console.error('获取实时行情数据时发生错误:', error);
            // 保持显示静态数据，不更新
        }
    }

    // 更新行情显示器
    function updateTicker(marketData) {
        tickerContent.innerHTML = '';
        marketData.forEach(item => {
            const direction = item.change_percent >= 0 ? 'positive' : 'negative';
            const changeSign = item.change_percent >= 0 ? '+' : '';
            
            const tickerItem = document.createElement('div');
            tickerItem.className = 'ticker-item';
            tickerItem.innerHTML = `
                <span class="symbol">${item.symbol}</span>
                <span class="price">${formatPrice(item.price)}</span>
                <span class="change ${direction}">${changeSign}${item.change_percent}%</span>
            `;
            tickerContent.appendChild(tickerItem);
        });
    }

    // 初始化并开始定时更新
    initializeTicker();
    
    // 立即获取一次数据
    fetchMarketData();
    
    // 每30秒更新一次数据
    setInterval(fetchMarketData, 30000);
    
    // 添加刷新按钮功能
    const refreshBadge = document.querySelector('.refresh-badge');
    if (refreshBadge) {
        refreshBadge.addEventListener('click', function() {
            this.textContent = '刷新中...';
            fetchMarketData().then(() => {
                setTimeout(() => {
                    this.textContent = 'Live';
                }, 1000);
            });
        });
        
        // 添加提示文字
        refreshBadge.title = '点击手动刷新行情';
        refreshBadge.style.cursor = 'pointer';
    }
});
