Spaces:
Running

File size: 10,315 Bytes
fec56b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// CryptoVoid Terminal - Main Script

// API Endpoints
const APIS = {
    crypto: 'https://api.coingecko.com/api/v3',
    stocks: 'https://query1.finance.yahoo.com/v8/finance/chart',
    news: 'https://min-api.cryptocompare.com/data/v2/news'
};

// State Management
const state = {
    cryptoData: [],
    stockData: [],
    newsData: [],
    lastUpdate: null,
    selectedTimeframe: '24h'
};

// Utility Functions
const formatCurrency = (value, decimals = 2) => {
    if (value >= 1e12) return `$${(value / 1e12).toFixed(decimals)}T`;
    if (value >= 1e9) return `$${(value / 1e9).toFixed(decimals)}B`;
    if (value >= 1e6) return `$${(value / 1e6).toFixed(decimals)}M`;
    if (value >= 1e3) return `$${(value / 1e3).toFixed(decimals)}K`;
    return `$${value.toFixed(decimals)}`;
};

const formatPercentage = (value) => {
    const sign = value >= 0 ? '+' : '';
    return `${sign}${value.toFixed(2)}%`;
};

const getChangeColor = (value) => {
    return value >= 0 ? 'text-accent-lime' : 'text-accent-magenta';
};

const getChangeBg = (value) => {
    return value >= 0 ? 'bg-accent-lime/10' : 'bg-accent-magenta/10';
};

// Fetch Crypto Data
async function fetchCryptoData() {
    try {
        const response = await fetch(
            `${APIS.crypto}/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=12&page=1&sparkline=true&price_change_percentage=24h,7d`
        );
        const data = await response.json();
        state.cryptoData = data;
        renderCryptoCards();
        updateGlobalStats();
    } catch (error) {
        console.error('Crypto fetch error:', error);
        renderCryptoSkeleton();
    }
}

// Fetch Stock Data (Simulated with popular tickers)
async function fetchStockData() {
    // Simulated stock data since Yahoo Finance has CORS restrictions
    const mockStocks = [
        { symbol: 'SPY', name: 'S&P 500 ETF', price: 445.23, change: 1.25, changePercent: 0.28, volume: '52.3M' },
        { symbol: 'QQQ', name: 'Nasdaq-100 ETF', price: 378.45, change: -2.15, changePercent: -0.57, volume: '38.7M' },
        { symbol: 'AAPL', name: 'Apple Inc.', price: 178.35, change: 2.45, changePercent: 1.39, volume: '45.2M' },
        { symbol: 'MSFT', name: 'Microsoft Corp.', price: 332.18, change: -1.82, changePercent: -0.54, volume: '22.1M' },
        { symbol: 'GOOGL', name: 'Alphabet Inc.', price: 136.42, change: 0.95, changePercent: 0.70, volume: '18.9M' },
        { symbol: 'AMZN', name: 'Amazon.com', price: 127.83, change: -0.67, changePercent: -0.52, volume: '31.4M' },
        { symbol: 'TSLA', name: 'Tesla Inc.', price: 242.65, change: 5.23, changePercent: 2.20, volume: '98.5M' },
        { symbol: 'NVDA', name: 'NVIDIA Corp.', price: 460.18, change: 8.45, changePercent: 1.87, volume: '42.7M' }
    ];
    
    // Add some randomization to simulate live data
    state.stockData = mockStocks.map(stock => ({
        ...stock,
        price: stock.price * (1 + (Math.random() - 0.5) * 0.02),
        change: stock.change + (Math.random() - 0.5) * 0.5
    }));
    
    renderStockCards();
}

// Fetch News
async function fetchNews() {
    try {
        const response = await fetch(
            `https://min-api.cryptocompare.com/data/v2/news/?lang=EN&limit=6`
        );
        const data = await response.json();
        state.newsData = data.Data || [];
        renderNews();
    } catch (error) {
        console.error('News fetch error:', error);
        renderNewsSkeleton();
    }
}

// Render Functions
function renderCryptoCards() {
    const grid = document.getElementById('crypto-grid');
    if (!grid) return;
    
    grid.innerHTML = state.cryptoData.map((coin, index) => `
        <void-crypto-card
            rank="${index + 1}"
            symbol="${coin.symbol.toUpperCase()}"
            name="${coin.name}"
            price="${coin.current_price}"
            change24h="${coin.price_change_percentage_24h || 0}"
            change7d="${coin.price_change_percentage_7d_in_currency || 0}"
            marketCap="${coin.market_cap}"
            volume="${coin.total_volume}"
            image="${coin.image}"
            sparkline='${JSON.stringify(coin.sparkline_in_7d?.price || [])}'
        ></void-crypto-card>
    `).join('');
}

function renderStockCards() {
    const grid = document.getElementById('stocks-grid');
    if (!grid) return;
    
    grid.innerHTML = state.stockData.map(stock => `
        <void-stock-card
            symbol="${stock.symbol}"
            name="${stock.name}"
            price="${stock.price.toFixed(2)}"
            change="${stock.change.toFixed(2)}"
            changePercent="${stock.changePercent.toFixed(2)}"
            volume="${stock.volume}"
        ></void-stock-card>
    `).join('');
}

function renderNews() {
    const container = document.getElementById('news-feed');
    if (!container) return;
    
    container.innerHTML = state.newsData.map((news, index) => `
        <article class="void-card bg-void-800 border border-void-600 rounded-lg p-5 hover:border-accent-cyan/50 transition-all group">
            <div class="flex gap-4">
                <img src="${news.imageurl || 'http://static.photos/technology/120x120/' + index}" 
                     alt="" 
                     class="w-20 h-20 rounded object-cover flex-shrink-0"
                     onerror="this.src='http://static.photos/abstract/120x120/1'">
                <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2 mb-2">
                        <span class="text-xs font-mono text-accent-cyan">${news.source}</span>
                        <span class="text-void-500">•</span>
                        <span class="text-xs text-void-400">${new Date(news.published_on * 1000).toLocaleDateString()}</span>
                    </div>
                    <h4 class="text-white font-medium mb-2 line-clamp-2 group-hover:text-accent-cyan transition-colors">
                        <a href="${news.url}" target="_blank" class="hover:underline">${news.title}</a>
                    </h4>
                    <p class="text-void-300 text-sm line-clamp-2">${news.body?.substring(0, 120) || 'No description available'}...</p>
                </div>
            </div>
        </article>
    `).join('');
}

function renderCryptoSkeleton() {
    const grid = document.getElementById('crypto-grid');
    if (!grid) return;
    
    grid.innerHTML = Array(6).fill(0).map(() => `
        <div class="bg-void-800 border border-void-600 rounded-lg p-5">
            <div class="flex items-center gap-3 mb-4">
                <div class="w-10 h-10 rounded-full skeleton"></div>
                <div class="flex-1">
                    <div class="h-4 w-20 skeleton rounded mb-2"></div>
                    <div class="h-3 w-12 skeleton rounded"></div>
                </div>
            </div>
            <div class="h-8 w-32 skeleton rounded mb-2"></div>
            <div class="h-4 w-24 skeleton rounded"></div>
        </div>
    `).join('');
}

function renderNewsSkeleton() {
    const container = document.getElementById('news-feed');
    if (!container) return;
    
    container.innerHTML = Array(4).fill(0).map(() => `
        <div class="bg-void-800 border border-void-600 rounded-lg p-5">
            <div class="flex gap-4">
                <div class="w-20 h-20 rounded skeleton flex-shrink-0"></div>
                <div class="flex-1">
                    <div class="h-3 w-16 skeleton rounded mb-2"></div>
                    <div class="h-5 w-full skeleton rounded mb-2"></div>
                    <div class="h-4 w-3/4 skeleton rounded"></div>
                </div>
            </div>
        </div>
    `).join('');
}

function updateGlobalStats() {
    const totalMcap = state.cryptoData.reduce((sum, coin) => sum + (coin.market_cap || 0), 0);
    const totalVolume = state.cryptoData.reduce((sum, coin) => sum + (coin.total_volume || 0), 0);
    const btcDominance = state.cryptoData[0] ? (state.cryptoData[0].market_cap / totalMcap * 100) : 0;
    
    document.getElementById('global-mcap').textContent = formatCurrency(totalMcap, 1);
    document.getElementById('global-volume').textContent = formatCurrency(totalVolume, 1);
    document.getElementById('btc-dominance').textContent = btcDominance.toFixed(1) + '%';
    
    // Simulate fear & greed
    const fearGreed = Math.floor(Math.random() * 40) + 30;
    const fearGreedEl = document.getElementById('fear-greed');
    fearGreedEl.textContent = fearGreed;
    fearGreedEl.className = `text-2xl font-bold ${fearGreed > 50 ? 'text-accent-lime' : 'text-accent-amber'}`;
}

function renderMarketChart() {
    const container = document.getElementById('market-chart');
    if (!container) return;
    
    const bars = 50;
    const heights = Array(bars).fill(0).map(() => Math.random() * 80 + 20);
    
    container.innerHTML = heights.map((h, i) => `
        <div class="chart-bar flex-1 rounded-t ${i % 2 === 0 ? 'bg-accent-cyan/60' : 'bg-accent-magenta/60'}" 
             style="height: ${h}%"></div>
    `).join('');
}

// Live Price Updates
function startLiveUpdates() {
    setInterval(() => {
        // Simulate price updates
        state.cryptoData.forEach(coin => {
            const change = (Math.random() - 0.5) * 0.002;
            coin.current_price *= (1 + change);
        });
        
        // Update displayed prices with flash effect
        document.querySelectorAll('.price-value').forEach(el => {
            const newPrice = parseFloat(el.dataset.price) * (1 + (Math.random() - 0.5) * 0.001);
            el.dataset.price = newPrice;
            el.textContent = formatCurrency(newPrice);
            
            const flashClass = Math.random() > 0.5 ? 'price-flash-up' : 'price-flash-down';
            el.classList.remove('price-flash-up', 'price-flash-down');
            void el.offsetWidth; // Trigger reflow
            el.classList.add(flashClass);
        });
    }, 5000);
}

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    fetchCryptoData();
    fetchStockData();
    fetchNews();
    renderMarketChart();
    startLiveUpdates();
    
    // Update every 60 seconds
    setInterval(() => {
        fetchCryptoData();
        fetchStockData();
    }, 60000);
    
    // Update news every 5 minutes
    setInterval(fetchNews, 300000);
});