"use client" import { fetchWithAuth } from "@/lib/apiClient"; import { useRef, useState, useEffect } from "react" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { BrainCircuit, Play, ChevronRight, Activity, Target, CheckCircle2, AlertTriangle, TrendingUp, Calendar, Zap, LayoutDashboard, Share2, Trophy, Lock, ArrowRight, Clock, Download } from "lucide-react" import { MistakeHeatmap } from "@/components/AI/MistakeHeatmap" import { AdaptiveStudyPlan } from "@/components/AI/AdaptiveStudyPlan" import { useActiveUser } from "@/hooks/useActiveUser" export default function DashboardPage() { const { user, userId, loading: userLoading, hasAccessTo, trialInfo } = useActiveUser() const [userStats, setUserStats] = useState(null) const [loading, setLoading] = useState(true) const [downloading, setDownloading] = useState(false) const [shareMenuOpen, setShareMenuOpen] = useState(false) const progressRef = useRef(null) useEffect(() => { if (userLoading) return const currentUserId = user?.id || userId if (!currentUserId) { setLoading(false) return } async function fetchStats() { try { const res = await fetchWithAuth(`/api/users/${currentUserId}/stats`) if (res.ok) { const data = await res.json() setUserStats(data) } } catch (e) { console.error("Failed to load user stats", e) } finally { setLoading(false) } } fetchStats() }, [userLoading, user?.id, userId]) const getShareUrl = () => { const score = isNew ? "0 / 0" : `${userStats?.today_score || 0} / ${userStats?.today_max_score || 60}` const accuracy = isNew ? "0%" : `${userStats?.overall_accuracy || 0}%` const qs = isNew ? "0" : (userStats?.total_questions_attempted || 0).toLocaleString() const rank = isNew ? "#--" : `#${userStats?.city_rank || 1} / ${userStats?.city_total || 50}` const target = user?.target_exam === "NEET" ? "NEET" : "JEE" const plan = user?.tier === "AI Coach" ? "AI Coach" : user?.tier || "Free" const name = user?.name || "Student" const date = new Intl.DateTimeFormat('en-IN', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'Asia/Kolkata', }).format(new Date()); const isDark = typeof document !== 'undefined' && document.documentElement.classList.contains('dark'); const themeParam = isDark ? 'dark' : 'light'; if (!user) return ""; return `/api/og/dashboard/${user.id}?theme=${themeParam}&date=${encodeURIComponent(date)}` } const handleDownload = async () => { try { setDownloading(true) const url = getShareUrl() const res = await fetch(url) const blob = await res.blob() const blobUrl = window.URL.createObjectURL(blob) const link = document.createElement('a') link.download = 'pragativeer-dashboard.png' link.href = blobUrl document.body.appendChild(link) link.click() document.body.removeChild(link) window.URL.revokeObjectURL(blobUrl) } catch (err) { console.error("Failed to export image", err) } finally { setDownloading(false) setShareMenuOpen(false) } } const handleShareFacebook = () => { const fullUrl = window.location.origin + getShareUrl() window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(fullUrl)}`, '_blank') setShareMenuOpen(false) } const handleShareWhatsApp = () => { const fullUrl = window.location.origin + getShareUrl() const text = `Check out my performance on PragatiVeer!\n\n${fullUrl}` window.open(`https://wa.me/?text=${encodeURIComponent(text)}`, '_blank') setShareMenuOpen(false) } if (loading) { return (

Loading dashboard...

) } const isNew = userStats ? userStats.is_new_user : true const isNeet = user?.target_exam === "NEET" return (
{/* Basic Performance Dashboard (F-05) */}

Performance Overview

Your overall progress, scores, and active study plan at a glance.

{shareMenuOpen && (
)}
{/* Today's Score */}

Today's Score

{isNew ? "0 / 0" : `${userStats.today_score} / ${userStats.today_max_score || 60}`}

{isNew ? "No tests taken today" : userStats.today_score > 0 ? "Daily session score" : "Start today's DPP"}

{/* Overall Accuracy */}

Overall Accuracy

{isNew ? "0%" : `${userStats.overall_accuracy}%`}

= 70 ? 'text-green-500' : 'text-amber-500'}`}> {isNew ? "Start a DPP to calculate" : userStats.overall_accuracy >= 70 ? "On Track" : "Needs Improvement"}

{/* Qs Attempted */}

Qs Attempted

{isNew ? "0" : (userStats.total_questions_attempted || 0).toLocaleString()}

{isNew ? "0 questions answered" : "Lifetime total"}

{/* City Rank */}

City Rank

{isNew ? ( #-- ) : ( <>#{userStats.city_rank || 1} / {userStats.city_total || 50} )}

{isNew ? "Unranked · Take a test" : `Top rank in ${user?.city || "your city"}`}

{/* Dynamic DPP Modules */}

Today's DPPs

Physics: Rotational Dynamics

20 Questions • High Priority

{hasAccessTo("topic-wise-microtests-unlimited") ? (

{isNeet ? "Biology: Human Physiology" : "Maths: Integral Calculus"}

30 Questions • Medium Priority

) : (

{isNeet ? "Biology: Human Physiology" : "Maths: Integral Calculus"}

Pro Feature

)}
{/* Upcoming CBTs */}

Upcoming CBTs

Mock Test Tomorrow, 10:00 AM

AITS Full Syllabus Test 4

180 Minutes • 720 Marks

{hasAccessTo("weekly-test-series") ? (

Part Test 3: Mechanics

Oct 24, 2026

) : (

Part Test 3: Mechanics

Oct 24, 2026

Pro Only
)}
) }