import { useState, useEffect } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { Trophy, Search, Plus, RefreshCw, ExternalLink, Code2, Sparkles, Flame, Award, CheckCircle2, Shield, User, Filter, X, Clock } from 'lucide-react'; import { getBackendUrl } from '@/lib/utils'; interface LeetcodeProfile { id: number; studentName: String; leetcodeUsername: string; department: string; year: string; totalSolved: number; easySolved: number; mediumSolved: number; hardSolved: number; ranking: number; reputation: number; lastUpdated: string; } const DEPARTMENTS = ['All', 'CSE', 'IT', 'AI&DS', 'ECE', 'EEE', 'MECH', 'CIVIL', 'CSBS']; const YEARS = ['All', '1st Year', '2nd Year', '3rd Year', '4th Year']; export default function LeetcodeLeaderboard() { const [profiles, setProfiles] = useState([]); const [loading, setLoading] = useState(true); const [searchQuery, setSearchQuery] = useState(''); const [selectedDept, setSelectedDept] = useState('All'); const [selectedYear, setSelectedYear] = useState('All'); const [showModal, setShowModal] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false); const [isSyncing, setIsSyncing] = useState(false); const [toastMessage, setToastMessage] = useState(null); // Form State const [studentName, setStudentName] = useState(''); const [leetcodeUsername, setLeetcodeUsername] = useState(''); const [department, setDepartment] = useState('CSE'); const [year, setYear] = useState('1st Year'); useEffect(() => { fetchLeaderboard(); }, []); const fetchLeaderboard = async () => { setLoading(true); try { const res = await fetch(getBackendUrl('/api/leetcode/leaderboard')); if (res.ok) { const data = await res.json(); setProfiles(data); } } catch (err) { console.error('Failed to fetch leaderboard:', err); } finally { setLoading(false); } }; const handleRegister = async (e: React.FormEvent) => { e.preventDefault(); if (!studentName.trim() || !leetcodeUsername.trim()) return; setIsSubmitting(true); try { const res = await fetch(getBackendUrl('/api/leetcode/register'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ studentName, leetcodeUsername, department, year }), }); if (res.ok) { setToastMessage('✅ Profile added successfully! Fetched latest LeetCode stats.'); setShowModal(false); setStudentName(''); setLeetcodeUsername(''); fetchLeaderboard(); } else { const errData = await res.json(); setToastMessage(`❌ ${errData.error || 'Failed to add profile'}`); } } catch (err) { setToastMessage('❌ Error connecting to server'); } finally { setIsSubmitting(false); setTimeout(() => setToastMessage(null), 4000); } }; const handleTriggerSync = async () => { setIsSyncing(true); try { const res = await fetch(getBackendUrl('/api/leetcode/sync'), { method: 'POST' }); if (res.ok) { setToastMessage('⚡ 24h background sync started! Requests are spaced out by 3s to prevent rate limits.'); } } catch (err) { setToastMessage('❌ Failed to trigger sync'); } finally { setIsSyncing(false); setTimeout(() => setToastMessage(null), 5000); } }; const filteredProfiles = profiles.filter((p) => { const matchesSearch = p.studentName.toLowerCase().includes(searchQuery.toLowerCase()) || p.leetcodeUsername.toLowerCase().includes(searchQuery.toLowerCase()); const matchesDept = selectedDept === 'All' || p.department === selectedDept; const matchesYear = selectedYear === 'All' || p.year === selectedYear; return matchesSearch && matchesDept && matchesYear; }); const totalCampusSolved = profiles.reduce((acc, curr) => acc + (curr.totalSolved || 0), 0); const topProfile = profiles.length > 0 ? profiles[0] : null; return (
{/* Toast Notification */} {toastMessage && ( {toastMessage} )}
{/* Banner Header */}
RIT LeetCode Arena

Campus LeetCode Leaderboard

Track top problem solvers across departments. Automatically updated every 24 hours with rate-limited, spaced background sync.

{/* Quick Metrics Bar */}
#1 Top Solver

{topProfile ? `${topProfile.studentName}` : 'N/A'}

{topProfile ? `${topProfile.totalSolved} Problems Solved` : ''}

Total Campus Solved

{totalCampusSolved.toLocaleString()}

Problems across all coders

Active Coders

{profiles.length}

Registered RIT coders

Sync Frequency

Every 24 Hours

3s spaced rate-limiting

{/* Search & Filter Controls */}
setSearchQuery(e.target.value)} className="w-full pl-10 pr-4 py-2.5 rounded-xl bg-[#F8FAFC] border border-[#E2E8F0] text-sm text-[#1E293B] placeholder-slate-400 focus:outline-none focus:border-[#F97316] transition-colors" />
{/* Leaderboard Table */}
{loading ? (

Fetching LeetCode rankings...

) : filteredProfiles.length === 0 ? (

No coders found

Be the first to register your LeetCode handle!

) : ( <> {/* Mobile Card View (Small Screens) */}
{filteredProfiles.map((p, index) => { const rank = index + 1; const total = p.totalSolved || 1; const easyPct = Math.round(((p.easySolved || 0) / total) * 100); const medPct = Math.round(((p.mediumSolved || 0) / total) * 100); const hardPct = Math.round(((p.hardSolved || 0) / total) * 100); return (
{rank === 1 ? ( 🥇 ) : rank === 2 ? ( 🥈 ) : rank === 3 ? ( 🥉 ) : ( #{rank} )}

{p.studentName}

@{p.leetcodeUsername}

{p.totalSolved}

Solved

{p.department} {p.year}
LeetCode Profile
{/* Progress Bar */}
Easy: {p.easySolved} Med: {p.mediumSolved} Hard: {p.hardSolved}
); })}
{/* Desktop Table View (Medium Screens & Up) */}
{filteredProfiles.map((p, index) => { const rank = index + 1; const total = p.totalSolved || 1; const easyPct = Math.round(((p.easySolved || 0) / total) * 100); const medPct = Math.round(((p.mediumSolved || 0) / total) * 100); const hardPct = Math.round(((p.hardSolved || 0) / total) * 100); return ( {/* Rank */} {/* Student Info */} {/* Dept & Year */} {/* Total Solved */} {/* Problem Breakdown Bars */} {/* LeetCode Global Rank */} {/* Profile Link */} ); })}
Rank Student Dept & Year Total Solved Problems Breakdown LeetCode Rank Profile
{rank === 1 ? (
🥇
) : rank === 2 ? (
🥈
) : rank === 3 ? (
🥉
) : ( #{rank} )}

{p.studentName}

@{p.leetcodeUsername}

{p.department} {p.year} {p.totalSolved}
Easy: {p.easySolved} Med: {p.mediumSolved} Hard: {p.hardSolved}
{p.ranking > 0 ? ( #{p.ranking.toLocaleString()} ) : ( - )}
)}
{/* Registration Modal */} {showModal && (

Register LeetCode Handle

Join the RIT campus coding rankings

setStudentName(e.target.value)} className="w-full px-4 py-2.5 rounded-xl bg-[#F8FAFC] border border-[#E2E8F0] text-sm text-[#1E293B] focus:outline-none focus:border-[#F97316]" />
setLeetcodeUsername(e.target.value)} className="w-full px-4 py-2.5 rounded-xl bg-[#F8FAFC] border border-[#E2E8F0] text-sm text-[#1E293B] focus:outline-none focus:border-[#F97316]" />

We will immediately fetch your problem stats from LeetCode.

)}
); }