<?php
session_start();

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

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

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

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

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

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

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

// ==========================================
// FETCH TOP TRADERS FROM DATABASE
// ==========================================
$traders = [];
$tradersQuery = mysqli_query($conn, "SELECT `id`, `name`, `initials`, `specialty`, `followers`, `roi`, `win_rate`, `tier`, `avatar_gradient` 
                                     FROM `expert_traders` 
                                     WHERE `is_active` = 1 
                                     ORDER BY `roi` DESC, `win_rate` DESC 
                                     LIMIT 20");

if ($tradersQuery && mysqli_num_rows($tradersQuery) > 0) {
    while ($row = mysqli_fetch_assoc($tradersQuery)) {
        $traders[] = [
            'id' => (int)$row['id'],
            'name' => $row['name'],
            'initials' => $row['initials'] ?? implode('', array_map(function($n) { return strtoupper($n[0]); }, explode(' ', $row['name']))),
            'specialty' => $row['specialty'],
            'followers' => (int)$row['followers'],
            'roi' => (float)$row['roi'],
            'win_rate' => (int)$row['win_rate'],
            'tier' => $row['tier'],
            'avatar_gradient' => $row['avatar_gradient'] ?? 'from-theme to-purple-600'
        ];
    }
}

// ==========================================
// HANDLE COPY/FOLLOW ACTION (mysqlnd-free)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'copy_trader') {
    ini_set('display_errors', 0);
    header('Content-Type: application/json');
    ob_start();

    try {
        $traderId = intval($_POST['trader_id'] ?? 0);
        
        if ($traderId <= 0) {
            throw new Exception('Invalid trader selected.');
        }

        // Check if already following — using bind_result instead of get_result
        $checkStmt = mysqli_prepare($conn, "SELECT `id` FROM `copy_relations` WHERE `follower_id` = ? AND `trader_id` = ? LIMIT 1");
        if (!$checkStmt) throw new Exception("Prepare failed: " . mysqli_error($conn));
        
        mysqli_stmt_bind_param($checkStmt, "ii", $userId, $traderId);
        mysqli_stmt_execute($checkStmt);
        mysqli_stmt_store_result($checkStmt);
        
        if (mysqli_stmt_num_rows($checkStmt) > 0) {
            mysqli_stmt_close($checkStmt);
            throw new Exception('You are already copying this trader.');
        }
        mysqli_stmt_close($checkStmt);

        // Verify trader exists and is active — using bind_result
        $verifyStmt = mysqli_prepare($conn, "SELECT `id` FROM `expert_traders` WHERE `id` = ? AND `is_active` = 1");
        if (!$verifyStmt) throw new Exception("Prepare failed: " . mysqli_error($conn));
        
        mysqli_stmt_bind_param($verifyStmt, "i", $traderId);
        mysqli_stmt_execute($verifyStmt);
        mysqli_stmt_store_result($verifyStmt);
        
        if (mysqli_stmt_num_rows($verifyStmt) === 0) {
            mysqli_stmt_close($verifyStmt);
            throw new Exception('Trader not found or inactive.');
        }
        mysqli_stmt_close($verifyStmt);

        // Insert copy relation
        $insertStmt = mysqli_prepare($conn, "INSERT INTO `copy_relations` (`follower_id`, `trader_id`, `created_at`) VALUES (?, ?, NOW())");
        if (!$insertStmt) throw new Exception("Prepare failed: " . mysqli_error($conn));
        
        mysqli_stmt_bind_param($insertStmt, "ii", $userId, $traderId);
        
        if (!mysqli_stmt_execute($insertStmt)) {
            throw new Exception("Execution Failed: " . mysqli_stmt_error($insertStmt));
        }

        $relationId = mysqli_insert_id($conn);
        mysqli_stmt_close($insertStmt);

        // Update follower count
        mysqli_query($conn, "UPDATE `expert_traders` SET `followers` = `followers` + 1 WHERE `id` = " . intval($traderId));

        ob_end_clean();
        echo json_encode([
            'success' => true,
            'message' => 'You are now copying this trader!',
            'relation_id' => $relationId
        ]);

    } catch (Throwable $e) {
        ob_end_clean();
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage()
        ]);
    }
    exit;
}

// ==========================================
// FETCH USER'S COPIED TRADERS
// ==========================================
$myCopies = [];
$copyQuery = mysqli_query($conn, "SELECT cr.`id` as relation_id, cr.`created_at`, et.`id`, et.`name`, et.`initials`, et.`specialty`, et.`followers`, et.`roi`, et.`win_rate`, et.`tier`, et.`avatar_gradient`
                                  FROM `copy_relations` cr
                                  JOIN `expert_traders` et ON cr.`trader_id` = et.`id`
                                  WHERE cr.`follower_id` = $userId
                                  ORDER BY cr.`created_at` DESC");
if ($copyQuery) {
    while ($row = mysqli_fetch_assoc($copyQuery)) {
        $myCopies[] = [
            'relation_id' => (int)$row['relation_id'],
            'id' => (int)$row['id'],
            'name' => $row['name'],
            'initials' => $row['initials'],
            'specialty' => $row['specialty'],
            'followers' => (int)$row['followers'],
            'roi' => (float)$row['roi'],
            'win_rate' => (int)$row['win_rate'],
            'tier' => $row['tier'],
            'avatar_gradient' => $row['avatar_gradient'],
            'copied_since' => $row['created_at']
        ];
    }
}
?>

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

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

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

    .trader-card {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .trader-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 20px 40px -12px rgba(0, 0, 0, 0.15);
    }
    .trader-card.copied {
        border: 2px solid var(--primary-theme);
        background: rgba(var(--primary-rgb), 0.05);
    }
    .trader-card.copied::after {
        content: '✓ Following';
        position: absolute;
        top: 12px;
        right: -28px;
        width: 120px;
        background: var(--primary-theme);
        color: white;
        text-align: center;
        font-size: 9px;
        font-weight: 900;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        padding: 4px 0;
        transform: rotate(45deg);
    }
    
    .tier-badge-pro { background: rgba(245, 158, 11, 0.1); color: #f59e0b; }
    .tier-badge-elite { background: rgba(99, 102, 241, 0.1); color: #6366f1; }
    .tier-badge-master { background: rgba(236, 72, 153, 0.1); color: #ec4899; }
    
    .stat-bar {
        height: 4px;
        border-radius: 2px;
        background: #e2e8f0;
        overflow: hidden;
    }
    .dark .stat-bar { background: #1e293b; }
    .stat-bar-fill {
        height: 100%;
        border-radius: 2px;
        background: var(--primary-theme);
        transition: width 0.6s ease;
    }
    
    .copy-btn {
        transition: all 0.2s ease;
        position: relative;
        overflow: hidden;
    }
    .copy-btn:active { transform: scale(0.95); }
    .copy-btn.copied {
        background: #10b981 !important;
        color: white !important;
    }
    
    .modal-overlay {
        background: rgba(0, 0, 0, 0.5);
        backdrop-filter: blur(4px);
    }
    
    .search-input {
        transition: all 0.3s ease;
    }
    .search-input:focus {
        border-color: var(--primary-theme);
        box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.1);
    }
    
    .filter-pill {
        transition: all 0.2s ease;
    }
    .filter-pill.active {
        background: var(--primary-theme);
        color: white;
        box-shadow: 0 4px 15px -3px rgba(var(--primary-rgb), 0.4);
    }
</style>

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

<div class="flex min-h-screen bg-slate-50 dark:bg-[#070b14] transition-colors duration-300"
     x-data='{
        traders: <?= json_encode($traders, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
        myCopies: <?= json_encode($myCopies, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
        balance: <?= $balance ?>,
        searchQuery: "",
        selectedTier: "all",
        sortBy: "roi",
        isSubmitting: false,
        showTraderModal: false,
        selectedTrader: null,
        
        get filteredTraders() {
            let filtered = this.traders;
            
            if (this.searchQuery) {
                const q = this.searchQuery.toLowerCase();
                filtered = filtered.filter(t => t.name.toLowerCase().includes(q) || t.specialty.toLowerCase().includes(q));
            }
            
            if (this.selectedTier !== "all") {
                filtered = filtered.filter(t => t.tier.toLowerCase() === this.selectedTier);
            }
            
            if (this.sortBy === "roi") {
                filtered = [...filtered].sort((a, b) => b.roi - a.roi);
            } else if (this.sortBy === "win_rate") {
                filtered = [...filtered].sort((a, b) => b.win_rate - a.win_rate);
            } else if (this.sortBy === "followers") {
                filtered = [...filtered].sort((a, b) => b.followers - a.followers);
            }
            
            return filtered;
        },
        
        isCopying(traderId) {
            return this.myCopies.some(c => c.id === traderId);
        },
        
        get totalCopiedRoi() {
            return this.myCopies.reduce((sum, t) => sum + t.roi, 0);
        },
        
        get avgWinRate() {
            if (this.myCopies.length === 0) return 0;
            return Math.round(this.myCopies.reduce((sum, t) => sum + t.win_rate, 0) / this.myCopies.length);
        },
        
        async copyTrader(trader) {
            if (this.isCopying(trader.id)) {
                Swal.fire({ icon: "info", title: "Already Following", text: "You are already copying " + trader.name, confirmButtonColor: "var(--primary-theme)" });
                return;
            }
            
            this.isSubmitting = true;
            
            const params = new URLSearchParams();
            params.append("action", "copy_trader");
            params.append("trader_id", trader.id);
            
            try {
                const response = await fetch("copytrade.php", { 
                    method: "POST", 
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: params.toString() 
                });
                const data = await response.json();
                
                if (data.success) {
                    Swal.fire({ 
                        icon: "success", 
                        title: "Trader Copied!", 
                        text: "You are now following " + trader.name + ". Their trades will be mirrored to your account.", 
                        confirmButtonColor: "var(--primary-theme)",
                        timer: 2500,
                        showConfirmButton: false
                    });
                    
                    this.myCopies.unshift({
                        ...trader,
                        relation_id: data.relation_id,
                        copied_since: new Date().toISOString()
                    });
                    
                    const t = this.traders.find(x => x.id === trader.id);
                    if (t) t.followers++;
                    
                } else {
                    Swal.fire({ icon: "error", title: "Copy Failed", text: data.message, confirmButtonColor: "var(--primary-theme)" });
                }
            } catch (error) {
                console.error("Copy error:", error);
                Swal.fire({ icon: "error", title: "Error", text: "Something went wrong. Please try again.", confirmButtonColor: "var(--primary-theme)" });
            } finally {
                this.isSubmitting = false;
            }
        },
        
        openTraderModal(trader) {
            this.selectedTrader = trader;
            this.showTraderModal = true;
        },
        
        formatNumber(num) {
            if (num >= 1000) return (num / 1000).toFixed(1) + "K";
            return num.toString();
        }
     }'>
  
  <?php include "include/sidebar.php"?>
  
  <main class="flex-1 min-w-0 md:ml-72 pb-24 md:pb-8">
    <div class="max-w-screen-2xl mx-auto px-4 sm:px-6 py-8">

      <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
        <div>
          <h1 class="text-3xl font-black text-slate-900 dark:text-white tracking-tight">
            Copy <span class="text-theme">Trading</span>
          </h1>
          <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Mirror positions from top-performing expert traders automatically.</p>
        </div>
        <div class="flex items-center gap-4">
            <div class="glass-card rounded-2xl px-5 py-3 flex items-center gap-3">
                <div class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></div>
                <span class="text-xs font-black uppercase tracking-widest text-slate-600 dark:text-slate-300">Balance</span>
                <span class="text-lg font-black text-slate-900 dark:text-white" x-text="'$' + balance.toFixed(2)"></span>
            </div>
        </div>
      </div>

      <!-- Stats Overview -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
        <div class="glass-card rounded-[2rem] p-6 border border-slate-200 dark:border-slate-800 relative overflow-hidden">
            <div class="relative z-10">
                <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Traders Following</p>
                <p class="text-3xl font-black text-slate-900 dark:text-white" x-text="myCopies.length"></p>
            </div>
            <div class="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-2xl bg-theme/10 flex items-center justify-center text-theme">
                <i data-lucide="users" class="w-6 h-6"></i>
            </div>
        </div>
        <div class="glass-card rounded-[2rem] p-6 border border-slate-200 dark:border-slate-800 relative overflow-hidden">
            <div class="relative z-10">
                <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Combined ROI</p>
                <p class="text-3xl font-black" :class="totalCopiedRoi >= 0 ? 'text-emerald-500' : 'text-rose-500'" x-text="(totalCopiedRoi >= 0 ? '+' : '') + totalCopiedRoi.toFixed(1) + '%'"></p>
            </div>
            <div class="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-2xl bg-emerald-500/10 flex items-center justify-center text-emerald-500">
                <i data-lucide="trending-up" class="w-6 h-6"></i>
            </div>
        </div>
        <div class="glass-card rounded-[2rem] p-6 border border-slate-200 dark:border-slate-800 relative overflow-hidden">
            <div class="relative z-10">
                <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Avg Win Rate</p>
                <p class="text-3xl font-black text-theme" x-text="avgWinRate + '%'"></p>
            </div>
            <div class="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-2xl bg-theme/10 flex items-center justify-center text-theme">
                <i data-lucide="target" class="w-6 h-6"></i>
            </div>
        </div>
      </div>

      <!-- My Copied Traders -->
      <div x-show="myCopies.length > 0" class="mb-8" x-transition>
        <h2 class="text-xs font-black uppercase tracking-widest text-slate-400 mb-4">Your Portfolio</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <template x-for="trader in myCopies" :key="trader.relation_id">
                <div class="trader-card copied glass-card rounded-[2rem] p-5 border border-slate-200 dark:border-slate-800">
                    <div class="flex items-center gap-4 mb-4">
                        <div class="w-14 h-14 rounded-2xl bg-gradient-to-br flex items-center justify-center text-white font-black text-xl shadow-lg" 
                             :class="trader.avatar_gradient" x-text="trader.initials"></div>
                        <div class="flex-1">
                            <div class="flex items-center gap-2">
                                <h3 class="text-sm font-black text-slate-900 dark:text-white" x-text="trader.name"></h3>
                                <span class="px-2 py-0.5 rounded text-[9px] font-black uppercase tracking-widest"
                                      :class="'tier-badge-' + trader.tier.toLowerCase()" x-text="trader.tier"></span>
                            </div>
                            <p class="text-xs text-slate-500 dark:text-slate-400 mt-0.5" x-text="trader.specialty"></p>
                        </div>
                    </div>
                    <div class="grid grid-cols-3 gap-3 mb-3">
                        <div class="text-center p-2 rounded-xl bg-slate-50 dark:bg-slate-900/50">
                            <p class="text-[9px] font-black uppercase tracking-widest text-slate-400">ROI</p>
                            <p class="text-sm font-black" :class="trader.roi >= 0 ? 'text-emerald-500' : 'text-rose-500'" x-text="(trader.roi >= 0 ? '+' : '') + trader.roi + '%'"></p>
                        </div>
                        <div class="text-center p-2 rounded-xl bg-slate-50 dark:bg-slate-900/50">
                            <p class="text-[9px] font-black uppercase tracking-widest text-slate-400">Win Rate</p>
                            <p class="text-sm font-black text-theme" x-text="trader.win_rate + '%'"></p>
                        </div>
                        <div class="text-center p-2 rounded-xl bg-slate-50 dark:bg-slate-900/50">
                            <p class="text-[9px] font-black uppercase tracking-widest text-slate-400">Followers</p>
                            <p class="text-sm font-black text-slate-900 dark:text-white" x-text="formatNumber(trader.followers)"></p>
                        </div>
                    </div>
                    <div class="flex items-center justify-between pt-3 border-t border-slate-200 dark:border-slate-800">
                        <span class="text-[9px] font-bold text-slate-400 uppercase tracking-widest">Copied <span x-text="new Date(trader.copied_since).toLocaleDateString()"></span></span>
                        <button class="px-4 py-2 rounded-xl bg-emerald-500 text-white text-xs font-black uppercase tracking-widest cursor-default">
                            Active
                        </button>
                    </div>
                </div>
            </template>
        </div>
      </div>

      <!-- Search & Filters -->
      <div class="glass-card rounded-[2rem] p-4 mb-6 border border-slate-200 dark:border-slate-800">
        <div class="flex flex-col md:flex-row gap-4">
            <div class="flex-1 relative">
                <i data-lucide="search" class="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"></i>
                <input type="text" x-model="searchQuery" placeholder="Search traders by name or specialty..."
                       class="search-input w-full pl-10 pr-4 py-3 rounded-xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white font-bold text-sm focus:outline-none">
            </div>
            <div class="flex gap-2 overflow-x-auto">
                <button @click="selectedTier = 'all'" :class="selectedTier === 'all' ? 'active' : 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap">All</button>
                <button @click="selectedTier = 'pro'" :class="selectedTier === 'pro' ? 'active' : 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap">Pro</button>
                <button @click="selectedTier = 'elite'" :class="selectedTier === 'elite' ? 'active' : 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap">Elite</button>
                <button @click="selectedTier = 'master'" :class="selectedTier === 'master' ? 'active' : 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap">Master</button>
            </div>
            <select x-model="sortBy" class="px-4 py-3 rounded-xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white font-bold text-xs uppercase tracking-widest focus:outline-none focus:border-theme">
                <option value="roi">Sort by ROI</option>
                <option value="win_rate">Sort by Win Rate</option>
                <option value="followers">Sort by Popularity</option>
            </select>
        </div>
      </div>

      <!-- Traders Grid -->
      <h2 class="text-xs font-black uppercase tracking-widest text-slate-400 mb-4">Expert Traders</h2>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <template x-for="trader in filteredTraders" :key="trader.id">
            <div @click="openTraderModal(trader)" 
                 :class="isCopying(trader.id) ? 'copied' : ''"
                 class="trader-card glass-card rounded-[2rem] p-5 border border-slate-200 dark:border-slate-800">
                
                <div class="flex items-center gap-4 mb-4">
                    <div class="w-14 h-14 rounded-2xl bg-gradient-to-br flex items-center justify-center text-white font-black text-xl shadow-lg" 
                         :class="trader.avatar_gradient" x-text="trader.initials"></div>
                    <div class="flex-1">
                        <div class="flex items-center gap-2">
                            <h3 class="text-sm font-black text-slate-900 dark:text-white" x-text="trader.name"></h3>
                            <span class="px-2 py-0.5 rounded text-[9px] font-black uppercase tracking-widest"
                                  :class="'tier-badge-' + trader.tier.toLowerCase()" x-text="trader.tier"></span>
                        </div>
                        <p class="text-xs text-slate-500 dark:text-slate-400 mt-0.5" x-text="trader.specialty"></p>
                    </div>
                </div>

                <div class="space-y-3 mb-4">
                    <div>
                        <div class="flex justify-between items-center mb-1">
                            <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">ROI (30d)</span>
                            <span class="text-xs font-black" :class="trader.roi >= 0 ? 'text-emerald-500' : 'text-rose-500'" x-text="(trader.roi >= 0 ? '+' : '') + trader.roi.toFixed(1) + '%'"></span>
                        </div>
                        <div class="stat-bar">
                            <div class="stat-bar-fill" :style="'width: ' + Math.min(Math.abs(trader.roi), 100) + '%'"></div>
                        </div>
                    </div>
                    <div>
                        <div class="flex justify-between items-center mb-1">
                            <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">Win Rate</span>
                            <span class="text-xs font-black text-theme" x-text="trader.win_rate + '%'"></span>
                        </div>
                        <div class="stat-bar">
                            <div class="stat-bar-fill" :style="'width: ' + trader.win_rate + '%'"></div>
                        </div>
                    </div>
                </div>

                <div class="flex items-center justify-between pt-3 border-t border-slate-200 dark:border-slate-800">
                    <div class="flex items-center gap-1">
                        <i data-lucide="users" class="w-3 h-3 text-slate-400"></i>
                        <span class="text-xs font-bold text-slate-500 dark:text-slate-400" x-text="formatNumber(trader.followers)"></span>
                    </div>
                    <button @click.stop="copyTrader(trader)" 
                            :disabled="isSubmitting || isCopying(trader.id)"
                            :class="isCopying(trader.id) ? 'copied' : 'bg-theme text-white hover:brightness-110'"
                            class="copy-btn px-5 py-2 rounded-xl text-xs font-black uppercase tracking-widest transition-all">
                        <span x-show="!isSubmitting && !isCopying(trader.id)">Copy Trader</span>
                        <span x-show="isCopying(trader.id)">Following</span>
                        <span x-show="isSubmitting" class="flex items-center gap-1">
                            <svg class="animate-spin h-3 w-3" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                        </span>
                    </button>
                </div>
            </div>
        </template>
        
        <div x-show="filteredTraders.length === 0" class="col-span-full text-center py-16">
            <i data-lucide="search-x" class="w-12 h-12 text-slate-300 mx-auto mb-4"></i>
            <p class="text-sm font-bold text-slate-500 uppercase tracking-widest">No traders found matching your criteria.</p>
        </div>
      </div>

    </div>
  </main>

  <!-- Trader Detail Modal -->
  <div x-show="showTraderModal" style="display: none;" class="fixed inset-0 z-50 flex items-center justify-center modal-overlay p-4" x-transition>
    <div class="glass-card rounded-[2.5rem] p-8 max-w-lg w-full border border-slate-200 dark:border-slate-800 shadow-2xl max-h-[85vh] overflow-y-auto relative" @click.away="showTraderModal = false">
        
        <button @click="showTraderModal = false" class="absolute top-6 right-6 w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-slate-400 hover:text-slate-600 transition-colors z-10">
            <i data-lucide="x" class="w-5 h-5"></i>
        </button>

        <template x-if="selectedTrader">
            <div>
                <div class="flex items-center gap-4 mb-6">
                    <div class="w-20 h-20 rounded-3xl bg-gradient-to-br flex items-center justify-center text-white font-black text-2xl shadow-xl" 
                         :class="selectedTrader.avatar_gradient" x-text="selectedTrader.initials"></div>
                    <div>
                        <div class="flex items-center gap-2 mb-1">
                            <h3 class="text-xl font-black text-slate-900 dark:text-white" x-text="selectedTrader.name"></h3>
                            <span class="px-2 py-0.5 rounded text-[10px] font-black uppercase tracking-widest"
                                  :class="'tier-badge-' + selectedTrader.tier.toLowerCase()" x-text="selectedTrader.tier"></span>
                        </div>
                        <p class="text-sm text-slate-500 dark:text-slate-400" x-text="selectedTrader.specialty"></p>
                        <div class="flex items-center gap-3 mt-2">
                            <div class="flex items-center gap-1">
                                <i data-lucide="users" class="w-3 h-3 text-slate-400"></i>
                                <span class="text-xs font-bold text-slate-500" x-text="formatNumber(selectedTrader.followers) + ' followers'"></span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4 mb-6">
                    <div class="p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800 text-center">
                        <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">30-Day ROI</p>
                        <p class="text-2xl font-black" :class="selectedTrader.roi >= 0 ? 'text-emerald-500' : 'text-rose-500'" x-text="(selectedTrader.roi >= 0 ? '+' : '') + selectedTrader.roi.toFixed(1) + '%'"></p>
                    </div>
                    <div class="p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800 text-center">
                        <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Win Rate</p>
                        <p class="text-2xl font-black text-theme" x-text="selectedTrader.win_rate + '%'"></p>
                    </div>
                </div>

                <div class="space-y-4 mb-6">
                    <div class="flex justify-between items-center p-3 rounded-xl bg-slate-50 dark:bg-slate-900/30">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Risk Level</span>
                        <span class="text-xs font-black text-amber-500">Moderate</span>
                    </div>
                    <div class="flex justify-between items-center p-3 rounded-xl bg-slate-50 dark:bg-slate-900/30">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Avg Trade Duration</span>
                        <span class="text-xs font-black text-slate-700 dark:text-slate-300">4h 32m</span>
                    </div>
                    <div class="flex justify-between items-center p-3 rounded-xl bg-slate-50 dark:bg-slate-900/30">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Profitable Months</span>
                        <span class="text-xs font-black text-emerald-500">8/12</span>
                    </div>
                    <div class="flex justify-between items-center p-3 rounded-xl bg-slate-50 dark:bg-slate-900/30">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Total Trades</span>
                        <span class="text-xs font-black text-slate-700 dark:text-slate-300">1,247</span>
                    </div>
                </div>

                <button @click="copyTrader(selectedTrader); showTraderModal = false" 
                        :disabled="isSubmitting || isCopying(selectedTrader.id)"
                        :class="isCopying(selectedTrader.id) ? 'bg-emerald-500 cursor-default' : 'bg-theme hover:brightness-110'"
                        class="w-full py-4 rounded-2xl text-white font-black uppercase tracking-widest text-sm shadow-xl transition-all flex items-center justify-center gap-2">
                    <span x-show="!isSubmitting && !isCopying(selectedTrader.id)">Start Copying</span>
                    <span x-show="isCopying(selectedTrader.id)">Already Following</span>
                    <span x-show="isSubmitting" class="flex items-center gap-2">
                        <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        Processing...
                    </span>
                </button>
            </div>
        </template>
    </div>
  </div>

</div>

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

<script src="https://unpkg.com/lucide@latest"></script>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        lucide.createIcons();
    });
    
    document.addEventListener('alpine:initialized', () => {
        Alpine.effect(() => {
            setTimeout(() => { lucide.createIcons(); }, 50);
        });
    });
</script>

</body>
</html>