"use client"; import { useState, useEffect, useCallback } from "react"; import { motion } from "framer-motion"; import { format } from "date-fns"; import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, } from "recharts"; import { CATEGORIES, CATEGORY_LABELS, CATEGORY_COLORS, } from "@/config/xp"; import type { Category } from "@/config/xp"; import { apiClient, ApiClientError } from "@/lib/api-client"; import type { BestScoreEntry, BestScoresResponse, PersonalBestRecord, StatsResponse, StatsDailyXp, } from "@/lib/api-client"; // ─── Helpers ────────────────────────────────────────────────────────────────── function fmtDuration(secs: number): string { if (secs < 60) return `${secs}s`; if (secs < 3600) return `${Math.round(secs / 60)}m`; const h = Math.floor(secs / 3600); const m = Math.round((secs % 3600) / 60); return m > 0 ? `${h}h ${m}m` : `${h}h`; } function getCategoryColor(cat: string): string { return CATEGORY_COLORS[cat as Category] ?? "#6366f1"; } function getCategoryLabel(cat: string): string { return CATEGORY_LABELS[cat as Category] ?? cat; } // ─── Custom Tooltip ─────────────────────────────────────────────────────────── function ChartTooltip({ active, payload, label, }: { active?: boolean; payload?: Array<{ value: number; payload: StatsDailyXp }>; label?: string; }) { if (!active || !payload?.length) return null; const d = payload[0].payload; return (
{label}
{d.xpEarned}{" "} XP · {d.activityCount} exercise{d.activityCount !== 1 ? "s" : ""}
{d.goalMet && (
✓ Goal met
)}
); } // ─── Main Page ──────────────────────────────────────────────────────────────── type ChartWindow = 7 | 30 | 90; const CHART_WINDOWS: { days: ChartWindow; label: string }[] = [ { days: 7, label: "7d" }, { days: 30, label: "30d" }, { days: 90, label: "90d" }, ]; const ACTIVITY_PAGE_SIZE = 25; export default function StatsPage() { const [data, setData] = useState(null); const [personalBests, setPersonalBests] = useState([]); const [bestScores, setBestScores] = useState(null); const [loading, setLoading] = useState(true); const [chartLoading, setChartLoading] = useState(false); const [loadingMore, setLoadingMore] = useState(false); const [filterLoading, setFilterLoading] = useState(false); const [error, setError] = useState(null); const [chartDays, setChartDays] = useState(30); const [activityCategory, setActivityCategory] = useState("all"); // Initial full load (stats + personal bests) const load = useCallback(async () => { setLoading(true); setError(null); try { const [json, pbJson, bsJson] = await Promise.all([ apiClient.getStats({ days: chartDays }), apiClient.getPersonalBests().catch(() => ({ records: [] })), apiClient.getBestScores().catch(() => null), ]); setData(json); setPersonalBests(pbJson.records); setBestScores(bsJson); } catch (e) { setError( e instanceof ApiClientError ? `Failed to load stats (${e.status})` : e instanceof Error ? e.message : "Unknown error", ); } finally { setLoading(false); } }, []); // eslint-disable-line react-hooks/exhaustive-deps // Lightweight chart-only reload when window changes (after initial load) const reloadChart = useCallback(async (days: ChartWindow) => { setChartLoading(true); try { const json = await apiClient.getStats({ days }); setData((prev) => prev ? { ...prev, dailyXp: json.dailyXp, windowDays: json.windowDays } : prev); } catch { // silently keep previous data on chart reload failure } finally { setChartLoading(false); } }, []); const handleChartWindowChange = useCallback((days: ChartWindow) => { setChartDays(days); reloadChart(days); }, [reloadChart]); // Category filter change — reset activity list and fetch page 1 with new filter const handleCategoryFilterChange = useCallback(async (cat: string) => { setActivityCategory(cat); setFilterLoading(true); try { const json = await apiClient.getStats({ activityOffset: 0, activityLimit: ACTIVITY_PAGE_SIZE, activityCategory: cat, }); setData((prev) => prev ? { ...prev, recentActivities: json.recentActivities, activityTotal: json.activityTotal, activityCategory: json.activityCategory, } : prev, ); } catch { // silently keep previous list on filter failure } finally { setFilterLoading(false); } }, []); // Load next page of activities and append to list const loadMoreActivities = useCallback(async () => { if (!data || loadingMore) return; setLoadingMore(true); try { const json = await apiClient.getStats({ activityOffset: data.recentActivities.length, activityLimit: ACTIVITY_PAGE_SIZE, activityCategory, }); setData((prev) => prev ? { ...prev, recentActivities: [...prev.recentActivities, ...json.recentActivities], activityTotal: json.activityTotal, } : prev, ); } catch { // silently fail — keep existing list } finally { setLoadingMore(false); } }, [data, loadingMore, activityCategory]); useEffect(() => { load(); }, [load]); if (loading) { return (
Loading stats…
); } if (error || !data) { return (
{error ?? "No data"}
); } const { dailyXp, categoryBreakdown, recentActivities, activityTotal, summary } = data; const hasMoreActivities = recentActivities.length < activityTotal; // Format chart data const chartData = dailyXp.map((d) => ({ ...d, label: format(new Date(d.date), "MMM d"), })); // Pie data const pieData = CATEGORIES.filter((cat) => categoryBreakdown[cat]) .map((cat) => ({ name: getCategoryLabel(cat), value: categoryBreakdown[cat].totalXp, color: getCategoryColor(cat), })) .filter((d) => d.value > 0); const totalPieXp = pieData.reduce((s, d) => s + d.value, 0); return (
{/* ── Header ── */}

Stats

Your training history and performance breakdown.

{/* ── Summary Cards ── */} {[ { label: "Total XP", value: summary.totalXpEarned.toLocaleString(), icon: "⚡" }, { label: "Exercises", value: summary.totalExercises.toLocaleString(), icon: "📚" }, { label: "Time Trained", value: fmtDuration(summary.totalDuration), icon: "⏱️" }, { label: "Accuracy", value: `${summary.correctSolveRate}%`, icon: "🎯", sub: `${summary.correctSolves} correct · ${summary.criticalHitRate}% crits`, }, ].map(({ label, value, icon, sub }) => (
{icon}
{value}
{label}
{sub && (
{sub}
)}
))}
{/* ── XP Over Time Chart ── */}

XP Over Time

{/* Time window toggle */}
{CHART_WINDOWS.map(({ days, label }) => { const active = chartDays === days; return ( ); })}
{chartData.length === 0 ? (
No data yet. Complete some exercises to see your progress!
) : (
} />
)}
{/* ── Category Breakdown (Pie + Table) ── */}

Category Breakdown

{pieData.length === 0 ? (
No exercises completed yet.
) : (
{/* Pie chart */}
{pieData.map((entry, i) => ( ))}
{/* Legend + stats */}
{CATEGORIES.map((cat) => { const bd = categoryBreakdown[cat]; if (!bd || bd.count === 0) return null; const pct = totalPieXp > 0 ? Math.round((bd.totalXp / totalPieXp) * 100) : 0; const color = getCategoryColor(cat); return (
{getCategoryLabel(cat)} {bd.totalXp.toLocaleString()} XP ({pct}%)
{bd.count} exercise{bd.count !== 1 ? "s" : ""} ·{" "} {fmtDuration(bd.totalDuration)}
); })}
)} {/* ── Personal Records ── */} {personalBests.length > 0 && (

🏆 Personal Records

Fastest correct solves per puzzle type and difficulty

{/* Group records by exerciseType */} {(() => { const grouped = new Map(); for (const r of personalBests) { if (!grouped.has(r.exerciseType)) grouped.set(r.exerciseType, []); grouped.get(r.exerciseType)!.push(r); } return Array.from(grouped.entries()).map(([type, records]) => (
{records[0].exerciseLabel}
{records.map((r) => { const diffColor = r.difficulty === "easy" ? "#10b981" : r.difficulty === "medium" ? "#f59e0b" : "#ef4444"; return (
{r.difficulty} ·{" "}{r.solveCount} solve{r.solveCount !== 1 ? "s" : ""}
{fmtDuration(r.bestSecs)}
); })}
)); })()}
)} {/* ── Best Scores ── */} {bestScores && bestScores.byExerciseType.length > 0 && (

🎯 Best Scores

All-time highest quality scores by category and exercise type

{/* Category summary row */}
{bestScores.byCategory.map((cat) => { const color = getCategoryColor(cat.category); const hasData = cat.attemptCount > 0; return (
{hasData ? `${Math.round(cat.bestScore * 100)}%` : "—"}
{cat.categoryLabel}
{hasData && (
avg {Math.round(cat.avgScore * 100)}%
)}
); })}
{/* Exercise type breakdown grouped by category */} {(() => { const grouped = new Map(); for (const entry of bestScores.byExerciseType) { if (!grouped.has(entry.category)) grouped.set(entry.category, []); grouped.get(entry.category)!.push(entry); } return Array.from(grouped.entries()).map(([cat, entries]) => { const color = getCategoryColor(cat); return (
{getCategoryLabel(cat)}
{entries.map((e) => (
{e.exerciseLabel} {e.scoredCount} scored / {e.attemptCount} total
{Math.round(e.bestScore * 100)}%
{format(new Date(e.achievedAt), "MMM d")}
))}
); }); })()} )} {/* ── Activity Log ── */}

Activity Log

{activityTotal > 0 && ( {recentActivities.length} / {activityTotal} )}
{/* Category filter tabs */}
{(["all", ...CATEGORIES] as const).map((cat) => { const isActive = activityCategory === cat; const color = cat === "all" ? "#6366f1" : getCategoryColor(cat); const label = cat === "all" ? "All" : getCategoryLabel(cat); return ( ); })}
{(recentActivities.length === 0 && !filterLoading) ? (
{activityCategory === "all" ? "No activities yet." : `No ${getCategoryLabel(activityCategory)} activities yet.`}
) : ( <>
{recentActivities.map((a) => { const color = getCategoryColor(a.category); return (
{/* Category dot */}
{/* Description */}
{a.description}
{getCategoryLabel(a.category)} · {a.exerciseType} {a.durationSecs ? ` · ${fmtDuration(a.durationSecs)}` : ""}
{/* XP */}
+{a.totalXp} XP {a.isCriticalHit && ( 💥 )}
{format(new Date(a.createdAt), "MMM d, h:mm a")}
); })}
{/* Load More */} {hasMoreActivities && (
)} )}
); }