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

// ── Check if user has any connected wallets ──
$walletCheckSql = "SELECT COUNT(*) as wallet_count FROM wallets WHERE user_id = $userId";
$walletCheckResult = mysqli_query($conn, $walletCheckSql);
$walletConnected = ($walletCheckResult && mysqli_fetch_assoc($walletCheckResult)['wallet_count'] > 0);

// Fetch Total Deposits
$depSql = "SELECT COALESCE(SUM(amount), 0) as total FROM deposits WHERE user_id = $userId AND status = 'completed'";
$depResult = mysqli_query($conn, $depSql);
$totalDeposit = ($depResult) ? mysqli_fetch_assoc($depResult)['total'] : 0;

// Fetch active/open trades (pending or running)
$activeTradesSql = "SELECT * FROM trades WHERE user_id = $userId AND status IN ('pending', 'running') ORDER BY created_at DESC";
$activeTradesResult = mysqli_query($conn, $activeTradesSql);
$activeTrades = [];
if ($activeTradesResult) {
    while ($row = mysqli_fetch_assoc($activeTradesResult)) {
        $activeTrades[] = $row;
    }
}

// Fetch completed trades history
$historySql = "SELECT * FROM trades WHERE user_id = $userId AND status IN ('win', 'loss', 'draw') ORDER BY closed_at DESC LIMIT 10";
$historyResult = mysqli_query($conn, $historySql);
$tradeHistory = [];
if ($historyResult) {
    while ($row = mysqli_fetch_assoc($historyResult)) {
        $tradeHistory[] = $row;
    }
}

// Fetch trading stats
$statsSql = "SELECT * FROM user_trading_stats WHERE user_id = $userId LIMIT 1";
$statsResult = mysqli_query($conn, $statsSql);
$tradingStats = ($statsResult && mysqli_num_rows($statsResult) > 0) ? mysqli_fetch_assoc($statsResult) : [
    'total_trades' => 0, 'win_count' => 0, 'loss_count' => 0, 'total_pnl' => 0
];

// Set values
$userBalance = $currentUser['balance'] ?? 0;
$totalProfit = $currentUser['profit'] ?? 0;
$totalBonus = $currentUser['bonus'] ?? 0;
$userName = $currentUser['username'] ?? 'Trader';
$dbTheme = $_SESSION['theme'] ?? ($currentUser['theme'] ?? '#0ea5e9');

$referralLink = "https://theinteractivebrokers.com/app/ref?" . htmlspecialchars($userName, ENT_QUOTES, 'UTF-8');

// Market configurations
$markets = [
    'crypto' => [
        'name' => 'Cryptocurrency',
        'icon' => 'bitcoin',
        'pairs' => ['BTC/USD', 'ETH/USD', 'SOL/USD', 'XRP/USD', 'ADA/USD', 'DOT/USD'],
        'min_amount' => 10,
        'max_amount' => 50000,
        'default_time' => 5 // minutes
    ],
    'forex' => [
        'name' => 'Forex',
        'icon' => 'banknote',
        'pairs' => ['EUR/USD', 'GBP/USD', 'USD/JPY', 'AUD/USD', 'USD/CHF', 'EUR/GBP'],
        'min_amount' => 10,
        'max_amount' => 100000,
        'default_time' => 15
    ],
    'stocks' => [
        'name' => 'Stocks',
        'icon' => 'trending-up',
        'pairs' => ['AAPL', 'TSLA', 'GOOGL', 'MSFT', 'AMZN', 'NVDA'],
        'min_amount' => 50,
        'max_amount' => 100000,
        'default_time' => 30
    ],
    'commodities' => [
        'name' => 'Commodities',
        'icon' => 'gem',
        'pairs' => ['GOLD', 'SILVER', 'OIL', 'NATGAS', 'COPPER', 'PLATINUM'],
        'min_amount' => 25,
        'max_amount' => 50000,
        'default_time' => 60
    ]
];

// Time options in minutes
$timeOptions = [1, 3, 5, 15, 30, 60, 120, 240, 480];
?>

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

<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; }
    .bg-theme-gradient { 
        background: linear-gradient(135deg, var(--primary-theme) 0%, #1e1b4b 100%) !important; 
    }
    .shadow-theme {
        box-shadow: 0 4px 20px -2px rgba(var(--primary-rgb), 0.25),
                    0 2px 8px -2px rgba(var(--primary-rgb), 0.15);
    }
    
    /* Glass morphism */
    .glass-card {
        background: rgba(30, 41, 59, 0.6);
        backdrop-filter: blur(12px);
        border: 1px solid rgba(255, 255, 255, 0.08);
    }
    .glass-card-light {
        background: rgba(255, 255, 255, 0.8);
        backdrop-filter: blur(12px);
        border: 1px solid rgba(0, 0, 0, 0.06);
    }
    
    /* Animated gradient border */
    .gradient-border {
        position: relative;
        background: linear-gradient(135deg, rgba(var(--primary-rgb), 0.1), rgba(30, 27, 75, 0.2));
        border-radius: 1rem;
    }
    .gradient-border::before {
        content: '';
        position: absolute;
        inset: 0;
        border-radius: 1rem;
        padding: 1.5px;
        background: linear-gradient(135deg, var(--primary-theme), rgba(var(--primary-rgb), 0.3), transparent);
        -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
        mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
        -webkit-mask-composite: xor;
        mask-composite: exclude;
        pointer-events: none;
    }
    
    /* Trade button glows */
    .btn-buy-glow {
        box-shadow: 0 0 20px rgba(16, 185, 129, 0.3), 0 4px 12px rgba(16, 185, 129, 0.2);
        transition: all 0.3s ease;
    }
    .btn-buy-glow:hover {
        box-shadow: 0 0 30px rgba(16, 185, 129, 0.5), 0 6px 16px rgba(16, 185, 129, 0.3);
        transform: translateY(-1px);
    }
    .btn-sell-glow {
        box-shadow: 0 0 20px rgba(244, 63, 94, 0.3), 0 4px 12px rgba(244, 63, 94, 0.2);
        transition: all 0.3s ease;
    }
    .btn-sell-glow:hover {
        box-shadow: 0 0 30px rgba(244, 63, 94, 0.5), 0 6px 16px rgba(244, 63, 94, 0.3);
        transform: translateY(-1px);
    }
    
    /* Status animations */
    @keyframes pulse-win {
        0%, 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4); }
        50% { box-shadow: 0 0 0 12px rgba(16, 185, 129, 0); }
    }
    @keyframes pulse-loss {
        0%, 100% { box-shadow: 0 0 0 0 rgba(244, 63, 94, 0.4); }
        50% { box-shadow: 0 0 0 12px rgba(244, 63, 94, 0); }
    }
    .trade-win { animation: pulse-win 2s infinite; }
    .trade-loss { animation: pulse-loss 2s infinite; }
    
    /* Live price shimmer */
    @keyframes shimmer {
        0% { background-position: -200% 0; }
        100% { background-position: 200% 0; }
    }
    .live-shimmer {
        background: linear-gradient(90deg, transparent, rgba(var(--primary-rgb), 0.1), transparent);
        background-size: 200% 100%;
        animation: shimmer 3s infinite;
    }
    
    /* Custom scrollbar */
    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-track { background: transparent; }
    ::-webkit-scrollbar-thumb { background: rgba(var(--primary-rgb), 0.3); border-radius: 99px; }
    ::-webkit-scrollbar-thumb:hover { background: rgba(var(--primary-rgb), 0.5); }
    
    /* Badges */
    .badge-win {
        background: linear-gradient(135deg, rgba(16, 185, 129, 0.15), rgba(16, 185, 129, 0.05));
        border: 1px solid rgba(16, 185, 129, 0.3);
        color: #10b981;
    }
    .badge-loss {
        background: linear-gradient(135deg, rgba(244, 63, 94, 0.15), rgba(244, 63, 94, 0.05));
        border: 1px solid rgba(244, 63, 94, 0.3);
        color: #f43f5e;
    }
    .badge-pending {
        background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(245, 158, 11, 0.05));
        border: 1px solid rgba(245, 158, 11, 0.3);
        color: #f59e0b;
    }
    .badge-running {
        background: linear-gradient(135deg, rgba(var(--primary-rgb), 0.15), rgba(var(--primary-rgb), 0.05));
        border: 1px solid rgba(var(--primary-rgb), 0.3);
        color: var(--primary-theme);
    }
    
    /* Timer countdown animation */
    @keyframes timer-pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.7; }
    }
    .timer-active {
        animation: timer-pulse 1s infinite;
    }
    
    /* Market tabs */
    .market-tab {
        transition: all 0.3s ease;
        position: relative;
    }
    .market-tab.active {
        background: var(--primary-theme);
        color: white;
        box-shadow: 0 4px 12px rgba(var(--primary-rgb), 0.3);
    }
    .market-tab:not(.active):hover {
        background: rgba(var(--primary-rgb), 0.1);
    }
    
    /* Chart glow */
    .chart-glow {
        box-shadow: 0 0 40px rgba(var(--primary-rgb), 0.08);
    }
    
    /* Position card slide in */
    @keyframes slideIn {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .position-card {
        animation: slideIn 0.3s ease-out;
    }
    
    /* Neon accent */
    .neon-accent {
        box-shadow: 0 0 15px rgba(var(--primary-rgb), 0.2),
                    inset 0 1px 0 rgba(255,255,255,0.1);
    }

    /* Wallet connected button styles */
    .btn-wallet-connected {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
        box-shadow: 0 4px 20px -2px rgba(16, 185, 129, 0.3), 0 2px 8px -2px rgba(16, 185, 129, 0.15) !important;
    }
    .btn-wallet-connected:hover {
        filter: brightness(1.1);
    }
</style>

<!-- NAVBAR -->
<?php include "include/nav.php"?>

<div class="flex min-h-screen bg-slate-50 dark:bg-[#0b111a] transition-colors duration-300">
  
  <!-- SIDEBAR -->
  <?php include "include/sidebar.php"?>
  
  <!-- MAIN CONTENT -->
  <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-6">

      <!-- Welcome Row -->
      <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
        <div>
          <h1 class="text-2xl sm:text-3xl font-bold text-slate-900 dark:text-white tracking-tight">
            Welcome back, <span class="text-theme"><?= htmlspecialchars($userName, ENT_QUOTES, 'UTF-8') ?></span>
          </h1>
          <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Professional Trading Terminal</p>
        </div>
        <div class="flex gap-3">
          <button onclick="window.location.href='deposit.php'" class="flex-1 md:flex-none flex items-center justify-center gap-2 px-4 py-2.5 bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 text-theme text-sm font-semibold rounded-xl transition-all border border-slate-200 dark:border-slate-700 shadow-sm">
            <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>
            Deposit
          </button>
          <?php if ($walletConnected): ?>
          <a href="connect-wallet.php" class="flex-1 md:flex-none flex items-center justify-center gap-2 px-4 py-2.5 btn-wallet-connected text-white text-sm font-semibold rounded-xl transition-all">
            <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></svg>
            Wallet Connected
          </a>
          <?php else: ?>
          <a href="connect-wallet.php" class="flex-1 md:flex-none flex items-center justify-center gap-2 px-4 py-2.5 bg-theme hover:brightness-110 text-white text-sm font-semibold rounded-xl transition-all shadow-theme">
            <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"/></svg>
            connect wallet
          </a>
          <?php endif; ?>
        </div>
      </div>

      <!-- Stats Overview -->
      <div class="grid grid-cols-1 lg:grid-cols-4 gap-4 mb-6" x-data="{ hideBalance: localStorage.getItem('hideBalance') === 'true' }" @balance-toggled.window="hideBalance = $event.detail.hidden">
        
        <!-- Total Balance -->
        <div class="lg:col-span-2 bg-theme-gradient rounded-2xl p-5 shadow-theme relative overflow-hidden">
          <div class="absolute top-0 right-0 w-64 h-64 bg-white/5 rounded-full blur-3xl -translate-y-1/2 translate-x-1/3"></div>
          
          <div class="flex justify-between items-start mb-6 relative z-10">
            <div class="flex items-center gap-2 text-white/90 font-medium text-sm">
              <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 10h20"/></svg>
              TOTAL BALANCE
            </div>
            <span class="px-2.5 py-1 bg-emerald-500/20 text-emerald-100 text-[10px] font-bold rounded-full border border-emerald-500/30 flex items-center gap-1.5">
              <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span> Active
            </span>
          </div>
          
          <div class="mb-6 relative z-10">
            <div class="text-4xl md:text-5xl font-bold text-white tracking-tight transition-all duration-300" 
                 id="main-balance" 
                 :class="hideBalance ? 'blur-md select-none opacity-50' : ''"
                 x-text="hideBalance ? '$••••••' : '$<?= number_format($userBalance, 2) ?>'">
                $<?= number_format($userBalance, 2) ?>
            </div>
            <p class="text-white/60 text-xs mt-2 flex items-center gap-1">
              <svg width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>
              Updated <?= date('M d, Y \a\t H:i') ?>
            </p>
          </div>

          <div class="flex gap-3 relative z-10">
            <a href="deposit.php" class="flex-1 flex justify-center items-center gap-2 py-3 bg-white/10 hover:bg-white/20 backdrop-blur-md rounded-xl text-white text-sm font-semibold transition-colors border border-white/10">
              <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 8v8M8 12h8"/></svg>
              Deposit
            </a>
            <a href="withdrawals.php" class="flex-1 flex justify-center items-center gap-2 py-3 bg-black/20 hover:bg-black/40 backdrop-blur-md rounded-xl text-white text-sm font-semibold transition-colors border border-white/5">
              <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M7 17l9.2-9.2M17 17V7H7"/></svg>
              Withdraw
            </a>
          </div>
        </div>

        <!-- Stat Cards -->
        <div class="lg:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-4">
          <!-- Total Profit -->
          <div class="glass-card-light dark:bg-slate-800 rounded-2xl p-5 shadow-sm flex flex-col justify-between transition-colors">
            <div class="flex justify-between items-start mb-2">
              <span class="text-[11px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Total Profit</span>
              <div class="w-8 h-8 rounded-full bg-emerald-500/10 flex items-center justify-center">
                <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-emerald-500"><path d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"/></svg>
              </div>
            </div>
            <div>
              <div class="text-2xl font-bold text-slate-900 dark:text-white transition-all duration-300" 
                   id="total-profit"
                   :class="hideBalance ? 'blur-sm select-none opacity-50' : ''"
                   x-text="hideBalance ? '$••••••' : '$<?= number_format($totalProfit, 2) ?>'">
                  $<?= number_format($totalProfit, 2) ?>
              </div>
              <div class="text-emerald-500 text-xs font-medium mt-1 flex items-center gap-1">
                <svg width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M12 19V5M5 12l7-7 7 7"/></svg>
                +<?= $tradingStats['win_count'] ?? 0 ?> wins
              </div>
            </div>
          </div>

          <!-- Total Deposit -->
          <div class="glass-card-light dark:bg-slate-800 rounded-2xl p-5 shadow-sm flex flex-col justify-between transition-colors">
            <div class="flex justify-between items-start mb-2">
              <span class="text-[11px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Total Deposit</span>
              <div class="w-8 h-8 rounded-full bg-theme/10 flex items-center justify-center">
                <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-theme"><path d="M12 5v14M19 12l-7 7-7-7"/></svg>
              </div>
            </div>
            <div>
              <div class="text-2xl font-bold text-slate-900 dark:text-white transition-all duration-300" 
                   :class="hideBalance ? 'blur-sm select-none opacity-50' : ''"
                   x-text="hideBalance ? '$••••••' : '$<?= number_format($totalDeposit, 2) ?>'">
                  $<?= number_format($totalDeposit, 2) ?>
              </div>
              <div class="text-slate-500 dark:text-slate-400 text-xs font-medium mt-1">Lifetime deposits</div>
            </div>
          </div>

          <!-- Trading Stats -->
          <div class="glass-card-light dark:bg-slate-800 rounded-2xl p-5 shadow-sm flex flex-col justify-between sm:col-span-2 transition-colors">
            <div class="flex justify-between items-start mb-2">
              <span class="text-[11px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Trading Performance</span>
              <div class="w-8 h-8 rounded-full bg-theme/10 flex items-center justify-center">
                <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-theme"><path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/></svg>
              </div>
            </div>
            <div class="flex items-end justify-between">
              <div>
                <div class="text-2xl font-bold text-slate-900 dark:text-white">
                    <?= $tradingStats['total_trades'] ?? 0 ?> <span class="text-sm font-normal text-slate-500">trades</span>
                </div>
                <div class="flex gap-3 mt-1">
                    <span class="text-xs text-emerald-500 font-medium"><?= $tradingStats['win_count'] ?? 0 ?> W</span>
                    <span class="text-xs text-rose-500 font-medium"><?= $tradingStats['loss_count'] ?? 0 ?> L</span>
                    <span class="text-xs text-theme font-medium">$<?= number_format($tradingStats['total_pnl'] ?? 0, 2) ?> P&L</span>
                </div>
              </div>
              <!-- Mini win rate circle -->
              <div class="relative w-12 h-12">
                <?php 
                $total = ($tradingStats['win_count'] ?? 0) + ($tradingStats['loss_count'] ?? 0);
                $rate = $total > 0 ? round(($tradingStats['win_count'] / $total) * 100) : 0;
                ?>
                <svg class="w-full h-full transform -rotate-90" viewBox="0 0 36 36">
                  <path class="text-slate-200 dark:text-slate-700" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" fill="none" stroke="currentColor" stroke-width="3"/>
                  <path class="text-theme" stroke-dasharray="<?= $rate ?>, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" fill="none" stroke="currentColor" stroke-width="3"/>
                </svg>
                <span class="absolute inset-0 flex items-center justify-center text-[10px] font-bold text-slate-700 dark:text-slate-300"><?= $rate ?>%</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- MAIN GRID -->
      <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
        
        <!-- LEFT COLUMN: Chart & Active Positions -->
        <div class="xl:col-span-2 space-y-6">
            
            <!-- TradingView Chart -->
            <div class="glass-card-light dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700/50 overflow-hidden flex flex-col chart-glow transition-colors">
              <div class="p-4 border-b border-slate-200 dark:border-slate-700/50 flex justify-between items-center">
                <div class="flex items-center gap-3">
                  <div class="w-8 h-8 rounded-lg bg-theme/10 flex items-center justify-center neon-accent">
                    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-theme"><path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/></svg>
                  </div>
                  <div>
                    <h3 class="font-bold text-slate-900 dark:text-white text-sm">Market Overview</h3>
                    <p class="text-xs text-slate-500 dark:text-slate-400">Real-time price action</p>
                  </div>
                </div>
                <div class="flex items-center gap-2">
                    <span class="px-2 py-1 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 text-[10px] font-bold rounded-md border border-emerald-500/20 flex items-center gap-1">
                        <span class="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"></span> LIVE
                    </span>
                    <a href="Trading Market.php" class="text-xs text-theme font-medium hover:brightness-125 ml-2">View History →</a>
                </div>
              </div>
              
              <div class="p-3 border-b border-slate-200 dark:border-slate-700/50 flex flex-wrap gap-2 bg-slate-50/50 dark:bg-slate-800/30">
                <span class="px-3 py-1.5 bg-white dark:bg-slate-800 rounded-lg text-xs font-medium text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 flex items-center gap-1.5 shadow-sm cursor-pointer hover:border-theme transition-colors" onclick="changeChart('BINANCE:BTCUSDT')">
                    <img src="https://cryptologos.cc/logos/bitcoin-btc-logo.svg?v=024" class="w-4 h-4"> 
                    <span class="font-bold">BTC</span> 
                    <span class="text-emerald-600 dark:text-emerald-400 font-mono" id="btc-price">$78,814</span>
                    <span class="text-emerald-500 text-[10px]">▲ 2.4%</span>
                </span>
                <span class="px-3 py-1.5 bg-white dark:bg-slate-800 rounded-lg text-xs font-medium text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 flex items-center gap-1.5 shadow-sm cursor-pointer hover:border-theme transition-colors" onclick="changeChart('BINANCE:ETHUSDT')">
                    <img src="https://cryptologos.cc/logos/ethereum-eth-logo.svg?v=024" class="w-4 h-4"> 
                    <span class="font-bold">ETH</span> 
                    <span class="text-emerald-600 dark:text-emerald-400 font-mono" id="eth-price">$2,346</span>
                    <span class="text-emerald-500 text-[10px]">▲ 1.8%</span>
                </span>
                <span class="px-3 py-1.5 bg-white dark:bg-slate-800 rounded-lg text-xs font-medium text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 flex items-center gap-1.5 shadow-sm cursor-pointer hover:border-theme transition-colors" onclick="changeChart('BINANCE:SOLUSDT')">
                    <img src="https://cryptologos.cc/logos/solana-sol-logo.svg?v=024" class="w-4 h-4"> 
                    <span class="font-bold">SOL</span> 
                    <span class="text-rose-500 font-mono">$142.30</span>
                    <span class="text-rose-500 text-[10px]">▼ 0.5%</span>
                </span>
                <span class="px-3 py-1.5 bg-white dark:bg-slate-800 rounded-lg text-xs font-medium text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 flex items-center gap-1.5 shadow-sm cursor-pointer hover:border-theme transition-colors" onclick="changeChart('FX:EURUSD')">
                    <span class="font-bold">EUR/USD</span> 
                    <span class="text-emerald-600 dark:text-emerald-400 font-mono">1.0845</span>
                    <span class="text-emerald-500 text-[10px]">▲ 0.2%</span>
                </span>
              </div>

              <div class="w-full h-[400px] md:h-[500px] bg-slate-900">
                  <div id="tradingview_dashboard" style="height:100%;width:100%"></div>
                  <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
                  <script type="text/javascript">
                  let tvWidget = null;
                  const tvIsDark = document.documentElement.classList.contains('dark');
                  
                  function initChart(symbol = 'BINANCE:BTCUSDT') {
                      if (tvWidget) {
                          tvWidget.remove();
                      }
                      tvWidget = new TradingView.widget({
                        "autosize": true,
                        "symbol": symbol,
                        "interval": "15",
                        "timezone": "Etc/UTC",
                        "theme": tvIsDark ? "dark" : "light",
                        "style": "1",
                        "locale": "en",
                        "backgroundColor": tvIsDark ? "#0f172a" : "#ffffff",
                        "gridColor": tvIsDark ? "#1e293b" : "#e2e8f0",
                        "hide_top_toolbar": false,
                        "container_id": "tradingview_dashboard"
                      });
                  }
                  
                  function changeChart(symbol) {
                      initChart(symbol);
                      showToast('Chart updated: ' + symbol);
                  }
                  
                  initChart();
                  </script>
              </div>
            </div>

            <!-- Active Positions (Real-time) -->
            <div class="glass-card-light dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700/50 overflow-hidden transition-colors">
                <div class="p-4 border-b border-slate-200 dark:border-slate-700/50 flex justify-between items-center">
                    <div class="flex items-center gap-3">
                        <div class="w-8 h-8 rounded-lg bg-amber-500/10 flex items-center justify-center neon-accent">
                            <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-amber-500"><path d="M12 2v4m0 12v4M4.93 4.93l2.83 2.83m8.48 8.48l2.83 2.83M2 12h4m12 0h4M4.93 19.07l2.83-2.83m8.48-8.48l2.83-2.83"/></svg>
                        </div>
                        <div>
                            <h3 class="font-bold text-slate-900 dark:text-white text-sm">Active Positions</h3>
                            <p class="text-xs text-slate-500 dark:text-slate-400">Running & pending trades</p>
                        </div>
                    </div>
                    <span class="text-xs font-bold text-amber-500" id="active-positions-count"><?= count($activeTrades) ?> Active</span>
                </div>
                <div class="overflow-x-auto" id="active-positions-container">
                    <?php if (empty($activeTrades)): ?>
                    <div class="p-8 text-center text-slate-500">
                        <div class="flex flex-col items-center gap-2">
                            <div class="w-12 h-12 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mb-2">
                                <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-slate-400"><path d="M12 2v4m0 12v4M4.93 4.93l2.83 2.83m8.48 8.48l2.83 2.83M2 12h4m12 0h4M4.93 19.07l2.83-2.83m8.48-8.48l2.83-2.83"/></svg>
                            </div>
                            <p class="text-sm">No active positions</p>
                            <p class="text-xs text-slate-400">Place a trade to get started</p>
                        </div>
                    </div>
                    <?php else: ?>
                    <div class="divide-y divide-slate-200 dark:divide-slate-700/50">
                        <?php foreach ($activeTrades as $trade): 
                            $isPending = $trade['status'] === 'pending';
                            $tradeType = strtoupper($trade['trade_type']);
                            $typeColor = $tradeType === 'BUY' ? 'text-emerald-500' : 'text-rose-500';
                            $typeBg = $tradeType === 'BUY' ? 'bg-emerald-500/10' : 'bg-rose-500/10';
                            $typeBorder = $tradeType === 'BUY' ? 'border-emerald-500/20' : 'border-rose-500/20';
                            
                            // Calculate remaining time
                            $created = strtotime($trade['created_at']);
                            $duration = intval($trade['duration']) * 60; // convert minutes to seconds
                            $expires = $created + $duration;
                            $now = time();
                            $remaining = max(0, $expires - $now);
                            $progress = $duration > 0 ? (($duration - $remaining) / $duration) * 100 : 0;
                        ?>
                        <div class="p-4 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors position-card" data-trade-id="<?= $trade['id'] ?>">
                            <div class="flex items-center justify-between mb-3">
                                <div class="flex items-center gap-3">
                                    <div class="w-10 h-10 rounded-xl <?= $typeBg ?> border <?= $typeBorder ?> flex items-center justify-center">
                                        <span class="text-xs font-bold <?= $typeColor ?>"><?= $tradeType ?></span>
                                    </div>
                                    <div>
                                        <div class="text-sm font-bold text-slate-900 dark:text-white"><?= htmlspecialchars($trade['asset']) ?></div>
                                        <div class="text-xs text-slate-500">$<?= number_format($trade['amount'], 2) ?> • <?= $trade['duration'] ?>min</div>
                                    </div>
                                </div>
                                <div class="text-right">
                                    <?php if ($isPending): ?>
                                    <span class="px-2 py-1 bg-amber-500/10 text-amber-500 text-[10px] font-bold rounded-full border border-amber-500/20">PENDING</span>
                                    <?php else: ?>
                                    <span class="px-2 py-1 bg-theme/10 text-theme text-[10px] font-bold rounded-full border border-theme/20 timer-active">RUNNING</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <?php if (!$isPending): ?>
                            <div class="space-y-2">
                                <div class="flex justify-between text-xs">
                                    <span class="text-slate-500">Time Remaining</span>
                                    <span class="font-mono font-bold text-theme" id="timer-<?= $trade['id'] ?>"><?= floor($remaining / 60) ?>:<?= str_pad($remaining % 60, 2, '0', STR_PAD_LEFT) ?></span>
                                </div>
                                <div class="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-2 overflow-hidden">
                                    <div id="progress-<?= $trade['id'] ?>" class="bg-theme h-2 rounded-full transition-all duration-1000" style="width: <?= $progress ?>%"></div>
                                </div>
                                <div class="flex justify-between text-xs mt-1">
                                    <span class="text-slate-500">Entry: <span class="font-mono text-slate-700 dark:text-slate-300">$<?= number_format($trade['entry_price'], 2) ?></span></span>
                                    <span class="text-slate-500">Current: <span class="font-mono text-theme" id="current-<?= $trade['id'] ?>">--</span></span>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Trade History -->
            <div class="glass-card-light dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700/50 overflow-hidden transition-colors">
                <div class="p-4 border-b border-slate-200 dark:border-slate-700/50 flex justify-between items-center">
                    <div class="flex items-center gap-3">
                        <div class="w-8 h-8 rounded-lg bg-slate-100 dark:bg-slate-800 flex items-center justify-center neon-accent">
                            <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-slate-500 dark:text-slate-400"><path d="M3 3v5h5"/><path d="M3.05 13A9 9 0 1 0 6 5.3L3 8"/><path d="M3 12v5h5"/></svg>
                        </div>
                        <div>
                            <h3 class="font-bold text-slate-900 dark:text-white text-sm">Recent History</h3>
                            <p class="text-xs text-slate-500 dark:text-slate-400">Completed trades</p>
                        </div>
                    </div>
                    <a href="trading history.php" class="text-xs text-theme font-medium hover:brightness-125">View All →</a>
                </div>
                <div class="overflow-x-auto">
                    <?php if (empty($tradeHistory)): ?>
                    <div class="p-8 text-center text-slate-500 text-sm">No trade history yet</div>
                    <?php else: ?>
                    <table class="w-full text-left text-sm">
                        <thead class="bg-slate-50 dark:bg-slate-800/50 text-xs uppercase text-slate-500">
                            <tr>
                                <th class="px-4 py-3 font-medium">Asset</th>
                                <th class="px-4 py-3 font-medium">Type</th>
                                <th class="px-4 py-3 font-medium">Amount</th>
                                <th class="px-4 py-3 font-medium">Result</th>
                                <th class="px-4 py-3 font-medium">P&L</th>
                                <th class="px-4 py-3 font-medium">Time</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-200 dark:divide-slate-700/50">
                            <?php foreach ($tradeHistory as $trade): 
                                $isWin = $trade['status'] === 'win';
                                $pnl = floatval($trade['pnl'] ?? 0);
                            ?>
                            <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/30 transition-colors">
                                <td class="px-4 py-3 font-medium text-slate-900 dark:text-white"><?= htmlspecialchars($trade['asset']) ?></td>
                                <td class="px-4 py-3">
                                    <span class="text-xs font-bold <?= strtoupper($trade['trade_type']) === 'BUY' ? 'text-emerald-500' : 'text-rose-500' ?>">
                                        <?= strtoupper($trade['trade_type']) ?>
                                    </span>
                                </td>
                                <td class="px-4 py-3 text-slate-600 dark:text-slate-400">$<?= number_format($trade['amount'], 2) ?></td>
                                <td class="px-4 py-3">
                                    <span class="px-2 py-1 text-[10px] font-bold rounded-full <?= $isWin ? 'badge-win' : 'badge-loss' ?>">
                                        <?= strtoupper($trade['status']) ?>
                                    </span>
                                </td>
                                <td class="px-4 py-3 font-mono font-bold <?= $pnl >= 0 ? 'text-emerald-500' : 'text-rose-500' ?>">
                                    <?= $pnl >= 0 ? '+' : '' ?>$<?= number_format(abs($pnl), 2) ?>
                                </td>
                                <td class="px-4 py-3 text-xs text-slate-500"><?= date('M d, H:i', strtotime($trade['closed_at'])) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php endif; ?>
                </div>
            </div>

        </div>

        <!-- RIGHT COLUMN: Quick Trade & Refer -->
        <div class="space-y-6">
            
            <!-- Quick Trade Panel -->
            <div class="gradient-border overflow-hidden">
                <div class="bg-theme-gradient p-6 text-center relative">
                    <div class="absolute inset-0 bg-[url('data:image/svg+xml,%3Csvg width=\"60\" height=\"60\" viewBox=\"0 0 60 60\" xmlns=\"http://www.w3.org/2000/svg\"%3E%3Cg fill=\"none\" fill-rule=\"evenodd\"%3E%3Cg fill=\"%23ffffff\" fill-opacity=\"0.03\"%3E%3Cpath d=\"M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z\"/%3E%3C/g%3E%3C/g%3E%3C/svg%3E')] opacity-50"></div>
                    <div class="relative">
                        <div class="w-14 h-14 rounded-full bg-white/20 flex items-center justify-center mx-auto mb-3 shadow-lg backdrop-blur-sm border border-white/30">
                            <svg width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-white"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>
                        </div>
                        <h3 class="text-lg font-bold text-white">New Trade</h3>
                        <p class="text-white/70 text-xs mt-1">Configure your position</p>
                    </div>
                </div>

                <div class="p-5 space-y-5 bg-white dark:bg-slate-900">
                    
                    <!-- Market Selection -->
                    <div>
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Market</label>
                        <div class="grid grid-cols-2 gap-2" id="market-selector">
                            <?php foreach ($markets as $key => $market): ?>
                            <button onclick="selectMarket('<?= $key ?>')" 
                                    class="market-tab px-3 py-2.5 rounded-xl text-xs font-bold border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 <?= $key === 'crypto' ? 'active' : '' ?>" 
                                    data-market="<?= $key ?>">
                                <div class="flex flex-col items-center gap-1">
                                    <span><?= $market['name'] ?></span>
                                    <span class="text-[9px] opacity-70 font-normal"><?= count($market['pairs']) ?> pairs</span>
                                </div>
                            </button>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Asset Selection -->
                    <div>
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Asset Pair</label>
                        <select id="trade-asset" class="w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-slate-200 text-sm rounded-xl px-4 py-3 outline-none focus:border-theme focus:ring-2 focus:ring-theme/20 transition-all appearance-none cursor-pointer">
                            <?php foreach ($markets['crypto']['pairs'] as $pair): ?>
                            <option value="<?= $pair ?>"><?= $pair ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Duration Selection -->
                    <div>
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Duration</label>
                        <div class="grid grid-cols-3 gap-2" id="time-selector">
                            <?php foreach ($timeOptions as $minutes): ?>
                            <button onclick="selectDuration(<?= $minutes ?>)" 
                                    class="duration-btn px-3 py-2 rounded-lg text-xs font-bold border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 hover:border-theme hover:text-theme transition-all <?= $minutes === 5 ? 'bg-theme text-white border-theme' : '' ?>" 
                                    data-minutes="<?= $minutes ?>">
                                <?php if ($minutes < 60): ?>
                                    <?= $minutes ?>m
                                <?php else: ?>
                                    <?= ($minutes / 60) ?>h
                                <?php endif; ?>
                            </button>
                            <?php endforeach; ?>
                        </div>
                        <input type="hidden" id="trade-duration" value="5">
                    </div>

                    <!-- Amount Input -->
                    <div>
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Amount (USD)</label>
                        <div class="relative">
                            <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-bold text-sm">$</span>
                            <input type="number" id="trade-amount" placeholder="0.00" min="10" step="1" 
                                   class="w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm rounded-xl pl-8 pr-4 py-3 outline-none focus:border-theme focus:ring-2 focus:ring-theme/20 transition-all font-mono">
                        </div>
                        <div class="flex gap-2 mt-2">
                            <button onclick="setTradeAmount(50)" class="flex-1 py-1.5 text-[10px] font-bold text-slate-600 dark:text-slate-400 bg-slate-100 dark:bg-slate-800 rounded-lg hover:bg-theme hover:text-white transition-colors">$50</button>
                            <button onclick="setTradeAmount(100)" class="flex-1 py-1.5 text-[10px] font-bold text-slate-600 dark:text-slate-400 bg-slate-100 dark:bg-slate-800 rounded-lg hover:bg-theme hover:text-white transition-colors">$100</button>
                            <button onclick="setTradeAmount(500)" class="flex-1 py-1.5 text-[10px] font-bold text-slate-600 dark:text-slate-400 bg-slate-100 dark:bg-slate-800 rounded-lg hover:bg-theme hover:text-white transition-colors">$500</button>
                            <button onclick="setTradeAmount(1000)" class="flex-1 py-1.5 text-[10px] font-bold text-slate-600 dark:text-slate-400 bg-slate-100 dark:bg-slate-800 rounded-lg hover:bg-theme hover:text-white transition-colors">$1K</button>
                        </div>
                        <p class="text-[10px] text-slate-400 mt-1" id="amount-limits">Min: $10 | Max: $50,000</p>
                    </div>

                    <!-- Trade Summary -->
                    <div class="bg-slate-50 dark:bg-slate-800 rounded-xl p-3 space-y-2">
                        <div class="flex justify-between text-xs">
                            <span class="text-slate-500">Potential Return</span>
                            <span class="font-bold text-emerald-500" id="potential-return">+$0.00</span>
                        </div>
                        <div class="flex justify-between text-xs">
                            <span class="text-slate-500">Risk Amount</span>
                            <span class="font-bold text-rose-500" id="risk-amount">-$0.00</span>
                        </div>
                    </div>

                    <div class="flex gap-3 pt-2">
                        <button onclick="executeTrade('BUY')" id="btn-buy" class="flex-1 py-3.5 bg-emerald-500 hover:bg-emerald-600 text-white text-sm font-bold rounded-xl transition-all btn-buy-glow flex items-center justify-center gap-2">
                            <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M12 19V5M5 12l7-7 7 7"/></svg>
                            BUY
                        </button>
                        <button onclick="executeTrade('SELL')" id="btn-sell" class="flex-1 py-3.5 bg-rose-500 hover:bg-rose-600 text-white text-sm font-bold rounded-xl transition-all btn-sell-glow flex items-center justify-center gap-2">
                            <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M12 5v14M19 12l-7 7-7-7"/></svg>
                            SELL
                        </button>
                    </div>
                    
                    <p class="text-[10px] text-center text-slate-400 dark:text-slate-500">
                        Trades execute at market price. Results determined at expiry.
                    </p>
                </div>
            </div>

            <!-- Refer & Earn -->
            <div class="glass-card-light dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700/50 p-5 transition-colors">
                <div class="flex items-center gap-3 mb-4">
                    <div class="w-10 h-10 rounded-xl bg-theme/10 flex items-center justify-center neon-accent">
                        <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-theme"><path d="M20 12V8H6a2 2 0 0 1-2-2c0-1.1.9-2 2-2h12v4"/><path d="M20 12v4H6a2 2 0 0 0-2 2c0 1.1.9 2 2 2h12v-4"/><path d="M20 12h-4"/><path d="M4 12h4"/></svg>
                    </div>
                    <div>
                        <h3 class="font-bold text-slate-900 dark:text-white text-sm">Refer & Earn</h3>
                        <p class="text-xs text-slate-500 dark:text-slate-400">5% commission per referral</p>
                    </div>
                </div>
                <div class="space-y-2">
                    <div class="flex gap-2">
                        <input type="text" value="<?= $referralLink ?>" readonly 
                               class="flex-1 bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 text-xs rounded-lg px-3 py-2.5 outline-none font-mono">
                        <button onclick="navigator.clipboard.writeText('<?= $referralLink ?>'); showToast('Link copied!')" 
                                class="px-3 py-2.5 bg-theme hover:brightness-110 text-white rounded-lg transition-all shadow-theme">
                            <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
                        </button>
                    </div>
                    <div class="flex items-center justify-between text-xs text-slate-500 mt-2">
                        <span>Total Referrals: <strong class="text-theme">0</strong></span>
                        <span>Earned: <strong class="text-emerald-500">$0.00</strong></span>
                    </div>
                </div>
            </div>

        </div>
      </div>
    </div>
  </main>
</div>

<!-- Toast Notification -->
<div id="toast" class="fixed top-20 right-4 z-50 transform translate-x-full transition-transform duration-300">
    <div class="bg-slate-900 dark:bg-white text-white dark:text-slate-900 px-4 py-3 rounded-xl shadow-2xl flex items-center gap-2 text-sm font-medium">
        <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-emerald-500"><path d="M20 6L9 17l-5-5"/></svg>
        <span id="toast-message">Success</span>
    </div>
</div>
<?php include "include/buttom-nav.php"?>
<script>
// ═══════════════════════════════════════════════════════════════
// MARKET CONFIGURATION
// ═══════════════════════════════════════════════════════════════

const markets = <?= json_encode($markets) ?>;
let currentMarket = 'crypto';
let currentDuration = 5;

// ═══════════════════════════════════════════════════════════════
// UI CONTROLS
// ═══════════════════════════════════════════════════════════════

function selectMarket(marketKey) {
    currentMarket = marketKey;
    const market = markets[marketKey];
    
    // Update tabs
    document.querySelectorAll('.market-tab').forEach(tab => {
        if (tab.dataset.market === marketKey) {
            tab.classList.add('active');
        } else {
            tab.classList.remove('active');
        }
    });
    
    // Update asset dropdown
    const assetSelect = document.getElementById('trade-asset');
    assetSelect.innerHTML = market.pairs.map(pair => 
        `<option value="${pair}">${pair}</option>`
    ).join('');
    
    // Update limits text
    document.getElementById('amount-limits').textContent = 
        `Min: $${market.min_amount} | Max: $${market.max_amount.toLocaleString()}`;
    
    // Update amount input constraints
    const amountInput = document.getElementById('trade-amount');
    amountInput.min = market.min_amount;
    amountInput.max = market.max_amount;
    
    updatePotentialReturn();
}

function selectDuration(minutes) {
    currentDuration = minutes;
    document.getElementById('trade-duration').value = minutes;
    
    document.querySelectorAll('.duration-btn').forEach(btn => {
        if (parseInt(btn.dataset.minutes) === minutes) {
            btn.classList.add('bg-theme', 'text-white', 'border-theme');
            btn.classList.remove('text-slate-600', 'dark:text-slate-300');
        } else {
            btn.classList.remove('bg-theme', 'text-white', 'border-theme');
            btn.classList.add('text-slate-600', 'dark:text-slate-300');
        }
    });
    
    updatePotentialReturn();
}

function setTradeAmount(amount) {
    document.getElementById('trade-amount').value = amount;
    updatePotentialReturn();
}

function updatePotentialReturn() {
    const amount = parseFloat(document.getElementById('trade-amount').value) || 0;
    // Simulate 85% return rate
    const potentialReturn = amount * 0.85;
    document.getElementById('potential-return').textContent = `+$${potentialReturn.toFixed(2)}`;
    document.getElementById('risk-amount').textContent = `-$${amount.toFixed(2)}`;
}

document.getElementById('trade-amount').addEventListener('input', updatePotentialReturn);

// ═══════════════════════════════════════════════════════════════
// TRADE EXECUTION
// ═══════════════════════════════════════════════════════════════

function showToast(message) {
    const toast = document.getElementById('toast');
    document.getElementById('toast-message').textContent = message;
    toast.classList.remove('translate-x-full');
    setTimeout(() => toast.classList.add('translate-x-full'), 3000);
}

async function executeTrade(type) {
    const amount = parseFloat(document.getElementById('trade-amount').value);
    const asset = document.getElementById('trade-asset').value;
    const duration = parseInt(document.getElementById('trade-duration').value);
    const market = markets[currentMarket];
    
    if (!amount || amount < market.min_amount) {
        showToast(`Minimum trade amount is $${market.min_amount}`);
        return;
    }
    if (amount > market.max_amount) {
        showToast(`Maximum trade amount is $${market.max_amount.toLocaleString()}`);
        return;
    }
    
    const btnBuy = document.getElementById('btn-buy');
    const btnSell = document.getElementById('btn-sell');
    
    // Disable buttons
    btnBuy.disabled = true;
    btnSell.disabled = true;
    btnBuy.classList.add('opacity-50');
    btnSell.classList.add('opacity-50');
    
    try {
        const response = await fetch('ajax/trade_execute.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
                asset, 
                amount, 
                type, 
                duration,
                market: currentMarket 
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            showToast(`Trade placed! Expires in ${duration} minutes`);
            updateBalance(result.new_balance);
            addActivePosition(result.trade);
            refreshPositions();
        } else {
            showToast(result.message || 'Trade failed');
        }
    } catch (error) {
        showToast('Network error. Please try again.');
        console.error(error);
    } finally {
        btnBuy.disabled = false;
        btnSell.disabled = false;
        btnBuy.classList.remove('opacity-50');
        btnSell.classList.remove('opacity-50');
    }
}

function updateBalance(newBalance) {
    const el = document.getElementById('main-balance');
    el.textContent = '$' + parseFloat(newBalance).toLocaleString('en-US', {minimumFractionDigits: 2});
}

function addActivePosition(trade) {
    const container = document.getElementById('active-positions-container');
    const emptyState = container.querySelector('.text-center');
    if (emptyState) {
        container.innerHTML = '<div class="divide-y divide-slate-200 dark:divide-slate-700/50"></div>';
    }
    
    const list = container.querySelector('.divide-y') || container;
    const tradeType = trade.trade_type.toUpperCase();
    const typeColor = tradeType === 'BUY' ? 'text-emerald-500' : 'text-rose-500';
    const typeBg = tradeType === 'BUY' ? 'bg-emerald-500/10' : 'bg-rose-500/10';
    const typeBorder = tradeType === 'BUY' ? 'border-emerald-500/20' : 'border-rose-500/20';
    
    const html = `
        <div class="p-4 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors position-card" data-trade-id="${trade.id}">
            <div class="flex items-center justify-between mb-3">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-xl ${typeBg} border ${typeBorder} flex items-center justify-center">
                        <span class="text-xs font-bold ${typeColor}">${tradeType}</span>
                    </div>
                    <div>
                        <div class="text-sm font-bold text-slate-900 dark:text-white">${trade.asset}</div>
                        <div class="text-xs text-slate-500">$${parseFloat(trade.amount).toFixed(2)} • ${trade.duration}min</div>
                    </div>
                </div>
                <div class="text-right">
                    <span class="px-2 py-1 bg-amber-500/10 text-amber-500 text-[10px] font-bold rounded-full border border-amber-500/20">PENDING</span>
                </div>
            </div>
        </div>
    `;
    
    list.insertAdjacentHTML('afterbegin', html);
    updatePositionCount();
}

function updatePositionCount() {
    const count = document.querySelectorAll('[data-trade-id]').length;
    document.getElementById('active-positions-count').textContent = count + ' Active';
}

// ═══════════════════════════════════════════════════════════════
// REAL-TIME POSITION TRACKING
// ═══════════════════════════════════════════════════════════════

let positionIntervals = {};

function startPositionTimer(tradeId, expiresAt) {
    if (positionIntervals[tradeId]) return;
    
    const updateTimer = () => {
        const now = Math.floor(Date.now() / 1000);
        const remaining = Math.max(0, expiresAt - now);
        const timerEl = document.getElementById(`timer-${tradeId}`);
        const progressEl = document.getElementById(`progress-${tradeId}`);
        
        if (!timerEl) {
            clearInterval(positionIntervals[tradeId]);
            delete positionIntervals[tradeId];
            return;
        }
        
        const mins = Math.floor(remaining / 60);
        const secs = remaining % 60;
        timerEl.textContent = `${mins}:${secs.toString().padStart(2, '0')}`;
        
        // Update progress bar (assuming we know total duration)
        // This is approximate; in production, calculate from created_at
        if (progressEl) {
            // You'll need to pass duration in the DOM or fetch it
            const duration = parseInt(progressEl.closest('.position-card').querySelector('.text-xs').textContent.match(/(\d+)min/)[1]) * 60;
            const elapsed = duration - remaining;
            const pct = Math.min(100, (elapsed / duration) * 100);
            progressEl.style.width = pct + '%';
        }
        
        if (remaining <= 0) {
            clearInterval(positionIntervals[tradeId]);
            delete positionIntervals[tradeId];
            refreshPositions(); // Will show result
        }
    };
    
    updateTimer();
    positionIntervals[tradeId] = setInterval(updateTimer, 1000);
}

// Initialize timers for existing positions
document.querySelectorAll('[data-trade-id]').forEach(card => {
    const tradeId = card.dataset.tradeId;
    const timerEl = document.getElementById(`timer-${tradeId}`);
    if (timerEl) {
        // Parse remaining time and calculate expiry
        const timeText = timerEl.textContent;
        const [mins, secs] = timeText.split(':').map(Number);
        const remainingSeconds = (mins * 60) + secs;
        const expiresAt = Math.floor(Date.now() / 1000) + remainingSeconds;
        startPositionTimer(tradeId, expiresAt);
    }
});

// ═══════════════════════════════════════════════════════════════
// AJAX REFRESHERS
// ═══════════════════════════════════════════════════════════════

async function refreshPositions() {
    try {
        const response = await fetch('ajax/get_positions.php');
        const html = await response.text();
        document.getElementById('active-positions-container').innerHTML = html;
        
        // Re-initialize timers
        document.querySelectorAll('[data-trade-id]').forEach(card => {
            const tradeId = card.dataset.tradeId;
            const timerEl = document.getElementById(`timer-${tradeId}`);
            if (timerEl) {
                const timeText = timerEl.textContent;
                const [mins, secs] = timeText.split(':').map(Number);
                const remainingSeconds = (mins * 60) + secs;
                const expiresAt = Math.floor(Date.now() / 1000) + remainingSeconds;
                startPositionTimer(tradeId, expiresAt);
            }
        });
        
        updatePositionCount();
    } catch (e) {
        console.error('Failed to refresh positions:', e);
    }
}

async function refreshHistory() {
    try {
        const response = await fetch('ajax/get_history.php?limit=10');
        const html = await response.text();
        // Update history table if needed
    } catch (e) {
        console.error('Failed to refresh history:', e);
    }
}

// ═══════════════════════════════════════════════════════════════
// INITIALIZATION
// ═══════════════════════════════════════════════════════════════

document.addEventListener('DOMContentLoaded', () => {
    updatePotentialReturn();
    
    // Auto-refresh positions every 30 seconds
    setInterval(refreshPositions, 30000);
    
    // Lucide icons
    if (typeof lucide !== 'undefined') lucide.createIcons();
});
</script>

</body>
</html>