<?php
require_once __DIR__ . '/includes/lang.php';
require_once __DIR__ . '/includes/header.php';
?>

<link rel="stylesheet" href="assets/css/index.css?v=<?php echo time(); ?>">

<main class="container pb-5" style="margin-top: 0px; padding-top: 80px !important;">
    <!-- Hero Carousel -->
    <div id="heroCarousel" class="carousel slide mb-5 shadow-lg" data-bs-ride="carousel" style="min-height: 550px; border-radius: 24px; overflow: hidden;">
        <div class="carousel-indicators">
            <button type="button" data-bs-target="#heroCarousel" data-bs-slide-to="0" class="active"></button>
            <button type="button" data-bs-target="#heroCarousel" data-bs-slide-to="1"></button>
            <button type="button" data-bs-target="#heroCarousel" data-bs-slide-to="2"></button>
        </div>
        <div class="carousel-inner">
            <div class="carousel-item active">
                <div class="carousel-content p-5 text-white d-flex align-items-center" style="height: 550px; background: url('assets/images/carousel/slide1.jpg') center/cover;">
                    <div class="carousel-overlay" style="background: linear-gradient(90deg, rgba(0,0,0,0.8) 0%, rgba(0,0,0,0.3) 100%); position: absolute; top:0; left:0; right:0; bottom:0;"></div>
                    <div class="container" style="position: relative; z-index: 10;">
                        <div class="row">
                            <div class="col-lg-8">
                                <h1 class="display-3 fw-bold mb-4 animate__animated animate__fadeInUp"><?php echo __('hero_title'); ?></h1>
                                <p class="lead fs-3 mb-5 text-light opacity-75 animate__animated animate__fadeInUp animate__delay-1s"><?php echo __('hero_subtitle'); ?></p>
                                <div class="d-flex gap-3 animate__animated animate__fadeInUp animate__delay-2s">
                                    <a href="/auth/register.php" class="btn btn-primary btn-lg px-5 py-3 fw-bold rounded-pill shadow-primary"><?php echo __('get_started'); ?></a>
                                    <a href="/market.php" class="btn btn-outline-light btn-lg px-5 py-3 fw-bold rounded-pill"><?= __('market_view') ?></a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="carousel-item">
                <div class="carousel-content p-5 text-white d-flex align-items-center" style="height: 550px; background: url('assets/images/carousel/slide2.jpg') center/cover;">
                    <div class="carousel-overlay" style="background: linear-gradient(90deg, rgba(0,0,0,0.8) 0%, rgba(0,0,0,0.3) 100%); position: absolute; top:0; left:0; right:0; bottom:0;"></div>
                    <div class="container" style="position: relative; z-index: 10;">
                        <div class="row">
                            <div class="col-lg-8">
                                <h1 class="display-3 fw-bold mb-4 animate__animated animate__fadeInLeft"><?php echo __('prof_terminal'); ?></h1>
                                <p class="lead fs-3 mb-5 text-light opacity-75 animate__animated animate__fadeInLeft animate__delay-1s"><?php echo __('prof_terminal_desc'); ?></p>
                                <div class="d-flex gap-3 animate__animated animate__fadeInLeft animate__delay-2s">
                                    <a href="/trade.php" class="btn btn-primary btn-lg px-5 py-3 fw-bold rounded-pill shadow-primary"><?php echo __('trade') ?></a>
                                    <a href="/app.php" class="btn btn-outline-light btn-lg px-5 py-3 fw-bold rounded-pill"><?= __('app_download') ?></a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="carousel-item">
                <div class="carousel-content p-5 text-white d-flex align-items-center" style="height: 550px; background: url('assets/images/carousel/slide3.jpg') center/cover;">
                    <div class="carousel-overlay" style="background: linear-gradient(90deg, rgba(0,0,0,0.8) 0%, rgba(0,0,0,0.3) 100%); position: absolute; top:0; left:0; right:0; bottom:0;"></div>
                    <div class="container" style="position: relative; z-index: 10;">
                        <div class="row">
                            <div class="col-lg-8">
                                <h1 class="display-3 fw-bold mb-4 animate__animated animate__fadeInRight"><?php echo __('inst_security'); ?></h1>
                                <p class="lead fs-3 mb-5 text-light opacity-75 animate__animated animate__fadeInRight animate__delay-1s"><?php echo __('inst_security_desc'); ?></p>
                                <div class="d-flex gap-3 animate__animated animate__fadeInRight animate__delay-2s">
                                    <a href="/auth/register.php" class="btn btn-primary btn-lg px-5 py-3 fw-bold rounded-pill shadow-primary"><?php echo __('get_started'); ?></a>
                                    <a href="/about.php" class="btn btn-outline-light btn-lg px-5 py-3 fw-bold rounded-pill"><?= __('about_us') ?></a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <button class="carousel-control-prev" type="button" data-bs-target="#heroCarousel" data-bs-slide="prev">
            <span class="carousel-control-prev-icon p-3 bg-dark bg-opacity-50 rounded-circle"></span>
        </button>
        <button class="carousel-control-next" type="button" data-bs-target="#heroCarousel" data-bs-slide="next">
            <span class="carousel-control-next-icon p-3 bg-dark bg-opacity-50 rounded-circle"></span>
        </button>
    </div>

    <style>
        .coin-card {
            background: #0b0e11;
            border: 1px solid #2b3139;
            transition: all 0.3s ease;
            border-radius: 16px;
        }
        .coin-card:hover {
            transform: translateY(-5px);
            border-color: #0062ff;
            background: #161a1e;
        }
        .price-display {
            color: #ffffff;
        }
        
        @media (max-width: 768px) {
            main.container {
                padding-top: 70px !important;
            }
            #heroCarousel, .carousel-content {
                height: 300px !important;
                min-height: 300px !important;
            }
            .carousel-item h1 {
                font-size: 1.5rem !important;
                margin-bottom: 10px !important;
            }
            .carousel-item p {
                font-size: 0.9rem !important;
                margin-bottom: 15px !important;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                overflow: hidden;
            }
            .carousel-item .btn {
                padding: 8px 16px !important;
                font-size: 12px !important;
            }
            .carousel-indicators {
                bottom: 10px;
            }
            .market-section h2 {
                font-size: 1.4rem;
            }
            .col-md-3 {
                width: 50% !important; /* 2 columns on mobile */
                padding: 5px !important;
            }
            .coin-card .card-body {
                padding: 12px !important;
            }
            .coin-card .fs-5 {
                font-size: 1rem !important;
            }
            .coin-card .fs-3 {
                font-size: 1.2rem !important;
            }
            .coin-card img {
                width: 24px !important;
                height: 24px !important;
            }
            .change-badge {
                font-size: 10px !important;
                padding: 4px 6px !important;
            }
            .partner-card {
                padding: 10px !important;
            }
            .partner-card .fs-2 {
                font-size: 1.5rem !important;
            }
            .partner-card span {
                font-size: 10px !important;
            }
            .why-us h4 {
                font-size: 1.1rem;
            }
            .why-us p {
                font-size: 0.8rem !important;
            }
        }
    </style>
    <!-- Popular Markets (3x4 Layout) -->
    <section class="market-section mb-5">
        <div class="d-flex justify-content-between align-items-end mb-4">
            <h2 class="fw-bold m-0"><?php echo __('popular_markets'); ?></h2>
            <a href="market.php" class="text-decoration-none text-primary"><?php echo __('view_more'); ?> <i class="bi bi-arrow-right"></i></a>
        </div>
        <div class="row g-2" id="market-list">
            <?php
            $coins = [
                ['symbol' => 'BTC', 'name' => __('bitcoin'), 'id' => 'bitcoin'],
                ['symbol' => 'ETH', 'name' => __('ethereum'), 'id' => 'ethereum'],
                ['symbol' => 'USDT', 'name' => __('tether'), 'id' => 'tether'],
                ['symbol' => 'BNB', 'name' => __('binance_coin'), 'id' => 'binancecoin'],
                ['symbol' => 'SOL', 'name' => __('solana'), 'id' => 'solana'],
                ['symbol' => 'XRP', 'name' => __('ripple'), 'id' => 'ripple'],
                ['symbol' => 'ADA', 'name' => __('cardano'), 'id' => 'cardano'],
                ['symbol' => 'DOGE', 'name' => __('dogecoin'), 'id' => 'dogecoin'],
                ['symbol' => 'DOT', 'name' => __('polkadot'), 'id' => 'polkadot'],
                ['symbol' => 'MATIC', 'name' => __('polygon'), 'id' => 'matic-network'],
                ['symbol' => 'LINK', 'name' => __('chainlink'), 'id' => 'chainlink'],
                ['symbol' => 'SHIB', 'name' => __('shiba_inu'), 'id' => 'shiba-inu']
            ];
            foreach ($coins as $coin):
            ?>
            <div class="col-6 col-md-3">
                <div class="card coin-card h-100" data-symbol="<?php echo $coin['symbol']; ?>" onclick="location.href='trade.php?symbol=<?php echo $coin['symbol']; ?>'" style="cursor: pointer;">
                    <div class="card-body p-4">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div class="d-flex align-items-center">
                                <img src="<?php echo getCoinIcon($coin['symbol']); ?>" width="32" height="32" class="me-2 rounded-circle bg-light p-1" alt="<?php echo $coin['symbol']; ?>" onerror="handleIconError(this, '<?php echo $coin['symbol']; ?>')">
                                <span class="fw-bold fs-5"><?php echo $lang === 'zh' ? __($coin['symbol']) : $coin['symbol']; ?></span>
                                <small class="text-muted ms-2 d-none d-md-inline">/USDT</small>
                            </div>
                            <span class="change-badge badge bg-success">+0.00%</span>
                        </div>
                        <div class="price-display fs-3 fw-bold mb-3" id="price-<?php echo $coin['symbol']; ?>">$0.00</div>
                        <div class="sparkline-container d-none d-md-block" style="height: 40px;">
                           <canvas class="sparkline-canvas" id="spark-<?php echo $coin['symbol']; ?>"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>

    <!-- Why Us -->
    <section class="why-us mb-5 py-5">
        <h2 class="text-center mb-5 fw-bold display-5"><?php echo __('why_choose_us'); ?></h2>
        <div class="row g-4">
            <div class="col-md-3">
                <div class="card h-100 border-0 bg-transparent text-center p-3">
                    <div class="icon-box mb-4 mx-auto shadow-sm" style="background: linear-gradient(135deg, #0062ff, #00d2ff); color: #fff;">
                        <i class="bi bi-shield-check fs-1"></i>
                    </div>
                    <h4 class="fw-bold mb-3"><?php echo __('advantage_1_title'); ?></h4>
                    <p class="text-muted small px-2"><?php echo __('advantage_1_desc'); ?></p>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100 border-0 bg-transparent text-center p-3">
                    <div class="icon-box mb-4 mx-auto shadow-sm" style="background: linear-gradient(135deg, #26a69a, #4db6ac); color: #fff;">
                        <i class="bi bi-graph-up-arrow fs-1"></i>
                    </div>
                    <h4 class="fw-bold mb-3"><?php echo __('advantage_2_title'); ?></h4>
                    <p class="text-muted small px-2"><?php echo __('advantage_2_desc'); ?></p>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100 border-0 bg-transparent text-center p-3">
                    <div class="icon-box mb-4 mx-auto shadow-sm" style="background: linear-gradient(135deg, #ffad00, #ffcc33); color: #fff;">
                        <i class="bi bi-headset fs-1"></i>
                    </div>
                    <h4 class="fw-bold mb-3"><?php echo __('advantage_3_title'); ?></h4>
                    <p class="text-muted small px-2"><?php echo __('advantage_3_desc'); ?></p>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100 border-0 bg-transparent text-center p-3">
                    <div class="icon-box mb-4 mx-auto shadow-sm" style="background: linear-gradient(135deg, #8247e5, #9c6df5); color: #fff;">
                        <i class="bi bi-cpu-fill fs-1"></i>
                    </div>
                    <h4 class="fw-bold mb-3"><?php echo __('advantage_4_title'); ?></h4>
                    <p class="text-muted small px-2"><?php echo __('advantage_4_desc'); ?></p>
                </div>
            </div>
        </div>
    </section>

    <!-- Partners (15 icons, 5 per row) -->
    <section class="partners mb-5 py-5 border-top border-secondary">
        <h2 class="text-center mb-5 fw-bold"><?php echo __('partners'); ?></h2>
        <div class="row row-cols-2 row-cols-md-5 g-4 text-center">
            <?php
            $partners = [
                ['name' => 'Binance', 'color' => '#f3ba2f', 'icon' => 'bi-currency-bitcoin'],
                ['name' => 'OKX', 'color' => '#ffffff', 'icon' => 'bi-box-seam'],
                ['name' => 'Bybit', 'color' => '#ffb11a', 'icon' => 'bi-activity'],
                ['name' => 'Huobi', 'color' => '#00b5f8', 'icon' => 'bi-globe'],
                ['name' => 'Coinbase', 'color' => '#0052ff', 'icon' => 'bi-shield-shaded'],
                ['name' => 'Kraken', 'color' => '#5741d9', 'icon' => 'bi-water'],
                ['name' => 'KuCoin', 'color' => '#24ae8f', 'icon' => 'bi-gem'],
                ['name' => 'MEXC', 'color' => '#1ea7e1', 'icon' => 'bi-cpu'],
                ['name' => 'Gate.io', 'color' => '#e14f4f', 'icon' => 'bi-door-open'],
                ['name' => 'Bitfinex', 'color' => '#00cf92', 'icon' => 'bi-lightning'],
                ['name' => 'Gemini', 'color' => '#00cf92', 'icon' => 'bi-stars'],
                ['name' => 'Upbit', 'color' => '#2a5ada', 'icon' => 'bi-arrow-up-right-circle'],
                ['name' => 'Poloniex', 'color' => '#0a6a5d', 'icon' => 'bi-stack'],
                ['name' => 'Bitstamp', 'color' => '#1d2128', 'icon' => 'bi-safe'],
                ['name' => 'Bithumb', 'color' => '#ff8a00', 'icon' => 'bi-wallet2']
            ];
            foreach ($partners as $p):
            ?>
            <div class="col">
                <div class="partner-card p-4 rounded-4 d-flex flex-column align-items-center justify-content-center border-opacity-25" style="border: 1px solid <?php echo $p['color']; ?>40;">
                    <div class="partner-icon mb-2 fs-2" style="color: <?php echo $p['color']; ?>"><i class="bi <?php echo $p['icon']; ?>"></i></div>
                    <span class="fw-bold small text-light opacity-75"><?php echo $p['name']; ?></span>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
</main>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const symbols = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT', 'SOLUSDT', 'XRPUSDT', 'ADAUSDT', 'DOGEUSDT', 'DOTUSDT', 'MATICUSDT', 'LINKUSDT', 'SHIBUSDT'];
const coinData = {};

async function fetchPrices() {
    try {
        const response = await fetch('https://api.binance.com/api/v3/ticker/24hr');
        const data = await response.json();
        const relevant = data.filter(t => symbols.includes(t.symbol));
        
        relevant.forEach(t => {
            const symbol = t.symbol.replace('USDT', '');
            updateUI(symbol, parseFloat(t.lastPrice), parseFloat(t.priceChangePercent));
        });
        
        // Handle USDT specially
        updateUI('USDT', 1.000, 0.01);
    } catch (err) {
        console.error('Failed to fetch real-time prices:', err);
    }
}

function initPriceUpdate() {
    fetchPrices();
    setInterval(fetchPrices, 5000);
}

function updateUI(symbol, price, change) {
    const card = document.querySelector(`.coin-card[data-symbol="${symbol}"]`);
    if (!card) return;
    
    const priceEl = card.querySelector('.price-display');
    const badge = card.querySelector('.change-badge');
    
    const oldPrice = parseFloat(priceEl.innerText.replace('$', '').replace(',', ''));
    
    // Smooth price transition simulation
    priceEl.innerText = '$' + price.toLocaleString(undefined, {
        minimumFractionDigits: symbol === 'SHIB' ? 6 : (price < 1 ? 4 : 2),
        maximumFractionDigits: symbol === 'SHIB' ? 6 : (price < 1 ? 4 : 2)
    });
    
    if (Math.abs(price - oldPrice) > 0.000001) {
        priceEl.style.transition = 'all 0.2s';
        const jumpDir = price > oldPrice ? -3 : 3;
        priceEl.style.transform = `translateY(${jumpDir}px)`;
        if (price > oldPrice) {
            priceEl.style.color = '#26a69a';
            setTimeout(() => {
                priceEl.style.transform = '';
                priceEl.style.color = '';
            }, 200);
        } else {
            priceEl.style.color = '#ef5350';
            setTimeout(() => {
                priceEl.style.transform = '';
                priceEl.style.color = '';
            }, 200);
        }
    }
    
    badge.innerText = (change > 0 ? '+' : '') + change + '%';
    badge.className = `change-badge badge ${change >= 0 ? 'bg-success' : 'bg-danger'}`;
}

// Sparklines with real data
async function initSparklines() {
    const symbols = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT', 'SOLUSDT', 'XRPUSDT', 'ADAUSDT', 'DOGEUSDT', 'DOTUSDT', 'MATICUSDT', 'LINKUSDT', 'SHIBUSDT'];
    
    for (const symbol of symbols) {
        try {
            const response = await fetch(`https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=1h&limit=20`);
            const data = await response.json();
            const prices = data.map(d => parseFloat(d[4]));
            const s = symbol.replace('USDT', '');
            const canvas = document.getElementById(`spark-${s}`);
            if (!canvas) continue;
            
            const ctx = canvas.getContext('2d');
            const isUp = prices[prices.length - 1] >= prices[0];
            
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: new Array(prices.length).fill(''),
                    datasets: [{
                        data: prices,
                        borderColor: isUp ? '#0ecb81' : '#f6465d',
                        borderWidth: 2,
                        pointRadius: 0,
                        fill: true,
                        backgroundColor: isUp ? 'rgba(14, 203, 129, 0.1)' : 'rgba(246, 70, 93, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    plugins: { legend: { display: false }, tooltip: { enabled: false } },
                    scales: { x: { display: false }, y: { display: false } },
                    maintainAspectRatio: false,
                    responsive: true
                }
            });
        } catch (err) {
            console.error(`Failed to fetch sparkline for ${symbol}:`, err);
        }
    }
}

initSparklines();
initPriceUpdate();
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
