// frontend/components/dashboard-stats.tsx - ONLY REAL DATA "use client" import { useState, useEffect } from "react" import { useAuth } from "@/context/auth-context" import { useRouter } from "next/navigation" import { toast } from "react-hot-toast" import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { Progress } from "@/components/ui/progress" import { Trophy, BookOpen, Code, CheckCircle2, Wallet, Shield, Activity, Target, Timer, Award, Zap, Globe, User, BarChart3, Flame, Brain, Loader2, AlertCircle } from "lucide-react" import { UsernameSetup } from "./UsernameSetup" import api from "@/lib/api" interface DashboardStats { total_xp: number courses_completed: number coding_problems_solved: number quiz_accuracy: number coding_streak: number longest_streak: number total_courses: number total_quizzes: number global_rank: number weekly_activity: number[] monthly_goals: { target: number; completed: number } blockchain: { wallet_connected: boolean wallet_address: string total_earned: number transactions: number certificates: number verified_achievements: number } learning_analytics: { time_spent_hours: number average_session_minutes: number completion_rate: number favorite_topics: string[] skill_levels: { [key: string]: number } } recent_achievements: Array<{ id: string title: string description: string earned_at: string points: number rarity: string }> } interface UserProfile { user_id: string wallet_address?: string display_name?: string username_set?: boolean avatar_url?: string created_at: string } interface ActivityData { id: string type: string title: string description: string completed_at: string points_earned: number blockchain_verified?: boolean } interface LeaderboardEntry { rank: number user_id: string username: string display_name?: string total_xp: number streak: number avatar?: string wallet_address?: string } export function DashboardStatsOverview() { const { walletAddress, walletConnected, isLoadingAuth } = useAuth() const router = useRouter() const [stats, setStats] = useState(null) const [userProfile, setUserProfile] = useState(null) const [activity, setActivity] = useState([]) const [leaderboard, setLeaderboard] = useState([]) const [isLoadingData, setIsLoadingData] = useState(true) const [usernameRequired, setUsernameRequired] = useState(false) const [error, setError] = useState(null) useEffect(() => { if (!isLoadingAuth && !walletConnected) { toast.error("Please connect your MetaMask wallet to view dashboard.") router.push("/auth/login") return } if (walletConnected && walletAddress) { fetchPureMongoDBData() } }, [walletConnected, walletAddress, isLoadingAuth, router]) const fetchPureMongoDBData = async () => { setIsLoadingData(true) setError(null) try { console.log('📊 Fetching PURE MongoDB data for wallet:', walletAddress) const [statsRes, activityRes, leaderboardRes] = await Promise.all([ api.get<{ success: boolean data?: DashboardStats user_profile: UserProfile username_required?: boolean data_source: string message?: string }>("/api/dashboard/comprehensive-stats"), api.get<{success: boolean, data: ActivityData[], data_source: string}>("/api/dashboard/recent-activity"), api.get<{success: boolean, data: LeaderboardEntry[], data_source: string}>("/api/dashboard/global-leaderboard") ]) // ✅ VERIFY DATA SOURCE IS PURE MONGODB if (statsRes.data.data_source !== "pure_mongodb_data" && statsRes.data.data_source !== "empty_real_data") { console.error("❌ Data source is not pure MongoDB:", statsRes.data.data_source) toast.error("Invalid data source detected. Refreshing...") return } if (statsRes.data.success) { if (statsRes.data.username_required) { setUsernameRequired(true) setUserProfile(statsRes.data.user_profile) setIsLoadingData(false) return } setStats(statsRes.data.data || null) setUserProfile(statsRes.data.user_profile) setUsernameRequired(false) console.log('✅ Pure MongoDB data loaded for user:', statsRes.data.user_profile?.display_name) console.log('📊 Data source verified:', statsRes.data.data_source) } if (activityRes.data.success && activityRes.data.data_source === "pure_mongodb_data") { setActivity(activityRes.data.data) console.log('✅ Real activity loaded:', activityRes.data.data.length, 'items') } if (leaderboardRes.data.success && leaderboardRes.data.data_source === "pure_mongodb_data") { setLeaderboard(leaderboardRes.data.data) console.log('✅ Real leaderboard loaded:', leaderboardRes.data.data.length, 'users') } } catch (err: any) { console.error("Failed to fetch pure MongoDB data:", err) setError(err.response?.data?.message || "Failed to load dashboard data.") if (err.response?.status === 401) { toast.error("MetaMask authentication required.") router.push("/auth/login") } else { toast.error("Failed to load real dashboard data.") setStats(null) setActivity([]) setLeaderboard([]) } } finally { setIsLoadingData(false) } } const handleUsernameSet = (profile: UserProfile) => { setUserProfile(profile) setUsernameRequired(false) fetchPureMongoDBData() } const formatTimeAgo = (dateString: string) => { const diff = Date.now() - new Date(dateString).getTime() const hours = Math.floor(diff / (1000 * 60 * 60)) const days = Math.floor(hours / 24) if (days > 0) return `${days}d ago` if (hours > 0) return `${hours}h ago` return 'Just now' } const getRarityColor = (rarity: string) => { switch (rarity) { case 'legendary': return 'bg-gradient-to-r from-yellow-400 to-orange-500 text-white' case 'epic': return 'bg-gradient-to-r from-purple-500 to-pink-500 text-white' case 'rare': return 'bg-gradient-to-r from-blue-500 to-cyan-500 text-white' default: return 'bg-gradient-to-r from-gray-500 to-gray-600 text-white' } } // Loading state if (isLoadingAuth || isLoadingData) { return (

Loading Pure MongoDB Data

Fetching your real learning progress from database...

{walletAddress && (

🦊 {walletAddress.slice(0, 6)}...{walletAddress.slice(-4)}

)}
) } // Username setup required if (usernameRequired && userProfile) { return ( ) } // Empty state - no real data if (!stats && userProfile) { return (

No Learning Data Found

Start your learning journey to see real analytics here!

{/* Show user profile info */}

{userProfile.display_name || 'New Learner'}

🦊 {userProfile.wallet_address?.slice(0, 6)}...{userProfile.wallet_address?.slice(-4)}

✅ Ready for learning - Pure MongoDB tracking

) } // Error state if (!stats) { return (

Unable to Load Dashboard

Please ensure your MetaMask wallet is connected and try again.

) } return (
{/* Header with Real User Info */}
User Avatar {stats.coding_streak > 0 && (
)}

Welcome, {userProfile?.display_name || 'Learner'}! 🦊

Your real learning progress from MongoDB

🦊 {walletAddress?.slice(0, 6)}...{walletAddress?.slice(-4)} ✅ Pure MongoDB Data
Rank #{stats.global_rank.toLocaleString()} {stats.total_xp.toLocaleString()} XP MetaMask Verified
{/* Real Metrics Grid */}
{/* Coding Streak */}
Real Coding Streak
{stats.coding_streak}

Best: {stats.longest_streak} days

0 ? (stats.coding_streak / stats.longest_streak) * 100 : 0} className="h-2" />
{/* Course Progress */} Real Course Progress
{stats.courses_completed}/{stats.total_courses}

{stats.total_courses > 0 ? Math.round((stats.courses_completed / stats.total_courses) * 100) : 0}% completed

0 ? (stats.courses_completed / stats.total_courses) * 100 : 0} className="h-2" />
{/* Problem Solving */} Real Problems Solved
{stats.coding_problems_solved}

{stats.learning_analytics.completion_rate.toFixed(1)}% success rate

MongoDB Verified
{/* Quiz Performance */} Real Quiz Accuracy
{stats.quiz_accuracy.toFixed(1)}%

{stats.total_quizzes} real quizzes completed

{/* Real Learning Analytics */} Real Learning Analytics from MongoDB 100% Authentic Data {/* Time Stats */}
{stats.learning_analytics.time_spent_hours}h

Real Time Spent

{stats.learning_analytics.average_session_minutes}m

Avg Session

{stats.learning_analytics.completion_rate.toFixed(1)}%

Real Completion Rate

{/* Real Skill Levels */}

Real Skill Progression from MongoDB

{Object.entries(stats.learning_analytics.skill_levels).map(([skill, level]) => (
{skill} {level}%
))}
{/* Real Weekly Activity */}

Real Weekly Activity Pattern

{stats.weekly_activity.map((activity, index) => { const maxActivity = Math.max(...stats.weekly_activity) || 1 return (
{['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][index]}
) })}
{/* Real Recent Activity */} Real Activity History from MongoDB {activity.length > 0 ? (
{activity.map((item) => (
{item.type === 'course' && } {item.type === 'quiz' && } {item.type === 'coding' && } {item.type === 'achievement' && }

{item.title}

{item.blockchain_verified && ( Verified )}

{item.description}

{formatTimeAgo(item.completed_at)} +{item.points_earned} XP
))}
) : (

No real activity found in MongoDB

Start learning to see your authentic activity here!

)}
{/* Real Global Leaderboard */} {leaderboard.length > 0 && ( Real Global Leaderboard from MongoDB
{leaderboard.slice(0, 10).map((entry) => (
{entry.rank}
{entry.username}
{entry.display_name || entry.username} {entry.wallet_address && ( 🦊 Real User )}

{entry.user_id.slice(0, 8)}...{entry.user_id.slice(-4)}

{entry.total_xp.toLocaleString()} Real XP
{entry.streak} day streak
))}
)}
) }