<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

require_once "include/db.php";
mysqli_set_charset($conn, "utf8mb4");

$userId = intval($_SESSION['user_id']);

// Fetch User Data for Theme
$sql = "SELECT * FROM users WHERE id = $userId LIMIT 1";
$result = mysqli_query($conn, $sql);
$currentUser = ($result && mysqli_num_rows($result) > 0) ? mysqli_fetch_assoc($result) : null;

if (!$currentUser) {
    header("Location: ../login.php");
    exit;
}

$dbTheme = $_SESSION['theme'] ?? ($currentUser['theme'] ?? '#3b82f6');

// Fetch user's balance
$balance = (float)($currentUser['balance'] ?? 0.00);

// ==========================================
// 🔴 FETCH ADMIN WIN/LOSS SETTINGS
// ==========================================
$settingsQuery = mysqli_query($conn, "SELECT `setting_key`, `setting_value` FROM `admin_settings` WHERE `setting_key` IN ('win_probability', 'loss_probability')");
$adminSettings = [];
if ($settingsQuery) {
    while ($sRow = mysqli_fetch_assoc($settingsQuery)) {
        $adminSettings[$sRow['setting_key']] = (int)$sRow['setting_value'];
    }
}
$winProbability = $adminSettings['win_probability'] ?? 30;
$lossProbability = $adminSettings['loss_probability'] ?? 70;

// ==========================================
// 🔴 FETCH LIVE ASSET PRICES
// ==========================================
$assetQuery = mysqli_query($conn, "SELECT `id`, `symbol`, `name`, `category`, `price`, `change_24h`, `icon`, `is_active` FROM `assets` WHERE `is_active` = 1 ORDER BY `category`, `name`");
$assets = [];
$categories = ['crypto' => [], 'stock' => [], 'forex' => [], 'index' => [], 'other' => []];

if ($assetQuery && mysqli_num_rows($assetQuery) > 0) {
    while ($row = mysqli_fetch_assoc($assetQuery)) {
        $cat = strtolower($row['category']);
        if (!isset($categories[$cat])) $cat = 'other';
        
        $asset = [
            'id' => (int)$row['id'],
            'symbol' => $row['symbol'],
            'name' => $row['name'],
            'price' => (float)$row['price'],
            'change' => (float)$row['change_24h'],
            'icon' => $row['icon'] ?? 'trending-up',
            'category' => $cat
        ];
        $categories[$cat][] = $asset;
        $assets[] = $asset;
    }
}

// ==========================================
// 🔴 HANDLE AJAX TRADE SUBMISSION (BULLETPROOF)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'place_trade') {
    // 1. Turn off HTML error reporting so it doesn't corrupt our JSON response
    ini_set('display_errors', 0);
    header('Content-Type: application/json');
    
    // 2. Start output buffering to trap any stray warnings from db.php
    ob_start(); 

    try {
        $assetId = intval($_POST['asset_id'] ?? 0);
        $tradeType = in_array($_POST['trade_type'] ?? '', ['buy', 'sell']) ? $_POST['trade_type'] : 'buy';
        $amount = floatval($_POST['amount'] ?? 0);
        $duration = intval($_POST['duration'] ?? 60);
        $market = in_array($_POST['market'] ?? '', ['real', 'demo']) ? $_POST['market'] : 'real';
        
        if ($amount <= 0) {
            throw new Exception('Invalid trade amount.');
        }
        
        if ($market === 'real' && $amount > $balance) {
            throw new Exception('Insufficient available balance.');
        }
        
        // Fetch asset info (Universal Approach)
        $priceStmt = mysqli_prepare($conn, "SELECT `price`, `symbol` FROM `assets` WHERE `id` = ? AND `is_active` = 1");
        if (!$priceStmt) throw new Exception("Assets SQL Error: " . mysqli_error($conn));
        
        mysqli_stmt_bind_param($priceStmt, "i", $assetId);
        mysqli_stmt_execute($priceStmt);
        
        // Bind the expected columns directly to variables
        mysqli_stmt_bind_result($priceStmt, $dbPrice, $dbSymbol);
        
        // Fetch the row
        if (!mysqli_stmt_fetch($priceStmt)) {
            mysqli_stmt_close($priceStmt);
            throw new Exception('Asset not found or inactive.');
        }
        
        $entryPrice = (float)$dbPrice;
        $assetSymbol = $dbSymbol;
        
        // Close the statement to free the connection for the next query
        mysqli_stmt_close($priceStmt);
        
        // Deduct balance for real trades
        if ($market === 'real') {
            $newBalance = $balance - $amount;
            mysqli_query($conn, "UPDATE `users` SET `balance` = $newBalance WHERE `id` = $userId");
        }
        
        $status = 'open';
        $expiresAt = date('Y-m-d H:i:s', strtotime("+$duration seconds"));
        
        // Insert Trade
        $insertStmt = mysqli_prepare($conn, "INSERT INTO `trades` (`user_id`, `asset`, `trade_type`, `amount`, `entry_price`, `status`, `created_at`, `expires_at`, `duration`, `market`) VALUES (?, ?, ?, ?, ?, ?, NOW(), ?, ?, ?)");
        
        if (!$insertStmt) {
            throw new Exception("Trades SQL Error: " . mysqli_error($conn)); // This will tell you if a column is missing!
        }

        mysqli_stmt_bind_param($insertStmt, "issddssis", $userId, $assetSymbol, $tradeType, $amount, $entryPrice, $status, $expiresAt, $duration, $market);
        
        if (!mysqli_stmt_execute($insertStmt)) {
            throw new Exception("Execution Failed: " . mysqli_stmt_error($insertStmt));
        }

        $tradeId = mysqli_insert_id($conn);
        
        // Success! Clear the trap and send valid JSON using UNIX timestamp
        ob_end_clean();
        echo json_encode([
            'success' => true, 
            'message' => 'Trade placed successfully!',
            'trade_id' => $tradeId,
            'expires_at' => strtotime($expiresAt) * 1000 // Convert to JS milliseconds
        ]);

    } catch (Throwable $e) {
        // Catch ANY fatal error, warning, or manual exception
        ob_end_clean(); // Wipe away any HTML that leaked
        echo json_encode([
            'success' => false, 
            'message' => $e->getMessage() // This will print the EXACT database error to your screen
        ]);
    }
    exit;
}

// ==========================================
// 🔴 FETCH USER'S OPEN TRADES
// ==========================================
$openTrades = [];
$openQuery = mysqli_query($conn, "SELECT `id`, `asset`, `trade_type`, `amount`, `entry_price`, `expires_at`, `duration`, `market` FROM `trades` WHERE `user_id` = $userId AND `status` = 'open' ORDER BY `created_at` DESC LIMIT 10");
if ($openQuery) {
    while ($row = mysqli_fetch_assoc($openQuery)) {
        $openTrades[] = [
            'id' => 'TRD-' . $row['id'],
            'asset' => $row['asset'],
            'type' => ucfirst($row['trade_type']),
            'amount' => (float)$row['amount'],
            'entry_price' => (float)$row['entry_price'],
            'expires_at' => strtotime($row['expires_at']) * 1000, // Convert to JS milliseconds
            'duration' => (int)$row['duration'],
            'market' => $row['market']
        ];
    }
}
?>

<?php include "include/header.php"?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
<script src="https://unpkg.com/lightweight-charts@5.2.0/dist/lightweight-charts.standalone.production.js"></script>

<style>
    :root {
        --primary-theme: <?php echo htmlspecialchars($dbTheme, ENT_QUOTES, 'UTF-8'); ?>;
        --primary-rgb: <?php 
            $hex = ltrim($dbTheme, '#');
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));
            echo "$r, $g, $b";
        ?>;
    }
    
    .text-theme { color: var(--primary-theme) !important; }
    .bg-theme { background-color: var(--primary-theme) !important; }
    .border-theme { border-color: var(--primary-theme) !important; }
    
    .glass-card {
        background: rgba(255, 255, 255, 0.8);
        backdrop-filter: blur(12px);
        border: 1px solid rgba(0, 0, 0, 0.05);
    }
    .dark .glass-card {
        background: rgba(15, 23, 42, 0.6);
        border: 1px solid rgba(255, 255, 255, 0.05);
    }

    /* Expert Banner */
    .expert-banner {
        background: linear-gradient(135deg, rgba(var(--primary-rgb), 0.1) 0%, rgba(var(--primary-rgb), 0.05) 100%);
        border: 1px solid rgba(var(--primary-rgb), 0.2);
        position: relative;
        overflow: hidden;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    .expert-banner:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 40px -10px rgba(var(--primary-rgb), 0.3);
        border-color: rgba(var(--primary-rgb), 0.4);
    }
    .expert-banner::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: linear-gradient(45deg, transparent, rgba(255,255,255,0.1), transparent);
        animation: shimmer 3s infinite;
    }
    @keyframes shimmer {
        0% { transform: translateX(-100%) translateY(-100%) rotate(45deg); }
        100% { transform: translateX(100%) translateY(100%) rotate(45deg); }
    }
    
    /* Asset Cards */
    .asset-card {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .asset-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 20px 40px -12px rgba(0, 0, 0, 0.15);
    }
    .asset-card.selected {
        border: 2px solid var(--primary-theme);
        background: rgba(var(--primary-rgb), 0.05);
    }
    .asset-card.selected::after {
        content: '✓';
        position: absolute;
        top: 8px;
        right: 8px;
        width: 20px;
        height: 20px;
        background: var(--primary-theme);
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 10px;
        font-weight: 900;
    }
    
    /* Live Price Ticker */
    .price-ticker {
        font-variant-numeric: tabular-nums;
        font-feature-settings: "tnum";
    }
    .price-up { color: #10b981; }
    .price-down { color: #f43f5e; }
    
    /* Trade Type Buttons */
    .trade-btn {
        transition: all 0.2s ease;
        position: relative;
        overflow: hidden;
    }
    .trade-btn::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        width: 0;
        height: 0;
        background: rgba(255,255,255,0.2);
        border-radius: 50%;
        transform: translate(-50%, -50%);
        transition: width 0.4s, height 0.4s;
    }
    .trade-btn:active::after {
        width: 200%;
        height: 200%;
    }
    
    /* Duration Pills */
    .duration-pill {
        transition: all 0.2s ease;
    }
    .duration-pill.active {
        background: var(--primary-theme);
        color: white;
        box-shadow: 0 4px 15px -3px rgba(var(--primary-rgb), 0.4);
    }
    
    /* Market Toggle */
    .market-toggle {
        position: relative;
        background: #e2e8f0;
        border-radius: 9999px;
        padding: 4px;
    }
    .dark .market-toggle { background: #1e293b; }
    .market-toggle-btn {
        transition: all 0.3s ease;
        border-radius: 9999px;
    }
    .market-toggle-btn.active {
        background: var(--primary-theme);
        color: white;
        box-shadow: 0 2px 8px rgba(var(--primary-rgb), 0.4);
    }
    
    /* Scrollbar */
    .asset-scroll::-webkit-scrollbar { height: 6px; }
    .asset-scroll::-webkit-scrollbar-thumb { background: rgba(var(--primary-rgb), 0.3); border-radius: 10px; }
    .asset-scroll { scrollbar-width: thin; scrollbar-color: rgba(var(--primary-rgb), 0.3) transparent; }
    
    /* Pulse Animation for Live */
    @keyframes pulse-dot {
        0%, 100% { opacity: 1; transform: scale(1); }
        50% { opacity: 0.5; transform: scale(1.2); }
    }
    .live-dot { animation: pulse-dot 2s infinite; }
    
    /* Modal Overlay */
    .modal-overlay {
        background: rgba(0, 0, 0, 0.5);
        backdrop-filter: blur(4px);
    }

    /* Chart Container */
    .chart-wrapper {
        position: relative;
        width: 100%;
        height: 400px;
        border-radius: 1.5rem;
        overflow: hidden;
    }
    .chart-wrapper #tradingChart {
        width: 100%;
        height: 100%;
    }
    
    /* Timeframe Buttons */
    .tf-btn {
        transition: all 0.2s ease;
        font-size: 10px;
        font-weight: 900;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        padding: 4px 10px;
        border-radius: 6px;
    }
    .tf-btn.active {
        background: var(--primary-theme);
        color: white;
    }
    .tf-btn:not(.active):hover {
        background: rgba(var(--primary-rgb), 0.1);
        color: var(--primary-theme);
    }
</style>

<?php include "include/nav.php"?>

<div class="flex min-h-screen bg-slate-50 dark:bg-[#070b14] transition-colors duration-300"
     x-data='{
        now: Date.now(),
        selectedAsset: null,
        selectedCategory: "crypto",
        tradeType: "buy",
        amount: 100,
        duration: 60,
        market: "real",
        balance: <?= $balance ?>,
        winProb: <?= $winProbability ?>,
        lossProb: <?= $lossProbability ?>,
        openTrades: <?= json_encode($openTrades, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
        categories: <?= json_encode($categories, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
        showConfirm: false,
        isSubmitting: false,
        showExpertModal: false,
        chartInstance: null,
        candleSeries: null,
        currentTf: "1m",
        
        init() {
            // Update the reactive "now" tracker every second
            setInterval(() => {
                this.now = Date.now();
            }, 1000);
        },
        
        get filteredAssets() {
            return this.categories[this.selectedCategory] || [];
        },
        
        get potentialProfit() {
            return this.amount * 0.85;
        },
        
        get potentialLoss() {
            return this.amount;
        },
        
        selectAsset(asset) {
            this.selectedAsset = asset;
            this.$nextTick(() => {
                initChart(asset.symbol, asset.price, this.currentTf);
            });
        },
        
        setDuration(sec) {
            this.duration = sec;
        },
        
        setTimeframe(tf) {
            this.currentTf = tf;
            if (this.selectedAsset) {
                initChart(this.selectedAsset.symbol, this.selectedAsset.price, tf);
            }
        },
        
        formatTimeLeft(expiresTimestamp) {
            const diff = expiresTimestamp - this.now;
            if (diff <= 0) return "00:00";
            const mins = Math.floor(diff / 60000);
            const secs = Math.floor((diff % 60000) / 1000);
            return `${mins.toString().padStart(2,"0")}:${secs.toString().padStart(2,"0")}`;
        },
        
        async submitTrade() {
            if (!this.selectedAsset) {
                Swal.fire({ icon: "warning", title: "Select Asset", text: "Please choose an asset to trade.", confirmButtonColor: "var(--primary-theme)" });
                return;
            }
            if (this.amount <= 0 || isNaN(this.amount)) {
                Swal.fire({ icon: "warning", title: "Invalid Amount", text: "Please enter a valid trade amount.", confirmButtonColor: "var(--primary-theme)" });
                return;
            }
            if (this.market === "real" && this.amount > this.balance) {
                Swal.fire({ icon: "error", title: "Insufficient Balance", text: "You dont have enough funds for this trade.", confirmButtonColor: "var(--primary-theme)" });
                return;
            }
            
            this.isSubmitting = true;
            
            // Use URLSearchParams instead of FormData for better compatibility
            const params = new URLSearchParams();
            params.append("action", "place_trade");
            params.append("asset_id", this.selectedAsset.id);
            params.append("trade_type", this.tradeType);
            params.append("amount", this.amount);
            params.append("duration", this.duration);
            params.append("market", this.market);
            
            try {
                const response = await fetch("trade_terminal.php", { 
                    method: "POST", 
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: params.toString() 
                });
                const data = await response.json();
                
                if (data.success) {
                    Swal.fire({ 
                        icon: "success", 
                        title: "Trade Executed!", 
                        text: `Your ${this.tradeType.toUpperCase()} order on ${this.selectedAsset.name} has been placed.`, 
                        confirmButtonColor: "var(--primary-theme)",
                        timer: 2000,
                        showConfirmButton: false
                    });
                    if (this.market === "real") this.balance -= this.amount;
                    this.openTrades.unshift({
                        id: "TRD-" + data.trade_id,
                        asset: this.selectedAsset.name,
                        symbol: this.selectedAsset.symbol,
                        type: this.tradeType.charAt(0).toUpperCase() + this.tradeType.slice(1),
                        amount: this.amount,
                        entry_price: this.selectedAsset.price,
                        expires_at: data.expires_at,
                        duration: this.duration,
                        market: this.market
                    });
                    this.showConfirm = false;
                } else {
                    Swal.fire({ icon: "error", title: "Trade Failed", text: data.message, confirmButtonColor: "var(--primary-theme)" });
                }
            } catch (error) {
                console.error("Trade error:", error);
                Swal.fire({ icon: "error", title: "Error", text: "Something went wrong. Please try again.", confirmButtonColor: "var(--primary-theme)" });
            } finally {
                this.isSubmitting = false;
            }
        }
     }'>
  
  <?php include "include/sidebar.php"?>
  
  <main class="flex-1 min-w-0 md:ml-72 pb-24 md:pb-8">
    <div class="max-w-screen-2xl mx-auto px-4 sm:px-6 py-8">

      <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
        <div>
          <h1 class="text-3xl font-black text-slate-900 dark:text-white tracking-tight">
            Trade <span class="text-theme">Terminal</span>
          </h1>
          <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Execute positions across global markets in real-time.</p>
        </div>
        <div class="flex items-center gap-4">
            <div class="glass-card rounded-2xl px-5 py-3 flex items-center gap-3">
                <div class="w-2 h-2 rounded-full bg-emerald-500 live-dot"></div>
                <span class="text-xs font-black uppercase tracking-widest text-slate-600 dark:text-slate-300">Balance</span>
                <span class="text-lg font-black text-slate-900 dark:text-white" x-text="'$' + balance.toFixed(2)"></span>
            </div>
        </div>
      </div>

      <div class="expert-banner rounded-[2rem] p-6 mb-8 flex items-center justify-between relative" @click="showExpertModal = true">
        <div class="flex items-center gap-4 z-10">
            <div class="w-14 h-14 rounded-2xl bg-theme/20 flex items-center justify-center text-theme">
                <i data-lucide="crown" class="w-7 h-7"></i>
            </div>
            <div>
                <h3 class="text-lg font-black text-slate-900 dark:text-white tracking-tight">Click for Expert Traders</h3>
                <p class="text-xs font-bold text-slate-500 dark:text-slate-400 mt-0.5 uppercase tracking-widest">Copy top-performing strategies & signals</p>
            </div>
        </div>
        <div class="hidden md:flex items-center gap-2 z-10">
            <div class="flex -space-x-2">
                <div class="w-8 h-8 rounded-full bg-slate-300 border-2 border-white dark:border-slate-800 flex items-center justify-center text-[10px] font-black text-slate-600">JD</div>
                <div class="w-8 h-8 rounded-full bg-theme/30 border-2 border-white dark:border-slate-800 flex items-center justify-center text-[10px] font-black text-theme">AK</div>
                <div class="w-8 h-8 rounded-full bg-emerald-400/30 border-2 border-white dark:border-slate-800 flex items-center justify-center text-[10px] font-black text-emerald-600">MR</div>
                <div class="w-8 h-8 rounded-full bg-amber-400/30 border-2 border-white dark:border-slate-800 flex items-center justify-center text-[10px] font-black text-amber-600">+42</div>
            </div>
            <i data-lucide="arrow-right" class="w-5 h-5 text-theme ml-2"></i>
        </div>
      </div>

      <div class="grid grid-cols-1 xl:grid-cols-12 gap-6">
        
        <div class="xl:col-span-8 space-y-6">
            
            <div class="glass-card rounded-[2.5rem] p-1 border border-slate-200 dark:border-slate-800 shadow-xl overflow-hidden">
                <div class="flex items-center justify-between px-6 py-3 border-b border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/20">
                    <div class="flex items-center gap-3">
                        <div class="w-8 h-8 rounded-lg bg-theme/10 flex items-center justify-center text-theme">
                            <i data-lucide="candlestick-chart" class="w-4 h-4"></i>
                        </div>
                        <div>
                            <h3 class="text-sm font-black text-slate-900 dark:text-white" x-text="selectedAsset ? selectedAsset.symbol + ' / USD' : 'Select an Asset'"></h3>
                            <p class="text-[9px] font-bold text-slate-400 uppercase tracking-widest" x-text="selectedAsset ? selectedAsset.name : 'Choose from categories below'"></p>
                        </div>
                    </div>
                    <div class="flex items-center gap-1">
                        <button @click="setTimeframe('1m')" :class="currentTf === '1m' ? 'active' : 'text-slate-500 dark:text-slate-400'" class="tf-btn">1m</button>
                        <button @click="setTimeframe('5m')" :class="currentTf === '5m' ? 'active' : 'text-slate-500 dark:text-slate-400'" class="tf-btn">5m</button>
                        <button @click="setTimeframe('15m')" :class="currentTf === '15m' ? 'active' : 'text-slate-500 dark:text-slate-400'" class="tf-btn">15m</button>
                        <button @click="setTimeframe('1h')" :class="currentTf === '1h' ? 'active' : 'text-slate-500 dark:text-slate-400'" class="tf-btn">1h</button>
                        <button @click="setTimeframe('4h')" :class="currentTf === '4h' ? 'active' : 'text-slate-500 dark:text-slate-400'" class="tf-btn">4h</button>
                        <button @click="setTimeframe('1d')" :class="currentTf === '1d' ? 'active' : 'text-slate-500 dark:text-slate-400'" class="tf-btn">1D</button>
                    </div>
                </div>
                <div class="chart-wrapper bg-white dark:bg-[#0b0e14]">
                    <div id="tradingChart"></div>
                </div>
                <div class="flex items-center justify-between px-6 py-3 border-t border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/20">
                    <div class="flex items-center gap-6">
                        <div>
                            <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">O</span>
                            <span class="text-xs font-bold text-slate-700 dark:text-slate-300 ml-1" id="chartOpen">--</span>
                        </div>
                        <div>
                            <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">H</span>
                            <span class="text-xs font-bold text-emerald-500 ml-1" id="chartHigh">--</span>
                        </div>
                        <div>
                            <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">L</span>
                            <span class="text-xs font-bold text-rose-500 ml-1" id="chartLow">--</span>
                        </div>
                        <div>
                            <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">C</span>
                            <span class="text-xs font-bold text-theme ml-1" id="chartClose">--</span>
                        </div>
                    </div>
                    <div class="flex items-center gap-2">
                        <div class="w-1.5 h-1.5 rounded-full bg-emerald-500 live-dot"></div>
                        <span class="text-[9px] font-bold text-slate-400 uppercase tracking-widest">Live Market Data</span>
                    </div>
                </div>
            </div>

            <div class="glass-card rounded-[2rem] p-2 flex gap-1 overflow-x-auto asset-scroll">
                <button @click="selectedCategory = 'crypto'" 
                        :class="selectedCategory === 'crypto' ? 'bg-theme text-white shadow-lg' : 'text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800'"
                        class="px-6 py-3 rounded-[1.5rem] text-xs font-black uppercase tracking-widest transition-all flex items-center gap-2 whitespace-nowrap flex-shrink-0">
                    <i data-lucide="bitcoin" class="w-4 h-4"></i> Crypto
                </button>
                <button @click="selectedCategory = 'stock'" 
                        :class="selectedCategory === 'stock' ? 'bg-theme text-white shadow-lg' : 'text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800'"
                        class="px-6 py-3 rounded-[1.5rem] text-xs font-black uppercase tracking-widest transition-all flex items-center gap-2 whitespace-nowrap flex-shrink-0">
                    <i data-lucide="bar-chart-3" class="w-4 h-4"></i> Stocks
                </button>
                <button @click="selectedCategory = 'forex'" 
                        :class="selectedCategory === 'forex' ? 'bg-theme text-white shadow-lg' : 'text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800'"
                        class="px-6 py-3 rounded-[1.5rem] text-xs font-black uppercase tracking-widest transition-all flex items-center gap-2 whitespace-nowrap flex-shrink-0">
                    <i data-lucide="banknote" class="w-4 h-4"></i> Forex
                </button>
                <button @click="selectedCategory = 'index'" 
                        :class="selectedCategory === 'index' ? 'bg-theme text-white shadow-lg' : 'text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800'"
                        class="px-6 py-3 rounded-[1.5rem] text-xs font-black uppercase tracking-widest transition-all flex items-center gap-2 whitespace-nowrap flex-shrink-0">
                    <i data-lucide="activity" class="w-4 h-4"></i> Indices
                </button>
                <button @click="selectedCategory = 'other'" 
                        :class="selectedCategory === 'other' ? 'bg-theme text-white shadow-lg' : 'text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800'"
                        class="px-6 py-3 rounded-[1.5rem] text-xs font-black uppercase tracking-widest transition-all flex items-center gap-2 whitespace-nowrap flex-shrink-0">
                    <i data-lucide="globe" class="w-4 h-4"></i> Others
                </button>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                <template x-for="asset in filteredAssets" :key="asset.id">
                    <div @click="selectAsset(asset)" 
                         :class="selectedAsset && selectedAsset.id === asset.id ? 'selected' : ''"
                         class="asset-card glass-card rounded-[2rem] p-5 border border-slate-200 dark:border-slate-800">
                        <div class="flex items-start justify-between mb-4">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-xl bg-theme/10 flex items-center justify-center text-theme">
                                    <i :data-lucide="asset.icon" class="w-5 h-5"></i>
                                </div>
                                <div>
                                    <p class="text-sm font-black text-slate-900 dark:text-white" x-text="asset.symbol"></p>
                                    <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest" x-text="asset.name"></p>
                                </div>
                            </div>
                            <div class="text-right">
                                <p class="text-xs font-black" :class="asset.change >= 0 ? 'text-emerald-500' : 'text-rose-500'" x-text="(asset.change >= 0 ? '+' : '') + asset.change + '%'"></p>
                            </div>
                        </div>
                        <div class="flex items-end justify-between">
                            <p class="text-2xl font-black text-slate-900 dark:text-white price-ticker" x-text="'$' + asset.price.toFixed(asset.price < 1 ? 6 : 2)"></p>
                            <div class="flex items-center gap-1">
                                <div class="w-1.5 h-1.5 rounded-full bg-emerald-500 live-dot"></div>
                                <span class="text-[9px] font-bold text-slate-400 uppercase tracking-widest">Live</span>
                            </div>
                        </div>
                    </div>
                </template>
                <div x-show="filteredAssets.length === 0" class="col-span-full text-center py-12">
                    <i data-lucide="search-x" class="w-10 h-10 text-slate-300 mx-auto mb-3"></i>
                    <p class="text-xs font-bold text-slate-500 uppercase tracking-widest">No assets available in this category.</p>
                </div>
            </div>

            <div class="glass-card rounded-[2.5rem] border border-slate-200 dark:border-slate-800 overflow-hidden" x-show="openTrades.length > 0">
                <div class="p-6 border-b border-slate-200 dark:border-slate-800">
                    <h3 class="text-xs font-black uppercase tracking-widest text-slate-400">Active Positions</h3>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full text-left">
                        <thead>
                            <tr class="text-[9px] font-black uppercase tracking-widest text-slate-400 border-b border-slate-200 dark:border-slate-800">
                                <th class="p-4 pl-6">Asset</th>
                                <th class="p-4">Type</th>
                                <th class="p-4">Amount</th>
                                <th class="p-4">Entry</th>
                                <th class="p-4 text-right">Time Left</th>
                            </tr>
                        </thead>
                        <tbody>
                            <template x-for="trade in openTrades" :key="trade.id">
                                <tr class="border-b border-slate-100 dark:border-slate-800/50 last:border-0">
                                    <td class="p-4 pl-6">
                                        <div class="flex items-center gap-3">
                                            <div class="w-8 h-8 rounded-lg bg-theme/10 flex items-center justify-center text-theme">
                                                <i data-lucide="candlestick-chart" class="w-4 h-4"></i>
                                            </div>
                                            <div>
                                                <p class="text-sm font-black text-slate-900 dark:text-white" x-text="trade.asset"></p>
                                                <p class="text-[9px] font-bold text-slate-400 tracking-widest" x-text="trade.id"></p>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="p-4">
                                        <span class="px-2 py-1 rounded text-[9px] font-black uppercase tracking-widest"
                                              :class="trade.type === 'Buy' ? 'bg-emerald-500/10 text-emerald-500' : 'bg-rose-500/10 text-rose-500'"
                                              x-text="trade.type"></span>
                                    </td>
                                    <td class="p-4">
                                        <p class="text-sm font-bold text-slate-900 dark:text-white" x-text="'$' + trade.amount.toFixed(2)"></p>
                                    </td>
                                    <td class="p-4">
                                        <p class="text-xs font-bold text-slate-600 dark:text-slate-300" x-text="trade.entry_price.toFixed(4)"></p>
                                    </td>
                                    <td class="p-4 text-right">
                                        <span class="text-sm font-black text-theme" x-text="formatTimeLeft(trade.expires_at)"></span>
                                    </td>
                                </tr>
                            </template>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="xl:col-span-4">
            <div class="glass-card rounded-[2.5rem] p-6 border border-slate-200 dark:border-slate-800 sticky top-6">
                
                <div class="flex justify-center mb-6">
                    <div class="market-toggle inline-flex">
                        <button @click="market = 'demo'" :class="market === 'demo' ? 'active' : 'text-slate-500'" class="market-toggle-btn px-6 py-2 text-xs font-black uppercase tracking-widest">Demo</button>
                        <button @click="market = 'real'" :class="market === 'real' ? 'active' : 'text-slate-500'" class="market-toggle-btn px-6 py-2 text-xs font-black uppercase tracking-widest">Real</button>
                    </div>
                </div>

                <div class="text-center mb-6 p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                    <template x-if="selectedAsset">
                        <div>
                            <p class="text-3xl font-black text-slate-900 dark:text-white mb-1" x-text="selectedAsset.symbol"></p>
                            <p class="text-sm font-bold text-slate-400 uppercase tracking-widest" x-text="selectedAsset.name"></p>
                            <p class="text-2xl font-black text-theme mt-2 price-ticker" x-text="'$' + selectedAsset.price.toFixed(selectedAsset.price < 1 ? 6 : 2)"></p>
                        </div>
                    </template>
                    <template x-if="!selectedAsset">
                        <div class="py-4">
                            <i data-lucide="mouse-pointer-click" class="w-8 h-8 text-slate-300 mx-auto mb-2"></i>
                            <p class="text-xs font-bold text-slate-400 uppercase tracking-widest">Select an asset to trade</p>
                        </div>
                    </template>
                </div>

                <div class="grid grid-cols-2 gap-3 mb-6">
                    <button @click="tradeType = 'buy'" 
                            :class="tradeType === 'buy' ? 'bg-emerald-500 text-white shadow-lg shadow-emerald-500/30' : 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400'"
                            class="trade-btn py-4 rounded-2xl text-sm font-black uppercase tracking-widest flex items-center justify-center gap-2">
                        <i data-lucide="trending-up" class="w-5 h-5"></i> Buy / Long
                    </button>
                    <button @click="tradeType = 'sell'" 
                            :class="tradeType === 'sell' ? 'bg-rose-500 text-white shadow-lg shadow-rose-500/30' : 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400'"
                            class="trade-btn py-4 rounded-2xl text-sm font-black uppercase tracking-widest flex items-center justify-center gap-2">
                        <i data-lucide="trending-down" class="w-5 h-5"></i> Sell / Short
                    </button>
                </div>

                <div class="mb-6">
                    <label class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-2 block">Trade Amount (USD)</label>
                    <div class="relative">
                        <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-black">$</span>
                        <input type="number" x-model.number="amount" min="10" step="10"
                               class="w-full pl-8 pr-4 py-4 rounded-2xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white font-black text-lg focus:outline-none focus:border-theme focus:ring-2 focus:ring-theme/20 transition-all"
                               placeholder="100.00">
                    </div>
                    <div class="flex gap-2 mt-3">
                        <button @click="amount = 50" class="flex-1 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 text-xs font-bold text-slate-600 dark:text-slate-400 hover:bg-theme hover:text-white transition-colors">$50</button>
                        <button @click="amount = 100" class="flex-1 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 text-xs font-bold text-slate-600 dark:text-slate-400 hover:bg-theme hover:text-white transition-colors">$100</button>
                        <button @click="amount = 500" class="flex-1 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 text-xs font-bold text-slate-600 dark:text-slate-400 hover:bg-theme hover:text-white transition-colors">$500</button>
                        <button @click="amount = 1000" class="flex-1 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 text-xs font-bold text-slate-600 dark:text-slate-400 hover:bg-theme hover:text-white transition-colors">$1K</button>
                    </div>
                </div>

                <div class="mb-6">
                    <label class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-2 block">Duration</label>
                    <div class="grid grid-cols-4 gap-2">
                        <button @click="setDuration(60)" :class="duration === 60 ? 'active' : 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" class="duration-pill py-3 rounded-xl text-[10px] font-black uppercase tracking-widest text-center">1m</button>
                        <button @click="setDuration(300)" :class="duration === 300 ? 'active' : 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" class="duration-pill py-3 rounded-xl text-[10px] font-black uppercase tracking-widest text-center">5m</button>
                        <button @click="setDuration(900)" :class="duration === 900 ? 'active' : 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" class="duration-pill py-3 rounded-xl text-[10px] font-black uppercase tracking-widest text-center">15m</button>
                        <button @click="setDuration(3600)" :class="duration === 3600 ? 'active' : 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" class="duration-pill py-3 rounded-xl text-[10px] font-black uppercase tracking-widest text-center">1h</button>
                    </div>
                </div>

                <div class="rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800 p-4 mb-6 space-y-2">
                    <div class="flex justify-between items-center">
                        <span class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Potential Profit</span>
                        <span class="text-sm font-black text-emerald-500" x-text="'+$' + potentialProfit.toFixed(2) + ' (85%)'"></span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Potential Loss</span>
                        <span class="text-sm font-black text-rose-500" x-text="'-$' + potentialLoss.toFixed(2)"></span>
                    </div>
                    <div class="border-t border-slate-200 dark:border-slate-800 pt-2 mt-2 flex justify-between items-center">
                        <span class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Win Probability</span>
                        <span class="text-xs font-black text-theme" x-text="winProb + '%'"></span>
                    </div>
                </div>

                <button @click="showConfirm = true" 
                        :disabled="!selectedAsset || isSubmitting"
                        :class="!selectedAsset ? 'opacity-50 cursor-not-allowed' : 'hover:brightness-110 active:scale-[0.98]'"
                        class="w-full py-5 rounded-2xl bg-theme text-white font-black uppercase tracking-widest text-sm shadow-xl shadow-theme/30 transition-all flex items-center justify-center gap-2">
                    <span x-show="!isSubmitting">Execute Trade</span>
                    <span x-show="isSubmitting" class="flex items-center gap-2">
                        <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        Processing...
                    </span>
                </button>

                <p class="text-center text-[9px] font-bold text-slate-400 uppercase tracking-widest mt-4">
                    Market: <span x-text="market.toUpperCase()" class="text-slate-600 dark:text-slate-300"></span> • 
                    Admin Win Rate: <span x-text="winProb + '%'" class="text-theme"></span>
                </p>
            </div>
        </div>

      </div>

    </div>
  </main>

  <div x-show="showConfirm" style="display: none;" class="fixed inset-0 z-50 flex items-center justify-center modal-overlay p-4" x-transition>
    <div class="glass-card rounded-[2.5rem] p-8 max-w-md w-full border border-slate-200 dark:border-slate-800 shadow-2xl" @click.away="showConfirm = false">
        <div class="text-center mb-6">
            <div class="w-16 h-16 rounded-full bg-theme/10 flex items-center justify-center text-theme mx-auto mb-4">
                <i data-lucide="shield-check" class="w-8 h-8"></i>
            </div>
            <h3 class="text-xl font-black text-slate-900 dark:text-white">Confirm Trade</h3>
            <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Review your order details before execution.</p>
        </div>
        
        <div class="space-y-3 mb-6 p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
            <div class="flex justify-between">
                <span class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Asset</span>
                <span class="text-sm font-black text-slate-900 dark:text-white" x-text="selectedAsset ? selectedAsset.symbol : '-'"></span>
            </div>
            <div class="flex justify-between">
                <span class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Direction</span>
                <span class="text-sm font-black" :class="tradeType === 'buy' ? 'text-emerald-500' : 'text-rose-500'" x-text="tradeType.toUpperCase()"></span>
            </div>
            <div class="flex justify-between">
                <span class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Amount</span>
                <span class="text-sm font-black text-slate-900 dark:text-white" x-text="'$' + amount.toFixed(2)"></span>
            </div>
            <div class="flex justify-between">
                <span class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Duration</span>
                <span class="text-sm font-black text-slate-900 dark:text-white" x-text="duration < 60 ? duration + 's' : (duration/60) + 'm'"></span>
            </div>
        </div>

        <div class="grid grid-cols-2 gap-3">
            <button @click="showConfirm = false" class="py-3 rounded-2xl bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 font-black uppercase tracking-widest text-xs hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors">Cancel</button>
            <button @click="submitTrade()" :disabled="isSubmitting" class="py-3 rounded-2xl bg-theme text-white font-black uppercase tracking-widest text-xs hover:brightness-110 transition-all">Confirm</button>
        </div>
    </div>
  </div>

  <div x-show="showExpertModal" style="display: none;" class="fixed inset-0 z-50 flex items-center justify-center modal-overlay p-4" x-transition>
    <div class="glass-card rounded-[2.5rem] p-8 max-w-lg w-full border border-slate-200 dark:border-slate-800 shadow-2xl max-h-[80vh] overflow-y-auto" @click.away="showExpertModal = false">
        <div class="flex items-center justify-between mb-6">
            <div>
                <h3 class="text-xl font-black text-slate-900 dark:text-white">Expert Traders</h3>
                <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Copy strategies from top performers.</p>
            </div>
            <button @click="showExpertModal = false" class="w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-slate-400 hover:text-slate-600 transition-colors">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>

        <div class="space-y-4">
            <div class="flex items-center gap-4 p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800 hover:border-theme/30 transition-colors cursor-pointer">
                <div class="w-12 h-12 rounded-full bg-gradient-to-br from-theme to-purple-600 flex items-center justify-center text-white font-black text-lg">JD</div>
                <div class="flex-1">
                    <div class="flex items-center gap-2">
                        <h4 class="text-sm font-black text-slate-900 dark:text-white">John Davidson</h4>
                        <span class="px-2 py-0.5 rounded bg-amber-500/10 text-amber-500 text-[9px] font-black uppercase tracking-widest">Pro</span>
                    </div>
                    <p class="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Forex Specialist • 847 Followers</p>
                    <div class="flex items-center gap-3 mt-2">
                        <span class="text-xs font-black text-emerald-500">+124.5% ROI</span>
                        <span class="text-[10px] text-slate-400">•</span>
                        <span class="text-xs font-bold text-slate-400">Win Rate: 78%</span>
                    </div>
                </div>
                <button class="px-4 py-2 rounded-xl bg-theme text-white text-xs font-black uppercase tracking-widest hover:brightness-110 transition-all">Copy</button>
            </div>

            <div class="flex items-center gap-4 p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800 hover:border-theme/30 transition-colors cursor-pointer">
                <div class="w-12 h-12 rounded-full bg-gradient-to-br from-emerald-500 to-teal-600 flex items-center justify-center text-white font-black text-lg">AK</div>
                <div class="flex-1">
                    <div class="flex items-center gap-2">
                        <h4 class="text-sm font-black text-slate-900 dark:text-white">Anna Kovacs</h4>
                        <span class="px-2 py-0.5 rounded bg-amber-500/10 text-amber-500 text-[9px] font-black uppercase tracking-widest">Pro</span>
                    </div>
                    <p class="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Crypto Analyst • 1,203 Followers</p>
                    <div class="flex items-center gap-3 mt-2">
                        <span class="text-xs font-black text-emerald-500">+198.2% ROI</span>
                        <span class="text-[10px] text-slate-400">•</span>
                        <span class="text-xs font-bold text-slate-400">Win Rate: 82%</span>
                    </div>
                </div>
                <button class="px-4 py-2 rounded-xl bg-theme text-white text-xs font-black uppercase tracking-widest hover:brightness-110 transition-all">Copy</button>
            </div>

            <div class="flex items-center gap-4 p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800 hover:border-theme/30 transition-colors cursor-pointer">
                <div class="w-12 h-12 rounded-full bg-gradient-to-br from-rose-500 to-orange-500 flex items-center justify-center text-white font-black text-lg">MR</div>
                <div class="flex-1">
                    <div class="flex items-center gap-2">
                        <h4 class="text-sm font-black text-slate-900 dark:text-white">Marcus Reid</h4>
                        <span class="px-2 py-0.5 rounded bg-slate-500/10 text-slate-500 text-[9px] font-black uppercase tracking-widest">Elite</span>
                    </div>
                    <p class="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Indices & Stocks • 2,451 Followers</p>
                    <div class="flex items-center gap-3 mt-2">
                        <span class="text-xs font-black text-emerald-500">+156.8% ROI</span>
                        <span class="text-[10px] text-slate-400">•</span>
                        <span class="text-xs font-bold text-slate-400">Win Rate: 74%</span>
                    </div>
                </div>
                <button class="px-4 py-2 rounded-xl bg-theme text-white text-xs font-black uppercase tracking-widest hover:brightness-110 transition-all">Copy</button>
            </div>

            <div class="flex items-center gap-4 p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800 hover:border-theme/30 transition-colors cursor-pointer">
                <div class="w-12 h-12 rounded-full bg-gradient-to-br from-violet-500 to-indigo-600 flex items-center justify-center text-white font-black text-lg">SL</div>
                <div class="flex-1">
                    <div class="flex items-center gap-2">
                        <h4 class="text-sm font-black text-slate-900 dark:text-white">Sarah Lin</h4>
                        <span class="px-2 py-0.5 rounded bg-amber-500/10 text-amber-500 text-[9px] font-black uppercase tracking-widest">Pro</span>
                    </div>
                    <p class="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Multi-Asset • 956 Followers</p>
                    <div class="flex items-center gap-3 mt-2">
                        <span class="text-xs font-black text-emerald-500">+89.4% ROI</span>
                        <span class="text-[10px] text-slate-400">•</span>
                        <span class="text-xs font-bold text-slate-400">Win Rate: 71%</span>
                    </div>
                </div>
                <button class="px-4 py-2 rounded-xl bg-theme text-white text-xs font-black uppercase tracking-widest hover:brightness-110 transition-all">Copy</button>
            </div>
        </div>
    </div>
  </div>

</div>

<?php if(file_exists('include/footer.php')) include "include/footer.php"; ?>

<script src="https://unpkg.com/lucide@latest"></script>
<script>
    // ==========================================
    // TRADINGVIEW LIGHTWEIGHT CHARTS INTEGRATION
    // ==========================================
    let chart = null;
    let candleSeries = null;
    let volumeSeries = null;
    let chartInterval = null; 
    let chartResizeObserver = null; 
    
    function generateCandleData(basePrice, count, volatility) {
        const data = [];
        let currentPrice = basePrice;
        const now = new Date();
        
        for (let i = count; i >= 0; i--) {
            const time = new Date(now.getTime() - i * 60000);
            const timestamp = Math.floor(time.getTime() / 1000);
            
            const change = (Math.random() - 0.5) * volatility;
            const open = currentPrice;
            const close = currentPrice + change;
            const high = Math.max(open, close) + Math.random() * volatility * 0.5;
            const low = Math.min(open, close) - Math.random() * volatility * 0.5;
            
            data.push({
                time: timestamp,
                open: parseFloat(open.toFixed(4)),
                high: parseFloat(high.toFixed(4)),
                low: parseFloat(low.toFixed(4)),
                close: parseFloat(close.toFixed(4))
            });
            
            currentPrice = close;
        }
        return data;
    }
    
    function initChart(symbol, basePrice, timeframe) {
        const container = document.getElementById('tradingChart');
        if (!container) return;
        
        if (chartInterval) clearInterval(chartInterval);
        if (chartResizeObserver) chartResizeObserver.disconnect();
        
        container.innerHTML = '';
        
        const isDark = document.documentElement.classList.contains('dark');
        
        const chartOptions = {
            layout: {
                background: { type: 'solid', color: isDark ? '#0b0e14' : '#ffffff' },
                textColor: isDark ? '#94a3b8' : '#64748b',
                fontFamily: 'inherit',
            },
            grid: {
                vertLines: { color: isDark ? '#1e293b' : '#f1f5f9' },
                horzLines: { color: isDark ? '#1e293b' : '#f1f5f9' },
            },
            crosshair: {
                mode: LightweightCharts.CrosshairMode.Normal,
                vertLine: {
                    color: 'rgba(var(--primary-rgb), 0.4)',
                    width: 1,
                    style: 2,
                    labelBackgroundColor: 'var(--primary-theme)',
                },
                horzLine: {
                    color: 'rgba(var(--primary-rgb), 0.4)',
                    width: 1,
                    style: 2,
                    labelBackgroundColor: 'var(--primary-theme)',
                },
            },
            rightPriceScale: {
                borderColor: isDark ? '#1e293b' : '#e2e8f0',
                scaleMargins: { top: 0.1, bottom: 0.2 },
            },
            timeScale: {
                borderColor: isDark ? '#1e293b' : '#e2e8f0',
                timeVisible: true,
                secondsVisible: false,
            },
            handleScroll: { vertTouchDrag: false },
        };
        
        chart = LightweightCharts.createChart(container, chartOptions);
        
        candleSeries = chart.addSeries(LightweightCharts.CandlestickSeries, {
            upColor: '#10b981',
            downColor: '#f43f5e',
            borderUpColor: '#10b981',
            borderDownColor: '#f43f5e',
            wickUpColor: '#10b981',
            wickDownColor: '#f43f5e',
        });
        
        let volatility = basePrice * 0.002; 
        let candleCount = 100;
        
        if (timeframe === '5m') { volatility = basePrice * 0.004; candleCount = 80; }
        if (timeframe === '15m') { volatility = basePrice * 0.008; candleCount = 60; }
        if (timeframe === '1h') { volatility = basePrice * 0.015; candleCount = 48; }
        if (timeframe === '4h') { volatility = basePrice * 0.03; candleCount = 30; }
        if (timeframe === '1d') { volatility = basePrice * 0.05; candleCount = 90; }
        
        const candleData = generateCandleData(basePrice, candleCount, volatility);
        candleSeries.setData(candleData);
        
        const lastCandle = candleData[candleData.length - 1];
        document.getElementById('chartOpen').textContent = lastCandle.open.toFixed(4);
        document.getElementById('chartHigh').textContent = lastCandle.high.toFixed(4);
        document.getElementById('chartLow').textContent = lastCandle.low.toFixed(4);
        document.getElementById('chartClose').textContent = lastCandle.close.toFixed(4);
        
        chart.timeScale().fitContent();
        
        chartInterval = setInterval(() => {
            if (!candleSeries) return;
            const lastData = candleData[candleData.length - 1];
            const newPrice = lastData.close + (Math.random() - 0.5) * volatility * 0.3;
            
            const updatedCandle = {
                time: lastData.time, 
                open: lastData.open,
                high: Math.max(lastData.high, newPrice),
                low: Math.min(lastData.low, newPrice),
                close: parseFloat(newPrice.toFixed(4))
            };
            
            candleSeries.update(updatedCandle);
            candleData[candleData.length - 1] = updatedCandle;
            
            document.getElementById('chartClose').textContent = updatedCandle.close.toFixed(4);
            if (updatedCandle.close > updatedCandle.open) {
                document.getElementById('chartClose').className = 'text-xs font-bold text-emerald-500 ml-1';
            } else {
                document.getElementById('chartClose').className = 'text-xs font-bold text-rose-500 ml-1';
            }
        }, 2000);
        
        chartResizeObserver = new ResizeObserver(entries => {
            if (entries.length === 0 || entries[0].contentRect.width === 0) return;
            const newRect = entries[0].contentRect;
            chart.applyOptions({ width: newRect.width, height: 400 });
        });
        chartResizeObserver.observe(container);
    }
    
    document.addEventListener('DOMContentLoaded', () => {
        lucide.createIcons();
        
        const firstCrypto = document.querySelector('.asset-card');
        if (firstCrypto) firstCrypto.click();
    });
    
    document.addEventListener('alpine:initialized', () => {
        Alpine.effect(() => {
            setTimeout(() => { lucide.createIcons(); }, 10);
        });
    });
</script>

</body>
</html>