{% extends 'base/base.html' %}
{% block title %}Markets - CryptoSignals Pro{% endblock %}

{% block extra_css %}
<style>
.coin-icon { width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; }
.coin-icon img { width: 100%; height: 100%; border-radius: 50%; }
.chart-container { position: relative; height: 400px; width: 100%; }
.price-up { color: #10b981 !important; }
.price-down { color: #ef4444 !important; }
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
.signal-badge { padding: 6px 12px; border-radius: 20px; font-weight: 600; font-size: 0.75rem; text-transform: uppercase; }
.signal-buy { background: rgba(16, 185, 129, 0.2); color: #10b981; }
.signal-sell { background: rgba(239, 68, 68, 0.2); color: #ef4444; }
.signal-neutral { background: rgba(245, 158, 11, 0.2); color: #f59e0b; }
.coin-row { cursor: pointer; transition: all 0.2s; border-bottom: 1px solid var(--border-color); }
.coin-row:hover { background: rgba(0, 212, 255, 0.1); }
.coin-row.active { background: rgba(0, 212, 255, 0.15); border-left: 3px solid var(--accent-cyan); }
.timeframe-btn { background: transparent; border: 1px solid var(--border-color); color: #94a3b8; padding: 6px 12px; border-radius: 8px; font-size: 0.75rem; cursor: pointer; transition: all 0.2s; }
.timeframe-btn:hover, .timeframe-btn.active { background: var(--accent-cyan); color: #fff; border-color: var(--accent-cyan); }
#coinListPanel { max-height: 500px; overflow-y: auto; }
.signal-card { background: var(--card-bg); border: 1px solid var(--border-color); border-radius: 12px; padding: 15px; margin-bottom: 10px; transition: all 0.3s; cursor: pointer; }
.signal-card:hover { transform: translateX(5px); border-color: var(--accent-cyan); }
.coin-mini-icon { width: 32px; height: 32px; border-radius: 50%; }
.live-price { font-weight: 600; font-size: 1.1rem; }
.market-chart-header { gap: 1rem; }
.market-chart-meta { min-width: 0; }
.market-timeframe-group { display: flex; gap: 0.5rem; flex-wrap: wrap; }

@media (max-width: 991.98px) {
    #coinListPanel { max-height: 320px; }
    .chart-container { height: 320px; }
}

@media (max-width: 767.98px) {
    .chart-container { height: 250px; }
    .market-chart-header,
    .market-chart-meta { flex-wrap: wrap; }
    .market-timeframe-group { width: 100%; }
    .market-timeframe-group .timeframe-btn { flex: 1 1 0; text-align: center; }
}

@media (max-width: 575.98px) {
    #coinListPanel { max-height: 260px; }
    .chart-container { height: 220px; }
    .signal-badge { font-size: 0.68rem; padding: 5px 9px; }
    .live-price { font-size: 0.95rem; }
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <h1 class="page-title">Trading Markets</h1>
    
    <div class="row">
        <!-- Coin List -->
        <div class="col-lg-3 col-md-4 mb-4">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 custom-text-white">All Coins</h5>
                    <span class="badge badge-active">
                        <i class="bi bi-circle-fill me-1" style="font-size: 0.5rem; animation: pulse 1.5s infinite;"></i>
                        Live
                    </span>
                </div>
                <div class="card-body p-0" id="coinListPanel">
                    <div id="coinList">
                        <div class="text-center py-4"><div class="spinner-border text-primary"></div></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Chart Section -->
        <div class="col-lg-6 col-md-8 mb-4">
            <div class="card h-100">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center flex-wrap market-chart-header">
                        <div class="d-flex align-items-center market-chart-meta">
                            <div class="coin-icon me-3" id="chartCoinIcon">
                                <img src="https://assets.coingecko.com/coins/images/1/small/bitcoin.png">
                            </div>
                            <div>
                                <h4 class="mb-0 custom-text-white" id="chartCoinName">Bitcoin</h4>
                                <small class="custom-text-muted" id="chartCoinSymbol">BTC/USDT</small>
                            </div>
                        </div>
                        <div class="market-timeframe-group">
                            <button class="timeframe-btn" onclick="changeTimeframe('1H')">1H</button>
                            <button class="timeframe-btn active" onclick="changeTimeframe('24H')">24H</button>
                            <button class="timeframe-btn" onclick="changeTimeframe('7D')">7D</button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-6">
                            <h3 class="mb-0 custom-text-white" id="chartPrice">$--</h3>
                            <span id="chartChange" class="custom-text-muted">--</span>
                        </div>
                        <div class="col-6 text-end">
                            <span class="signal-badge" id="chartSignal">--</span>
                        </div>
                    </div>
                    <div class="chart-container">
                        <canvas id="mainChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Stats & Info -->
        <div class="col-lg-3 mb-4">
            <div class="card mb-3" style="background: linear-gradient(135deg, rgba(0, 212, 255, 0.1) 0%, rgba(123, 47, 247, 0.1) 100%); border: 1px solid rgba(0, 212, 255, 0.2);">
                <div class="card-body">
                    <h5 class="custom-text-white mb-3">Coin Stats</h5>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="custom-text-muted">24h High</span>
                        <span class="custom-text-white" id="statHigh">$--</span>
                    </div>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="custom-text-muted">24h Low</span>
                        <span class="custom-text-white" id="statLow">$--</span>
                    </div>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="custom-text-muted">24h Volume</span>
                        <span class="custom-text-white" id="statVolume">$--</span>
                    </div>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="custom-text-muted">Market Cap</span>
                        <span class="custom-text-white" id="statMCap">$--</span>
                    </div>
                    <div class="d-flex justify-content-between">
                        <span class="custom-text-muted">RSI (14)</span>
                        <span id="statRSI">--</span>
                    </div>
                </div>
            </div>
            
            <div class="card">
                <div class="card-header"><h5 class="mb-0 custom-text-white">Trading Signal</h5></div>
                <div class="card-body text-center">
                    <div class="mb-3">
                        <span class="signal-badge" style="font-size: 1rem; padding: 10px 20px;" id="signalBadge">--</span>
                    </div>
                    <p class="custom-text-muted small mb-0" id="signalReason">Based on RSI and price action analysis</p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Live Trading Signals -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 custom-text-white">
                        <i class="bi bi-lightning-charge-fill me-2" style="color: #f59e0b;"></i>
                        Live Trading Signals
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row" id="signalsContainer"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const COINGECKO_API = 'https://api.coingecko.com/api/v3';

let coinsData = [];
let mainChart = null;
let selectedCoin = 'bitcoin';
let currentTimeframe = '24H';

const coinIdMap = {
    'bitcoin': { name: 'Bitcoin', symbol: 'BTC', image: 'https://assets.coingecko.com/coins/images/1/small/bitcoin.png' },
    'ethereum': { name: 'Ethereum', symbol: 'ETH', image: 'https://assets.coingecko.com/coins/images/279/small/ethereum.png' },
    'binancecoin': { name: 'BNB', symbol: 'BNB', image: 'https://assets.coingecko.com/coins/images/825/small/bnb-icon2_2x.png' },
    'solana': { name: 'Solana', symbol: 'SOL', image: 'https://assets.coingecko.com/coins/images/4128/small/solana.png' },
    'ripple': { name: 'XRP', symbol: 'XRP', image: 'https://assets.coingecko.com/coins/images/44/small/xrp-symbol-white-128.png' },
    'cardano': { name: 'Cardano', symbol: 'ADA', image: 'https://assets.coingecko.com/coins/images/975/small/cardano.png' },
    'dogecoin': { name: 'Dogecoin', symbol: 'DOGE', image: 'https://assets.coingecko.com/coins/images/5/small/dogecoin.png' },
    'polkadot': { name: 'Polkadot', symbol: 'DOT', image: 'https://assets.coingecko.com/coins/images/12171/small/polkadot.png' }
};

function calculateRSI(prices) {
    if (prices.length < 14) return 50;
    let gains = 0, losses = 0;
    for (let i = prices.length - 13; i < prices.length; i++) {
        const change = prices[i] - prices[i - 1];
        if (change > 0) gains += change;
        else losses -= change;
    }
    const avgGain = gains / 14;
    const avgLoss = losses / 14;
    if (avgLoss === 0) return 100;
    const rs = avgGain / avgLoss;
    return 100 - (100 / (1 + rs));
}

function generateSignal(priceChange, rsi) {
    if (rsi < 30 && priceChange > 0) return { signal: 'STRONG BUY', class: 'signal-buy', reason: 'Oversold + Upward momentum' };
    if (rsi < 35 && priceChange > 0) return { signal: 'BUY', class: 'signal-buy', reason: 'Near oversold' };
    if (rsi > 70 && priceChange < 0) return { signal: 'STRONG SELL', class: 'signal-sell', reason: 'Overbought + Downward' };
    if (rsi > 65 && priceChange < 0) return { signal: 'SELL', class: 'signal-sell', reason: 'Near overbought' };
    if (priceChange > 3) return { signal: 'BUY', class: 'signal-buy', reason: 'Strong momentum' };
    if (priceChange < -3) return { signal: 'SELL', class: 'signal-sell', reason: 'Weak momentum' };
    return { signal: 'HOLD', class: 'signal-neutral', reason: 'Neutral' };
}

async function fetchData() {
    try {
        const response = await fetch(
            `${COINGECKO_API}/coins/markets?vs_currency=usd&ids=bitcoin,ethereum,binancecoin,solana,ripple,cardano,dogecoin,polkadot&order=market_cap_desc&sparkline=true&price_change_percentage=1h,24h,7d`
        );
        
        if (!response.ok) throw new Error('Failed to fetch');
        
        coinsData = await response.json();
        renderCoinList();
        renderSignals();
        updateChart(coinsData.find(c => c.id === selectedCoin));
        
        setTimeout(fetchData, 30000);
    } catch (error) {
        console.error('Error:', error);
    }
}

function renderCoinList() {
    const list = document.getElementById('coinList');
    list.innerHTML = coinsData.map(coin => {
        const change = coin.price_change_percentage_24h || 0;
        const changeClass = change >= 0 ? 'price-up' : 'price-down';
        const isActive = coin.id === selectedCoin ? 'active' : '';
        
        return `
        <div class="coin-row p-3 ${isActive}" onclick="selectCoin('${coin.id}')">
            <div class="d-flex justify-content-between align-items-center">
                <div class="d-flex align-items-center">
                    <div class="coin-icon me-2">
                        <img src="${coin.image}" alt="${coin.symbol}">
                    </div>
                    <div>
                        <strong style="color: #fff;">${coin.symbol.toUpperCase()}</strong>
                        <small class="d-block custom-text-muted">${coin.name}</small>
                    </div>
                </div>
                <div class="text-end">
                    <div style="color: #fff;">$${coin.current_price.toLocaleString()}</div>
                    <small class="${changeClass}">${change >= 0 ? '+' : ''}${change.toFixed(2)}%</small>
                </div>
            </div>
        </div>
        `;
    }).join('');
}

function renderSignals() {
    const container = document.getElementById('signalsContainer');
    
    container.innerHTML = coinsData.map(coin => {
        const prices = coin.sparkline_in_7d?.price || [];
        const rsi = calculateRSI(prices);
        const change = coin.price_change_percentage_24h || 0;
        const signalInfo = generateSignal(change, rsi);
        
        return `
        <div class="col-lg-3 col-md-4 col-sm-6 mb-3">
            <div class="signal-card" onclick="selectCoin('${coin.id}')">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <div class="d-flex align-items-center">
                        <img src="${coin.image}" class="coin-mini-icon me-2" alt="${coin.symbol}">
                        <div>
                            <strong style="color: #fff;">${coin.symbol.toUpperCase()}</strong>
                            <small class="d-block custom-text-muted">${coin.name}</small>
                        </div>
                    </div>
                    <span class="signal-badge ${signalInfo.class}">${signalInfo.signal}</span>
                </div>
                <div class="d-flex justify-content-between align-items-center">
                    <span class="live-price" style="color: #fff;">$${coin.current_price.toLocaleString()}</span>
                    <span class="${change >= 0 ? 'price-up' : 'price-down'}">
                        ${change >= 0 ? '<i class="bi bi-caret-up-fill"></i>' : '<i class="bi bi-caret-down-fill"></i>'}
                        ${change >= 0 ? '+' : ''}${change.toFixed(2)}%
                    </span>
                </div>
                <div class="mt-2">
                    <small class="custom-text-muted">${signalInfo.reason}</small>
                </div>
            </div>
        </div>
        `;
    }).join('');
}

function selectCoin(coinId) {
    selectedCoin = coinId;
    renderCoinList();
    updateChart(coinsData.find(c => c.id === coinId));
}

function changeTimeframe(tf) {
    currentTimeframe = tf;
    document.querySelectorAll('.timeframe-btn').forEach(btn => btn.classList.remove('active'));
    event.target.classList.add('active');
    updateChart(coinsData.find(c => c.id === selectedCoin));
}

function updateChart(coin) {
    if (!coin) return;
    
    const coinInfo = coinIdMap[coin.id] || { name: coin.name, symbol: coin.symbol.toUpperCase(), image: coin.image };
    const change = coin.price_change_percentage_24h || 0;
    const prices = coin.sparkline_in_7d?.price || [];
    const rsi = calculateRSI(prices);
    const signalInfo = generateSignal(change, rsi);
    
    document.getElementById('chartCoinName').textContent = coinInfo.name;
    document.getElementById('chartCoinSymbol').textContent = coinInfo.symbol + '/USDT';
    document.getElementById('chartCoinIcon').innerHTML = `<img src="${coinInfo.image}">`;
    document.getElementById('chartPrice').textContent = '$' + coin.current_price.toLocaleString();
    
    const changeEl = document.getElementById('chartChange');
    changeEl.innerHTML = `${change >= 0 ? '+' : ''}${change.toFixed(2)}% (24h)`;
    changeEl.className = change >= 0 ? 'price-up' : 'price-down';
    
    document.getElementById('chartSignal').className = `signal-badge ${signalInfo.class}`;
    document.getElementById('chartSignal').textContent = signalInfo.signal;
    
    document.getElementById('statHigh').textContent = '$' + coin.high_24h.toLocaleString();
    document.getElementById('statLow').textContent = '$' + coin.low_24h.toLocaleString();
    document.getElementById('statVolume').textContent = '$' + (coin.total_volume / 1e9).toFixed(2) + 'B';
    document.getElementById('statMCap').textContent = '$' + (coin.market_cap / 1e9).toFixed(0) + 'B';
    document.getElementById('statRSI').textContent = rsi.toFixed(0);
    document.getElementById('statRSI').style.color = rsi < 30 ? '#10b981' : rsi > 70 ? '#ef4444' : '#94a3b8';
    
    document.getElementById('signalBadge').className = `signal-badge ${signalInfo.class}`;
    document.getElementById('signalBadge').textContent = signalInfo.signal;
    document.getElementById('signalReason').textContent = signalInfo.reason;
    
    let chartData;
    if (currentTimeframe === '1H') chartData = prices.slice(-24);
    else if (currentTimeframe === '24H') chartData = prices;
    else chartData = coin.sparkline_in_7d?.price || prices;
    
    if (mainChart) mainChart.destroy();
    
    const ctx = document.getElementById('mainChart').getContext('2d');
    const color = change >= 0 ? '#10b981' : '#ef4444';
    const gradient = ctx.createLinearGradient(0, 0, 0, 400);
    gradient.addColorStop(0, change >= 0 ? 'rgba(16, 185, 129, 0.3)' : 'rgba(239, 68, 68, 0.3)');
    gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
    
    mainChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: chartData.map((_, i) => i),
            datasets: [{
                data: chartData,
                borderColor: color,
                backgroundColor: gradient,
                borderWidth: 2,
                fill: true,
                pointRadius: 0,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: {
                x: { display: false },
                y: { grid: { color: 'rgba(255,255,255,0.05)' }, ticks: { color: '#64748b' } }
            }
        }
    });
}

document.addEventListener('DOMContentLoaded', fetchData);
</script>
{% endblock %}
