<?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>

    <!-- Platform Demo Section (Terminal Style) -->
    <section class="platform-demo mb-5 py-5">
        <div class="text-center mb-5">
            <h2 class="fw-bold display-5 mb-4 px-3"><?php echo __('demo_title'); ?></h2>
            <p class="lead text-muted mx-auto px-4" style="max-width: 800px;">
                <?php echo __('demo_subtitle'); ?>
            </p>
        </div>
        
        <!-- Desktop Terminal Wrapper -->
        <div class="demo-wrapper mx-auto d-none d-md-block" style="width: 100%; padding: 0;">
            <div class="terminal-mockup shadow-2xl animate__animated animate__fadeInUp" style="border-radius: 12px; overflow: hidden; background: #0b0e11; border: 1px solid #2b3139; display: flex; flex-direction: column; height: 700px;">
                
                <!-- Terminal Navbar -->
                <div class="terminal-nav d-flex align-items-center border-bottom border-secondary border-opacity-25" style="background: #161a1e; height: 48px;">
                    <div class="d-flex px-3 gap-2 me-4 border-end border-secondary border-opacity-25 h-100 align-items-center">
                        <span class="rounded-circle" style="width: 10px; height: 10px; background: #ff5f56;"></span>
                        <span class="rounded-circle" style="width: 10px; height: 10px; background: #ffbd2e;"></span>
                        <span class="rounded-circle" style="width: 10px; height: 10px; background: #27c93f;"></span>
                    </div>
                    <div class="terminal-modes d-flex h-100">
                        <div class="mode-tab active" data-mode="spot" onclick="switchDemoMode('spot')">
                            <?php echo __('spot_trading'); ?>
                        </div>
                        <div class="mode-tab" data-mode="futures" onclick="switchDemoMode('futures')">
                            <?php echo __('futures_trading'); ?>
                        </div>
                        <div class="mode-tab" data-mode="binary" onclick="switchDemoMode('binary')">
                            <?php echo __('binary_trading'); ?>
                        </div>
                    </div>
                    <div class="ms-auto px-3 d-flex gap-3 small text-muted">
                        <span>BTC/USDT <span class="text-success demo-price">68,234.12</span></span>
                    </div>
                </div>

                <!-- Main Terminal Body -->
                <div class="terminal-body d-flex flex-grow-1 overflow-hidden">
                    
                    <!-- Left Sidebar: Markets -->
                    <div class="terminal-sidebar border-end border-secondary border-opacity-25" style="width: 260px; background: #0b0e11;">
                        <div class="p-2 border-bottom border-secondary border-opacity-25">
                            <input type="text" class="form-control form-control-sm bg-dark border-secondary text-light opacity-50" placeholder="<?php echo __('search'); ?>..." style="font-size: 12px;">
                        </div>
                        <div class="market-list py-2 overflow-hidden" id="demo-market-list">
                            <!-- Injected by JS -->
                        </div>
                    </div>

                    <!-- Center: Chart -->
                    <div class="terminal-center flex-grow-1 d-flex flex-column border-end border-secondary border-opacity-25">
                        <div class="chart-header p-2 d-flex justify-content-between align-items-center border-bottom border-secondary border-opacity-25" style="background: #161a1e;">
                            <div class="d-flex gap-3 small">
                                <span class="fw-bold text-light">BTC/USDT</span>
                                <span class="text-success fw-bold demo-price">68,234.12</span>
                                <span class="text-success demo-change">+2.45%</span>
                            </div>
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-secondary active py-0 px-2" style="font-size: 10px;"><?php echo __('time_15m'); ?></button>
                                <button class="btn btn-outline-secondary py-0 px-2" style="font-size: 10px;"><?php echo __('time_1h'); ?></button>
                                <button class="btn btn-outline-secondary py-0 px-2" style="font-size: 10px;"><?php echo __('time_1d'); ?></button>
                            </div>
                        </div>
                        <div class="chart-area flex-grow-1 position-relative" style="background: #0b0e11; overflow: hidden;">
                            <canvas id="demo-main-chart" style="width: 100%; height: 100%;"></canvas>
                            <!-- Interactive overlay -->
                            <div class="chart-cursor-line" style="position: absolute; top: 0; bottom: 0; width: 1px; background: rgba(255,255,255,0.1); display: none;"></div>
                        </div>
                        <div class="order-tabs border-top border-secondary border-opacity-25" style="background: #161a1e; height: 180px; flex-shrink: 0; overflow-y: auto;">
                            <div class="d-flex gap-4 p-2 border-bottom border-secondary border-opacity-25 small text-muted fw-bold">
                                <span class="text-primary border-bottom border-primary pb-1"><?php echo __('open_orders'); ?>(0)</span>
                                <span><?php echo __('trade_history'); ?></span>
                            </div>
                            <div id="demo-history-list">
                                <div class="p-3 text-center text-muted opacity-25 small">
                                    <i class="bi bi-file-earmark-text fs-1 d-block mb-2"></i>
                                    <?php echo __('no_records_found'); ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Right Sidebar: Order Panel & Book -->
                    <div class="terminal-right d-flex flex-column" style="width: 300px; background: #161a1e;">
                        
                        <!-- Order Book -->
                        <div class="order-book-section h-50 border-bottom border-secondary border-opacity-25 overflow-hidden p-2">
                            <div class="d-flex justify-content-between small text-muted mb-2 px-1">
                                <span><?php echo __('price'); ?>(USDT)</span>
                                <span><?php echo __('amount'); ?>(BTC)</span>
                            </div>
                            <div class="order-book-list small" id="demo-order-book">
                                <!-- Injected by JS -->
                            </div>
                        </div>

                        <!-- Trade Panel -->
                        <div class="trade-panel-section flex-grow-1 p-3 d-flex flex-column" id="demo-trade-panel">
                            <!-- Dynamic based on mode -->
                        </div>

                    </div>

                </div>

                <!-- Terminal Footer -->
                <div class="terminal-footer d-flex align-items-center px-3 py-1 border-top border-secondary border-opacity-25 text-muted" style="background: #161a1e; font-size: 10px; height: 28px;">
                    <div class="d-flex align-items-center gap-4">
                        <span class="text-success"><i class="bi bi-circle-fill me-1" style="font-size: 6px;"></i> <?php echo __('network_status_normal'); ?></span>
                        <span><?php echo __('latency'); ?>: 18ms</span>
                        <span><?php echo __('api_connected'); ?></span>
                    </div>
                    <div class="ms-auto">
                        BYRO TRADING ENGINE v4.2.0
                    </div>
                </div>

            </div>
        </div>

        <!-- Mobile Fallback -->
        <div class="d-md-none text-center px-3">
            <div class="mobile-terminal-preview rounded-4 shadow overflow-hidden border border-secondary border-opacity-25" style="background: #0b0e11;">
                <div class="p-3 border-bottom border-secondary border-opacity-25 d-flex justify-content-between align-items-center">
                    <span class="fw-bold text-light">BTC/USDT</span>
                    <span class="text-success fw-bold">68,234.12</span>
                </div>
                <div style="height: 200px;">
                    <canvas id="demo-mobile-chart" style="width: 100%; height: 100%;"></canvas>
                </div>
                <div class="p-3 bg-dark bg-opacity-50">
                    <a href="/trade.php" class="btn btn-primary w-100 py-2 rounded-pill fw-bold"><?php echo __('app_experience_now'); ?></a>
                </div>
            </div>
        </div>
    </section>

    <style>
        .terminal-mockup { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
        .mode-tab { 
            padding: 0 24px; 
            height: 100%; 
            display: flex; 
            align-items: center; 
            color: #848e9c; 
            font-size: 13px; 
            font-weight: 600; 
            cursor: pointer; 
            transition: all 0.2s;
            border-right: 1px solid rgba(255,255,255,0.05);
        }
        .mode-tab:hover { background: rgba(255,255,255,0.02); color: #fff; }
        .mode-tab.active { background: #0b0e11; color: #fff; border-top: 2px solid #f0b90b; }
        
        .market-row { 
            padding: 8px 12px; 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            font-size: 12px; 
            cursor: pointer;
            transition: background 0.1s;
        }
        .market-row:hover { background: rgba(255,255,255,0.03); }
        .market-row.active { background: rgba(255,255,255,0.05); }

        .ob-row { display: flex; justify-content: space-between; position: relative; padding: 2px 4px; z-index: 1; }
        .ob-bg { position: absolute; top: 0; right: 0; bottom: 0; z-index: -1; transition: width 0.3s; }
        
        .trade-input-group { 
            background: #2b3139; 
            border: 1px solid transparent; 
            border-radius: 4px; 
            padding: 4px 8px; 
            display: flex; 
            justify-content: space-between; 
            align-items: center;
            margin-bottom: 12px;
            transition: border-color 0.2s;
        }
        .trade-input-group:focus-within { border-color: #f0b90b; }
        .trade-input-group input { 
            background: transparent; 
            border: none; 
            color: #fff; 
            width: 70%; 
            outline: none; 
            font-weight: 600;
            font-size: 14px;
        }
        .trade-input-group .label { font-size: 11px; color: #848e9c; width: 30%; }
        .trade-input-group .unit { font-size: 11px; color: #848e9c; }

        .btn-buy { background: #0ecb81; color: #fff; border: none; font-weight: 700; }
        .btn-buy:hover { background: #0dbb76; }
        .btn-sell { background: #f6465d; color: #fff; border: none; font-weight: 700; }
        .btn-sell:hover { background: #e03f53; }
        
        .leverage-badge { 
            background: #2b3139; 
            color: #f0b90b; 
            font-size: 10px; 
            padding: 2px 6px; 
            border-radius: 2px;
            font-weight: 700;
        }
    </style>

    <!-- 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' => 'Bitget', 'color' => '#00d2d2', '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 = {};

// Platform Demo Global State
let demoMode = 'spot';
let currentDemoPrice = 68234.12;
const demoCoins = [
    { symbol: 'BTC', name: 'Bitcoin', price: 68234.12, change: '+2.45%' },
    { symbol: 'ETH', name: 'Ethereum', price: 3456.20, change: '+1.12%' },
    { symbol: 'BNB', name: 'Binance', price: 598.40, change: '-0.56%' },
    { symbol: 'SOL', name: 'Solana', price: 145.20, change: '+5.67%' },
    { symbol: 'XRP', name: 'Ripple', price: 0.62, change: '-1.23%' }
];

async function fetchPrices() {
    try {
        const response = await fetch('api/prices.php?type=ticker');
        const data = await response.json();
        
        // Ensure data is an array
        const tickerArray = Array.isArray(data) ? data : (data && typeof data === 'object' && data.symbol ? [data] : []);
        if (tickerArray.length === 0) return;

        // Existing UI update
        const relevant = tickerArray.filter(t => symbols.includes(t.symbol));
        relevant.forEach(t => {
            const symbol = t.symbol.replace('USDT', '');
            updateUI(symbol, parseFloat(t.lastPrice), parseFloat(t.priceChangePercent));
        });

        // Sync Demo Module with Real BTC Price
        const btcTicker = tickerArray.find(t => t.symbol === 'BTCUSDT');
        if (btcTicker) {
            const realPrice = parseFloat(btcTicker.lastPrice);
            // If demo price is too far from real price, sync it
            if (Math.abs(currentDemoPrice - realPrice) > 500) {
                currentDemoPrice = realPrice;
            }
            
            // Sync demo market list
            demoCoins.forEach(dc => {
                const ticker = tickerArray.find(t => t.symbol === dc.symbol + 'USDT');
                if (ticker) {
                    dc.price = parseFloat(ticker.lastPrice);
                    dc.change = (ticker.priceChangePercent >= 0 ? '+' : '') + ticker.priceChangePercent + '%';
                }
            });
            
            if (typeof updateDemoMarkets === 'function') updateDemoMarkets();
        }
        
        // 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);
}

// Platform Demo Logic
function switchDemoMode(mode) {
    demoMode = mode;
    document.querySelectorAll('.mode-tab').forEach(t => {
        t.classList.toggle('active', t.dataset.mode === mode);
    });
    renderTradePanel();
}

function renderTradePanel() {
    const panel = document.getElementById('demo-trade-panel');
    if (!panel) return;

    let html = '';
    const buyLabel = demoMode === 'futures' ? "<?php echo __('buy_long'); ?>" : "<?php echo __('buy_btn'); ?>";
    const sellLabel = demoMode === 'futures' ? "<?php echo __('sell_short'); ?>" : "<?php echo __('sell_btn'); ?>";

    if (demoMode === 'spot' || demoMode === 'futures') {
        html = `
            <div class="d-flex gap-3 mb-3">
                <button class="btn btn-sm flex-fill fw-bold py-1 ${demoMode === 'futures' ? 'btn-outline-primary active' : 'text-success border-bottom border-success'}" style="font-size: 12px;">${buyLabel}</button>
                <button class="btn btn-sm flex-fill fw-bold py-1 text-muted" style="font-size: 12px;">${sellLabel}</button>
            </div>
            ${demoMode === 'futures' ? `
                <div class="mb-3 d-flex justify-content-between align-items-center">
                    <span class="small text-muted"><?php echo __('leverage'); ?></span>
                    <span class="leverage-badge">100x</span>
                </div>
            ` : ''}
            <div class="trade-input-group">
                <span class="label"><?php echo __('price'); ?></span>
                <input type="text" class="demo-price-input" value="68,234.12" readonly>
                <span class="unit">USDT</span>
            </div>
            <div class="trade-input-group">
                <span class="label"><?php echo __('quantity'); ?></span>
                <input type="text" placeholder="0.00">
                <span class="unit">BTC</span>
            </div>
            <div class="mt-auto">
                <div class="d-flex justify-content-between small text-muted mb-2">
                    <span><?php echo __('balance'); ?></span>
                    <span class="text-light">12,450.00 USDT</span>
                </div>
                <button class="btn ${demoMode === 'futures' ? 'btn-buy' : 'btn-buy'} w-100 py-2 rounded mb-2">
                    ${demoMode === 'futures' ? "<?php echo __('long'); ?>" : "<?php echo __('buy_btn'); ?>"} BTC
                </button>
                <button class="btn btn-sell w-100 py-2 rounded">
                    ${demoMode === 'futures' ? "<?php echo __('short'); ?>" : "<?php echo __('sell_btn'); ?>"} BTC
                </button>
            </div>
        `;
    } else if (demoMode === 'binary') {
        html = `
            <div class="section-title small text-muted mb-2 fw-bold"><?php echo __('cycle_settlement'); ?></div>
            <div class="d-grid gap-2 mb-3" style="grid-template-columns: 1fr 1fr;">
                <button class="btn btn-dark btn-sm active" style="font-size: 11px; background: #2b3139;">60<?php echo __('seconds'); ?> (8%)</button>
                <button class="btn btn-dark btn-sm" style="font-size: 11px; background: #2b3139;">120<?php echo __('seconds'); ?> (15%)</button>
            </div>
            <div class="trade-input-group">
                <span class="label"><?php echo __('amount'); ?></span>
                <input type="text" value="100">
                <span class="unit">USDT</span>
            </div>
            <div class="mt-auto">
                <div class="bg-black bg-opacity-25 p-2 rounded mb-3 border border-secondary border-opacity-25">
                    <div class="d-flex justify-content-between small text-muted">
                        <span><?php echo __('expected_profit'); ?></span>
                        <span class="text-success fw-bold">8.00 USDT</span>
                    </div>
                </div>
                <button class="btn btn-buy w-100 py-3 rounded mb-2 d-flex flex-column align-items-center">
                    <span class="fw-bold"><?php echo __('buy_up'); ?></span>
                    <span style="font-size: 10px; opacity: 0.8;"><?php echo __('profit'); ?> 8%</span>
                </button>
                <button class="btn btn-sell w-100 py-3 rounded d-flex flex-column align-items-center">
                    <span class="fw-bold"><?php echo __('buy_down'); ?></span>
                    <span style="font-size: 10px; opacity: 0.8;"><?php echo __('profit'); ?> 8%</span>
                </button>
            </div>
        `;
    }
    panel.innerHTML = html;
}

function initDemoModule() {
    const canvas = document.getElementById('demo-main-chart');
    const mobileCanvas = document.getElementById('demo-mobile-chart');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    const mCtx = mobileCanvas ? mobileCanvas.getContext('2d') : null;
    
    const marketList = document.getElementById('demo-market-list');
    const orderBook = document.getElementById('demo-order-book');
    const priceDisplays = document.querySelectorAll('.demo-price');
    const changeDisplays = document.querySelectorAll('.demo-change');

    let candles = [];
    const maxCandles = 50;
    
    // Initialize OHLC candles
    function generateInitialData() {
        let lastClose = currentDemoPrice;
        for(let i=0; i<maxCandles; i++) {
            const open = lastClose + (Math.random() - 0.5) * 100;
            const close = open + (Math.random() - 0.5) * 200;
            const high = Math.max(open, close) + Math.random() * 50;
            const low = Math.min(open, close) - Math.random() * 50;
            const vol = Math.random() * 100 + 20;
            candles.push({o: open, h: high, l: low, c: close, v: vol});
            lastClose = close;
        }
        currentDemoPrice = lastClose;
    }
    generateInitialData();

    function drawChart(context, cvs) {
        if (!context || !cvs) return;
        cvs.width = cvs.offsetWidth * window.devicePixelRatio;
        cvs.height = cvs.offsetHeight * window.devicePixelRatio;
        context.scale(window.devicePixelRatio, window.devicePixelRatio);
        
        const w = cvs.offsetWidth;
        const h = cvs.offsetHeight;
        const paddingRight = 60;
        const paddingTop = 20;
        const paddingBottom = 40;
        const chartW = w - paddingRight;
        const chartH = h - paddingTop - paddingBottom;

        const minPrice = Math.min(...candles.map(c => c.l)) * 0.999;
        const maxPrice = Math.max(...candles.map(c => c.h)) * 1.001;
        const range = maxPrice - minPrice;

        context.clearRect(0, 0, w, h);
        
        // Grid Lines & Price Axis
        context.strokeStyle = 'rgba(255,255,255,0.05)';
        context.setLineDash([5, 5]);
        context.font = '10px Arial';
        context.fillStyle = '#848e9c';
        for(let i=0; i<6; i++) {
            const y = paddingTop + (chartH / 5) * i;
            const price = maxPrice - (range / 5) * i;
            context.beginPath(); context.moveTo(0, y); context.lineTo(chartW, y); context.stroke();
            context.fillText(price.toFixed(2), chartW + 5, y + 4);
        }
        context.setLineDash([]);

        const candleW = (chartW / maxCandles) * 0.8;
        const candleSpacing = (chartW / maxCandles);

        candles.forEach((c, i) => {
            const x = candleSpacing * i + (candleSpacing - candleW) / 2;
            const color = c.c >= c.o ? '#0ecb81' : '#f6465d';
            
            // High/Low line
            const hY = paddingTop + (1 - (c.h - minPrice) / range) * chartH;
            const lY = paddingTop + (1 - (c.l - minPrice) / range) * chartH;
            context.strokeStyle = color;
            context.lineWidth = 1;
            context.beginPath();
            context.moveTo(x + candleW / 2, hY);
            context.lineTo(x + candleW / 2, lY);
            context.stroke();

            // Body
            const oY = paddingTop + (1 - (c.o - minPrice) / range) * chartH;
            const cY = paddingTop + (1 - (c.c - minPrice) / range) * chartH;
            context.fillStyle = color;
            context.fillRect(x, Math.min(oY, cY), candleW, Math.abs(oY - cY) || 1);

            // Volume bar
            const volH = (c.v / 150) * 40;
            context.globalAlpha = 0.2;
            context.fillRect(x, h - 5, candleW, -volH);
            context.globalAlpha = 1.0;
        });

        // Current Price Line
        const lastCandle = candles[candles.length - 1];
        const lastY = paddingTop + (1 - (lastCandle.c - minPrice) / range) * chartH;
        context.strokeStyle = '#f0b90b';
        context.setLineDash([2, 2]);
        context.beginPath();
        context.moveTo(0, lastY);
        context.lineTo(chartW, lastY);
        context.stroke();
        context.setLineDash([]);
        
        // Price Label on axis
        context.fillStyle = '#f0b90b';
        context.fillRect(chartW, lastY - 8, paddingRight, 16);
        context.fillStyle = '#000';
        context.fillText(lastCandle.c.toFixed(2), chartW + 5, lastY + 4);
    }

    window.updateDemoMarkets = function() {
        if (!marketList) return;
        marketList.innerHTML = demoCoins.map(c => `
            <div class="market-row ${c.symbol === 'BTC' ? 'active' : ''}">
                <div class="d-flex align-items-center gap-2">
                    <span class="fw-bold text-light" style="font-size: 13px;">${c.symbol}</span>
                    <span class="text-muted" style="font-size: 10px;">/USDT</span>
                </div>
                <div class="text-end">
                    <div class="text-light fw-bold" style="font-size: 12px;">${c.price.toLocaleString()}</div>
                    <div class="${c.change.includes('+') ? 'text-success' : 'text-danger'}" style="font-size: 10px;">${c.change}</div>
                </div>
            </div>
        `).join('');
    }

    function updateOrderBook() {
        if (!orderBook) return;
        let html = '';
        const lastC = candles[candles.length - 1].c;
        // Sells
        for(let i=0; i<8; i++) {
            const p = (lastC + (8 - i) * 1.2).toFixed(2);
            const q = (Math.random() * 1.5).toFixed(4);
            const depth = Math.random() * 80;
            html += `<div class="ob-row text-danger" style="height: 20px; line-height: 20px;">
                        <div class="ob-bg" style="width: ${depth}%; background: rgba(246, 70, 93, 0.1);"></div>
                        <span>${p}</span><span>${q}</span>
                     </div>`;
        }
        // Mid Price
        html += `<div class="text-center py-2 fw-bold text-success fs-5" style="background: rgba(0,0,0,0.2);">${lastC.toFixed(2)}</div>`;
        // Buys
        for(let i=0; i<8; i++) {
            const p = (lastC - (i + 1) * 1.2).toFixed(2);
            const q = (Math.random() * 1.5).toFixed(4);
            const depth = Math.random() * 80;
            html += `<div class="ob-row text-success" style="height: 20px; line-height: 20px;">
                        <div class="ob-bg" style="width: ${depth}%; background: rgba(14, 203, 129, 0.1);"></div>
                        <span>${p}</span><span>${q}</span>
                     </div>`;
        }
        orderBook.innerHTML = html;
    }

    let tickCount = 0;
    function tick() {
        const last = candles[candles.length - 1];
        const volatility = demoMode === 'binary' ? 20 : 10;
        const change = (Math.random() - 0.5) * volatility;
        
        // Update current candle
        last.c += change;
        last.h = Math.max(last.h, last.c);
        last.l = Math.min(last.l, last.c);
        last.v += Math.random() * 5;

        tickCount++;
        // Create new candle every 5 ticks
        if(tickCount >= 5) {
            tickCount = 0;
            candles.shift();
            const newOpen = last.c;
            candles.push({o: newOpen, h: newOpen, l: newOpen, c: newOpen, v: Math.random() * 50 + 10});
        }

        const formatted = last.c.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
        currentDemoPrice = last.c; // Update global state
        priceDisplays.forEach(el => el.innerText = formatted);
        
        const priceInput = document.querySelector('.demo-price-input');
        if (priceInput) priceInput.value = formatted;

        updateOrderBook();
        drawChart(ctx, canvas);
        if (mCtx) drawChart(mCtx, mobileCanvas);
    }

    function updateHistory() {
        const historyList = document.getElementById('demo-history-list');
        if (!historyList) return;
        
        const now = new Date();
        const mockHistory = [
            { pair: 'BTC/USDT', type: 'buy', price: (currentDemoPrice - 5).toFixed(2), amount: '0.0450', time: now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() },
            { pair: 'BTC/USDT', type: 'sell', price: (currentDemoPrice + 12).toFixed(2), amount: '0.1200', time: now.getHours() + ':' + (now.getMinutes()-1) + ':24' }
        ];

        historyList.innerHTML = `
            <div class="table-responsive">
                <table class="table table-dark table-borderless mb-0" style="font-size: 11px;">
                    <thead>
                        <tr class="text-muted border-bottom border-secondary border-opacity-25">
                            <th class="py-1"><?php echo __('time'); ?></th>
                            <th class="py-1"><?php echo __('type'); ?></th>
                            <th class="py-1"><?php echo __('price'); ?></th>
                            <th class="py-1"><?php echo __('amount'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        ${mockHistory.map(h => `
                            <tr>
                                <td class="py-1 text-muted">${h.time}</td>
                                <td class="py-1 ${h.type === 'buy' ? 'text-success' : 'text-danger'}">${h.type === 'buy' ? '<?php echo __('buy'); ?>' : '<?php echo __('sell'); ?>'}</td>
                                <td class="py-1">${h.price}</td>
                                <td class="py-1">${h.amount}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        `;
    }

    switchDemoMode('spot');
    updateHistory();
    window.updateDemoMarkets();
    setInterval(tick, 500); // Faster update for better dynamic feel
    window.addEventListener('resize', () => {
        drawChart(ctx, canvas);
        if (mCtx) drawChart(mCtx, mobileCanvas);
    });
}


function updateUI(symbol, price, change) {
    if (!symbol) return;
    const card = document.querySelector(`.coin-card[data-symbol="${symbol}"]`);
    if (!card) return;
    
    const priceEl = card.querySelector('.price-display');
    const badge = card.querySelector('.change-badge');
    if (!priceEl || !badge) return;
    
    const currentText = priceEl.innerText.replace('$', '').replace(/,/g, '');
    const oldPrice = parseFloat(currentText) || 0;
    
    // Format price
    let formattedPrice;
    if (price < 0.0001) formattedPrice = price.toFixed(8);
    else if (price < 1) formattedPrice = price.toFixed(6);
    else if (price < 100) formattedPrice = price.toFixed(4);
    else formattedPrice = price.toLocaleString(undefined, {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
    
    priceEl.innerText = '$' + formattedPrice;
    
    if (Math.abs(price - oldPrice) > 0.000001 && oldPrice > 0) {
        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);
        }
    }
    
    if (badge && !isNaN(change)) {
        badge.innerText = (change >= 0 ? '+' : '') + change.toFixed(2) + '%';
        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(`api/prices.php?type=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();
initDemoModule();
</script>

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