"use client" import { fetchWithAuth } from "@/lib/apiClient"; import Link from "next/link"; 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, isDemoUser, DEFAULT_USER_ID } from "@/hooks/useActiveUser" import { formatISTDate } from "@/lib/dateUtils" export default function DashboardPage() { const { user, userId, loading: userLoading, hasAccessTo, trialInfo } = useActiveUser() const [userStats, setUserStats] = useState(() => { const currentId = (typeof window !== "undefined" ? localStorage.getItem("activeUserId") : null) || DEFAULT_USER_ID; if (isDemoUser(currentId)) { return { today_score: 42, today_max_score: 60, overall_accuracy: 82.0, total_questions_attempted: 1245, city_rank: 42, city_total: 1200, is_new_user: false, }; } return { today_score: 0, today_max_score: 0, overall_accuracy: 0, total_questions_attempted: 0, city_rank: null, city_total: null, is_new_user: true, }; }) const [loading, setLoading] = useState(true) const [dpps, setDpps] = useState([]) const [cbts, setCbts] = useState([]) const [downloading, setDownloading] = useState(false) const [shareMenuOpen, setShareMenuOpen] = useState(false) const progressRef = useRef(null) useEffect(() => { const currentUserId = user?.id || userId || (typeof window !== "undefined" ? localStorage.getItem("activeUserId") : null) || DEFAULT_USER_ID; if (!currentUserId) { setLoading(false) return } async function fetchStatsAndTests() { try { const pattern = user?.target_exam || "JEE_Main"; const [statsRes, dppRes, cbtRes] = await Promise.all([ fetchWithAuth(`/api/users/${currentUserId}/stats`), fetchWithAuth(`/api/tests?type=DPS&exam_pattern=${pattern}`), fetchWithAuth(`/api/tests?type=Mock&exam_pattern=${pattern}`) ]); if (statsRes.ok) setUserStats(await statsRes.json()); if (dppRes.ok) setDpps((await dppRes.json()).slice(0, 2)); if (cbtRes.ok) setCbts((await cbtRes.json()).slice(0, 2)); } catch (e) { console.error("Failed to load user data", e) } finally { setLoading(false) } } fetchStatsAndTests() }, [user?.id, userId, user?.target_exam]) 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) } const isNew = userStats ? userStats.is_new_user : true const isNeet = user?.target_exam === "NEET" return (
{/* Page Header */}

Performance Overview

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

{shareMenuOpen && (
)}
{/* KPI Stat Cards */}
{/* 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"}`}

{/* Tests & DPPs Grid */}
{/* Dynamic DPP Modules */}

Today's DPPs

{dpps.length > 0 ? ( dpps.map((dpp) => (

{dpp.title}

{dpp.total_time} Minutes • {dpp.difficulty || "Medium"} Priority

)) ) : loading ? (
{[1, 2].map((i) => (
))}
) : (

No DPPs scheduled for today.

)}
{/* Upcoming CBTs */}

Upcoming CBTs

{cbts.length > 0 ? ( cbts.map((cbt, idx) => (
{cbt.exam_pattern} {cbt.scheduled_date ? formatISTDate(cbt.scheduled_date) : 'Available Now'}

{cbt.title}

{cbt.total_time} Minutes • {cbt.difficulty || 'Medium'}

)) ) : loading ? (
) : (

No upcoming CBTs at the moment.

)}
{/* AI Intelligence Grid */}
) }