<?php
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth.php';
requireLogin();

 $cid  = (int)($_GET['cid'] ?? 0);
 $comp = null;
if ($cid) {
  $s = $pdo->prepare("SELECT id,title,event_date FROM competitions WHERE id=?");
  $s->execute([$cid]);
  $comp = $s->fetch(PDO::FETCH_ASSOC);
}

/** Role-aware fallback destinations */
 $roleToPage = [
  'dancer' => 'dancer_dashboard.php',
  'choreo' => 'choreographer.php',        
  'judge'  => 'judge_dashboard.php',
  'admin'  => 'admin_dashboard.php',      
];

 $role     = $_SESSION['type'] ?? 'dancer';
 $backHref = $roleToPage[$role] ?? 'index.html';

/** Optional override via query, e.g. results.php?cid=1&from=choreo */
 $from = $_GET['from'] ?? '';
if ($from && isset($roleToPage[$from])) {
  $backHref = $roleToPage[$from];
}

/** Helper: pretty date */
function pretty_date($d) {
  if (!$d) return '—';
  try { return (new DateTime($d))->format('M j, Y'); } catch (Throwable $e) { return htmlspecialchars($d); }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leaderboard • DanceComp</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #6366f1;
            --primary-dark: #4f46e5;
            --secondary: #8b5cf6;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
            --light: #f8fafc;
            --dark: #1e293b;
            --gray: #64748b;
            --border-radius: 12px;
            --transition: all 0.3s ease;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            color: var(--dark);
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            position: sticky;
            top: 0;
            z-index: 100;
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px 24px;
        }
        
        .logo {
            font-size: 1.5rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .back-btn {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 8px 16px;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            color: var(--gray);
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
        }
        
        .back-btn:hover {
            background: var(--light);
            border-color: var(--primary);
            color: var(--primary);
            transform: translateY(-1px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 2.5rem;
            font-weight: 800;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            text-align: center;
            margin-bottom: 24px;
        }
        
        .competition-info {
            background: white;
            border-radius: var(--border-radius);
            padding: 16px 24px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            margin-bottom: 24px;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 16px;
        }
        
        .user-rank {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            border-radius: var(--border-radius);
            padding: 16px 24px;
            margin-bottom: 24px;
            color: white;
            box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
            display: flex;
            align-items: center;
            gap: 12px;
            opacity: 0;
            transform: translateY(10px);
            transition: var(--transition);
        }
        
        .user-rank.show {
            opacity: 1;
            transform: translateY(0);
        }
        
        .rank-icon {
            font-size: 1.5rem;
        }
        
        .rank-text {
            font-size: 1.125rem;
            font-weight: 500;
        }
        
        .leaderboard-container {
            background: white;
            border-radius: var(--border-radius);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            overflow: hidden;
        }
        
        .leaderboard-header {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            padding: 16px 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .leaderboard-title {
            font-size: 1.25rem;
            font-weight: 600;
        }
        
        .refresh-indicator {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 0.875rem;
            opacity: 0.8;
        }
        
        .leaderboard {
            padding: 0;
        }
        
        .leaderboard-item {
            display: flex;
            align-items: center;
            padding: 16px 24px;
            border-bottom: 1px solid #f1f5f9;
            transition: var(--transition);
        }
        
        .leaderboard-item:last-child {
            border-bottom: none;
        }
        
        .leaderboard-item:hover {
            background: var(--light);
        }
        
        .rank-badge {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            margin-right: 16px;
            flex-shrink: 0;
        }
        
        .rank-badge.top-1 {
            background: linear-gradient(135deg, #fbbf24, #f59e0b);
            color: white;
            box-shadow: 0 4px 8px rgba(251, 191, 36, 0.4);
        }
        
        .rank-badge.top-2 {
            background: linear-gradient(135deg, #cbd5e1, #94a3b8);
            color: white;
            box-shadow: 0 4px 8px rgba(203, 213, 225, 0.4);
        }
        
        .rank-badge.top-3 {
            background: linear-gradient(135deg, #f87171, #ef4444);
            color: white;
            box-shadow: 0 4px 8px rgba(248, 113, 113, 0.4);
        }
        
        .rank-badge.other {
            background: #f1f5f9;
            color: var(--gray);
        }
        
        .dancer-info {
            flex-grow: 1;
        }
        
        .dancer-name {
            font-weight: 600;
            font-size: 1.125rem;
            color: var(--dark);
        }
        
        .dancer-score {
            font-size: 0.875rem;
            color: var(--gray);
            margin-top: 2px;
        }
        
        .loading {
            padding: 40px;
            text-align: center;
            color: var(--gray);
        }
        
        .spinner {
            display: inline-block;
            width: 24px;
            height: 24px;
            border: 3px solid rgba(99, 102, 241, 0.2);
            border-radius: 50%;
            border-top-color: var(--primary);
            animation: spin 1s ease-in-out infinite;
            margin-right: 8px;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .error-message {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #b91c1c;
            padding: 12px 16px;
            border-radius: 8px;
            margin: 20px 0;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .trophy {
            color: var(--warning);
        }
        
        .crown {
            color: var(--warning);
            font-size: 1.25rem;
        }
        
        @media (max-width: 640px) {
            .container {
                padding: 10px;
            }
            
            .page-title {
                font-size: 2rem;
            }
            
            .competition-info {
                flex-direction: column;
                gap: 12px;
            }
            
            .leaderboard-item {
                padding: 12px 16px;
            }
            
            .rank-badge {
                width: 32px;
                height: 32px;
                font-size: 0.875rem;
            }
        }
    </style>
</head>
<body>
    <header>
        <div class="header-content">
            <div class="logo">
                <i class="fas fa-music"></i>
                DanceComp
            </div>
            <button class="back-btn" onclick="goBackRoleAware('<?= htmlspecialchars($backHref, ENT_QUOTES) ?>')">
                <i class="fas fa-arrow-left"></i>
                Back
            </button>
        </div>
    </header>

    <div class="container">
        <main>
            <h1 class="page-title">Leaderboard</h1>

            <?php if ($comp): ?>
                <div class="competition-info">
                    <div class="competition-title"><?= htmlspecialchars($comp['title']) ?></div>
                    <div class="competition-date"><?= htmlspecialchars(pretty_date($comp['event_date'])) ?></div>
                </div>
            <?php endif; ?>

            <div id="myRank" class="user-rank">
                <i class="fas fa-trophy rank-icon"></i>
                <div class="rank-text">Your current rank: <span id="rankValue">--</span></div>
            </div>

            <div id="error-container" style="display: none;"></div>

            <div class="leaderboard-container">
                <div class="leaderboard-header">
                    <h2 class="leaderboard-title">Current Rankings</h2>
                    <div class="refresh-indicator">
                        <i class="fas fa-sync-alt"></i>
                        <span>Auto-refresh in <span id="countdown">8</span>s</span>
                    </div>
                </div>
                <div id="leaderboard" class="leaderboard">
                    <div class="loading">
                        <div class="spinner"></div>
                        Loading leaderboard...
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        function sameOrigin(u) {
            try {
                const a = new URL(u, location.href);
                return a.origin === location.origin;
            } catch (e) {
                return false;
            }
        }
        
        function goBackRoleAware(fallback) {
            if (document.referrer && sameOrigin(document.referrer)) {
                history.back();
            } else {
                location.href = fallback;
            }
        }

        const cid = <?= (int)$cid ?>;
        const leaderboard = document.getElementById('leaderboard');
        const myRank = document.getElementById('myRank');
        const rankValue = document.getElementById('rankValue');
        const errorContainer = document.getElementById('error-container');
        let countdown = 8;
        const countdownElement = document.getElementById('countdown');

        // Countdown timer
        setInterval(() => {
            countdown--;
            countdownElement.textContent = countdown;
            if (countdown <= 0) {
                countdown = 8;
                loadBoard();
            }
        }, 1000);

        async function loadBoard() {
            try {
                const res = await fetch('leaderboard.php?cid=' + cid, { cache: 'no-store' });
                const data = await res.json();
                
                // Clear error messages
                errorContainer.style.display = 'none';
                
                // Update user rank
                if (data.my_rank) {
                    myRank.classList.add('show');
                    rankValue.textContent = '#' + data.my_rank;
                } else {
                    myRank.classList.remove('show');
                }
                
                // Update leaderboard
                leaderboard.innerHTML = '';
                
                if (data.leaders && data.leaders.length > 0) {
                    data.leaders.forEach(row => {
                        const div = document.createElement('div');
                        div.className = 'leaderboard-item';
                        
                        // Determine rank badge class
                        let rankClass = 'other';
                        if (row.rank <= 3) {
                            rankClass = 'top-' + row.rank;
                        }
                        
                        div.innerHTML = `
                            <div class="rank-badge ${rankClass}">
                                ${row.rank <= 3 ? '<i class="fas fa-crown"></i>' : row.rank}
                            </div>
                            <div class="dancer-info">
                                <div class="dancer-name">${row.name}</div>
                                <div class="dancer-score">Avg. score: ${row.avg_score}</div>
                            </div>
                        `;
                        
                        leaderboard.appendChild(div);
                    });
                } else {
                    leaderboard.innerHTML = '<div class="loading">No participants yet</div>';
                }
            } catch (error) {
                console.error('Error loading leaderboard:', error);
                errorContainer.innerHTML = `
                    <div class="error-message">
                        <i class="fas fa-exclamation-circle"></i>
                        <span>Failed to load leaderboard. Please try again later.</span>
                    </div>
                `;
                errorContainer.style.display = 'block';
            }
        }
        
        // Initial load
        loadBoard();
    </script>
</body>
</html>