<?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"; // This loads generateReferralCode() from 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;

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

// Generate referral code if not exists (Uses function from db.php)
if (empty($currentUser['referral_code'])) {
    $referralCode = generateReferralCode($conn);
    $updateCodeSql = "UPDATE users SET referral_code = '$referralCode' WHERE id = $userId";
    mysqli_query($conn, $updateCodeSql);
    $currentUser['referral_code'] = $referralCode;
}

$dbTheme = $_SESSION['theme'] ?? ($currentUser['theme'] ?? '#0ea5e9');
$userName = $currentUser['username'] ?? 'Trader';
$userBalance = floatval($currentUser['balance'] ?? 0);
$referralCode = $currentUser['referral_code'] ?? '';
$totalReferrals = intval($currentUser['total_referrals'] ?? 0);
$referralEarnings = floatval($currentUser['referral_earnings'] ?? 0);
$referralClicks = intval($currentUser['referral_link_clicks'] ?? 0);

// Build referral link
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$basePath = dirname(dirname($_SERVER['PHP_SELF']));
$referralLink = $protocol . '://' . $host . $basePath . '/register.php?ref=' . $referralCode;

$success = '';
$error = '';

// Handle AJAX: Track click
if (isset($_GET['action']) && $_GET['action'] === 'track_click') {
    header('Content-Type: application/json');
    $trackSql = "UPDATE users SET referral_link_clicks = referral_link_clicks + 1 WHERE id = $userId";
    mysqli_query($conn, $trackSql);
    echo json_encode(['success' => true]);
    exit;
}

// Handle AJAX: Withdraw referral earnings
if (isset($_GET['action']) && $_GET['action'] === 'withdraw_earnings' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    $amount = floatval($_POST['amount'] ?? 0);
    $password = trim($_POST['password'] ?? '');
    $storedHashedPassword = $currentUser['password'] ?? '';
    
    // FIXED: Proper Password Verification for Hashed Passwords
    if (!password_verify($password, $storedHashedPassword)) {
        echo json_encode(['success' => false, 'message' => 'Incorrect password']);
        exit;
    }
    
    if ($amount <= 0 || $amount > $referralEarnings) {
        echo json_encode(['success' => false, 'message' => 'Invalid amount or insufficient earnings']);
        exit;
    }
    
    mysqli_begin_transaction($conn);
    try {
        $newEarnings = $referralEarnings - $amount;
        $updateEarningsSql = "UPDATE users SET referral_earnings = $newEarnings, balance = balance + $amount WHERE id = $userId";
        mysqli_query($conn, $updateEarningsSql);
        
        $withdrawSql = "INSERT INTO referral_earnings 
            (referrer_id, referred_id, amount, type, description, status, paid_at) 
            VALUES ($userId, 0, $amount, 'withdrawal', 'Referral earnings withdrawal', 'paid', NOW())";
        mysqli_query($conn, $withdrawSql);
        
        mysqli_commit($conn);
        
        echo json_encode([
            'success' => true, 
            'message' => 'Successfully withdrawn $' . number_format($amount, 2) . ' to your balance',
            'new_balance' => $userBalance + $amount,
            'new_earnings' => $newEarnings
        ]);
    } catch (Exception $e) {
        mysqli_rollback($conn);
        echo json_encode(['success' => false, 'message' => 'System error occurred.']);
    }
    exit;
}

// ... Rest of your histories/leaderboard code stays the same ...

// IMPORTANT: The generateReferralCode() function definition has been REMOVED from here 
// because it is now defined in account/include/db.php
?>

<!-- UI / HTML remains exactly as you had it -->
// Fetch referral history
$referralHistory = [];
$historySql = "SELECT 
    rt.*,
    u.username,
    u.full_name,
    u.email,
    u.profile_photo
FROM referral_tracking rt
LEFT JOIN users u ON rt.referred_id = u.id
WHERE rt.referrer_id = $userId
ORDER BY rt.created_at DESC LIMIT 50";
$historyResult = mysqli_query($conn, $historySql);
if ($historyResult) {
    while ($row = mysqli_fetch_assoc($historyResult)) {
        $referralHistory[] = $row;
    }
}

// Fetch earnings history
$earningsHistory = [];
$earningsSql = "SELECT * FROM referral_earnings 
    WHERE referrer_id = $userId 
    ORDER BY created_at DESC LIMIT 50";
$earningsResult = mysqli_query($conn, $earningsSql);
if ($earningsResult) {
    while ($row = mysqli_fetch_assoc($earningsResult)) {
        $earningsHistory[] = $row;
    }
}

// Get leaderboard
$leaderboard = [];
$leaderSql = "SELECT 
    u.id,
    u.username,
    u.full_name,
    u.profile_photo,
    u.total_referrals,
    u.referral_earnings
FROM users u
WHERE u.total_referrals > 0
ORDER BY u.referral_earnings DESC, u.total_referrals DESC
LIMIT 10";
$leaderResult = mysqli_query($conn, $leaderSql);
if ($leaderResult) {
    $rank = 1;
    while ($row = mysqli_fetch_assoc($leaderResult)) {
        $row['rank'] = $rank++;
        $leaderboard[] = $row;
    }
}

// Get initials for avatar
$initials = strtoupper(substr($currentUser['full_name'] ?? $currentUser['username'] ?? 'U', 0, 1));
if (!empty($currentUser['full_name'])) {
    $nameParts = explode(' ', $currentUser['full_name']);
    $initials = strtoupper(substr($nameParts[0], 0, 1) . (isset($nameParts[1]) ? substr($nameParts[1], 0, 1) : ''));
}

function generateReferralCode($conn) {
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    do {
        $code = '';
        for ($i = 0; $i < 8; $i++) {
            $code .= $chars[random_int(0, strlen($chars) - 1)];
        }
        $checkSql = "SELECT id FROM users WHERE referral_code = '$code' LIMIT 1";
        $checkResult = mysqli_query($conn, $checkSql);
    } while ($checkResult && mysqli_num_rows($checkResult) > 0);
    return $code;
}
?>

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

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

<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);
    }
    .shadow-theme-lg {
        box-shadow: 0 10px 40px -10px rgba(var(--primary-rgb), 0.3);
    }
    
    .glass-card {
        background: rgba(30, 41, 59, 0.6);
        backdrop-filter: blur(12px);
        -webkit-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);
        -webkit-backdrop-filter: blur(12px);
        border: 1px solid rgba(0, 0, 0, 0.06);
    }
    
    .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;
    }
    
    .mesh-bg {
        background: 
            radial-gradient(at 40% 20%, rgba(var(--primary-rgb), 0.15) 0px, transparent 50%),
            radial-gradient(at 80% 0%, rgba(139, 92, 246, 0.1) 0px, transparent 50%),
            radial-gradient(at 0% 50%, rgba(236, 72, 153, 0.08) 0px, transparent 50%);
    }
    
    ::-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); }
    
    .neon-accent {
        box-shadow: 0 0 15px rgba(var(--primary-rgb), 0.2),
                    inset 0 1px 0 rgba(255,255,255,0.1);
    }
    
    .input-field {
        transition: all 0.2s ease;
    }
    .input-field:focus {
        border-color: var(--primary-theme);
        box-shadow: 0 0 0 4px rgba(var(--primary-rgb), 0.08);
    }
    
    .btn-primary {
        background: var(--primary-theme);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        position: relative;
        overflow: hidden;
    }
    .btn-primary:hover {
        filter: brightness(1.15);
        transform: translateY(-2px);
        box-shadow: 0 10px 30px -10px rgba(var(--primary-rgb), 0.4);
    }
    .btn-primary:active {
        transform: translateY(0);
    }
    
    .referral-card {
        transition: all 0.3s ease;
    }
    .referral-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px -5px rgba(var(--primary-rgb), 0.15);
    }
    
    .stat-card {
        transition: all 0.3s ease;
    }
    .stat-card:hover {
        transform: translateY(-2px);
    }
    
    .copy-btn {
        transition: all 0.2s ease;
    }
    .copy-btn:hover {
        background: var(--primary-theme);
        color: white;
        border-color: var(--primary-theme);
    }
    .copy-btn.copied {
        background: #10b981;
        color: white;
        border-color: #10b981;
    }
    
    .referral-row {
        transition: all 0.3s ease;
    }
    .referral-row:hover {
        background: rgba(var(--primary-rgb), 0.03);
    }
    
    .leaderboard-row {
        transition: all 0.2s ease;
    }
    .leaderboard-row:hover {
        background: rgba(var(--primary-rgb), 0.05);
    }
    
    .tier-badge {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 4px 12px;
        border-radius: 99px;
        font-size: 11px;
        font-weight: 700;
    }
    .tier-bronze { background: rgba(205, 127, 50, 0.15); color: #cd7f32; border: 1px solid rgba(205, 127, 50, 0.3); }
    .tier-silver { background: rgba(192, 192, 192, 0.15); color: #a0a0a0; border: 1px solid rgba(192, 192, 192, 0.3); }
    .tier-gold { background: rgba(255, 215, 0, 0.15); color: #daa520; border: 1px solid rgba(255, 215, 0, 0.3); }
    .tier-platinum { background: rgba(229, 228, 226, 0.15); color: #e5e4e2; border: 1px solid rgba(229, 228, 226, 0.3); }
    .tier-diamond { background: rgba(185, 242, 255, 0.15); color: #b9f2ff; border: 1px solid rgba(185, 242, 255, 0.3); }
    
    @keyframes pulse-glow {
        0%, 100% { box-shadow: 0 0 5px rgba(var(--primary-rgb), 0.2); }
        50% { box-shadow: 0 0 20px rgba(var(--primary-rgb), 0.4); }
    }
    .pulse-glow {
        animation: pulse-glow 2s ease-in-out infinite;
    }
    
    .loading-spinner {
        animation: spin 1s linear infinite;
    }
    @keyframes spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }
    
    .fade-in {
        animation: fadeIn 0.5s ease-out;
    }
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .swal2-input.password-input {
        border-radius: 1rem !important;
        padding: 0.75rem 1rem !important;
        font-size: 1rem !important;
    }
</style>

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

<div class="flex min-h-screen bg-slate-50 dark:bg-[#0b111a] transition-colors duration-300">
  
  <?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-6">

      <!-- Hero Section -->
      <div class="relative rounded-3xl overflow-hidden mb-8 mesh-bg bg-theme-gradient">
        <div class="absolute inset-0 bg-[url('data:image/svg+xml,%3Csvg width=\'100\' height=\'100\' viewBox=\'0 0 100 100\' xmlns=\'http://www.w3.org/2000/svg\'%3E%3Cpath d=\'M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zM32 63c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm57-13c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-9-21c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM60 91c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM35 41c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM12 60c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2z\' fill=\'%23ffffff\' fill-opacity=\'0.03\'/%3E%3C/svg%3E')] opacity-30"></div>
        
        <div class="relative z-10 p-8 md:p-12">
          <div class="flex flex-col md:flex-row md:items-center justify-between gap-6">
            <div class="max-w-xl">
              <div class="inline-flex items-center gap-2 px-3 py-1.5 bg-white/10 backdrop-blur-md rounded-full border border-white/20 mb-4">
                <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-white/90"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
                <span class="text-xs font-semibold text-white/90">Refer & Earn</span>
              </div>
              <h1 class="text-3xl md:text-4xl font-bold text-white tracking-tight mb-3">
                Referral <span class="text-white/80">Program</span>
              </h1>
              <p class="text-white/60 text-sm md:text-base leading-relaxed max-w-md">
                Invite friends and earn commissions on their activity. The more you refer, the more you earn.
              </p>
            </div>
            
            <div class="bg-white/10 backdrop-blur-md rounded-2xl p-5 border border-white/20 min-w-[300px]">
              <div class="text-xs text-white/60 uppercase tracking-wider mb-1">Total Earnings</div>
              <div class="text-3xl font-bold text-white" style="font-size:28px !important;">$<?= number_format($referralEarnings, 2) ?></div>
              <div class="flex items-center gap-2 mt-2">
                <span class="w-2 h-2 rounded-full bg-emerald-400 animate-pulse"></span>
                <span class="text-xs text-white/70"><?= $totalReferrals ?> total referrals</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Stats Grid -->
      <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
        <div class="stat-card glass-card-light dark:bg-slate-800 rounded-2xl p-5 border border-slate-200 dark:border-slate-700/50">
          <div class="flex items-center justify-between mb-3">
            <span class="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Referrals</span>
            <div class="w-8 h-8 rounded-lg 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="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
            </div>
          </div>
          <div class="text-2xl font-bold text-slate-900 dark:text-white" id="stat-referrals"><?= $totalReferrals ?></div>
          <div class="text-[10px] text-slate-400 mt-1">Total invited users</div>
        </div>
        
        <div class="stat-card glass-card-light dark:bg-slate-800 rounded-2xl p-5 border border-slate-200 dark:border-slate-700/50">
          <div class="flex items-center justify-between mb-3">
            <span class="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Active</span>
            <div class="w-8 h-8 rounded-lg 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="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
            </div>
          </div>
          <div class="text-2xl font-bold text-slate-900 dark:text-white" id="stat-active">0</div>
          <div class="text-[10px] text-slate-400 mt-1">Active refer I'll continue from where the previous response was cut off and provide the complete remaining code.

```php
rals</div>
        </div>
        
        <div class="stat-card glass-card-light dark:bg-slate-800 rounded-2xl p-5 border border-slate-200 dark:border-slate-700/50">
          <div class="flex items-center justify-between mb-3">
            <span class="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Clicks</span>
            <div class="w-8 h-8 rounded-lg bg-amber-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-amber-500"><path d="M15 15l-2 5L9 9l11 4-5 2zm0 0l5 5M7.188 2.239l.777 2.897M5.136 7.965l-2.898-.777M13.95 4.05l-2.122 2.122m-5.657 5.656l-2.12 2.122"/></svg>
            </div>
          </div>
          <div class="text-2xl font-bold text-slate-900 dark:text-white" id="stat-clicks"><?= $referralClicks ?></div>
          <div class="text-[10px] text-slate-400 mt-1">Link clicks</div>
        </div>
        
        <div class="stat-card glass-card-light dark:bg-slate-800 rounded-2xl p-5 border border-slate-200 dark:border-slate-700/50">
          <div class="flex items-center justify-between mb-3">
            <span class="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Rate</span>
            <div class="w-8 h-8 rounded-lg bg-violet-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-violet-500"><path d="M18 20V10"/><path d="M12 20V4"/><path d="M6 20v-6"/></svg>
            </div>
          </div>
          <div class="text-2xl font-bold text-slate-900 dark:text-white" id="stat-rate">0%</div>
          <div class="text-[10px] text-slate-400 mt-1">Conversion rate</div>
        </div>
      </div>

      <!-- Main Grid -->
      <div class="grid grid-cols-1 xl:grid-cols-5 gap-6">
        
        <!-- LEFT: Referral Tools (3 cols) -->
        <div class="xl:col-span-3 space-y-6">
          
          <!-- Referral Link Card -->
          <div class="glass-card-light dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700/50 overflow-hidden transition-colors shadow-lg">
            <div class="p-5 border-b border-slate-200 dark:border-slate-700/50 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/30">
              <div class="flex items-center gap-3">
                <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="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
                </div>
                <div>
                  <h3 class="font-bold text-slate-900 dark:text-white text-base">Your Referral Link</h3>
                  <p class="text-xs text-slate-500 dark:text-slate-400">Share and earn commissions</p>
                </div>
              </div>
              <?php 
                $tier = 'Bronze';
                if ($totalReferrals >= 50) $tier = 'Diamond';
                elseif ($totalReferrals >= 25) $tier = 'Platinum';
                elseif ($totalReferrals >= 10) $tier = 'Gold';
                elseif ($totalReferrals >= 5) $tier = 'Silver';
              ?>
              <span class="tier-badge tier-<?= strtolower($tier) ?>">
                <svg width="12" height="12" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>
                <?= $tier ?> Tier
              </span>
            </div>
            
            <div class="p-6 space-y-5">
              <!-- Link Display -->
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Referral URL</label>
                <div class="relative">
                  <input type="text" id="referral-link" readonly value="<?= htmlspecialchars($referralLink) ?>"
                         class="w-full bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm rounded-xl pl-4 pr-32 py-3 outline-none font-mono text-xs">
                  <button onclick="copyReferralLink()" id="copy-btn" 
                          class="copy-btn absolute right-2 top-1/2 -translate-y-1/2 px-4 py-1.5 bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 text-xs font-bold rounded-lg border border-slate-200 dark:border-slate-700">
                    Copy
                  </button>
                </div>
              </div>
              
              <!-- Referral Code -->
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Referral Code</label>
                <div class="flex gap-2">
                  <div class="flex-1 bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-xl px-4 py-3 flex items-center justify-between">
                    <span class="font-mono text-lg font-bold text-theme tracking-widest" id="referral-code"><?= $referralCode ?></span>
                    <button onclick="copyCode()" class="text-slate-400 hover:text-theme transition-colors">
                      <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>
              </div>
              
              <!-- Share Buttons -->
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Quick Share</label>
                <div class="flex gap-2">
                  <button onclick="shareSocial('twitter')" class="flex-1 py-2.5 bg-[#1da1f2]/10 text-[#1da1f2] rounded-xl text-xs font-bold border border-[#1da1f2]/20 hover:bg-[#1da1f2]/20 transition-all flex items-center justify-center gap-2">
                    <svg width="14" height="14" fill="currentColor" viewBox="0 0 24 24"><path d="M23.953 4.57a10 10 0 0 1-2.825.775 4.958 4.958 0 0 0 2.163-2.723c-.951.555-2.005.959-3.127 1.184a4.92 4.92 0 0 0-8.384 4.482C7.69 8.095 4.067 6.13 1.64 3.162a4.822 4.822 0 0 0-.666 2.475c0 1.71.87 3.213 2.188 4.096a4.904 4.904 0 0 1-2.228-.616v.06a4.923 4.923 0 0 0 3.946 4.827 4.996 4.996 0 0 1-2.212.085 4.936 4.936 0 0 0 4.604 3.417 9.867 9.867 0 0 1-6.102 2.105c-.39 0-.779-.023-1.17-.067a13.995 13.995 0 0 0 7.557 2.209c9.053 0 13.998-7.496 13.998-13.985 0-.21 0-.42-.015-.63A9.935 9.935 0 0 0 24 4.59z"/></svg>
                    Twitter
                  </button>
                  <button onclick="shareSocial('facebook')" class="flex-1 py-2.5 bg-[#4267B2]/10 text-[#4267B2] rounded-xl text-xs font-bold border border-[#4267B2]/20 hover:bg-[#4267B2]/20 transition-all flex items-center justify-center gap-2">
                    <svg width="14" height="14" fill="currentColor" viewBox="0 0 24 24"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
                    Facebook
                  </button>
                  <button onclick="shareSocial('whatsapp')" class="flex-1 py-2.5 bg-[#25d366]/10 text-[#25d366] rounded-xl text-xs font-bold border border-[#25d366]/20 hover:bg-[#25d366]/20 transition-all flex items-center justify-center gap-2">
                    <svg width="14" height="14" fill="currentColor" viewBox="0 0 24 24"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413Z"/></svg>
                    WhatsApp
                  </button>
                  <button onclick="shareSocial('telegram')" class="flex-1 py-2.5 bg-[#0088cc]/10 text-[#0088cc] rounded-xl text-xs font-bold border border-[#0088cc]/20 hover:bg-[#0088cc]/20 transition-all flex items-center justify-center gap-2">
                    <svg width="14" height="14" fill="currentColor" viewBox="0 0 24 24"><path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/></svg>
                    Telegram
                  </button>
                </div>
              </div>
              
              <!-- Commission Structure -->
              <div class="bg-slate-50 dark:bg-slate-800/50 rounded-xl p-4 border border-slate-200 dark:border-slate-700">
                <h4 class="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-3 tracking-wider">Commission Structure</h4>
                <div class="space-y-2">
                  <div class="flex justify-between items-center text-sm">
                    <span class="text-slate-600 dark:text-slate-400">Tier 1 (Direct)</span>
                    <span class="font-bold text-emerald-500">10%</span>
                  </div>
                  <div class="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-1.5">
                    <div class="bg-emerald-500 h-1.5 rounded-full" style="width: 100%"></div>
                  </div>
                  
                  <div class="flex justify-between items-center text-sm mt-3">
                    <span class="text-slate-600 dark:text-slate-400">Tier 2 (Indirect)</span>
                    <span class="font-bold text-theme">5%</span>
                  </div>
                  <div class="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-1.5">
                    <div class="bg-theme h-1.5 rounded-full" style="width: 50%"></div>
                  </div>
                  
                  <div class="flex justify-between items-center text-sm mt-3">
                    <span class="text-slate-600 dark:text-slate-400">Tier 3 (Indirect)</span>
                    <span class="font-bold text-violet-500">2%</span>
                  </div>
                  <div class="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-1.5">
                    <div class="bg-violet-500 h-1.5 rounded-full" style="width: 20%"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Withdraw Earnings -->
          <div class="glass-card-light dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700/50 overflow-hidden transition-colors shadow-lg">
            <div class="p-5 border-b border-slate-200 dark:border-slate-700/50 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/30">
              <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-emerald-500/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-emerald-500"><path d="M12 1v22M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
                </div>
                <div>
                  <h3 class="font-bold text-slate-900 dark:text-white text-base">Withdraw Earnings</h3>
                  <p class="text-xs text-slate-500 dark:text-slate-400">Transfer to main balance</p>
                </div>
              </div>
            </div>
            
            <div class="p-6">
              <div class="flex items-center justify-between mb-4">
                <div>
                  <div class="text-xs text-slate-500 dark:text-slate-400">Available to withdraw</div>
                  <div class="text-2xl font-bold text-emerald-500" id="withdraw-balance">$<?= number_format($referralEarnings, 2) ?></div>
                </div>
                <button onclick="withdrawEarnings()" id="withdraw-btn"
                        class="px-6 py-2.5 bg-emerald-500 hover:bg-emerald-600 text-white text-sm font-bold rounded-xl transition-all flex items-center gap-2 <?= $referralEarnings < 10 ? 'opacity-50 cursor-not-allowed' : '' ?>"
                        <?= $referralEarnings < 10 ? 'disabled' : '' ?>>
                  <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>
                  Withdraw
                </button>
              </div>
              <p class="text-[10px] text-slate-400">Minimum withdrawal: $10.00</p>
            </div>
          </div>

        </div>

        <!-- RIGHT: History & Leaderboard (2 cols) -->
        <div class="xl:col-span-2 space-y-6">
          
          <!-- Referral 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 shadow-lg">
            <div class="p-5 border-b border-slate-200 dark:border-slate-700/50 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/30">
              <div class="flex items-center gap-3">
                <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="M12 8v4l3 3m6-3a9 9 0 1 1-18 0 9 9 0 0 1 18 0z"/></svg>
                </div>
                <div>
                  <h3 class="font-bold text-slate-900 dark:text-white text-base">Referral History</h3>
                  <p class="text-xs text-slate-500 dark:text-slate-400">Your invited users</p>
                </div>
              </div>
              <span class="px-2 py-1 bg-slate-100 dark:bg-slate-700 text-slate-500 text-[10px] font-bold rounded-lg" id="history-count"><?= count($referralHistory) ?> total</span>
            </div>
            
            <div class="overflow-x-auto max-h-[400px] overflow-y-auto" id="referral-list">
              <?php if (empty($referralHistory)): ?>
              <div class="p-12 text-center">
                <div class="flex flex-col items-center gap-3">
                  <div class="w-16 h-16 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mb-2">
                    <svg width="28" height="28" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-slate-400"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
                  </div>
                  <p class="text-sm font-semibold text-slate-900 dark:text-white">No referrals yet</p>
                  <p class="text-xs text-slate-400">Share your link to start earning</p>
                </div>
              </div>
              <?php else: ?>
              <div class="divide-y divide-slate-200 dark:divide-slate-700/50">
                <?php foreach ($referralHistory as $ref): 
                  $isActive = $ref['status'] === 'active';
                  $refName = !empty($ref['full_name']) ? $ref['full_name'] : $ref['username'];
                  $refInitials = strtoupper(substr($refName, 0, 1) . (strpos($refName, ' ') !== false ? substr($refName, strpos($refName, ' ')+1, 1) : ''));
                ?>
                <div class="referral-row p-4">
                  <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-full bg-theme/10 flex items-center justify-center text-theme font-bold text-xs shrink-0">
                      <?= $refInitials ?>
                    </div>
                    <div class="flex-1 min-w-0">
                      <div class="flex items-center justify-between">
                        <span class="text-sm font-bold text-slate-900 dark:text-white truncate"><?= htmlspecialchars($refName) ?></span>
                        <span class="px-2 py-0.5 text-[9px] font-bold rounded-full <?= $isActive ? 'bg-emerald-500/10 text-emerald-500' : 'bg-amber-500/10 text-amber-500' ?> border border-current/20">
                          <?= ucfirst($ref['status']) ?>
                        </span>
                      </div>
                      <div class="flex items-center justify-between mt-0.5">
                        <span class="text-[10px] text-slate-400"><?= date('M d, Y', strtotime($ref['created_at'])) ?></span>
                        <span class="text-[10px] font-mono text-emerald-500">+$<?= number_format($ref['earnings'], 2) ?></span>
                      </div>
                    </div>
                  </div>
                </div>
                <?php endforeach; ?>
              </div>
              <?php endif; ?>
            </div>
          </div>

          <!-- Leaderboard -->
          <div class="glass-card-light dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700/50 overflow-hidden transition-colors shadow-lg">
            <div class="p-5 border-b border-slate-200 dark:border-slate-700/50 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/30">
              <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-amber-500/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-amber-500"><path d="M6 9H4.5a2.5 2.5 0 0 0 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></svg>
                </div>
                <div>
                  <h3 class="font-bold text-slate-900 dark:text-white text-base">Top Referrers</h3>
                  <p class="text-xs text-slate-500 dark:text-slate-400">This month's leaderboard</p>
                </div>
              </div>
            </div>
            
            <div class="overflow-x-auto max-h-[350px] overflow-y-auto">
              <?php if (empty($leaderboard)): ?>
              <div class="p-8 text-center">
                <p class="text-sm text-slate-400">No data available</p>
              </div>
              <?php else: ?>
              <div class="divide-y divide-slate-200 dark:divide-slate-700/50">
                <?php foreach ($leaderboard as $leader): 
                  $isCurrentUser = intval($leader['id']) === $userId;
                  $leaderName = !empty($leader['full_name']) ? $leader['full_name'] : $leader['username'];
                  $leaderInitials = strtoupper(substr($leaderName, 0, 1) . (strpos($leaderName, ' ') !== false ? substr($leaderName, strpos($leaderName, ' ')+1, 1) : ''));
                ?>
                <div class="leaderboard-row p-4 <?= $isCurrentUser ? 'bg-theme/5' : '' ?>">
                  <div class="flex items-center gap-3">
                    <div class="w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold shrink-0
                      <?= $leader['rank'] === 1 ? 'bg-amber-500/20 text-amber-500' : 
                         ($leader['rank'] === 2 ? 'bg-slate-300/20 text-slate-500' : 
                         ($leader['rank'] === 3 ? 'bg-orange-400/20 text-orange-400' : 'bg-slate-100 dark:bg-slate-700 text-slate-400')) ?>">
                      <?= $leader['rank'] ?>
                    </div>
                    <div class="w-8 h-8 rounded-full bg-theme/10 flex items-center justify-center text-theme font-bold text-[10px] shrink-0">
                      <?= $leaderInitials ?>
                    </div>
                    <div class="flex-1 min-w-0">
                      <div class="flex items-center justify-between">
                        <span class="text-sm font-bold text-slate-900 dark:text-white truncate <?= $isCurrentUser ? 'text-theme' : '' ?>">
                          <?= htmlspecialchars($leaderName) ?> <?= $isCurrentUser ? '(You)' : '' ?>
                        </span>
                        <span class="text-xs font-mono font-bold text-emerald-500">$<?= number_format($leader['referral_earnings'], 2) ?></span>
                      </div>
                      <div class="text-[10px] text-slate-400 mt-0.5"><?= $leader['total_referrals'] ?> referrals</div>
                    </div>
                  </div>
                </div>
                <?php endforeach; ?>
              </div>
              <?php endif; ?>
            </div>
          </div>

          <!-- Info Card -->
          <div class="gradient-border p-6">
            <div class="relative z-10">
              <h4 class="font-bold text-slate-900 dark:text-white mb-4 flex items-center gap-2">
                <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-theme"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>
                How It Works
              </h4>
              <div class="space-y-3">
                <div class="flex items-start gap-3">
                  <div class="w-6 h-6 rounded-full bg-theme/10 flex items-center justify-center shrink-0 mt-0.5 text-[10px] font-bold text-theme">1</div>
                  <p class="text-xs text-slate-500 dark:text-slate-400">Share your unique referral link with friends</p>
                </div>
                <div class="flex items-start gap-3">
                  <div class="w-6 h-6 rounded-full bg-theme/10 flex items-center justify-center shrink-0 mt-0.5 text-[10px] font-bold text-theme">2</div>
                  <p class="text-xs text-slate-500 dark:text-slate-400">They sign up using your link</p>
                </div>
                <div class="flex items-start gap-3">
                  <div class="w-6 h-6 rounded-full bg-theme/10 flex items-center justify-center shrink-0 mt-0.5 text-[10px] font-bold text-theme">3</div>
                  <p class="text-xs text-slate-500 dark:text-slate-400">Earn commissions on their trading activity</p>
                </div>
                <div class="flex items-start gap-3">
                  <div class="w-6 h-6 rounded-full bg-emerald-500/10 flex items-center justify-center shrink-0 mt-0.5 text-[10px] font-bold text-emerald-500">$</div>
                  <p class="text-xs text-slate-500 dark:text-slate-400">Withdraw earnings to your main balance anytime</p>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>

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

<?php include "include/footer.php"?>
<?php include "include/buttom-nav.php"?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
let currentEarnings = <?= $referralEarnings ?>;
let currentBalance = <?= $userBalance ?>;

function copyReferralLink() {
    const linkInput = document.getElementById('referral-link');
    const copyBtn = document.getElementById('copy-btn');
    
    linkInput.select();
    linkInput.setSelectionRange(0, 99999);
    navigator.clipboard.writeText(linkInput.value).then(() => {
        copyBtn.textContent = 'Copied!';
        copyBtn.classList.add('copied');
        
        fetch(window.location.pathname.split('/').pop() + '?action=track_click');
        
        setTimeout(() => {
            copyBtn.textContent = 'Copy';
            copyBtn.classList.remove('copied');
        }, 2000);
    });
}

function copyCode() {
    const code = document.getElementById('referral-code').textContent.trim();
    navigator.clipboard.writeText(code).then(() => {
        Swal.fire({
            icon: 'success',
            title: 'Code Copied!',
            text: 'Referral code copied to clipboard',
            timer: 1500,
            showConfirmButton: false,
            customClass: { popup: 'rounded-2xl' }
        });
    });
}

function shareSocial(platform) {
    const link = encodeURIComponent(document.getElementById('referral-link').value);
    const text = encodeURIComponent('Join me and start trading! Use my referral link: ');
    
    let url = '';
    switch(platform) {
        case 'twitter':
            url = `https://twitter.com/intent/tweet?text=${text}&url=${link}`;
            break;
        case 'facebook':
            url = `https://www.facebook.com/sharer/sharer.php?u=${link}`;
            break;
        case 'whatsapp':
            url = `https://wa.me/?text=${text}${link}`;
            break;
        case 'telegram':
            url = `https://t.me/share/url?url=${link}&text=${text}`;
            break;
    }
    
    if (url) {
        window.open(url, '_blank', 'width=600,height=400');
    }
}

function withdrawEarnings() {
    if (currentEarnings < 10) {
        Swal.fire({
            icon: 'warning',
            title: 'Minimum Withdrawal',
            text: 'You need at least $10.00 to withdraw',
            confirmButtonColor: 'var(--primary-theme)',
            customClass: { popup: 'rounded-2xl' }
        });
        return;
    }
    
    Swal.fire({
        title: 'Withdraw Earnings',
        html: `
            <div class="text-center mb-4">
                <p class="text-sm text-slate-600 dark:text-slate-400">Available: <strong class="text-emerald-500">$${currentEarnings.toFixed(2)}</strong></p>
                <p class="text-xs text-slate-400 mt-1">This will transfer to your main balance</p>
            </div>
            <input type="number" id="withdraw-amount" class="swal2-input password-input" 
                   placeholder="Amount to withdraw" max="${currentEarnings}" step="0.01"
                   value="${Math.floor(currentEarnings)}">
        `,
        showCancelButton: true,
        confirmButtonColor: 'var(--primary-theme)',
        cancelButtonColor: '#64748b',
        confirmButtonText: 'Continue',
        cancelButtonText: 'Cancel',
        reverseButtons: true,
        customClass: {
            popup: 'rounded-2xl',
            title: 'text-lg font-bold'
        },
        preConfirm: () => {
            const amount = parseFloat(document.getElementById('withdraw-amount').value);
            if (!amount || amount <= 0 || amount > currentEarnings) {
                Swal.showValidationMessage('Invalid amount');
                return false;
            }
            if (amount < 10) {
                Swal.showValidationMessage('Minimum withdrawal is $10.00');
                return false;
            }
            return amount;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            promptForWithdrawPassword(result.value);
        }
    });
}

function promptForWithdrawPassword(amount) {
    Swal.fire({
        title: 'Security Verification',
        html: `
            <div class="text-center mb-4">
                <div class="w-16 h-16 rounded-full bg-amber-500/10 flex items-center justify-center mx-auto mb-3">
                    <svg width="28" height="28" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-amber-500"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
                </div>
                <p class="text-sm text-slate-600 dark:text-slate-400">Enter password to withdraw <strong class="text-emerald-500">$${amount.toFixed(2)}</strong></p>
            </div>
        `,
        input: 'password',
        inputPlaceholder: 'Your account password',
        inputAttributes: {
            autocapitalize: 'off',
            autocomplete: 'off'
        },
        showCancelButton: true,
        confirmButtonColor: 'var(--primary-theme)',
        cancelButtonColor: '#64748b',
        confirmButtonText: 'Authorize',
        cancelButtonText: 'Cancel',
        reverseButtons: true,
        allowOutsideClick: false,
        customClass: {
            popup: 'rounded-2xl',
            title: 'text-lg font-bold',
            input: 'password-input'
        },
        inputValidator: (value) => {
            if (!value) return 'Please enter your password';
        }
    }).then((result) => {
        if (result.isConfirmed) {
            processWithdrawal(amount, result.value);
        }
    });
}

function processWithdrawal(amount, password) {
    Swal.fire({
        title: 'Processing...',
        html: 'Withdrawing earnings to your balance',
        allowOutsideClick: false,
        allowEscapeKey: false,
        didOpen: () => {
            Swal.showLoading();
        },
        customClass: { popup: 'rounded-2xl' }
    });
    
    const formData = new FormData();
    formData.append('amount', amount);
    formData.append('password', password);
    
    fetch(window.location.pathname.split('/').pop() + '?action=withdraw_earnings', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            currentEarnings = data.new_earnings;
            currentBalance = data.new_balance;
            
            document.getElementById('withdraw-balance').textContent = '$' + currentEarnings.toFixed(2);
            
            const withdrawBtn = document.getElementById('withdraw-btn');
            if (currentEarnings < 10) {
                withdrawBtn.disabled = true;
                withdrawBtn.classList.add('opacity-50', 'cursor-not-allowed');
            }
            
            Swal.fire({
                icon: 'success',
                title: 'Withdrawal Successful!',
                html: `<div class="text-sm text-slate-600">$${amount.toFixed(2)} has been added to your balance</div>`,
                confirmButtonColor: 'var(--primary-theme)',
                confirmButtonText: 'Awesome!',
                timer: 5000,
                timerProgressBar: true,
                customClass: { popup: 'rounded-2xl' }
            });
            
            loadStats();
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Withdrawal Failed',
                text: data.message || 'Something went wrong',
                confirmButtonColor: '#f43f5e',
                confirmButtonText: 'Try Again',
                customClass: { popup: 'rounded-2xl' }
            });
        }
    })
    .catch(err => {
        console.error('Withdrawal error:', err);
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Unable to process withdrawal. Please try again.',
            confirmButtonColor: '#f43f5e',
            customClass: { popup: 'rounded-2xl' }
        });
    });
}

function loadStats() {
    fetch(window.location.pathname.split('/').pop() + '?action=get_stats')
        .then(r => r.json())
        .then(data => {
            document.getElementById('stat-referrals').textContent = data.total_referrals;
            document.getElementById('stat-active').textContent = data.active_referrals;
            document.getElementById('stat-clicks').textContent = data.total_clicks;
            document.getElementById('stat-rate').textContent = data.conversion_rate + '%';
            
            const historyCount = document.getElementById('history-count');
            if (historyCount) historyCount.textContent = data.total_referrals + ' total';
            
            if (data.referrals && data.referrals.length > 0) {
                updateReferralList(data.referrals);
            }
        })
        .catch(err => console.error('Stats load error:', err));
}

function updateReferralList(referrals) {
    const listContainer = document.getElementById('referral-list');
    if (!listContainer) return;
    
    if (referrals.length === 0) {
        listContainer.innerHTML = `
            <div class="p-12 text-center">
                <div class="flex flex-col items-center gap-3">
                    <div class="w-16 h-16 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mb-2">
                        <svg width="28" height="28" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-slate-400"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
                    </div>
                    <p class="text-sm font-semibold text-slate-900 dark:text-white">No referrals yet</p>
                    <p class="text-xs text-slate-400">Share your link to start earning</p>
                </div>
            </div>
        `;
        return;
    }
    
    let html = '<div class="divide-y divide-slate-200 dark:divide-slate-700/50">';
    referrals.forEach(ref => {
        const isActive = ref.status === 'active';
        const refName = ref.full_name || ref.username || 'Unknown';
        const nameParts = refName.split(' ');
        const refInitials = (nameParts[0].charAt(0) + (nameParts[1] ? nameParts[1].charAt(0) : '')).toUpperCase();
        const dateStr = new Date(ref.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
        
        html += `
            <div class="referral-row p-4 fade-in">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-full bg-theme/10 flex items-center justify-center text-theme font-bold text-xs shrink-0">
                        ${refInitials}
                    </div>
                    <div class="flex-1 min-w-0">
                        <div class="flex items-center justify-between">
                            <span class="text-sm font-bold text-slate-900 dark:text-white truncate">${escapeHtml(refName)}</span>
                            <span class="px-2 py-0.5 text-[9px] font-bold rounded-full ${isActive ? 'bg-emerald-500/10 text-emerald-500' : 'bg-amber-500/10 text-amber-500'} border border-current/20">
                                ${capitalizeFirst(ref.status)}
                            </span>
                        </div>
                        <div class="flex items-center justify-between mt-0.5">
                            <span class="text-[10px] text-slate-400">${dateStr}</span>
                            <span class="text-[10px] font-mono text-emerald-500">+$${parseFloat(ref.earnings || 0).toFixed(2)}</span>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    html += '</div>';
    listContainer.innerHTML = html;
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function capitalizeFirst(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

setInterval(loadStats, 30000);

document.addEventListener('DOMContentLoaded', () => {
    loadStats();
    if (typeof lucide !== 'undefined') lucide.createIcons();
});

<?php if ($success): ?>
document.addEventListener('DOMContentLoaded', () => {
    Swal.fire({
        icon: 'success',
        title: 'Success!',
        html: '<div class="text-sm text-slate-600"><?= addslashes($success) ?></div>',
        confirmButtonColor: 'var(--primary-theme)',
        confirmButtonText: 'Great!',
        timer: 5000,
        timerProgressBar: true,
        customClass: { popup: 'rounded-2xl' }
    });
});
<?php endif; ?>

<?php if ($error): ?>
document.addEventListener('DOMContentLoaded', () => {
    Swal.fire({
        icon: 'error',
        title: 'Error',
        html: '<div class="text-sm text-slate-600"><?= addslashes($error) ?></div>',
        confirmButtonColor: '#f43f5e',
        confirmButtonText: 'OK',
        customClass: { popup: 'rounded-2xl' }
    });
});
<?php endif; ?>
</script>

</body>
</html>