<?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 PREMIUM SIGNALS FROM DATABASE
// ==========================================
$signals = [];
$signalsQuery = mysqli_query($conn, "SELECT `id`, `symbol`, `type`, `entry_price`, `target_price`, `stop_loss`, 
                                     `timeframe`, `status`, `accuracy`, `created_at`, `closed_at`, `profit_loss`, 
                                     `signal_provider`, `provider_tier`, `confidence_score`, `market`, `description`
                                     FROM `premium_signals` 
                                     WHERE `status` IN ('active', 'pending', 'completed') 
                                     ORDER BY `created_at` DESC 
                                     LIMIT 50");

if ($signalsQuery && mysqli_num_rows($signalsQuery) > 0) {
    while ($row = mysqli_fetch_assoc($signalsQuery)) {
        $signals[] = [
            'id' => (int)$row['id'],
            'symbol' => $row['symbol'],
            'type' => strtolower($row['type']),
            'entry_price' => (float)$row['entry_price'],
            'target_price' => (float)$row['target_price'],
            'stop_loss' => (float)$row['stop_loss'],
            'timeframe' => $row['timeframe'],
            'status' => $row['status'],
            'accuracy' => (int)$row['accuracy'],
            'created_at' => $row['created_at'],
            'closed_at' => $row['closed_at'],
            'profit_loss' => $row['profit_loss'] !== null ? (float)$row['profit_loss'] : null,
            'signal_provider' => $row['signal_provider'],
            'provider_tier' => $row['provider_tier'],
            'confidence_score' => (int)$row['confidence_score'],
            'market' => $row['market'] ?? 'crypto',
            'description' => $row['description'] ?? ''
        ];
    }
}

// ==========================================
// FETCH USER'S ACTIVE SIGNAL SUBSCRIPTIONS
// ==========================================
$mySignals = [];
$mySignalsQuery = mysqli_query($conn, "SELECT ps.`id`, ps.`symbol`, ps.`type`, ps.`entry_price`, ps.`target_price`, 
                                       ps.`stop_loss`, ps.`timeframe`, ps.`status`, ps.`accuracy`, ps.`created_at`, 
                                       ps.`profit_loss`, ps.`signal_provider`, ps.`provider_tier`, ps.`confidence_score`, 
                                       ps.`market`, ss.`subscribed_at`, ss.`id` as subscription_id
                                       FROM `signal_subscriptions` ss
                                       JOIN `premium_signals` ps ON ss.`signal_id` = ps.`id`
                                       WHERE ss.`user_id` = $userId AND ps.`status` IN ('active', 'pending')
                                       ORDER BY ss.`subscribed_at` DESC");
if ($mySignalsQuery) {
    while ($row = mysqli_fetch_assoc($mySignalsQuery)) {
        $mySignals[] = [
            'id' => (int)$row['id'],
            'subscription_id' => (int)$row['subscription_id'],
            'symbol' => $row['symbol'],
            'type' => strtolower($row['type']),
            'entry_price' => (float)$row['entry_price'],
            'target_price' => (float)$row['target_price'],
            'stop_loss' => (float)$row['stop_loss'],
            'timeframe' => $row['timeframe'],
            'status' => $row['status'],
            'accuracy' => (int)$row['accuracy'],
            'created_at' => $row['created_at'],
            'profit_loss' => $row['profit_loss'] !== null ? (float)$row['profit_loss'] : null,
            'signal_provider' => $row['signal_provider'],
            'provider_tier' => $row['provider_tier'],
            'confidence_score' => (int)$row['confidence_score'],
            'market' => $row['market'],
            'subscribed_at' => $row['subscribed_at']
        ];
    }
}

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

    try {
        $signalId = intval($_POST['signal_id'] ?? 0);
        
        if ($signalId <= 0) {
            throw new Exception('Invalid signal selected.');
        }

        // Check if already subscribed — using bind_result
        $checkStmt = mysqli_prepare($conn, "SELECT `id` FROM `signal_subscriptions` WHERE `user_id` = ? AND `signal_id` = ? LIMIT 1");
        if (!$checkStmt) throw new Exception("Prepare failed: " . mysqli_error($conn));
        
        mysqli_stmt_bind_param($checkStmt, "ii", $userId, $signalId);
        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 subscribed to this signal.');
        }
        mysqli_stmt_close($checkStmt);

        // Verify signal exists and is active/pending
        $verifyStmt = mysqli_prepare($conn, "SELECT `id`, `symbol`, `type`, `entry_price`, `target_price`, `stop_loss`, 
                                              `timeframe`, `status`, `accuracy`, `created_at`, `signal_provider`, 
                                              `provider_tier`, `confidence_score`, `market` 
                                              FROM `premium_signals` 
                                              WHERE `id` = ? AND `status` IN ('active', 'pending')");
        if (!$verifyStmt) throw new Exception("Prepare failed: " . mysqli_error($conn));
        
        mysqli_stmt_bind_param($verifyStmt, "i", $signalId);
        mysqli_stmt_execute($verifyStmt);
        mysqli_stmt_store_result($verifyStmt);
        
        if (mysqli_stmt_num_rows($verifyStmt) === 0) {
            mysqli_stmt_close($verifyStmt);
            throw new Exception('Signal not found or no longer active.');
        }
        
        mysqli_stmt_bind_result($verifyStmt, $sigId, $sigSymbol, $sigType, $sigEntry, $sigTarget, $sigStop, 
                                $sigTimeframe, $sigStatus, $sigAccuracy, $sigCreated, $sigProvider, 
                                $sigTier, $sigConfidence, $sigMarket);
        mysqli_stmt_fetch($verifyStmt);
        mysqli_stmt_close($verifyStmt);

        // Insert subscription
        $insertStmt = mysqli_prepare($conn, "INSERT INTO `signal_subscriptions` (`user_id`, `signal_id`, `subscribed_at`) VALUES (?, ?, NOW())");
        if (!$insertStmt) throw new Exception("Prepare failed: " . mysqli_error($conn));
        
        mysqli_stmt_bind_param($insertStmt, "ii", $userId, $signalId);
        
        if (!mysqli_stmt_execute($insertStmt)) {
            throw new Exception("Execution Failed: " . mysqli_stmt_error($insertStmt));
        }

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

        ob_end_clean();
        echo json_encode([
            'success' => true,
            'message' => 'Successfully subscribed to ' . $sigSymbol . ' signal!',
            'subscription_id' => $subscriptionId,
            'signal' => [
                'id' => $sigId,
                'symbol' => $sigSymbol,
                'type' => $sigType,
                'entry_price' => (float)$sigEntry,
                'target_price' => (float)$sigTarget,
                'stop_loss' => (float)$sigStop,
                'timeframe' => $sigTimeframe,
                'status' => $sigStatus,
                'accuracy' => (int)$sigAccuracy,
                'created_at' => $sigCreated,
                'signal_provider' => $sigProvider,
                'provider_tier' => $sigTier,
                'confidence_score' => (int)$sigConfidence,
                'market' => $sigMarket,
                'subscribed_at' => date('Y-m-d H:i:s')
            ]
        ]);

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

// ==========================================
// FETCH SIGNAL PERFORMANCE STATS
// ==========================================
$stats = [
    'total_signals' => 0,
    'active_signals' => 0,
    'win_rate' => 0,
    'avg_profit' => 0.00
];

$statsQuery = mysqli_query($conn, "SELECT 
                                    COUNT(*) as total,
                                    SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
                                    AVG(CASE WHEN profit_loss > 0 THEN 1 ELSE 0 END) * 100 as win_rate,
                                    AVG(profit_loss) as avg_profit
                                    FROM `premium_signals`");
if ($statsQuery && $row = mysqli_fetch_assoc($statsQuery)) {
    $stats['total_signals'] = (int)$row['total'];
    $stats['active_signals'] = (int)$row['active'];
    $stats['win_rate'] = round((float)$row['win_rate'], 1);
    $stats['avg_profit'] = round((float)$row['avg_profit'], 2);
}
?>

<?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);
    }

    .signal-card {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .signal-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 20px 40px -12px rgba(0, 0, 0, 0.15);
    }
    .signal-card.subscribed {
        border: 2px solid var(--primary-theme);
        background: rgba(var(--primary-rgb), 0.05);
    }
    .signal-card.subscribed::after {
        content: '✓ Active';
        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);
    }
    
    .type-badge-buy { background: rgba(16, 185, 129, 0.1); color: #10b981; }
    .type-badge-sell { background: rgba(244, 63, 94, 0.1); color: #f43f5e; }
    
    .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; }
    
    .confidence-bar {
        height: 4px;
        border-radius: 2px;
        background: #e2e8f0;
        overflow: hidden;
    }
    .dark .confidence-bar { background: #1e293b; }
    .confidence-fill {
        height: 100%;
        border-radius: 2px;
        background: var(--primary-theme);
        transition: width 0.6s ease;
    }
    
    .subscribe-btn {
        transition: all 0.2s ease;
        position: relative;
        overflow: hidden;
    }
    .subscribe-btn:active { transform: scale(0.95); }
    .subscribe-btn.subscribed {
        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);
    }
    
    .price-up { color: #10b981; }
    .price-down { color: #f43f5e; }
    
    .status-dot {
        width: 6px;
        height: 6px;
        border-radius: 50%;
        display: inline-block;
    }
    .status-active { background: #10b981; box-shadow: 0 0 8px #10b981; animation: pulse 2s infinite; }
    .status-pending { background: #f59e0b; box-shadow: 0 0 8px #f59e0b; }
    .status-completed { background: #6366f1; }
    
    @keyframes pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.5; }
    }
    
    .signal-detail-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        border-radius: 12px;
        background: rgba(248, 250, 252, 0.5);
        margin-bottom: 8px;
    }
    .dark .signal-detail-row {
        background: rgba(30, 41, 59, 0.5);
    }
</style>

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

<div class="flex min-h-screen bg-slate-50 dark:bg-[#070b14] transition-colors duration-300"
     x-data='{
        signals: <?= json_encode($signals, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
        mySignals: <?= json_encode($mySignals, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
        balance: <?= $balance ?>,
        searchQuery: "",
        selectedType: "all",
        selectedMarket: "all",
        selectedStatus: "all",
        sortBy: "newest",
        isSubmitting: false,
        showSignalModal: false,
        selectedSignal: null,
        
        get filteredSignals() {
            let filtered = this.signals;
            
            if (this.searchQuery) {
                const q = this.searchQuery.toLowerCase();
                filtered = filtered.filter(s => s.symbol.toLowerCase().includes(q) || 
                                               s.signal_provider.toLowerCase().includes(q) ||
                                               s.description.toLowerCase().includes(q));
            }
            
            if (this.selectedType !== "all") {
                filtered = filtered.filter(s => s.type === this.selectedType);
            }
            
            if (this.selectedMarket !== "all") {
                filtered = filtered.filter(s => s.market === this.selectedMarket);
            }
            
            if (this.selectedStatus !== "all") {
                filtered = filtered.filter(s => s.status === this.selectedStatus);
            }
            
            if (this.sortBy === "newest") {
                filtered = [...filtered].sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
            } else if (this.sortBy === "confidence") {
                filtered = [...filtered].sort((a, b) => b.confidence_score - a.confidence_score);
            } else if (this.sortBy === "accuracy") {
                filtered = [...filtered].sort((a, b) => b.accuracy - a.accuracy);
            }
            
            return filtered;
        },
        
        isSubscribed(signalId) {
            return this.mySignals.some(s => s.id === signalId);
        },
        
        get activeSubscriptions() {
            return this.mySignals.filter(s => s.status === "active" || s.status === "pending").length;
        },
        
        get totalPotentialProfit() {
            return this.mySignals.reduce((sum, s) => {
                if (s.status === "active" && s.profit_loss !== null) return sum + s.profit_loss;
                return sum;
            }, 0);
        },
        
        get avgConfidence() {
            if (this.mySignals.length === 0) return 0;
            return Math.round(this.mySignals.reduce((sum, s) => sum + s.confidence_score, 0) / this.mySignals.length);
        },
        
        async subscribeToSignal(signal) {
            if (this.isSubscribed(signal.id)) {
                Swal.fire({ icon: "info", title: "Already Subscribed", text: "You are already following " + signal.symbol, confirmButtonColor: "var(--primary-theme)" });
                return;
            }
            
            this.isSubmitting = true;
            
            const params = new URLSearchParams();
            params.append("action", "subscribe_signal");
            params.append("signal_id", signal.id);
            
            try {
                const response = await fetch("PremiumSignals.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: "Signal Subscribed!", 
                        text: "You are now tracking " + signal.symbol + ". You will receive updates when targets are hit.", 
                        confirmButtonColor: "var(--primary-theme)",
                        timer: 2500,
                        showConfirmButton: false
                    });
                    
                    this.mySignals.unshift(data.signal);
                    
                } else {
                    Swal.fire({ icon: "error", title: "Subscription Failed", text: data.message, confirmButtonColor: "var(--primary-theme)" });
                }
            } catch (error) {
                console.error("Subscription error:", error);
                Swal.fire({ icon: "error", title: "Error", text: "Something went wrong. Please try again.", confirmButtonColor: "var(--primary-theme)" });
            } finally {
                this.isSubmitting = false;
            }
        },
        
        openSignalModal(signal) {
            this.selectedSignal = signal;
            this.showSignalModal = true;
        },
        
        formatPrice(price) {
            return price.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 8 });
        },
        
        formatNumber(num) {
            if (num >= 1000) return (num / 1000).toFixed(1) + "K";
            return num.toString();
        },
        
        timeAgo(dateString) {
            const date = new Date(dateString);
            const now = new Date();
            const seconds = Math.floor((now - date) / 1000);
            
            if (seconds < 60) return "Just now";
            const minutes = Math.floor(seconds / 60);
            if (minutes < 60) return minutes + "m ago";
            const hours = Math.floor(minutes / 60);
            if (hours < 24) return hours + "h ago";
            const days = Math.floor(hours / 24);
            return days + "d ago";
        },
        
        getProfitPercent(entry, current, type) {
            const change = ((current - entry) / entry) * 100;
            return type === "buy" ? change : -change;
        }
     }'>
  
  <?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">
            Premium <span class="text-theme">Signals</span>
          </h1>
          <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Real-time trading signals from elite market analysts.</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="&#39;$&#39; + balance.toFixed(2)"></span>
            </div>
        </div>
      </div>

      <!-- Stats Overview -->
      <div class="grid grid-cols-1 md:grid-cols-4 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">Active Signals</p>
                <p class="text-3xl font-black text-slate-900 dark:text-white"><?= $stats['active_signals'] ?></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="activity" 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">Your Subscriptions</p>
                <p class="text-3xl font-black text-theme" x-text="activeSubscriptions"></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="bell" 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">Signal Win Rate</p>
                <p class="text-3xl font-black text-emerald-500"><?= $stats['win_rate'] ?>%</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="target" 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 Profit</p>
                <p class="text-3xl font-black" :class="<?= $stats['avg_profit'] >= 0 ? '&#39;text-emerald-500&#39;' : '&#39;text-rose-500&#39;' ?>">
                    <?= ($stats['avg_profit'] >= 0 ? '+' : '') . $stats['avg_profit'] ?>%
                </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>

      <!-- My Active Signals -->
      <div x-show="mySignals.length > 0" class="mb-8" x-transition>
        <h2 class="text-xs font-black uppercase tracking-widest text-slate-400 mb-4">Your Active Signals</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <template x-for="signal in mySignals" :key="signal.subscription_id">
                <div class="signal-card subscribed glass-card rounded-[2rem] p-5 border border-slate-200 dark:border-slate-800">
                    <div class="flex items-center justify-between mb-4">
                        <div class="flex items-center gap-3">
                            <div class="w-12 h-12 rounded-2xl bg-gradient-to-br from-theme to-purple-600 flex items-center justify-center text-white font-black text-lg shadow-lg" 
                                 x-text="signal.symbol.substring(0, 2)"></div>
                            <div>
                                <div class="flex items-center gap-2">
                                    <h3 class="text-sm font-black text-slate-900 dark:text-white" x-text="signal.symbol"></h3>
                                    <span class="px-2 py-0.5 rounded text-[9px] font-black uppercase tracking-widest"
                                          :class="&#39;type-badge-&#39; + signal.type" x-text="signal.type.toUpperCase()"></span>
                                </div>
                                <p class="text-xs text-slate-500 dark:text-slate-400 mt-0.5" x-text="signal.signal_provider"></p>
                            </div>
                        </div>
                        <div class="status-dot" :class="&#39;status-&#39; + signal.status"></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">Entry</p>
                            <p class="text-sm font-black text-slate-900 dark:text-white" x-text="&#39;$&#39; + formatPrice(signal.entry_price)"></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">Target</p>
                            <p class="text-sm font-black text-emerald-500" x-text="&#39;$&#39; + formatPrice(signal.target_price)"></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">Stop</p>
                            <p class="text-sm font-black text-rose-500" x-text="&#39;$&#39; + formatPrice(signal.stop_loss)"></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" x-text="timeAgo(signal.subscribed_at)"></span>
                        <span class="px-3 py-1.5 rounded-xl bg-emerald-500/10 text-emerald-500 text-[9px] font-black uppercase tracking-widest">
                            Tracking
                        </span>
                    </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 lg: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 signals by symbol or provider..."
                       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="selectedType = &#39;all&#39;" :class="selectedType === &#39;all&#39; ? &#39;active&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400&#39;" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap">All</button>
                <button @click="selectedType = &#39;buy&#39;" :class="selectedType === &#39;buy&#39; ? &#39;active&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400&#39;" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap">Buy</button>
                <button @click="selectedType = &#39;sell&#39;" :class="selectedType === &#39;sell&#39; ? &#39;active&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400&#39;" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap">Sell</button>
            </div>
            <div class="flex gap-2 overflow-x-auto">
                <button @click="selectedMarket = &#39;all&#39;" :class="selectedMarket === &#39;all&#39; ? &#39;active&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400&#39;" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap">All Markets</button>
                <button @click="selectedMarket = &#39;crypto&#39;" :class="selectedMarket === &#39;crypto&#39; ? &#39;active&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400&#39;" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap">Crypto</button>
                <button @click="selectedMarket = &#39;forex&#39;" :class="selectedMarket === &#39;forex&#39; ? &#39;active&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400&#39;" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap">Forex</button>
                <button @click="selectedMarket = &#39;stocks&#39;" :class="selectedMarket === &#39;stocks&#39; ? &#39;active&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400&#39;" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap">Stocks</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="newest">Newest First</option>
                <option value="confidence">Highest Confidence</option>
                <option value="accuracy">Best Accuracy</option>
            </select>
        </div>
      </div>

      <!-- Signals Grid -->
      <h2 class="text-xs font-black uppercase tracking-widest text-slate-400 mb-4">Premium Signal Feed</h2>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <template x-for="signal in filteredSignals" :key="signal.id">
            <div @click="openSignalModal(signal)" 
                 :class="isSubscribed(signal.id) ? &#39;subscribed&#39; : &#39;&#39;"
                 class="signal-card glass-card rounded-[2rem] p-5 border border-slate-200 dark:border-slate-800">
                
                <div class="flex items-center justify-between mb-4">
                    <div class="flex items-center gap-3">
                        <div class="w-12 h-12 rounded-2xl bg-gradient-to-br from-theme to-purple-600 flex items-center justify-center text-white font-black text-lg shadow-lg" 
                             x-text="signal.symbol.substring(0, 2)"></div>
                        <div>
                            <div class="flex items-center gap-2">
                                <h3 class="text-sm font-black text-slate-900 dark:text-white" x-text="signal.symbol"></h3>
                                <span class="px-2 py-0.5 rounded text-[9px] font-black uppercase tracking-widest"
                                      :class="&#39;type-badge-&#39; + signal.type" x-text="signal.type.toUpperCase()"></span>
                            </div>
                            <div class="flex items-center gap-2 mt-0.5">
                                <p class="text-xs text-slate-500 dark:text-slate-400" x-text="signal.signal_provider"></p>
                                <span class="px-1.5 py-0.5 rounded text-[8px] font-black uppercase tracking-widest"
                                      :class="&#39;tier-badge-&#39; + signal.provider_tier.toLowerCase()" x-text="signal.provider_tier"></span>
                            </div>
                        </div>
                    </div>
                    <div class="flex flex-col items-end">
                        <div class="status-dot mb-1" :class="&#39;status-&#39; + signal.status"></div>
                        <span class="text-[8px] font-black uppercase tracking-widest text-slate-400" x-text="timeAgo(signal.created_at)"></span>
                    </div>
                </div>

                <div class="space-y-3 mb-4">
                    <div class="flex justify-between items-center p-3 rounded-xl bg-slate-50 dark:bg-slate-900/50">
                        <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">Entry Price</span>
                        <span class="text-sm font-black text-slate-900 dark:text-white" x-text="&#39;$&#39; + formatPrice(signal.entry_price)"></span>
                    </div>
                    <div class="flex justify-between items-center p-3 rounded-xl bg-slate-50 dark:bg-slate-900/50">
                        <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">Target</span>
                        <span class="text-sm font-black text-emerald-500" x-text="&#39;$&#39; + formatPrice(signal.target_price)"></span>
                    </div>
                    <div class="flex justify-between items-center p-3 rounded-xl bg-slate-50 dark:bg-slate-900/50">
                        <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">Stop Loss</span>
                        <span class="text-sm font-black text-rose-500" x-text="&#39;$&#39; + formatPrice(signal.stop_loss)"></span>
                    </div>
                </div>

                <div class="mb-4">
                    <div class="flex justify-between items-center mb-1">
                        <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">Confidence</span>
                        <span class="text-xs font-black text-theme" x-text="signal.confidence_score + &#39;%&#39;"></span>
                    </div>
                    <div class="confidence-bar">
                        <div class="confidence-fill" :style="&#39;width: &#39; + signal.confidence_score + &#39;%&#39;"></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-3">
                        <div class="flex items-center gap-1">
                            <i data-lucide="clock" class="w-3 h-3 text-slate-400"></i>
                            <span class="text-[9px] font-bold text-slate-500 uppercase tracking-widest" x-text="signal.timeframe"></span>
                        </div>
                        <div class="flex items-center gap-1">
                            <i data-lucide="bar-chart-2" class="w-3 h-3 text-slate-400"></i>
                            <span class="text-[9px] font-bold text-slate-500 uppercase tracking-widest" x-text="signal.accuracy + &#39;%&#39;"></span>
                        </div>
                    </div>
                    <button @click.stop="subscribeToSignal(signal)" 
                            :disabled="isSubmitting || isSubscribed(signal.id)"
                            :class="isSubscribed(signal.id) ? &#39;subscribed&#39; : &#39;bg-theme text-white hover:brightness-110&#39;"
                            class="subscribe-btn px-5 py-2 rounded-xl text-xs font-black uppercase tracking-widest transition-all">
                        <span x-show="!isSubmitting && !isSubscribed(signal.id)">Subscribe</span>
                        <span x-show="isSubscribed(signal.id)">Tracking</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="filteredSignals.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 signals found matching your criteria.</p>
        </div>
      </div>

    </div>
  </main>

  <!-- Signal Detail Modal -->
  <div x-show="showSignalModal" 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="showSignalModal = false">
        
        <button @click="showSignalModal = 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="selectedSignal">
            <div>
                <div class="flex items-center gap-4 mb-6">
                    <div class="w-20 h-20 rounded-3xl bg-gradient-to-br from-theme to-purple-600 flex items-center justify-center text-white font-black text-2xl shadow-xl" 
                         x-text="selectedSignal.symbol.substring(0, 2)"></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="selectedSignal.symbol"></h3>
                            <span class="px-2 py-0.5 rounded text-[10px] font-black uppercase tracking-widest"
                                  :class="&#39;type-badge-&#39; + selectedSignal.type" x-text="selectedSignal.type.toUpperCase()"></span>
                        </div>
                        <p class="text-sm text-slate-500 dark:text-slate-400" x-text="selectedSignal.signal_provider"></p>
                        <div class="flex items-center gap-3 mt-2">
                            <span class="px-2 py-0.5 rounded text-[9px] font-black uppercase tracking-widest"
                                  :class="&#39;tier-badge-&#39; + selectedSignal.provider_tier.toLowerCase()" x-text="selectedSignal.provider_tier"></span>
                            <div class="flex items-center gap-1">
                                <div class="status-dot" :class="&#39;status-&#39; + selectedSignal.status"></div>
                                <span class="text-xs font-bold text-slate-500 uppercase tracking-widest" x-text="selectedSignal.status"></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">Entry Price</p>
                        <p class="text-2xl font-black text-slate-900 dark:text-white" x-text="&#39;$&#39; + formatPrice(selectedSignal.entry_price)"></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">Target</p>
                        <p class="text-2xl font-black text-emerald-500" x-text="&#39;$&#39; + formatPrice(selectedSignal.target_price)"></p>
                    </div>
                </div>

                <div class="space-y-3 mb-6">
                    <div class="signal-detail-row">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Stop Loss</span>
                        <span class="text-sm font-black text-rose-500" x-text="&#39;$&#39; + formatPrice(selectedSignal.stop_loss)"></span>
                    </div>
                    <div class="signal-detail-row">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Timeframe</span>
                        <span class="text-sm font-black text-slate-700 dark:text-slate-300" x-text="selectedSignal.timeframe"></span>
                    </div>
                    <div class="signal-detail-row">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Market</span>
                        <span class="text-sm font-black text-slate-700 dark:text-slate-300 capitalize" x-text="selectedSignal.market"></span>
                    </div>
                    <div class="signal-detail-row">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Provider Accuracy</span>
                        <span class="text-sm font-black text-theme" x-text="selectedSignal.accuracy + &#39;%&#39;"></span>
                    </div>
                    <div class="signal-detail-row">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Confidence Score</span>
                        <div class="flex items-center gap-2">
                            <div class="w-24 h-2 rounded-full bg-slate-200 dark:bg-slate-700 overflow-hidden">
                                <div class="h-full rounded-full bg-theme transition-all" :style="&#39;width: &#39; + selectedSignal.confidence_score + &#39;%&#39;"></div>
                            </div>
                            <span class="text-sm font-black text-theme" x-text="selectedSignal.confidence_score + &#39;%&#39;"></span>
                        </div>
                    </div>
                    <div class="signal-detail-row">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Signal Age</span>
                        <span class="text-sm font-black text-slate-700 dark:text-slate-300" x-text="timeAgo(selectedSignal.created_at)"></span>
                    </div>
                </div>

                <div x-show="selectedSignal.description" class="mb-6 p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/30 border border-slate-200 dark:border-slate-800">
                    <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-2">Analysis</p>
                    <p class="text-sm text-slate-600 dark:text-slate-300 leading-relaxed" x-text="selectedSignal.description"></p>
                </div>

                <button @click="subscribeToSignal(selectedSignal); showSignalModal = false" 
                        :disabled="isSubmitting || isSubscribed(selectedSignal.id)"
                        :class="isSubscribed(selectedSignal.id) ? &#39;bg-emerald-500 cursor-default&#39; : &#39;bg-theme hover:brightness-110&#39;"
                        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 && !isSubscribed(selectedSignal.id)">Subscribe to Signal</span>
                    <span x-show="isSubscribed(selectedSignal.id)">Already Tracking</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>