<?php
/**
 * TOPBD — Bangladesh's Live Ranking & Outbid Marketplace
 * Main Frontend Application Entry Point (PHP 8+ / MySQL / Apache / cPanel / Hostinger)
 */

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/ranking.php';

$timeFilter = $_GET['time'] ?? 'all_time';
$categorySlug = $_GET['cat'] ?? 'all';
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = (int)get_setting('pagination_size', '50');

$db = get_db();

// 1. Fetch rankings & metrics
$rankingData = RankingEngine::getRankings($timeFilter, $categorySlug, $page, $perPage);
$topListing = RankingEngine::getTopListing();
$totalGenerated = RankingEngine::getTotalGenerated();
$liveVisitors = RankingEngine::getLiveVisitors((int)get_setting('visitor_timeout_seconds', '180'));

// 2. Fetch categories
$catsStmt = $db->query("SELECT * FROM categories WHERE is_active = 1 ORDER BY display_order ASC, id ASC");
$categories = $catsStmt->fetchAll();

// 3. Fetch menu items
$menuStmt = $db->query("SELECT * FROM menu_items WHERE is_active = 1 ORDER BY display_order ASC");
$menuItems = $menuStmt->fetchAll();

// 4. Fetch enabled payment gateways
$gwStmt = $db->query("SELECT * FROM gateway_configs WHERE is_enabled = 1 ORDER BY gateway_id ASC");
$enabledGateways = $gwStmt->fetchAll();

// 5. Fetch active content pages for modal viewing
$pagesStmt = $db->query("SELECT slug, title, content FROM pages");
$pages = $pagesStmt->fetchAll(PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);

// 6. Dynamic Bid Next Calculation
$minInc = (float)get_setting('minimum_bid_increment', '1');
$initMin = (float)get_setting('initial_minimum_bid', '10');
$currentTopBid = $topListing ? (float)$topListing['current_bid'] : $initMin;
$nextTopBid = $currentTopBid + $minInc;
$currency = get_setting('currency_symbol', '৳');

// Payment return status notification
$paymentStatus = $_GET['payment_status'] ?? '';
$txnId = $_GET['txn_id'] ?? '';
?>
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?= e(get_setting('site_name', 'TOPBD')) ?> — <?= e(get_setting('site_subtitle', "Bangladesh's Live Ranking & Outbid Marketplace")) ?></title>
    <meta name="description" content="<?= e(get_text('claim_hero_desc')) ?>">
    
    <!-- Tailwind CSS Engine -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Dynamic CSS Variables directly driven from Admin Settings -->
    <style>
        :root {
            --primary-color: <?= e(get_setting('primary_color', '#006A4E')) ?>;
            --secondary-color: <?= e(get_setting('secondary_color', '#F42A41')) ?>;
            --bg-color: <?= e(get_setting('background_color', '#0A0D0F')) ?>;
            --card-color: <?= e(get_setting('card_color', '#13181D')) ?>;
            --text-color: <?= e(get_setting('text_color', '#F0F4F8')) ?>;
            --muted-text-color: <?= e(get_setting('muted_text_color', '#8A99A8')) ?>;
            --border-color: <?= e(get_setting('border_color', '#222A33')) ?>;
            --accent-color: <?= e(get_setting('accent_color', '#F59E0B')) ?>;
            --rank1-bg: <?= e(get_setting('rank1_bg', '#1C2422')) ?>;
            --rank1-border: <?= e(get_setting('rank1_border', '#EAB308')) ?>;
            --rank2-bg: <?= e(get_setting('rank2_bg', '#171E24')) ?>;
            --rank3-bg: <?= e(get_setting('rank3_bg', '#141B20')) ?>;
            --header-bg: <?= e(get_setting('header_bg', '#0A0D0FEE')) ?>;
            --footer-bg: <?= e(get_setting('footer_bg', '#07090B')) ?>;
            --border-radius: <?= e(get_setting('border_radius', '12px')) ?>;
        }

        body {
            background-color: var(--bg-color);
            color: var(--text-color);
            font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            overflow-x: hidden;
            margin: 0;
            padding: 0;
            -webkit-tap-highlight-color: transparent;
        }

        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: #0A0D0F; }
        ::-webkit-scrollbar-thumb { background: #222A33; border-radius: 3px; }
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
    </style>
</head>
<body class="min-h-screen flex flex-col selection:bg-emerald-500 selection:text-white">

    <!-- Payment Status Notification Toast -->
    <?php if ($paymentStatus === 'success'): ?>
        <div id="payment-toast" class="bg-emerald-600 text-white px-4 py-3 text-center text-xs sm:text-sm font-semibold flex items-center justify-between shadow-lg">
            <div class="max-w-7xl mx-auto flex items-center gap-2">
                <span>🎉 <strong>Payment Verified!</strong> Your listing is now updated and live on the leaderboard.</span>
                <?php if ($txnId): ?>
                    <span class="font-mono text-xs opacity-90">(Txn: <?= e($txnId) ?>)</span>
                <?php endif; ?>
            </div>
            <button onclick="document.getElementById('payment-toast').remove()" class="text-white hover:opacity-75 font-bold text-base">&times;</button>
        </div>
    <?php elseif ($paymentStatus === 'cancelled'): ?>
        <div id="payment-toast" class="bg-amber-600 text-white px-4 py-2.5 text-center text-xs font-semibold flex items-center justify-between shadow-lg">
            <div class="max-w-7xl mx-auto">
                <span>⚠️ Payment process was cancelled. You can try again anytime.</span>
            </div>
            <button onclick="document.getElementById('payment-toast').remove()" class="text-white hover:opacity-75 font-bold text-base">&times;</button>
        </div>
    <?php endif; ?>

    <!-- Sticky Header -->
    <header class="sticky top-0 z-40 w-full border-b backdrop-blur-md transition-colors" style="background-color: var(--header-bg); border-color: var(--border-color);">
        <div class="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8 h-16 flex items-center justify-between gap-2 sm:gap-4">
            <!-- Left: Logo -->
            <div class="flex items-center gap-2 sm:gap-3 shrink-0">
                <a href="/" class="flex items-center gap-2 group">
                    <div class="w-8 h-8 sm:w-9 sm:h-9 rounded-lg bg-gradient-to-tr from-emerald-600 to-emerald-400 flex items-center justify-center shadow-lg shadow-emerald-950/40 group-hover:scale-105 transition-transform shrink-0">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" class="text-white sm:w-5 sm:h-5">
                            <path d="M4 18L9 13H13L18 6M18 6H13M18 6V11" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
                            <circle cx="18" cy="6" r="1.5" fill="#F42A41"/>
                        </svg>
                    </div>
                    <span class="font-extrabold text-base sm:text-lg tracking-tight text-white font-mono"><?= e(get_text('site_logo_text', 'TOPBD')) ?></span>
                </a>
            </div>

            <!-- Center: Time Switch (ALL TIME / TODAY) -->
            <div class="flex items-center justify-center">
                <div id="time-switch-tabs" class="inline-flex items-center p-0.5 sm:p-1 rounded-lg bg-[#141A20] border border-[#222A33] shadow-inner text-xs font-semibold">
                    <a href="?time=all_time&cat=<?= urlencode($categorySlug) ?>" class="px-2.5 sm:px-3 py-1 text-[11px] sm:text-xs rounded-md transition-all whitespace-nowrap <?= $timeFilter === 'all_time' ? 'bg-emerald-600 text-white shadow-sm' : 'text-slate-400 hover:text-slate-200' ?>">
                        <?= e(get_text('tab_all_time', 'ALL TIME')) ?>
                    </a>
                    <a href="?time=today&cat=<?= urlencode($categorySlug) ?>" class="px-2.5 sm:px-3 py-1 text-[11px] sm:text-xs rounded-md transition-all whitespace-nowrap <?= $timeFilter === 'today' ? 'bg-emerald-600 text-white shadow-sm' : 'text-slate-400 hover:text-slate-200' ?>">
                        <?= e(get_text('tab_today', 'TODAY')) ?>
                    </a>
                </div>
            </div>

            <!-- Right: Navigation Links & Actions -->
            <div class="flex items-center gap-2 sm:gap-4 shrink-0">
                <!-- Nav Menu (Desktop) -->
                <nav class="hidden md:flex items-center gap-4 text-xs font-medium text-slate-300">
                    <?php foreach ($menuItems as $item): 
                        $isModalLink = in_array(strtolower(trim($item['title'])), ['rules', 'terms', 'privacy', 'live stats']);
                        $slug = strtolower(str_replace(' ', '', $item['title']));
                    ?>
                        <?php if ($isModalLink && isset($pages[$slug])): ?>
                            <button onclick="openPageModal('<?= $slug ?>')" class="hover:text-white transition-colors py-1 cursor-pointer"><?= e($item['title']) ?></button>
                        <?php else: ?>
                            <a href="<?= e($item['url']) ?>" target="<?= e($item['target']) ?>" class="hover:text-white transition-colors py-1"><?= e($item['title']) ?></a>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </nav>

                <!-- Refresh Action -->
                <button onclick="window.location.reload()" title="Refresh Rankings" class="p-1.5 sm:p-2 rounded-lg bg-[#141A20] hover:bg-[#1C242C] border border-[#222A33] text-slate-300 hover:text-white transition-all active:scale-95 cursor-pointer">
                    <svg class="w-3.5 h-3.5 sm:w-4 sm:h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
                </button>

                <!-- Mobile Menu Button -->
                <button onclick="document.getElementById('mobile-menu').classList.toggle('hidden')" class="md:hidden p-1.5 sm:p-2 rounded-lg bg-[#141A20] border border-[#222A33] text-slate-300 cursor-pointer">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"/></svg>
                </button>
            </div>
        </div>

        <!-- Mobile Dropdown Menu -->
        <div id="mobile-menu" class="hidden md:hidden border-t border-[#222A33] bg-[#0E1216] px-4 py-3 animate-in slide-in-from-top-2">
            <div class="grid grid-cols-2 gap-2 text-xs">
                <?php foreach ($menuItems as $item): 
                    $isModalLink = in_array(strtolower(trim($item['title'])), ['rules', 'terms', 'privacy', 'live stats']);
                    $slug = strtolower(str_replace(' ', '', $item['title']));
                ?>
                    <?php if ($isModalLink && isset($pages[$slug])): ?>
                        <button onclick="openPageModal('<?= $slug ?>')" class="px-3 py-2.5 rounded-lg bg-[#141A20] hover:bg-[#1A222A] border border-[#222A33] text-left text-slate-300 hover:text-white font-medium transition-colors cursor-pointer">
                            <?= e($item['title']) ?>
                        </button>
                    <?php else: ?>
                        <a href="<?= e($item['url']) ?>" target="<?= e($item['target']) ?>" class="px-3 py-2.5 rounded-lg bg-[#141A20] hover:bg-[#1A222A] border border-[#222A33] text-left text-slate-300 hover:text-white font-medium transition-colors">
                            <?= e($item['title']) ?>
                        </a>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
        </div>
    </header>

    <!-- Dynamic Live Visitor Sub-Bar -->
    <div id="visitor-stats-bar" class="w-full border-b py-2 px-4 transition-colors" style="background-color: var(--header-bg); border-color: var(--border-color);">
        <div class="max-w-7xl mx-auto flex items-center justify-center text-center">
            <div class="inline-flex items-center gap-2 flex-wrap justify-center text-xs sm:text-sm font-medium">
                <span class="inline-flex items-center gap-1.5 font-semibold text-emerald-400">
                    <span class="relative flex h-2 w-2">
                        <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                        <span class="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
                    </span>
                    <span class="font-mono" id="visitor-count-val"><?= $liveVisitors ?></span>
                    <span>online</span>
                </span>
                <span class="text-slate-600 font-bold select-none">·</span>
                <span class="text-slate-300">
                    <span class="font-mono font-semibold text-slate-100">1,317,974</span> visitors since launch
                </span>
            </div>
        </div>
    </div>

    <!-- Main Content Area -->
    <main class="flex-1 w-full">
        <!-- Claim #1 Hero Section -->
        <section class="pt-8 pb-6 px-4 max-w-5xl mx-auto text-center">
            <div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-emerald-950/60 border border-emerald-700/40 text-emerald-400 text-xs font-medium mb-4">
                <span>🔥 Bangladesh's #1 Live Outbid Board</span>
                <?php if ($topListing): ?>
                    <span class="text-slate-400 border-l border-emerald-800 pl-2">
                        Leader: <strong class="text-white"><?= e($topListing['name']) ?></strong>
                    </span>
                <?php endif; ?>
            </div>

            <h1 class="text-3xl sm:text-5xl font-black tracking-tight text-white font-mono">
                <?= e(get_text('claim_hero_title', 'Claim #1 for')) ?>
                <span class="text-transparent bg-clip-text bg-gradient-to-r from-emerald-400 via-teal-300 to-amber-300">
                    <?= $currency ?><?= number_format($nextTopBid, 0) ?>
                </span>
            </h1>

            <p class="mt-3 text-sm sm:text-base text-slate-400 max-w-2xl mx-auto leading-relaxed">
                <?= e(get_text('claim_hero_desc')) ?>
            </p>

            <div class="mt-5 flex flex-wrap items-center justify-center gap-3">
                <button onclick="openOutbidModal(<?= $topListing ? (int)$topListing['id'] : 0 ?>, '<?= e($topListing ? $topListing['name'] : '#1 Spot') ?>', <?= $currentTopBid ?>)" class="px-6 py-3 rounded-xl bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 text-white font-bold text-sm sm:text-base shadow-lg shadow-emerald-950/60 transition-all cursor-pointer">
                    🏆 <?= e(get_text('outbid_btn_text', 'OUTBID')) ?> #1 SPOT ↗
                </button>
            </div>
        </section>

        <!-- Category Navigation & More Categories Trigger -->
        <div class="max-w-5xl mx-auto px-4 mt-2 mb-6">
            <div class="flex items-center gap-1.5 overflow-x-auto no-scrollbar py-2">
                <a href="?time=<?= urlencode($timeFilter) ?>&cat=all" class="flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-all <?= $categorySlug === 'all' ? 'bg-emerald-600 text-white' : 'bg-[#141A20] text-slate-400 border border-[#222A33]' ?>">
                    <span><?= e(get_text('category_all', 'ALL')) ?></span>
                </a>
                <?php foreach (array_slice($categories, 0, 7) as $cat): ?>
                    <a href="?time=<?= urlencode($timeFilter) ?>&cat=<?= urlencode($cat['slug']) ?>" class="flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-all <?= $categorySlug === $cat['slug'] ? 'bg-emerald-600 text-white' : 'bg-[#141A20] text-slate-400 border border-[#222A33]' ?>">
                        <span><?= e($cat['name']) ?></span>
                    </a>
                <?php endforeach; ?>

                <?php if (count($categories) > 7): ?>
                    <button onclick="openMoreCategoriesModal()" class="flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap bg-[#141A20] hover:bg-[#1C242C] text-amber-400 border border-amber-500/30 cursor-pointer">
                        <span><?= e(get_text('category_more', 'More Categories')) ?> ▼</span>
                    </button>
                <?php endif; ?>
            </div>
        </div>

        <!-- Ranking Listings -->
        <div id="ranking-list" class="max-w-4xl mx-auto px-4 space-y-2.5 pb-8">
            <?php if (empty($rankingData['listings'])): ?>
                <div class="p-12 text-center text-slate-400 bg-[#13181D] rounded-2xl border border-[#222A33]">
                    No listings found in this category. Be the first to claim it!
                </div>
            <?php else: ?>
                <?php foreach ($rankingData['listings'] as $listing): 
                    $rank = (int)$listing['rank'];
                    $isRank1 = ($rank === 1);
                    $isRank2 = ($rank === 2);
                    $isRank3 = ($rank === 3);

                    $cardBg = 'var(--card-color)';
                    $cardBorder = 'var(--border-color)';
                    if ($isRank1) { $cardBg = 'var(--rank1-bg)'; $cardBorder = 'var(--rank1-border)'; }
                    elseif ($isRank2) { $cardBg = 'var(--rank2-bg)'; }
                    elseif ($isRank3) { $cardBg = 'var(--rank3-bg)'; }
                ?>
                    <div class="rounded-xl sm:rounded-2xl border p-3 sm:p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-3.5 transition-all" style="background-color: <?= $cardBg ?>; border-color: <?= $cardBorder ?>;">
                        <div class="flex items-center gap-3 sm:gap-4 min-w-0 flex-1">
                            <div class="w-9 h-9 sm:w-10 sm:h-10 shrink-0 rounded-xl border flex items-center justify-center font-mono font-bold text-sm <?= $isRank1 ? 'text-amber-300 bg-amber-950/80 border-amber-500' : 'text-slate-400 bg-slate-800 border-slate-700' ?>">
                                <?= $isRank1 ? '👑' : '#' . $rank ?>
                            </div>

                            <img src="<?= e($listing['image_url']) ?>" alt="" class="w-12 h-12 sm:w-14 sm:h-14 rounded-xl object-cover border border-slate-700 bg-slate-900 shrink-0" />

                            <div class="min-w-0 flex-1">
                                <div class="flex items-center gap-2 flex-wrap">
                                    <h3 class="text-sm sm:text-base font-bold text-white truncate"><?= e($listing['name']) ?></h3>
                                </div>
                                <a href="<?= e($listing['url']) ?>" target="_blank" onclick="trackClick(<?= (int)$listing['id'] ?>)" class="text-xs text-slate-400 hover:text-emerald-400 truncate block mt-0.5">
                                    <?= e($listing['url']) ?> ↗
                                </a>
                                <div class="flex items-center gap-1.5 text-[11px] text-slate-400 mt-1 font-medium select-none flex-wrap">
                                    <span><?= format_bid_age($listing['last_bid_at'] ?? $listing['created_at'] ?? '') ?></span>
                                    <span class="text-slate-600 font-bold">•</span>
                                    <span class="text-emerald-400 font-medium">
                                        #<?= (int)($listing['category_rank'] ?? 1) ?> in <?= e($listing['category_name']) ?>
                                    </span>
                                </div>
                            </div>
                        </div>

                        <div class="flex items-center justify-between sm:justify-end gap-3 sm:gap-4 border-t sm:border-t-0 pt-2 sm:pt-0 border-slate-800">
                            <div class="flex items-center gap-2 text-xs">
                                <span class="bg-slate-900/60 px-2.5 py-1 rounded-lg border border-slate-800 text-slate-400 font-mono text-[11px]">
                                    Clicks <span id="clicks-<?= $listing['id'] ?>"><?= number_format($listing['clicks']) ?></span>
                                </span>
                                <button onclick="trackHeart(<?= (int)$listing['id'] ?>)" class="bg-slate-900/60 hover:bg-rose-950/40 px-2 py-1 rounded-lg border border-slate-800 text-rose-400 font-mono cursor-pointer">
                                    ❤️ <span id="hearts-<?= $listing['id'] ?>"><?= number_format($listing['hearts']) ?></span>
                                </button>
                            </div>

                            <div class="flex items-center gap-2.5">
                                <div class="text-right">
                                    <div class="text-[10px] uppercase text-slate-500 font-semibold"><?= e(get_text('current_bid_label', 'Current Bid')) ?></div>
                                    <div class="text-sm sm:text-base font-black font-mono text-emerald-400">
                                        <?= $currency ?><?= number_format($listing['current_bid'], 0) ?>
                                    </div>
                                </div>

                                <button onclick="openOutbidModal(<?= (int)$listing['id'] ?>, '<?= e($listing['name']) ?>', <?= (float)$listing['current_bid'] ?>)" class="px-3.5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs sm:text-sm shadow-md cursor-pointer">
                                    <?= e(get_text('outbid_btn_text', 'OUTBID')) ?>
                                </button>
                            </div>
                        </div>
                    </div>

                    <?php if ($rank === 3 && count($rankingData['listings']) > 3): ?>
                        <div class="py-2.5 flex items-center gap-3">
                            <div class="flex-1 h-px bg-[#2A3744]"></div>
                            <span class="text-[11px] font-mono font-bold tracking-widest text-amber-400 uppercase px-3 py-0.5 rounded-full bg-[#13181D] border border-amber-500/20">TOP 3</span>
                            <div class="flex-1 h-px bg-[#2A3744]"></div>
                        </div>
                    <?php elseif ($rank === 10 && count($rankingData['listings']) > 10): ?>
                        <div class="py-2.5 flex items-center gap-3">
                            <div class="flex-1 h-px bg-[#2A3744]"></div>
                            <span class="text-[11px] font-mono font-bold tracking-widest text-slate-400 uppercase px-3 py-0.5 rounded-full bg-[#13181D] border border-slate-700">TOP 10</span>
                            <div class="flex-1 h-px bg-[#2A3744]"></div>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>

                <!-- Pagination (50 Items Per Page) -->
                <?php if ($rankingData['totalPages'] > 1): ?>
                    <div class="pt-6 flex items-center justify-center gap-2 text-xs font-semibold font-mono">
                        <?php if ($page > 1): ?>
                            <a href="?time=<?= urlencode($timeFilter) ?>&cat=<?= urlencode($categorySlug) ?>&page=<?= $page - 1 ?>" class="px-3 py-1.5 rounded-lg bg-[#141A20] border border-[#222A33] text-slate-300 hover:text-white">← Previous</a>
                        <?php endif; ?>
                        
                        <span class="px-3 py-1.5 rounded-lg bg-emerald-950 text-emerald-300 border border-emerald-700/60">
                            Page <?= $page ?> of <?= $rankingData['totalPages'] ?>
                        </span>

                        <?php if ($page < $rankingData['totalPages']): ?>
                            <a href="?time=<?= urlencode($timeFilter) ?>&cat=<?= urlencode($categorySlug) ?>&page=<?= $page + 1 ?>" class="px-3 py-1.5 rounded-lg bg-[#141A20] border border-[#222A33] text-slate-300 hover:text-white">Next →</a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <!-- Total Revenue Banner -->
        <section class="max-w-4xl mx-auto px-4 my-8">
            <div class="rounded-2xl bg-gradient-to-b from-[#141B20] to-[#0D1216] border border-[#222A33] p-6 sm:p-8 text-center space-y-2">
                <div class="text-xs font-semibold text-slate-400 uppercase tracking-wider font-mono">
                    <?= e(get_text('total_generated_prefix', 'TOPBD has generated')) ?>
                </div>
                <div class="text-3xl sm:text-5xl font-black font-mono text-white">
                    <span class="text-transparent bg-clip-text bg-gradient-to-r from-emerald-400 via-teal-200 to-amber-300">
                        <?= $currency ?><?= number_format($totalGenerated, 0) ?>
                    </span>
                </div>
                <p class="text-xs text-slate-500">
                    <?= e(get_text('total_generated_suffix', 'in verified bids since launch')) ?>
                </p>
            </div>
        </section>
    </main>

    <!-- Footer -->
    <footer class="border-t py-8 mt-auto" style="background-color: var(--footer-bg); border-color: var(--border-color);">
        <div class="max-w-7xl mx-auto px-4 flex flex-col sm:flex-row items-center justify-between gap-4 text-xs text-slate-400">
            <div>
                <?php if (($settings['developer_enabled'] ?? '1') === '1'): ?>
                    <button onclick="openDeveloperModal()" class="hover:text-emerald-400 font-semibold cursor-pointer underline underline-offset-4 decoration-slate-700">
                        <?= e(get_text('footer_attribution', 'Built by @arafat')) ?>
                    </button>
                <?php else: ?>
                    <span><?= e(get_text('footer_attribution', 'Built by @arafat')) ?></span>
                <?php endif; ?>
                <span><?= e(get_text('footer_brand_tagline', '· Brought to you by TOPBD')) ?></span>
            </div>
            <div class="flex items-center gap-4 sm:gap-5 font-medium">
                <button onclick="openPageModal('rules')" class="hover:text-white transition-colors cursor-pointer">Rules</button>
                <span class="text-slate-600">·</span>
                <button onclick="openPageModal('terms')" class="hover:text-white transition-colors cursor-pointer">Terms</button>
                <span class="text-slate-600">·</span>
                <button onclick="openPageModal('privacy')" class="hover:text-white transition-colors cursor-pointer">Privacy</button>
            </div>
        </div>
    </footer>

    <!-- OUTBID MODAL -->
    <div id="outbid-modal" class="fixed inset-0 z-50 hidden flex items-center justify-center p-3 sm:p-4 bg-black/80 backdrop-blur-sm overflow-y-auto">
        <div class="w-full max-w-lg rounded-2xl bg-[#13181D] border border-[#2A3440] p-4 sm:p-6 shadow-2xl space-y-4 max-h-[94vh] overflow-y-auto">
            <div class="flex items-center justify-between border-b border-[#222A33] pb-3">
                <h3 class="font-bold text-white text-base">Outbid & Claim Spot</h3>
                <button onclick="closeOutbidModal()" class="text-slate-400 hover:text-white text-lg cursor-pointer">&times;</button>
            </div>

            <form id="outbid-form" onsubmit="submitOutbid(event)" class="space-y-3.5 text-xs">
                <input type="hidden" id="modal-target-id" value="0" />

                <div class="p-3 rounded-xl bg-[#0A0D0F] border border-[#222A33]">
                    <div class="flex flex-col sm:grid sm:grid-cols-2 gap-2 sm:items-center">
                        <div class="min-w-0">
                            <span class="text-slate-400 block text-[10px] uppercase font-bold"><?= e(get_text('modal_target_label', 'TARGET')) ?>:</span>
                            <span id="modal-target-name" class="font-bold text-white truncate block">#1 Spot</span>
                        </div>
                        <div class="flex items-center justify-between sm:justify-end sm:border-l sm:border-slate-800 sm:pl-3 border-t sm:border-t-0 border-slate-800/80 pt-2 sm:pt-0">
                            <span class="text-emerald-400 block text-[10px] uppercase font-bold"><?= e(get_text('next_bid_label', 'Next Bid')) ?>:</span>
                            <span id="modal-min-bid" class="font-bold font-mono text-emerald-400 text-sm ml-2 whitespace-nowrap">৳10,001</span>
                        </div>
                    </div>
                </div>

                <div>
                    <label class="block text-slate-300 font-semibold mb-1">Business, Product or Creator Name</label>
                    <input type="text" id="modal-input-name" required placeholder="<?= e(get_text('modal_name_placeholder', 'Business, product or personal name')) ?>" class="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white focus:outline-none focus:border-emerald-500" />
                </div>

                <div>
                    <label class="block text-slate-300 font-semibold mb-1">Target URL</label>
                    <input type="url" id="modal-input-url" required placeholder="<?= e(get_text('modal_url_placeholder', 'https://yourwebsite.com or social profile')) ?>" class="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white focus:outline-none focus:border-emerald-500" />
                </div>

                <!-- Avatar Upload / URL -->
                <div>
                    <label class="block text-slate-300 font-semibold mb-1">Avatar / Logo Image (Square 1:1)</label>
                    <div class="flex gap-2">
                        <input type="url" id="modal-input-image" placeholder="https://images.unsplash.com/..." class="flex-1 px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white focus:outline-none" />
                        <label class="px-3 py-2 bg-[#1A222A] hover:bg-[#222D38] border border-[#2A3744] rounded-xl text-slate-300 cursor-pointer text-xs font-semibold whitespace-nowrap">
                            <span>📁 Upload</span>
                            <input type="file" id="modal-file-upload" accept="image/png,image/jpeg,image/webp" onchange="uploadImageFile(this)" class="hidden" />
                        </label>
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-slate-300 font-semibold mb-1">Category</label>
                        <select id="modal-input-cat" class="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white focus:outline-none">
                            <?php foreach ($categories as $c): ?>
                                <option value="<?= $c['id'] ?>"><?= e($c['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-slate-300 font-semibold mb-1"><?= e(get_text('additional_amount_label', 'Additional amount')) ?> (<?= $currency ?>)</label>
                        <input type="number" id="modal-input-extra" value="0" min="0" oninput="recalcTotal()" class="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono focus:outline-none focus:border-emerald-500" />
                    </div>
                </div>

                <div>
                    <label class="block text-slate-300 font-semibold mb-1"><?= e(get_text('payment_method_label', 'Select Payment Gateway')) ?></label>
                    <select id="modal-input-gw" class="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white focus:outline-none font-mono">
                        <?php foreach ($enabledGateways as $gw): ?>
                            <option value="<?= e($gw['gateway_id']) ?>"><?= e($gw['name']) ?> (<?= strtoupper($gw['mode']) ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <button type="submit" id="modal-submit-btn" class="w-full py-3 rounded-xl bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 text-white font-bold shadow-lg shadow-emerald-950/60 transition-all cursor-pointer">
                    Proceed to Verification Payment
                </button>
            </form>
        </div>
    </div>

    <!-- MORE CATEGORIES MODAL -->
    <div id="more-cats-modal" class="fixed inset-0 z-50 hidden flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm">
        <div class="w-full max-w-md rounded-2xl bg-[#13181D] border border-[#2A3440] p-6 shadow-2xl space-y-4 max-h-[85vh] flex flex-col">
            <div class="flex items-center justify-between border-b border-[#222A33] pb-3">
                <h3 class="font-bold text-white text-base">All Categories</h3>
                <button onclick="closeMoreCategoriesModal()" class="text-slate-400 hover:text-white text-lg">&times;</button>
            </div>
            <div class="overflow-y-auto space-y-2 flex-1 pr-1">
                <a href="?time=<?= urlencode($timeFilter) ?>&cat=all" class="flex items-center justify-between p-3 rounded-xl bg-[#0A0D0F] hover:bg-[#1A222A] border border-[#222A33] text-xs font-semibold text-white">
                    <span><?= e(get_text('category_all', 'ALL')) ?></span>
                    <span class="text-slate-500">View all</span>
                </a>
                <?php foreach ($categories as $cat): ?>
                    <a href="?time=<?= urlencode($timeFilter) ?>&cat=<?= urlencode($cat['slug']) ?>" class="flex items-center justify-between p-3 rounded-xl bg-[#0A0D0F] hover:bg-[#1A222A] border border-[#222A33] text-xs font-semibold text-white">
                        <span><?= e($cat['name']) ?></span>
                        <span class="text-emerald-400 font-mono">→</span>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- DEVELOPER ATTRIBUTION POPUP MODAL -->
    <div id="developer-modal" class="fixed inset-0 z-50 hidden flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm">
        <div class="w-full max-w-md rounded-2xl bg-[#13181D] border border-[#2A3440] p-6 shadow-2xl space-y-4">
            <div class="flex items-center justify-between border-b border-[#222A33] pb-3">
                <h3 class="font-bold text-white text-base">Creator Profile</h3>
                <button onclick="closeDeveloperModal()" class="text-slate-400 hover:text-white text-lg">&times;</button>
            </div>
            <div class="flex items-center gap-4">
                <img src="<?= e($settings['developer_image'] ?? 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=200&auto=format&fit=crop&q=80') ?>" class="w-16 h-16 rounded-2xl object-cover border border-slate-700 shadow-md" />
                <div>
                    <h4 class="font-bold text-base text-white"><?= e($settings['developer_name'] ?? 'Arafat Rahman') ?></h4>
                    <span class="text-xs font-mono text-emerald-400 font-semibold"><?= e($settings['developer_handle'] ?? '@arafat') ?></span>
                </div>
            </div>
            <p class="text-xs text-slate-300 leading-relaxed">
                <?= e($settings['developer_bio'] ?? 'Software engineer building real-time high-performance web applications and ranking engines in Bangladesh.') ?>
            </p>
            <div class="flex gap-2 pt-2 border-t border-[#222A33]">
                <?php if (!empty($settings['developer_github'])): ?>
                    <a href="<?= e($settings['developer_github']) ?>" target="_blank" class="flex-1 py-2 rounded-xl bg-[#0A0D0F] hover:bg-[#1A222A] border border-[#222A33] text-center text-xs font-semibold text-white">
                        GitHub Profile ↗
                    </a>
                <?php endif; ?>
                <?php if (!empty($settings['developer_twitter'])): ?>
                    <a href="<?= e($settings['developer_twitter']) ?>" target="_blank" class="flex-1 py-2 rounded-xl bg-[#0A0D0F] hover:bg-[#1A222A] border border-[#222A33] text-center text-xs font-semibold text-teal-400">
                        Twitter / X ↗
                    </a>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- CONTENT PAGES MODAL (RULES, TERMS, PRIVACY, STATS) -->
    <div id="content-modal" class="fixed inset-0 z-50 hidden flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm">
        <div class="w-full max-w-2xl rounded-2xl bg-[#13181D] border border-[#2A3440] p-6 shadow-2xl space-y-4 max-h-[85vh] flex flex-col">
            <div class="flex items-center justify-between border-b border-[#222A33] pb-3">
                <h3 id="content-modal-title" class="font-bold text-white text-base">Information</h3>
                <button onclick="closePageModal()" class="text-slate-400 hover:text-white text-lg">&times;</button>
            </div>
            <div id="content-modal-body" class="overflow-y-auto space-y-3 flex-1 text-xs sm:text-sm text-slate-300 leading-relaxed pr-1 font-sans">
                <!-- Injected via JavaScript -->
            </div>
        </div>
    </div>

    <!-- Frontend AJAX Scripts -->
    <script>
        let currentTargetBid = 0;
        const minIncrement = <?= $minInc ?>;
        const currencySym = '<?= $currency ?>';
        const pageData = <?= json_encode($pages) ?>;

        function openOutbidModal(targetId, targetName, currentBid) {
            document.getElementById('modal-target-id').value = targetId;
            document.getElementById('modal-target-name').innerText = targetName;
            currentTargetBid = currentBid;
            recalcTotal();
            document.getElementById('outbid-modal').classList.remove('hidden');
        }

        function closeOutbidModal() {
            document.getElementById('outbid-modal').classList.add('hidden');
        }

        function openMoreCategoriesModal() {
            document.getElementById('more-cats-modal').classList.remove('hidden');
        }

        function closeMoreCategoriesModal() {
            document.getElementById('more-cats-modal').classList.add('hidden');
        }

        function openDeveloperModal() {
            document.getElementById('developer-modal').classList.remove('hidden');
        }

        function closeDeveloperModal() {
            document.getElementById('developer-modal').classList.add('hidden');
        }

        function openPageModal(slug) {
            const modal = document.getElementById('content-modal');
            const titleEl = document.getElementById('content-modal-title');
            const bodyEl = document.getElementById('content-modal-body');

            if (pageData[slug]) {
                titleEl.innerText = pageData[slug].title;
                bodyEl.innerHTML = pageData[slug].content;
            } else {
                titleEl.innerText = slug.toUpperCase();
                bodyEl.innerText = 'Content details for ' + slug;
            }
            modal.classList.remove('hidden');
        }

        function closePageModal() {
            document.getElementById('content-modal').classList.add('hidden');
        }

        function recalcTotal() {
            const extra = Math.max(0, parseFloat(document.getElementById('modal-input-extra').value) || 0);
            const minNext = currentTargetBid + minIncrement;
            const total = minNext + extra;
            document.getElementById('modal-min-bid').innerText = currencySym + total.toLocaleString();
        }

        async function uploadImageFile(input) {
            if (!input.files || !input.files[0]) return;
            const formData = new FormData();
            formData.append('image', input.files[0]);

            try {
                const res = await fetch('/api/upload.php', { method: 'POST', body: formData });
                const data = await res.json();
                if (data.success && data.image_url) {
                    document.getElementById('modal-input-image').value = data.image_url;
                } else {
                    alert(data.message || 'Image upload failed');
                }
            } catch (e) {
                alert('Upload network error');
            }
        }

        async function trackClick(id) {
            try {
                const res = await fetch('/api/click.php?action=click&listing_id=' + id);
                const data = await res.json();
                if (data.success) {
                    const el = document.getElementById('clicks-' + id);
                    if (el) el.innerText = data.clicks.toLocaleString();
                }
            } catch (e) {}
        }

        async function trackHeart(id) {
            try {
                const res = await fetch('/api/click.php?action=heart&listing_id=' + id);
                const data = await res.json();
                if (data.success) {
                    const el = document.getElementById('hearts-' + id);
                    if (el) el.innerText = data.hearts.toLocaleString();
                }
            } catch (e) {}
        }

        async function submitOutbid(e) {
            e.preventDefault();
            const btn = document.getElementById('modal-submit-btn');
            btn.disabled = true;
            btn.innerText = 'Initializing payment...';

            const payload = {
                target_id: document.getElementById('modal-target-id').value,
                name: document.getElementById('modal-input-name').value,
                url: document.getElementById('modal-input-url').value,
                image_url: document.getElementById('modal-input-image').value,
                category_id: document.getElementById('modal-input-cat').value,
                additional_amount: document.getElementById('modal-input-extra').value,
                gateway: document.getElementById('modal-input-gw').value
            };

            try {
                const res = await fetch('/api/payment.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
                const data = await res.json();

                if (data.success && data.checkout_url) {
                    window.location.href = data.checkout_url;
                } else {
                    alert(data.message || 'Payment initialization failed.');
                    btn.disabled = false;
                    btn.innerText = 'Proceed to Verification Payment';
                }
            } catch (err) {
                alert('Network connection error.');
                btn.disabled = false;
                btn.innerText = 'Proceed to Verification Payment';
            }
        }

        // Live Heartbeat polling every 10s
        setInterval(async () => {
            try {
                const res = await fetch('/api/visitors.php');
                const data = await res.json();
                if (data.success && typeof data.visitors !== 'undefined') {
                    const el = document.getElementById('visitor-count-val');
                    if (el) el.innerText = data.visitors;
                }
            } catch (e) {}
        }, 10000);
    </script>
</body>
</html>
