<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Weekly Tournament';
include 'side.php';

// ── Week boundaries (Mon 00:00 → Sun 23:59) ──
$now       = new DateTime('now', new DateTimeZone('Africa/Nairobi'));
$dayOfWeek = intval($now->format('N'));
$weekStart = clone $now;
$weekStart->modify('-' . ($dayOfWeek - 1) . ' days')->setTime(0, 0, 0);
$weekEnd   = clone $weekStart;
$weekEnd->modify('+6 days')->setTime(23, 59, 59);

$wsStr = $weekStart->format('Y-m-d H:i:s');
$weStr = $weekEnd->format('Y-m-d H:i:s');
$nextSunday = clone $weekEnd;
$nextSunday->setTime(23, 59, 59);

// ── Weekly Prize configuration ──
$prizes = [
    1 => ['amount' => 3000, 'label' => '1st Place', 'icon' => '🥇', 'min_referrals' => 3000],
    2 => ['amount' => 2000, 'label' => '2nd Place', 'icon' => '🥈', 'min_referrals' => 3000],
    3 => ['amount' => 1000, 'label' => '3rd Place', 'icon' => '🥉', 'min_referrals' => 3000],
];
$minReferralsForPrize = 3000;

// ── Grand Prize configuration ──
$grandPrize = ['amount' => 10000, 'target' => 7000, 'slots' => 3];

// ── Leaderboard (weekly) ──
$lbQuery = $conn->prepare("
    SELECT r.id, r.username, r.country,
           COUNT(DISTINCT u.id) AS active_referrals
    FROM users r
    INNER JOIN users u
        ON  u.referred_by = r.id
        AND u.status = 'active'
        AND u.activation_date >= ?
        AND u.activation_date <= ?
    GROUP BY r.id, r.username, r.country
    HAVING active_referrals > 0
    ORDER BY active_referrals DESC
    LIMIT 10000
");
$lbQuery->bind_param("ss", $wsStr, $weStr);
$lbQuery->execute();
$leaderboard = $lbQuery->get_result()->fetch_all(MYSQLI_ASSOC);

// ── Create tables if not exist ──
$conn->query("CREATE TABLE IF NOT EXISTS tournament_awards (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    week_start DATE NOT NULL,
    rank_position INT NOT NULL,
    prize_amount DECIMAL(10,2) NOT NULL,
    active_referrals INT NOT NULL,
    awarded_at DATETIME DEFAULT NOW(),
    UNIQUE KEY unique_week_rank (week_start, rank_position)
)");
$conn->query("CREATE TABLE IF NOT EXISTS grand_prize_awards (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL UNIQUE,
    active_referrals INT NOT NULL,
    awarded_at DATETIME DEFAULT NOW()
)");

$weekStartDate = $weekStart->format('Y-m-d');

// Load weekly awards already given
$existingAwards = $conn->prepare("SELECT rank_position, user_id, prize_amount FROM tournament_awards WHERE week_start=?");
$existingAwards->bind_param("s", $weekStartDate);
$existingAwards->execute();
$existingAwardsData = [];
while ($row = $existingAwards->get_result()->fetch_assoc()) {
    $existingAwardsData[$row['rank_position']] = $row;
}

// ── Grand Prize ──
// Only referrals activated on or after the grand prize launch date count
$gpStartDate = '2026-05-20 00:00:00';

$gpAwarded = [];
$gpRes = $conn->query("SELECT user_id FROM grand_prize_awards ORDER BY awarded_at ASC LIMIT 3");
while ($r = $gpRes->fetch_assoc()) $gpAwarded[] = intval($r['user_id']);
$gpSlotsRemaining = max(0, $grandPrize['slots'] - count($gpAwarded));

$gpQuery = $conn->prepare("
    SELECT r.id, r.username, r.country, COUNT(DISTINCT u.id) AS active_referrals
    FROM users r
    INNER JOIN users u
        ON  u.referred_by = r.id
        AND u.status = 'active'
        AND u.activation_date >= ?
    GROUP BY r.id, r.username, r.country
    HAVING active_referrals > 0
    ORDER BY active_referrals DESC LIMIT 1000000
");
$gpQuery->bind_param("s", $gpStartDate);
$gpQuery->execute();
$gpAllLeaders = $gpQuery->get_result()->fetch_all(MYSQLI_ASSOC);

$gpDisplaySlots = [];
foreach ($gpAwarded as $awardedUid) {
    foreach ($gpAllLeaders as $gl) {
        if (intval($gl['id']) == $awardedUid) { $gpDisplaySlots[] = array_merge($gl, ['claimed'=>true]); break; }
    }
}
foreach ($gpAllLeaders as $gl) {
    if (count($gpDisplaySlots) >= 3) break;
    if (!in_array(intval($gl['id']), $gpAwarded)) $gpDisplaySlots[] = array_merge($gl, ['claimed'=>false]);
}
while (count($gpDisplaySlots) < 3) $gpDisplaySlots[] = null;

// Current user's GP referrals — only from launch date onwards
$myGpStmt = $conn->prepare("SELECT COUNT(*) as c FROM users WHERE referred_by=? AND status='active' AND activation_date >= ?");
$myGpStmt->bind_param("is", $userId, $gpStartDate);
$myGpStmt->execute();
$myAllTimeActive = intval($myGpStmt->get_result()->fetch_assoc()['c'] ?? 0);

$myGpAwarded   = in_array($userId, $gpAwarded);
$myGpQualifies = $myAllTimeActive >= $grandPrize['target'];
$myGpPct       = min(100, round($myAllTimeActive / $grandPrize['target'] * 100));
$myGpNeeds     = max(0, $grandPrize['target'] - $myAllTimeActive);

// Current user weekly rank
$myRank = 0; $myActive = 0;
foreach ($leaderboard as $idx => $row) {
    if ($row['id'] == $userId) { $myRank = $idx+1; $myActive = intval($row['active_referrals']); break; }
}

$myAllTime  = intval($conn->query("SELECT COUNT(*) as c FROM users WHERE referred_by=$userId AND status='active'")->fetch_assoc()['c'] ?? 0);
$stmt       = $conn->prepare("SELECT currency_symbol FROM countries WHERE name=?");
$stmt->bind_param("s", $userData['country']); $stmt->execute();
$cs         = $stmt->get_result()->fetch_assoc()['currency_symbol'] ?? 'Ksh';
$weekLabel  = $weekStart->format('M j') . ' – ' . $weekEnd->format('M j, Y');
$themeColor = getSetting('theme_color', '#6366f1');

$myQualifies = ($myRank >= 1 && $myRank <= 3 && $myActive >= $minReferralsForPrize);
$myNeeds     = max(0, $minReferralsForPrize - $myActive);
?>
<style>
/* ─── DARK MODE VARIABLES (default) ─── */
:root, [data-theme="dark"] {
    --tn-page-bg:      #0f1117;
    --tn-card:         #1a1d27;
    --tn-card2:        #22263a;
    --tn-border:       #2e3347;
    --tn-text:         #f1f5f9;
    --tn-text-sub:     #94a3b8;
    --tn-text-muted:   #64748b;
    --tn-row-hover:    #1e2236;
    /* Gold */
    --tn-gold:         #fbbf24;
    --tn-gold-dim:     #d97706;
    --tn-gold-bg:      #1c1608;
    --tn-gold-border:  #854d0e;
    /* Silver */
    --tn-silver:       #cbd5e1;
    --tn-silver-dim:   #94a3b8;
    --tn-silver-bg:    #161b26;
    --tn-silver-border:#334155;
    /* Bronze */
    --tn-bronze:       #fb923c;
    --tn-bronze-dim:   #ea580c;
    --tn-bronze-bg:    #1c0e06;
    --tn-bronze-border:#7c2d12;
    /* Blue — grand prize */
    --tn-blue:         #38bdf8;
    --tn-blue-dim:     #0ea5e9;
    --tn-blue-bg:      #061520;
    --tn-blue-border:  #0c4a6e;
    --tn-blue-text:    #7dd3fc;
    /* Green */
    --tn-green:        #34d399;
    --tn-green-bg:     #052e16;
    --tn-green-border: #065f46;
    /* Amber warning */
    --tn-amber:        #fbbf24;
    --tn-amber-bg:     #1c1204;
    --tn-amber-border: #92400e;
    /* Shadow */
    --tn-shadow:       rgba(0,0,0,.5);
}

/* ─── LIGHT MODE VARIABLES ─── */
[data-theme="light"] {
    --tn-page-bg:      #f1f5f9;
    --tn-card:         #ffffff;
    --tn-card2:        #f8fafc;
    --tn-border:       #e2e8f0;
    --tn-text:         #0f172a;
    --tn-text-sub:     #334155;
    --tn-text-muted:   #64748b;
    --tn-row-hover:    #f8fafc;
    /* Gold */
    --tn-gold:         #92400e;
    --tn-gold-dim:     #b45309;
    --tn-gold-bg:      #fffbeb;
    --tn-gold-border:  #fde68a;
    /* Silver */
    --tn-silver:       #1e293b;
    --tn-silver-dim:   #475569;
    --tn-silver-bg:    #f8fafc;
    --tn-silver-border:#cbd5e1;
    /* Bronze */
    --tn-bronze:       #9a3412;
    --tn-bronze-dim:   #c2410c;
    --tn-bronze-bg:    #fff7ed;
    --tn-bronze-border:#fed7aa;
    /* Blue */
    --tn-blue:         #0369a1;
    --tn-blue-dim:     #0284c7;
    --tn-blue-bg:      #eff6ff;
    --tn-blue-border:  #93c5fd;
    --tn-blue-text:    #1e40af;
    /* Green */
    --tn-green:        #059669;
    --tn-green-bg:     #ecfdf5;
    --tn-green-border: #6ee7b7;
    /* Amber */
    --tn-amber:        #92400e;
    --tn-amber-bg:     #fffbeb;
    --tn-amber-border: #fde68a;
    /* Shadow */
    --tn-shadow:       rgba(0,0,0,.08);
}

/* ─── BASE ─── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
.tn-page { padding: 14px; overflow-x: hidden; }
@media(max-width:480px){ .tn-page { padding: 10px; } }

@keyframes tnUp { from { opacity:0; transform:translateY(14px) } to { opacity:1; transform:translateY(0) } }
@keyframes crownFloat { 0%,100%{ transform:translateY(0) } 50%{ transform:translateY(-5px) } }
@keyframes pulseGold { 0%,100%{ box-shadow:0 0 0 0 rgba(251,191,36,.5) } 60%{ box-shadow:0 0 0 10px rgba(251,191,36,0) } }

/* ─── SHARED CARD ─── */
.tn-card {
    background: var(--tn-card);
    border: 1.5px solid var(--tn-border);
    border-radius: 16px;
    box-shadow: 0 4px 24px var(--tn-shadow);
    padding: 18px 16px;
    margin-bottom: 12px;
}
.tn-eyebrow {
    display: inline-flex; align-items: center; gap: 6px;
    font-size: 10px; font-weight: 800; letter-spacing: 2px; text-transform: uppercase;
    padding: 4px 12px; border-radius: 20px;
    background: var(--tn-card2); border: 1.5px solid var(--tn-border);
    color: var(--tn-text-sub);
    margin-bottom: 10px;
}
.tn-amount-huge {
    font-size: 34px; font-weight: 900; letter-spacing: -1.5px;
    line-height: 1; margin-bottom: 4px;
}
.tn-desc { font-size: 12px; color: var(--tn-text-sub); line-height: 1.5; margin-bottom: 4px; }
.tn-note { font-size: 11px; color: var(--tn-text-muted); margin-bottom: 14px; }
.tn-note strong { color: var(--tn-text-sub); font-weight: 700; }
.tn-divider { height: 1px; background: var(--tn-border); margin: 10px 0; }

/* ─── GRAND PRIZE BANNER ─── */
.tn-gp-banner {
    background: var(--tn-blue-bg);
    border-color: var(--tn-blue-border);
    animation: tnUp .4s ease both;
}
.tn-gp-banner .tn-eyebrow { color: var(--tn-blue-text); border-color: var(--tn-blue-border); background: var(--tn-card); }
.tn-gp-banner .tn-amount-huge { color: var(--tn-blue-text); }
.tn-gp-banner .tn-note strong { color: var(--tn-blue-text); }

.tn-gp-slots { display: flex; gap: 8px; margin-bottom: 14px; }
.tn-gp-slot {
    flex: 1; border-radius: 12px; padding: 13px 9px; text-align: center;
    background: var(--tn-card);
    border: 1.5px solid var(--tn-blue-border);
    transition: transform .15s;
}
.tn-gp-slot:hover { transform: translateY(-2px); }
.tn-gp-slot.claimed {
    background: var(--tn-green-bg);
    border-color: var(--tn-green-border);
}
.tn-gp-slot.open {
    background: var(--tn-card2);
    border-color: var(--tn-border);
    opacity: .7;
}
.tn-gp-slot-icon { font-size: 20px; display: block; margin-bottom: 5px; }
.tn-gp-slot-label { font-size: 9px; font-weight: 800; text-transform: uppercase; letter-spacing: .8px; color: var(--tn-text-muted); margin-bottom: 4px; }
.tn-gp-slot-amt { font-size: 17px; font-weight: 900; color: var(--tn-blue-text); letter-spacing: -1px; line-height: 1; margin-bottom: 2px; }
.tn-gp-slot.claimed .tn-gp-slot-amt { color: var(--tn-green); }
.tn-gp-slot-cur { font-size: 8.5px; font-weight: 700; color: var(--tn-text-muted); text-transform: uppercase; margin-bottom: 8px; }
.tn-gp-slot-sep { height: 1px; background: var(--tn-border); margin-bottom: 8px; }
.tn-gp-slot-lbl2 { font-size: 8.5px; font-weight: 600; text-transform: uppercase; letter-spacing: .4px; color: var(--tn-text-muted); margin-bottom: 3px; }
.tn-gp-slot-name { font-size: 10px; font-weight: 800; color: var(--tn-blue-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.tn-gp-slot.claimed .tn-gp-slot-name { color: var(--tn-green); }
.tn-gp-slot-refs { font-size: 9px; color: var(--tn-text-muted); margin-top: 2px; }
.tn-gp-slot-open { font-size: 10px; color: var(--tn-text-muted); font-style: italic; }
.tn-gp-claimed-badge {
    display: inline-flex; align-items: center; gap: 3px;
    background: var(--tn-green-bg); border: 1px solid var(--tn-green-border);
    color: var(--tn-green); border-radius: 6px;
    font-size: 9px; font-weight: 700; padding: 3px 8px; margin-top: 5px;
}

/* GP Progress */
.tn-gp-progress {
    background: var(--tn-card);
    border: 1.5px solid var(--tn-blue-border);
    border-radius: 12px; padding: 12px 14px;
}
.tn-gp-prog-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.tn-gp-prog-label { font-size: 12px; font-weight: 700; color: var(--tn-text); }
.tn-gp-prog-val { font-size: 12px; font-weight: 800; color: var(--tn-blue-text); }
.tn-prog-track { height: 8px; background: var(--tn-border); border-radius: 99px; overflow: hidden; margin-bottom: 6px; }
.tn-prog-fill-blue { height: 100%; border-radius: 99px; background: linear-gradient(90deg, var(--tn-blue-dim), var(--tn-blue)); transition: width .8s ease; }
.tn-gp-prog-note { font-size: 10.5px; color: var(--tn-text-muted); text-align: center; }
.tn-gp-prog-success { font-size: 12px; font-weight: 700; color: var(--tn-green); text-align: center; padding: 4px 0; }

/* ─── WEEKLY PRIZE BANNER ─── */
.tn-weekly-banner {
    background: var(--tn-gold-bg);
    border-color: var(--tn-gold-border);
    animation: tnUp .42s ease .04s both;
}
.tn-weekly-banner .tn-eyebrow { color: var(--tn-gold); border-color: var(--tn-gold-border); background: var(--tn-card); }
.tn-weekly-banner .tn-amount-huge { color: var(--tn-gold); }
.tn-weekly-banner .tn-note strong { color: var(--tn-gold-dim); }

.tn-prize-row { display: flex; gap: 8px; }
.tn-prize-slot {
    flex: 1; border-radius: 12px; padding: 13px 9px; text-align: center;
    background: var(--tn-card);
    border: 1.5px solid var(--tn-border);
    transition: transform .15s;
}
.tn-prize-slot:hover { transform: translateY(-2px); }
.tn-prize-slot.p1 { border-color: var(--tn-gold-border); }
.tn-prize-slot.p2 { border-color: var(--tn-silver-border); }
.tn-prize-slot.p3 { border-color: var(--tn-bronze-border); }
.tn-prize-slot-icon { font-size: 20px; display: block; margin-bottom: 5px; }
.tn-prize-slot-lbl { font-size: 9px; font-weight: 800; text-transform: uppercase; letter-spacing: .8px; margin-bottom: 4px; }
.tn-prize-slot.p1 .tn-prize-slot-lbl { color: var(--tn-gold); }
.tn-prize-slot.p2 .tn-prize-slot-lbl { color: var(--tn-silver-dim); }
.tn-prize-slot.p3 .tn-prize-slot-lbl { color: var(--tn-bronze-dim); }
.tn-prize-slot-amt { font-size: 17px; font-weight: 900; letter-spacing: -1px; line-height: 1; margin-bottom: 2px; }
.tn-prize-slot.p1 .tn-prize-slot-amt { color: var(--tn-gold); }
.tn-prize-slot.p2 .tn-prize-slot-amt { color: var(--tn-silver); }
.tn-prize-slot.p3 .tn-prize-slot-amt { color: var(--tn-bronze); }
.tn-prize-slot-cur { font-size: 8.5px; font-weight: 700; color: var(--tn-text-muted); text-transform: uppercase; margin-bottom: 8px; }
.tn-prize-slot-sep { height: 1px; background: var(--tn-border); margin-bottom: 8px; }
.tn-prize-slot-who-lbl { font-size: 8.5px; font-weight: 600; text-transform: uppercase; letter-spacing: .4px; color: var(--tn-text-muted); margin-bottom: 3px; }
.tn-prize-slot-who { font-size: 10px; font-weight: 800; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.tn-prize-slot.p1 .tn-prize-slot-who { color: var(--tn-gold); }
.tn-prize-slot.p2 .tn-prize-slot-who { color: var(--tn-silver); }
.tn-prize-slot.p3 .tn-prize-slot-who { color: var(--tn-bronze); }
.tn-prize-not-qual { font-size: 9px; color: var(--tn-text-muted); font-style: italic; margin-top: 2px; }
.tn-prize-open { font-size: 10px; color: var(--tn-text-muted); font-style: italic; }
.tn-awarded-badge {
    display: inline-flex; align-items: center; gap: 3px;
    background: var(--tn-green-bg); border: 1px solid var(--tn-green-border);
    color: var(--tn-green); border-radius: 6px;
    font-size: 9px; font-weight: 700; padding: 3px 8px; margin-top: 5px;
}

/* ─── MY STATUS CARD ─── */
.tn-my-status {
    display: flex; align-items: center; gap: 12px;
    border-radius: 14px; padding: 14px;
    border: 2px solid var(--tn-border);
    background: var(--tn-card);
    animation: tnUp .44s ease .06s both;
    box-shadow: 0 4px 20px var(--tn-shadow);
    margin-bottom: 12px;
}
.tn-my-status.s-prize { background: var(--tn-gold-bg); border-color: var(--tn-gold-border); }
.tn-my-status.s-warn  { background: var(--tn-amber-bg); border-color: var(--tn-amber-border); }
.tn-my-ico {
    width: 46px; height: 46px; border-radius: 12px; flex-shrink: 0;
    display: flex; align-items: center; justify-content: center; font-size: 20px;
    background: var(--tn-card2); border: 1.5px solid var(--tn-border);
}
.tn-my-status.s-prize .tn-my-ico { background: var(--tn-gold-bg); border-color: var(--tn-gold-border); }
.tn-my-status.s-warn  .tn-my-ico { background: var(--tn-amber-bg); border-color: var(--tn-amber-border); }
.tn-my-body { flex: 1; min-width: 0; }
.tn-my-title { font-size: 13px; font-weight: 800; color: var(--tn-text); margin-bottom: 3px; }
.tn-my-status.s-prize .tn-my-title { color: var(--tn-gold); }
.tn-my-status.s-warn  .tn-my-title { color: var(--tn-amber); }
.tn-my-desc { font-size: 11px; color: var(--tn-text-sub); line-height: 1.5; }
.tn-my-prog-track { height: 6px; background: var(--tn-border); border-radius: 99px; overflow: hidden; margin-top: 8px; }
.tn-my-prog-fill { height: 100%; border-radius: 99px; background: linear-gradient(90deg, var(--tn-gold-dim), var(--tn-gold)); transition: width .8s ease; }
.tn-my-prog-note { font-size: 9.5px; color: var(--tn-text-muted); margin-top: 4px; }
.tn-my-right { text-align: right; flex-shrink: 0; min-width: 72px; }
.tn-my-big { font-size: 22px; font-weight: 900; letter-spacing: -1px; line-height: 1; color: var(--tn-text); }
.tn-my-status.s-prize .tn-my-big { color: var(--tn-gold); }
.tn-my-status.s-warn  .tn-my-big { color: var(--tn-amber); }
.tn-my-small { font-size: 9px; font-weight: 700; text-transform: uppercase; letter-spacing: .5px; color: var(--tn-text-muted); margin-top: 2px; }

/* ─── HEADER ─── */
.tn-header {
    background: var(--tn-card);
    border: 1.5px solid var(--tn-border);
    border-radius: 16px; padding: 20px 16px 16px;
    margin-bottom: 12px;
    animation: tnUp .5s ease .1s both;
    box-shadow: 0 4px 24px var(--tn-shadow);
}
.tn-crown { text-align: center; margin-bottom: 10px; }
.tn-crown-icon { font-size: 38px; display: inline-block; animation: crownFloat 3s ease-in-out infinite; }
.tn-title-main { font-size: 22px; font-weight: 900; letter-spacing: -.5px; color: var(--tn-text); text-align: center; margin-bottom: 2px; }
.tn-title-sub { font-size: 11.5px; color: var(--tn-text-sub); text-align: center; margin-bottom: 10px; }
.tn-week-badge {
    display: inline-flex; align-items: center; gap: 6px;
    padding: 5px 14px; border-radius: 20px;
    background: var(--tn-gold-bg); border: 1.5px solid var(--tn-gold-border);
    font-size: 10.5px; font-weight: 700; color: var(--tn-gold);
    margin: 0 auto 16px;
}
.tn-center { display: flex; justify-content: center; }

/* Countdown */
.tn-countdown { display: flex; justify-content: center; gap: 8px; margin-bottom: 16px; }
.tn-cd-block {
    display: flex; flex-direction: column; align-items: center;
    background: var(--tn-card2); border: 1.5px solid var(--tn-border);
    border-radius: 12px; padding: 10px 14px; min-width: 58px;
}
.tn-cd-num { font-size: 24px; font-weight: 900; color: var(--tn-gold); letter-spacing: -1px; line-height: 1; }
.tn-cd-lbl { font-size: 9px; font-weight: 700; color: var(--tn-text-muted); text-transform: uppercase; letter-spacing: .7px; margin-top: 3px; }
.tn-cd-sep { font-size: 22px; font-weight: 900; color: var(--tn-gold); align-self: center; margin-top: -4px; opacity: .5; }

/* My rank strip */
.tn-myrank {
    display: flex; align-items: center; gap: 11px;
    padding: 12px 14px; border-radius: 12px;
    background: var(--tn-card2); border: 1.5px solid var(--tn-border);
}
.tn-myrank-ico {
    width: 42px; height: 42px; border-radius: 11px; flex-shrink: 0;
    background: var(--tn-gold-bg); border: 1.5px solid var(--tn-gold-border);
    display: flex; align-items: center; justify-content: center; font-size: 18px;
}
.tn-myrank-info { flex: 1; min-width: 0; }
.tn-myrank-t { font-size: 12.5px; font-weight: 700; color: var(--tn-text); margin-bottom: 3px; }
.tn-myrank-s { font-size: 10.5px; color: var(--tn-text-sub); line-height: 1.45; }
.tn-dot-green { color: var(--tn-green); font-weight: 700; }
.tn-dot-amber { color: var(--tn-amber); font-weight: 700; }
.tn-myrank-val { text-align: right; flex-shrink: 0; }
.tn-myrank-big { font-size: 24px; font-weight: 900; color: var(--tn-gold); letter-spacing: -1px; line-height: 1; }
.tn-myrank-lbl { font-size: 9px; font-weight: 700; text-transform: uppercase; letter-spacing: .5px; color: var(--tn-text-muted); margin-top: 2px; }

/* ─── PODIUM ─── */
.tn-podium { display: flex; align-items: flex-end; justify-content: center; gap: 8px; margin-bottom: 12px; animation: tnUp .5s ease .18s both; }
.tn-pod {
    flex: 1; max-width: 130px;
    border-radius: 14px 14px 0 0;
    padding: 16px 10px 14px; text-align: center;
    border-width: 1.5px; border-style: solid; border-bottom: none;
}
.tn-pod.r1 { background: var(--tn-gold-bg); border-color: var(--tn-gold-border); padding-top: 22px; }
.tn-pod.r2 { background: var(--tn-silver-bg); border-color: var(--tn-silver-border); }
.tn-pod.r3 { background: var(--tn-bronze-bg); border-color: var(--tn-bronze-border); }
.tn-pod.empty { background: var(--tn-card2); border-color: var(--tn-border); opacity: .55; }
.tn-pod-rnk { font-size: 9px; font-weight: 800; text-transform: uppercase; letter-spacing: .9px; margin-bottom: 8px; }
.tn-pod.r1 .tn-pod-rnk { color: var(--tn-gold); }
.tn-pod.r2 .tn-pod-rnk { color: var(--tn-silver-dim); }
.tn-pod.r3 .tn-pod-rnk { color: var(--tn-bronze-dim); }
.tn-pod.empty .tn-pod-rnk { color: var(--tn-text-muted); }
.tn-badge {
    width: 48px; height: 48px; border-radius: 50%;
    margin: 0 auto 8px; display: flex; align-items: center;
    justify-content: center; font-size: 18px; font-weight: 900; color: #fff;
}
.tn-pod.r1 .tn-badge { background: linear-gradient(135deg,#d97706,#fbbf24); animation: pulseGold 2.5s infinite; font-size: 22px; }
.tn-pod.r2 .tn-badge { background: linear-gradient(135deg,#475569,#94a3b8); }
.tn-pod.r3 .tn-badge { background: linear-gradient(135deg,#c2410c,#f97316); }
.tn-pod.empty .tn-badge { background: var(--tn-border); color: var(--tn-text-muted); }
.tn-pod-name { font-size: 12px; font-weight: 800; color: var(--tn-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-bottom: 2px; }
.tn-pod.empty .tn-pod-name { color: var(--tn-text-muted); }
.tn-pod-ctry { font-size: 9.5px; color: var(--tn-text-muted); margin-bottom: 8px; }
.tn-pod-count { font-size: 28px; font-weight: 900; letter-spacing: -1.5px; line-height: 1; margin-bottom: 2px; }
.tn-pod.r1 .tn-pod-count { color: var(--tn-gold); }
.tn-pod.r2 .tn-pod-count { color: var(--tn-silver); }
.tn-pod.r3 .tn-pod-count { color: var(--tn-bronze); }
.tn-pod.empty .tn-pod-count { color: var(--tn-border); }
.tn-pod-sublbl { font-size: 8.5px; font-weight: 700; text-transform: uppercase; letter-spacing: .6px; color: var(--tn-text-muted); margin-bottom: 8px; }
.tn-pod-chip {
    display: inline-flex; align-items: center; gap: 3px;
    border-radius: 8px; padding: 4px 10px; font-size: 9.5px; font-weight: 800;
}
.tn-pod.r1 .tn-pod-chip { background: var(--tn-gold-bg); color: var(--tn-gold); border: 1.5px solid var(--tn-gold-border); }
.tn-pod.r2 .tn-pod-chip { background: var(--tn-silver-bg); color: var(--tn-silver); border: 1.5px solid var(--tn-silver-border); }
.tn-pod.r3 .tn-pod-chip { background: var(--tn-bronze-bg); color: var(--tn-bronze); border: 1.5px solid var(--tn-bronze-border); }
.tn-pod-chip.locked { background: var(--tn-card2); color: var(--tn-text-muted); border: 1.5px solid var(--tn-border); }

/* ─── LEADERBOARD ─── */
.tn-list-card {
    border-radius: 14px; overflow: hidden;
    background: var(--tn-card); border: 1.5px solid var(--tn-border);
    box-shadow: 0 4px 20px var(--tn-shadow);
    margin-bottom: 12px;
    animation: tnUp .5s ease .26s both;
}
.tn-list-hdr {
    display: flex; align-items: center; justify-content: space-between;
    padding: 12px 16px; background: var(--tn-card2);
    border-bottom: 1.5px solid var(--tn-border);
}
.tn-list-title { font-size: 13px; font-weight: 800; color: var(--tn-text); display: flex; align-items: center; gap: 8px; }
.tn-list-badge {
    font-size: 10px; font-weight: 700; color: var(--tn-gold);
    background: var(--tn-gold-bg); border: 1px solid var(--tn-gold-border);
    padding: 3px 10px; border-radius: 20px;
}
.tn-row {
    display: flex; align-items: center; gap: 10px;
    padding: 11px 16px; border-bottom: 1px solid var(--tn-border);
    transition: background .15s;
}
.tn-row:last-child { border-bottom: none; }
.tn-row:hover { background: var(--tn-row-hover); }
.tn-row.pos-1 { background: var(--tn-gold-bg); }
.tn-row.pos-2 { background: var(--tn-silver-bg); }
.tn-row.pos-3 { background: var(--tn-bronze-bg); }
.tn-row.pos-1:hover, .tn-row.pos-2:hover, .tn-row.pos-3:hover { filter: brightness(.98); }
.tn-row.is-me { border-left: 3px solid <?= $themeColor ?>; }
.tn-rank-num { width: 28px; flex-shrink: 0; text-align: center; font-size: 13px; font-weight: 800; color: var(--tn-text-muted); }
.tn-medal { font-size: 16px; }
.tn-av {
    width: 40px; height: 40px; flex-shrink: 0; border-radius: 11px;
    display: flex; align-items: center; justify-content: center;
    font-size: 15px; font-weight: 800; color: #fff; position: relative;
}
.tn-av-ring { position: absolute; inset: -2px; border-radius: 13px; border: 2px solid transparent; }
.tn-row.pos-1 .tn-av-ring { border-color: var(--tn-gold); }
.tn-row.pos-2 .tn-av-ring { border-color: var(--tn-silver-dim); }
.tn-row.pos-3 .tn-av-ring { border-color: var(--tn-bronze-dim); }
.tn-info { flex: 1; min-width: 0; }
.tn-name { font-size: 13px; font-weight: 700; color: var(--tn-text); display: flex; align-items: center; gap: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-bottom: 2px; }
.tn-you-tag {
    font-size: 8px; font-weight: 800; padding: 2px 6px; border-radius: 4px; flex-shrink: 0;
    background: <?= $themeColor ?>22; color: <?= $themeColor ?>; border: 1px solid <?= $themeColor ?>55;
    text-transform: uppercase; letter-spacing: .4px;
}
.tn-ctry { font-size: 10px; color: var(--tn-text-muted); display: flex; align-items: center; gap: 4px; margin-bottom: 5px; }
.tn-bar-wrap { height: 4px; background: var(--tn-border); border-radius: 99px; overflow: hidden; }
.tn-bar-fill { height: 100%; border-radius: 99px; width: 0%; transition: width .7s ease; }
.tn-row.pos-1 .tn-bar-fill { background: linear-gradient(90deg, var(--tn-gold-dim), var(--tn-gold)); }
.tn-row.pos-2 .tn-bar-fill { background: linear-gradient(90deg, var(--tn-silver-dim), var(--tn-silver)); }
.tn-row.pos-3 .tn-bar-fill { background: linear-gradient(90deg, var(--tn-bronze-dim), var(--tn-bronze)); }
.tn-bar-fill.def { background: linear-gradient(90deg, #4f46e5, #818cf8); }
.tn-right { text-align: right; flex-shrink: 0; min-width: 82px; }
.tn-ref-count { font-size: 22px; font-weight: 900; letter-spacing: -1px; line-height: 1; color: var(--tn-text); }
.tn-row.pos-1 .tn-ref-count { color: var(--tn-gold); }
.tn-row.pos-2 .tn-ref-count { color: var(--tn-silver); }
.tn-row.pos-3 .tn-ref-count { color: var(--tn-bronze); }
.tn-ref-lbl { font-size: 9px; font-weight: 700; text-transform: uppercase; letter-spacing: .5px; color: var(--tn-text-muted); margin-top: 1px; }
.tn-chip {
    display: inline-flex; align-items: center; gap: 3px;
    margin-top: 4px; padding: 3px 8px; border-radius: 6px; font-size: 8.5px; font-weight: 800;
}
.pos-1 .tn-chip { background: var(--tn-gold-bg); color: var(--tn-gold); border: 1px solid var(--tn-gold-border); }
.pos-2 .tn-chip { background: var(--tn-silver-bg); color: var(--tn-silver); border: 1px solid var(--tn-silver-border); }
.pos-3 .tn-chip { background: var(--tn-bronze-bg); color: var(--tn-bronze); border: 1px solid var(--tn-bronze-border); }
.tn-chip.locked { background: var(--tn-card2); color: var(--tn-text-muted); border: 1px solid var(--tn-border); }

.tn-empty { text-align: center; padding: 44px 20px; }
.tn-empty-icon { font-size: 38px; margin-bottom: 12px; display: block; }
.tn-empty-t { font-size: 14px; font-weight: 700; color: var(--tn-text); margin-bottom: 6px; }
.tn-empty-s { font-size: 11.5px; color: var(--tn-text-sub); line-height: 1.6; }

/* ─── RULES ─── */
.tn-rules {
    border-radius: 14px; padding: 16px;
    background: var(--tn-card); border: 1.5px solid var(--tn-border);
    box-shadow: 0 4px 20px var(--tn-shadow);
    margin-bottom: 14px;
    animation: tnUp .5s ease .34s both;
}
.tn-rules-title {
    font-size: 11px; font-weight: 800; letter-spacing: 1.5px; text-transform: uppercase;
    color: var(--tn-text); margin-bottom: 14px;
    display: flex; align-items: center; gap: 8px;
}
.tn-rules-title::after { content: ''; flex: 1; height: 1.5px; background: var(--tn-border); }
.tn-rule { display: flex; align-items: flex-start; gap: 10px; margin-bottom: 13px; }
.tn-rule:last-child { margin-bottom: 0; }
.tn-rule-ico {
    width: 32px; height: 32px; border-radius: 9px; flex-shrink: 0;
    display: flex; align-items: center; justify-content: center; font-size: 14px;
    background: var(--tn-card2); border: 1.5px solid var(--tn-border);
}
.tn-rule-txt { font-size: 12px; color: var(--tn-text-sub); line-height: 1.6; padding-top: 6px; }
.tn-rule-txt strong { color: var(--tn-text); font-weight: 700; }
</style>

<div class="tn-page">

<!-- ══ GRAND PRIZE BANNER ══ -->
<div class="tn-card tn-gp-banner">
    <div style="text-align:center">
        <div class="tn-eyebrow">💎 Grand Prize — All Time</div>
    </div>
    <div class="tn-amount-huge" style="text-align:center">
        Ksh 10,000 <span style="font-size:15px;font-weight:600;opacity:.55">each</span>
    </div>
    <div class="tn-desc" style="text-align:center">First 3 people to reach 7,000 active referrals since <strong style="color:var(--tn-blue-text)">MAY 20, 2026</strong> win Ksh 10,000 each</div>
    <div class="tn-note" style="text-align:center;margin-bottom:14px">
        <strong><?= count($gpAwarded) ?>/3 slots claimed</strong> &nbsp;·&nbsp; <?= $gpSlotsRemaining ?> remaining &nbsp;·&nbsp; Target: <strong>7,000 referrals from MAY 20, 2026</strong>
    </div>

    <div class="tn-gp-slots">
        <?php foreach($gpDisplaySlots as $slot => $gpRow):
            $slotNum   = $slot + 1;
            $isClaimed = $gpRow && $gpRow['claimed'];
            $isLeading = $gpRow && !$isClaimed;
            $cardClass = $isClaimed ? 'claimed' : ($isLeading ? '' : 'open');
        ?>
        <div class="tn-gp-slot <?= $cardClass ?>">
            <span class="tn-gp-slot-icon"><?= $isClaimed ? '✅' : ($isLeading ? '💎' : '🔒') ?></span>
            <div class="tn-gp-slot-label">Slot <?= $slotNum ?></div>
            <div class="tn-gp-slot-amt">10,000</div>
            <div class="tn-gp-slot-cur">KES</div>
            <div class="tn-gp-slot-sep"></div>
            <?php if($isClaimed): ?>
                <div class="tn-gp-slot-lbl2">Winner</div>
                <div class="tn-gp-slot-name"><?= htmlspecialchars($gpRow['username']) ?></div>
                <div class="tn-gp-slot-refs"><?= number_format($gpRow['active_referrals']) ?> refs</div>
                <div class="tn-gp-claimed-badge">✓ Claimed</div>
            <?php elseif($isLeading):
                $slotRefs    = intval($gpRow['active_referrals']);
                $slotQual    = $slotRefs >= $grandPrize['target'];
                $slotPct     = min(100, round($slotRefs / $grandPrize['target'] * 100));
            ?>
                <div class="tn-gp-slot-lbl2"><?= $slotQual ? 'Qualified ✓' : 'Leading' ?></div>
                <div class="tn-gp-slot-name"><?= htmlspecialchars($gpRow['username']) ?></div>
                <?php if($slotQual): ?>
                    <div class="tn-gp-slot-refs" style="color:var(--tn-green);font-weight:700">7,000 / 7,000 ✓</div>
                <?php else: ?>
                    <div class="tn-gp-slot-refs"><?= number_format($slotRefs) ?> / 7,000</div>
                    <div style="height:4px;background:var(--tn-border);border-radius:99px;overflow:hidden;margin-top:5px">
                        <div style="height:100%;width:<?= $slotPct ?>%;background:linear-gradient(90deg,var(--tn-blue-dim),var(--tn-blue));border-radius:99px"></div>
                    </div>
                <?php endif; ?>
            <?php else: ?>
                <div class="tn-gp-slot-lbl2">Status</div>
                <div class="tn-gp-slot-open">— open —</div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>

    <div class="tn-gp-progress">
        <?php if($myGpAwarded): ?>
            <div class="tn-gp-prog-success">🎉 You've claimed your Grand Prize! Ksh 10,000 has been awarded.</div>
        <?php elseif($gpSlotsRemaining <= 0): ?>
            <div style="text-align:center;font-size:11.5px;color:var(--tn-text-muted);padding:4px 0">All 3 Grand Prize slots have been claimed.</div>
        <?php else: ?>
            <div class="tn-gp-prog-header">
                <span class="tn-gp-prog-label">Your Grand Prize Progress</span>
                <span class="tn-gp-prog-val" style="<?= $myGpQualifies ? 'color:var(--tn-green)' : '' ?>">
                    <?= $myGpQualifies ? '7,000 / 7,000 ✓' : number_format($myAllTimeActive).' / 7,000' ?>
                </span>
            </div>
            <div class="tn-prog-track">
                <div class="tn-prog-fill-blue" style="width:<?= $myGpPct ?>%;<?= $myGpQualifies ? 'background:linear-gradient(90deg,var(--tn-green),#4ade80)' : '' ?>"></div>
            </div>
            <?php if($myGpQualifies): ?>
                <div class="tn-gp-prog-note" style="color:var(--tn-green);font-weight:700">✓ You qualify! Ksh 10,000 will be credited to your wallet soon.</div>
            <?php else: ?>
                <div class="tn-gp-prog-note"><?= number_format($myGpNeeds) ?> more referrals needed &nbsp;·&nbsp; <?= $gpSlotsRemaining ?> slot<?= $gpSlotsRemaining!=1?'s':'' ?> remaining</div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<!-- ══ WEEKLY PRIZE BANNER ══ -->
<div class="tn-card tn-weekly-banner">
    <div style="text-align:center">
        <div class="tn-eyebrow" style="color:var(--tn-gold);border-color:var(--tn-gold-border)">🏆 Weekly Tournament Prizes</div>
    </div>
    <div class="tn-amount-huge" style="text-align:center;color:var(--tn-gold)">
        Ksh 6,000 <span style="font-size:15px;font-weight:600;opacity:.55">pool</span>
    </div>
    <div class="tn-desc" style="text-align:center">Awarded every Sunday to the top 3 ranked users</div>
    <div class="tn-note" style="text-align:center;margin-bottom:14px">
        Minimum <strong>3,000 active referrals this week</strong> required for all prize positions
    </div>

    <div class="tn-prize-row">
        <?php foreach($prizes as $rank => $prize):
            $pClass    = 'p'.$rank;
            $rowData   = $leaderboard[$rank-1] ?? null;
            $qualifies = $rowData && intval($rowData['active_referrals']) >= $prize['min_referrals'];
            $awarded   = isset($existingAwardsData[$rank]);
        ?>
        <div class="tn-prize-slot <?= $pClass ?>">
            <span class="tn-prize-slot-icon"><?= $prize['icon'] ?></span>
            <div class="tn-prize-slot-lbl"><?= $prize['label'] ?></div>
            <div class="tn-prize-slot-amt"><?= number_format($prize['amount']) ?></div>
            <div class="tn-prize-slot-cur">KES</div>
            <div class="tn-prize-slot-sep"></div>
            <?php if($awarded): ?>
                <div class="tn-awarded-badge">✓ Awarded</div>
            <?php endif; ?>
            <div class="tn-prize-slot-who-lbl"><?= $qualifies ? 'Qualified Leader' : 'Current Leader' ?></div>
            <?php if($rowData): ?>
                <div class="tn-prize-slot-who"><?= htmlspecialchars($rowData['username']) ?></div>
                <?php if(!$qualifies): ?><div class="tn-prize-not-qual">🔒 Under 3,000 refs</div><?php endif; ?>
            <?php else: ?>
                <div class="tn-prize-open">— open —</div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- ══ MY WEEKLY STATUS ══ -->
<?php
$myStatusClass = '';
$myStatusIcon  = '📈';
$myStatusTitle = 'Not in Prize Position';
$myStatusDesc  = 'You\'re not in the top 3 this week. Refer more members to climb.';
$myStatusRight = null;

if ($myRank >= 1 && $myRank <= 3 && $myQualifies) {
    $myStatusClass = 's-prize';
    $myStatusIcon  = $prizes[$myRank]['icon'];
    $myStatusTitle = "You're in Prize Position!";
    $myStatusDesc  = "Rank #{$myRank} · {$myActive} active referrals this week · Hold your spot to win Ksh " . number_format($prizes[$myRank]['amount']);
    $myStatusRight = ['val' => 'Ksh '.number_format($prizes[$myRank]['amount']), 'lbl' => 'Your Prize'];
} elseif ($myRank >= 1 && $myRank <= 3 && !$myQualifies) {
    $myStatusClass = 's-warn';
    $myStatusIcon  = '⚠️';
    $myStatusTitle = "Top 3 — Need " . number_format($myNeeds) . " More to Qualify";
    $myStatusDesc  = "Ranked #{$myRank} but need {$myNeeds} more active referrals to unlock your Ksh " . number_format($prizes[$myRank]['amount']) . " prize.";
    $myStatusRight = ['val' => "#{$myRank}", 'lbl' => 'Your Rank'];
} elseif ($myRank > 3 && $myActive > 0) {
    $needed3rd = isset($leaderboard[2]) ? max(0, intval($leaderboard[2]['active_referrals']) - $myActive + 1) : '?';
    $myStatusTitle = "Rank #{$myRank} — Keep Climbing";
    $myStatusDesc  = "{$myActive} active referrals this week. Need {$needed3rd} more to enter top 3.";
    $myStatusRight = ['val' => "#{$myRank}", 'lbl' => 'Your Rank'];
}
$progressPct = $minReferralsForPrize > 0 ? min(100, round($myActive / $minReferralsForPrize * 100)) : 0;
?>
<div class="tn-my-status <?= $myStatusClass ?>">
    <div class="tn-my-ico"><?= $myStatusIcon ?></div>
    <div class="tn-my-body">
        <div class="tn-my-title"><?= $myStatusTitle ?></div>
        <div class="tn-my-desc"><?= $myStatusDesc ?></div>
        <?php if($myRank >= 1 && $myRank <= 3 && !$myQualifies): ?>
        <div class="tn-my-prog-track">
            <div class="tn-my-prog-fill" style="width:<?= $progressPct ?>%"></div>
        </div>
        <div class="tn-my-prog-note"><?= $myActive ?> / <?= number_format($minReferralsForPrize) ?> referrals to qualify</div>
        <?php endif; ?>
    </div>
    <?php if($myStatusRight): ?>
    <div class="tn-my-right">
        <div class="tn-my-big"><?= $myStatusRight['val'] ?></div>
        <div class="tn-my-small"><?= $myStatusRight['lbl'] ?></div>
    </div>
    <?php endif; ?>
</div>

<!-- ══ HEADER ══ -->
<div class="tn-header">
    <div class="tn-crown"><span class="tn-crown-icon">👑</span></div>
    <div class="tn-title-main">Referral Tournament</div>
    <div class="tn-title-sub">Who referred the most new members this week?</div>
    <div class="tn-center">
        <div class="tn-week-badge"><i class="fa-regular fa-calendar-days"></i><?= $weekLabel ?></div>
    </div>
    <div class="tn-countdown">
        <div class="tn-cd-block"><div class="tn-cd-num" id="cd-d">--</div><div class="tn-cd-lbl">Days</div></div>
        <div class="tn-cd-sep">:</div>
        <div class="tn-cd-block"><div class="tn-cd-num" id="cd-h">--</div><div class="tn-cd-lbl">Hrs</div></div>
        <div class="tn-cd-sep">:</div>
        <div class="tn-cd-block"><div class="tn-cd-num" id="cd-m">--</div><div class="tn-cd-lbl">Min</div></div>
        <div class="tn-cd-sep">:</div>
        <div class="tn-cd-block"><div class="tn-cd-num" id="cd-s">--</div><div class="tn-cd-lbl">Sec</div></div>
    </div>
    <div class="tn-myrank">
        <div class="tn-myrank-ico">
            <?php if($myRank>0&&$myRank<=3): echo ['🥇','🥈','🥉'][$myRank-1];
            elseif($myRank>0): ?><i class="fa-solid fa-ranking-star"></i><?php
            else: ?><i class="fa-solid fa-users"></i><?php endif; ?>
        </div>
        <div class="tn-myrank-info">
            <div class="tn-myrank-t">Your Weekly Position</div>
            <div class="tn-myrank-s">
                <?php if($myRank>0): ?>
                    Rank #<?= $myRank ?> &middot; <?= $myActive ?> active referral<?= $myActive!=1?'s':'' ?>
                    <?php if($myQualifies): ?> &middot; <span class="tn-dot-green">✓ Prize Qualified</span>
                    <?php elseif($myRank<=3): ?> &middot; <span class="tn-dot-amber">Need <?= number_format($myNeeds) ?> more to qualify</span>
                    <?php endif; ?>
                <?php else: ?>No active referrals this week &middot; <?= $myAllTime ?> active all-time<?php endif; ?>
            </div>
        </div>
        <div class="tn-myrank-val">
            <?php if($myActive>0): ?>
            <div class="tn-myrank-big"><?= $myActive ?></div>
            <div class="tn-myrank-lbl">Active</div>
            <?php else: ?>
            <div class="tn-myrank-big" style="color:var(--tn-border)">—</div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- ══ PODIUM ══ -->
<?php $podDisplay = [['rank'=>2,'cls'=>'r2','label'=>'2nd'],['rank'=>1,'cls'=>'r1','label'=>'1st'],['rank'=>3,'cls'=>'r3','label'=>'3rd']]; ?>
<div class="tn-podium">
<?php foreach($podDisplay as $pod):
    $idx   = $pod['rank'] - 1;
    $data  = $leaderboard[$idx] ?? null;
    $init  = $data ? strtoupper(substr($data['username'],0,1)) : '?';
    $act   = $data ? intval($data['active_referrals']) : 0;
    $pd    = $prizes[$pod['rank']] ?? null;
    $qual  = $act >= $minReferralsForPrize;
    $awd   = isset($existingAwardsData[$pod['rank']]);
    $bgs   = [1=>'linear-gradient(135deg,#d97706,#fbbf24)',2=>'linear-gradient(135deg,#475569,#94a3b8)',3=>'linear-gradient(135deg,#c2410c,#f97316)'];
?>
<div class="tn-pod <?= $pod['cls'] ?> <?= !$data?'empty':'' ?>">
    <div class="tn-pod-rnk"><?= $pod['label'] ?> Place</div>
    <div class="tn-badge" style="background:<?= $bgs[$pod['rank']] ?>"><?= $data ? $init : '?' ?></div>
    <div class="tn-pod-name"><?= $data ? htmlspecialchars($data['username']) : 'Empty' ?></div>
    <div class="tn-pod-ctry"><?php if($data): ?><i class="fa-solid fa-earth-africa" style="font-size:8px"></i> <?= htmlspecialchars($data['country']??'—') ?><?php else: ?>—<?php endif; ?></div>
    <div class="tn-pod-count"><?= $data ? $act : '—' ?></div>
    <div class="tn-pod-sublbl">Active Referral<?= $act!=1?'s':'' ?></div>
    <?php if($pd && $data): ?>
        <div class="tn-pod-chip <?= !$qual?'locked':'' ?>">
            <?php if($awd): ?>✓ Ksh <?= number_format($pd['amount']) ?>
            <?php elseif($qual): ?>🏆 Ksh <?= number_format($pd['amount']) ?>
            <?php else: ?>🔒 Need 3,000+ refs<?php endif; ?>
        </div>
    <?php elseif($pd): ?>
        <div class="tn-pod-chip locked">🔒 Need 3,000+ refs</div>
    <?php endif; ?>
</div>
<?php endforeach; ?>
</div>

<!-- ══ LEADERBOARD ══ -->
<?php $maxRefs = !empty($leaderboard) ? max(1,intval($leaderboard[0]['active_referrals'])) : 1; ?>
<div class="tn-list-card">
    <div class="tn-list-hdr">
        <div class="tn-list-title"><i class="fa-solid fa-trophy" style="color:var(--tn-gold);font-size:13px"></i> Weekly Rankings</div>
        <div class="tn-list-badge"><?= count($leaderboard) ?> referrer<?= count($leaderboard)!=1?'s':'' ?></div>
    </div>
    <?php if(empty($leaderboard)): ?>
    <div class="tn-empty">
        <span class="tn-empty-icon">🏆</span>
        <div class="tn-empty-t">No activity yet this week!</div>
        <div class="tn-empty-s">Share your invite link and bring new members.<br>1st place wins Ksh 3,000 — minimum 3,000 referrals required.</div>
    </div>
    <?php else: ?>
    <?php foreach($leaderboard as $i=>$row):
        $rank   = $i+1;
        $isMe   = ($row['id']==$userId);
        $active = intval($row['active_referrals']);
        $pct    = round($active/$maxRefs*100);
        $init   = strtoupper(substr($row['username'],0,1));
        $bgs    = [1=>'linear-gradient(135deg,#d97706,#fbbf24)',2=>'linear-gradient(135deg,#475569,#94a3b8)',3=>'linear-gradient(135deg,#c2410c,#f97316)'];
        $bg     = $bgs[$rank]??'linear-gradient(135deg,#4f46e5,#818cf8)';
        $medals = [1=>'🥇',2=>'🥈',3=>'🥉'];
        $prow   = $prizes[$rank] ?? null;
        $qual   = $rank <= 3 && $active >= $minReferralsForPrize;
        $awd    = isset($existingAwardsData[$rank]);
    ?>
    <div class="tn-row <?= $rank<=3?'pos-'.$rank:'pos-other' ?> <?= $isMe?'is-me':'' ?>">
        <div class="tn-rank-num"><?php if(isset($medals[$rank])): ?><span class="tn-medal"><?= $medals[$rank] ?></span><?php else: ?><?= $rank ?><?php endif; ?></div>
        <div class="tn-av" style="background:<?= $bg ?>"><?= $init ?><div class="tn-av-ring"></div></div>
        <div class="tn-info">
            <div class="tn-name"><?= htmlspecialchars($row['username']) ?><?php if($isMe): ?><span class="tn-you-tag">YOU</span><?php endif; ?></div>
            <div class="tn-ctry"><i class="fa-solid fa-earth-africa"></i><?= htmlspecialchars($row['country']??'—') ?></div>
            <div class="tn-bar-wrap"><div class="tn-bar-fill <?= $rank>3?'def':'' ?>" data-pct="<?= $pct ?>"></div></div>
        </div>
        <div class="tn-right">
            <div class="tn-ref-count"><?= $active ?></div>
            <div class="tn-ref-lbl">Active invites</div>
            <?php if($prow && $rank <= 3): ?>
                <div class="tn-chip <?= !$qual?'locked':'' ?>">
                    <?php if($awd): ?>✓ Ksh <?= number_format($prow['amount']) ?>
                    <?php elseif($qual): ?>🏆 Ksh <?= number_format($prow['amount']) ?>
                    <?php else: ?>🔒 Need 3,000<?php endif; ?>
                </div>
            <?php elseif($rank > 3): ?>
                <div class="tn-chip locked">No prize</div>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- ══ RULES ══ -->
<div class="tn-rules">
    <div class="tn-rules-title"><i class="fa-solid fa-circle-info"></i> Prizes &amp; Rules</div>
    <div class="tn-rule">
        <div class="tn-rule-ico" style="color:var(--tn-blue-text)"><i class="fa-solid fa-gem"></i></div>
        <div class="tn-rule-txt"><strong>Grand Prize: Ksh 10,000 each — 3 winners ever</strong> — The first 3 people to reach 7,000 active referrals since <strong>MAY 20, 2026</strong> each win Ksh 10,000. Previous referrals do not count. Only 3 slots, forever. First come, first served.</div>
    </div>
    <div class="tn-rule">
        <div class="tn-rule-ico" style="color:var(--tn-gold)"><i class="fa-solid fa-trophy"></i></div>
        <div class="tn-rule-txt"><strong>Weekly Prize Pool: Ksh 6,000</strong> — 🥇 1st → Ksh 3,000 · 🥈 2nd → Ksh 2,000 · 🥉 3rd → Ksh 1,000. Only the top 3 ranked users each week receive prizes.</div>
    </div>
    <div class="tn-rule">
        <div class="tn-rule-ico" style="color:var(--tn-amber)"><i class="fa-solid fa-lock"></i></div>
        <div class="tn-rule-txt"><strong>3,000 referral minimum for all weekly prizes</strong> — All 3 prize positions require at least 3,000 active referrals that week. Being in the top 3 alone is not enough — you must also hit 3,000.</div>
    </div>
    <div class="tn-rule">
        <div class="tn-rule-ico" style="color:var(--tn-green)"><i class="fa-solid fa-users"></i></div>
        <div class="tn-rule-txt"><strong>Active referrals only</strong> — Only members who joined AND activated this week count for weekly prizes. All-time active referrals count for the Grand Prize.</div>
    </div>
    <div class="tn-rule">
        <div class="tn-rule-ico" style="color:var(--tn-text-muted)"><i class="fa-regular fa-calendar-xmark"></i></div>
        <div class="tn-rule-txt"><strong>Resets every Monday</strong> — The weekly leaderboard clears at midnight Sunday. Prizes are awarded to qualified top 3 at end of each week.</div>
    </div>
    <div class="tn-rule">
        <div class="tn-rule-ico" style="color:var(--tn-gold)"><i class="fa-solid fa-share-nodes"></i></div>
        <div class="tn-rule-txt"><strong>Share your link</strong> — Visit the Affiliates page to copy your personal invite link and start climbing today.</div>
    </div>
</div>

</div>

<script>
(function(){
    var endTs=<?= $nextSunday->getTimestamp()*1000 ?>;
    function pad(n){return n<10?'0'+n:''+n}
    function tick(){
        var diff=Math.max(0,Math.floor((endTs-Date.now())/1000));
        if(diff<=0){location.reload();return;}
        var d=Math.floor(diff/86400),h=Math.floor((diff%86400)/3600),m=Math.floor((diff%3600)/60),s=diff%60;
        var dEl=document.getElementById('cd-d'),hEl=document.getElementById('cd-h'),mEl=document.getElementById('cd-m'),sEl=document.getElementById('cd-s');
        if(dEl)dEl.textContent=pad(d);if(hEl)hEl.textContent=pad(h);if(mEl)mEl.textContent=pad(m);if(sEl)sEl.textContent=pad(s);
        setTimeout(tick,1000);
    }
    tick();
    setTimeout(function(){
        document.querySelectorAll('.tn-bar-fill').forEach(function(el){
            var pct=el.dataset.pct||'0';
            requestAnimationFrame(function(){requestAnimationFrame(function(){el.style.width=pct+'%'})});
        });
    },450);
}());
</script>

<?php include 'footer.php'; ?>