RotNot / src /app /stats /page.tsx
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
30.6 kB
"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 (
<div
className="glass-md rounded-lg px-3 py-2 text-xs space-y-1"
style={{ border: "1px solid rgba(99,102,241,0.3)" }}
>
<div style={{ color: "var(--text-secondary)", fontWeight: 600 }}>
{label}
</div>
<div>
<span style={{ color: "#6366f1", fontWeight: 700 }}>{d.xpEarned}</span>{" "}
XP · {d.activityCount} exercise{d.activityCount !== 1 ? "s" : ""}
</div>
{d.goalMet && (
<div style={{ color: "#10b981" }}>✓ Goal met</div>
)}
</div>
);
}
// ─── 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<StatsResponse | null>(null);
const [personalBests, setPersonalBests] = useState<PersonalBestRecord[]>([]);
const [bestScores, setBestScores] = useState<BestScoresResponse | null>(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<string | null>(null);
const [chartDays, setChartDays] = useState<ChartWindow>(30);
const [activityCategory, setActivityCategory] = useState<string>("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 (
<div className="max-w-5xl mx-auto py-16 flex items-center justify-center">
<div
className="text-lg animate-pulse"
style={{ color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}
>
Loading stats…
</div>
</div>
);
}
if (error || !data) {
return (
<div className="max-w-5xl mx-auto py-16">
<div
className="glass-md rounded-xl p-8 text-center"
style={{ color: "#f43f5e" }}
>
{error ?? "No data"}
</div>
</div>
);
}
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 (
<div className="max-w-5xl mx-auto space-y-8">
{/* ── Header ── */}
<motion.div
initial={{ opacity: 0, y: -16 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4 }}
>
<h1
className="text-3xl font-bold tracking-tight"
style={{ fontFamily: "var(--font-mono)" }}
>
Stats
</h1>
<p className="mt-1" style={{ color: "var(--text-secondary)" }}>
Your training history and performance breakdown.
</p>
</motion.div>
{/* ── Summary Cards ── */}
<motion.div
className="grid grid-cols-2 md:grid-cols-4 gap-4"
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.05, duration: 0.4 }}
>
{[
{ 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 }) => (
<div key={label} className="glass-md rounded-xl p-5 text-center">
<div className="text-2xl mb-2">{icon}</div>
<div
className="text-2xl font-bold"
style={{ fontFamily: "var(--font-mono)" }}
>
{value}
</div>
<div
className="text-xs mt-1 uppercase tracking-wider"
style={{ color: "var(--text-muted)" }}
>
{label}
</div>
{sub && (
<div
className="text-xs mt-0.5"
style={{ color: "var(--text-muted)" }}
>
{sub}
</div>
)}
</div>
))}
</motion.div>
{/* ── XP Over Time Chart ── */}
<motion.div
className="glass-md rounded-2xl p-6 space-y-4"
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1, duration: 0.4 }}
>
<div className="flex items-center justify-between gap-2 flex-wrap">
<h2
className="text-lg font-bold uppercase tracking-widest"
style={{ fontFamily: "var(--font-mono)", color: "var(--text-secondary)" }}
>
XP Over Time
</h2>
{/* Time window toggle */}
<div className="flex items-center gap-1">
{CHART_WINDOWS.map(({ days, label }) => {
const active = chartDays === days;
return (
<button
key={days}
onClick={() => handleChartWindowChange(days)}
disabled={chartLoading}
className="px-2.5 py-1 rounded-lg text-xs font-semibold transition-all disabled:opacity-50"
style={{
background: active
? "rgba(99,102,241,0.25)"
: "rgba(255,255,255,0.05)",
border: `1px solid ${active ? "rgba(99,102,241,0.6)" : "rgba(255,255,255,0.08)"}`,
color: active ? "#a5b4fc" : "var(--text-muted)",
cursor: chartLoading ? "wait" : "pointer",
}}
>
{label}
</button>
);
})}
</div>
</div>
{chartData.length === 0 ? (
<div
className="py-16 text-center text-sm"
style={{ color: "var(--text-muted)" }}
>
No data yet. Complete some exercises to see your progress!
</div>
) : (
<div style={{ width: "100%", height: 280, opacity: chartLoading ? 0.5 : 1, transition: "opacity 0.2s" }}>
<ResponsiveContainer>
<AreaChart data={chartData} margin={{ top: 8, right: 8, left: -16, bottom: 0 }}>
<defs>
<linearGradient id="xpGradient" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#6366f1" stopOpacity={0.4} />
<stop offset="95%" stopColor="#6366f1" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid
strokeDasharray="3 3"
stroke="rgba(255,255,255,0.06)"
/>
<XAxis
dataKey="label"
tick={{ fill: "rgba(255,255,255,0.4)", fontSize: 11 }}
tickLine={false}
axisLine={{ stroke: "rgba(255,255,255,0.08)" }}
/>
<YAxis
tick={{ fill: "rgba(255,255,255,0.4)", fontSize: 11 }}
tickLine={false}
axisLine={false}
/>
<Tooltip content={<ChartTooltip />} />
<Area
type="monotone"
dataKey="xpEarned"
stroke="#6366f1"
strokeWidth={2}
fill="url(#xpGradient)"
dot={false}
activeDot={{
r: 5,
fill: "#6366f1",
stroke: "#fff",
strokeWidth: 2,
}}
/>
</AreaChart>
</ResponsiveContainer>
</div>
)}
</motion.div>
{/* ── Category Breakdown (Pie + Table) ── */}
<motion.div
className="glass-md rounded-2xl p-6 space-y-4"
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.15, duration: 0.4 }}
>
<h2
className="text-lg font-bold uppercase tracking-widest"
style={{ fontFamily: "var(--font-mono)", color: "var(--text-secondary)" }}
>
Category Breakdown
</h2>
{pieData.length === 0 ? (
<div
className="py-12 text-center text-sm"
style={{ color: "var(--text-muted)" }}
>
No exercises completed yet.
</div>
) : (
<div className="flex flex-col md:flex-row gap-6 items-center">
{/* Pie chart */}
<div style={{ width: 200, height: 200, flexShrink: 0 }}>
<ResponsiveContainer>
<PieChart>
<Pie
data={pieData}
cx="50%"
cy="50%"
innerRadius={50}
outerRadius={85}
paddingAngle={2}
dataKey="value"
stroke="none"
>
{pieData.map((entry, i) => (
<Cell key={i} fill={entry.color} />
))}
</Pie>
</PieChart>
</ResponsiveContainer>
</div>
{/* Legend + stats */}
<div className="flex-1 space-y-3 w-full">
{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 (
<div key={cat} className="flex items-center gap-3">
<div
className="w-3 h-3 rounded-sm flex-shrink-0"
style={{ background: color }}
/>
<div className="flex-1 min-w-0">
<div className="flex justify-between items-baseline">
<span
className="text-sm font-semibold"
style={{ color }}
>
{getCategoryLabel(cat)}
</span>
<span
className="text-xs"
style={{ color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}
>
{bd.totalXp.toLocaleString()} XP ({pct}%)
</span>
</div>
<div
className="text-xs"
style={{ color: "var(--text-muted)" }}
>
{bd.count} exercise{bd.count !== 1 ? "s" : ""} ·{" "}
{fmtDuration(bd.totalDuration)}
</div>
</div>
</div>
);
})}
</div>
</div>
)}
</motion.div>
{/* ── Personal Records ── */}
{personalBests.length > 0 && (
<motion.div
className="glass-md rounded-2xl p-6 space-y-4"
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.15, duration: 0.4 }}
>
<h2
className="text-lg font-bold uppercase tracking-widest"
style={{ fontFamily: "var(--font-mono)", color: "var(--text-secondary)" }}
>
🏆 Personal Records
</h2>
<p className="text-xs" style={{ color: "var(--text-muted)" }}>
Fastest correct solves per puzzle type and difficulty
</p>
{/* Group records by exerciseType */}
{(() => {
const grouped = new Map<string, PersonalBestRecord[]>();
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]) => (
<div key={type} className="space-y-1">
<div
className="text-xs font-semibold uppercase tracking-wider pt-1"
style={{ color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}
>
{records[0].exerciseLabel}
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
{records.map((r) => {
const diffColor =
r.difficulty === "easy"
? "#10b981"
: r.difficulty === "medium"
? "#f59e0b"
: "#ef4444";
return (
<div
key={`${r.exerciseType}-${r.difficulty}`}
className="flex items-center justify-between px-3 py-2 rounded-lg"
style={{ background: "rgba(255,255,255,0.04)" }}
>
<div className="flex items-center gap-2">
<span
className="text-xs font-semibold capitalize"
style={{ color: diffColor }}
>
{r.difficulty}
</span>
<span
className="text-xs"
style={{ color: "var(--text-muted)" }}
>
·{" "}{r.solveCount} solve{r.solveCount !== 1 ? "s" : ""}
</span>
</div>
<span
className="text-sm font-bold"
style={{
fontFamily: "var(--font-mono)",
color: "#a78bfa",
}}
>
{fmtDuration(r.bestSecs)}
</span>
</div>
);
})}
</div>
</div>
));
})()}
</motion.div>
)}
{/* ── Best Scores ── */}
{bestScores && bestScores.byExerciseType.length > 0 && (
<motion.div
className="glass-md rounded-2xl p-6 space-y-4"
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.18, duration: 0.4 }}
>
<h2
className="text-lg font-bold uppercase tracking-widest"
style={{ fontFamily: "var(--font-mono)", color: "var(--text-secondary)" }}
>
🎯 Best Scores
</h2>
<p className="text-xs" style={{ color: "var(--text-muted)" }}>
All-time highest quality scores by category and exercise type
</p>
{/* Category summary row */}
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-2">
{bestScores.byCategory.map((cat) => {
const color = getCategoryColor(cat.category);
const hasData = cat.attemptCount > 0;
return (
<div
key={cat.category}
className="rounded-lg px-3 py-2.5 text-center"
style={{
background: hasData ? `${color}15` : "rgba(255,255,255,0.03)",
border: `1px solid ${hasData ? color + "30" : "rgba(255,255,255,0.06)"}`,
}}
>
<div
className="text-lg font-bold"
style={{
fontFamily: "var(--font-mono)",
color: hasData ? color : "var(--text-muted)",
}}
>
{hasData ? `${Math.round(cat.bestScore * 100)}%` : "—"}
</div>
<div
className="text-[10px] font-semibold uppercase tracking-wider mt-0.5"
style={{ color: hasData ? color : "var(--text-muted)" }}
>
{cat.categoryLabel}
</div>
{hasData && (
<div
className="text-[10px] mt-0.5"
style={{ color: "var(--text-muted)" }}
>
avg {Math.round(cat.avgScore * 100)}%
</div>
)}
</div>
);
})}
</div>
{/* Exercise type breakdown grouped by category */}
{(() => {
const grouped = new Map<string, BestScoreEntry[]>();
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 (
<div key={cat} className="space-y-1">
<div
className="text-xs font-semibold uppercase tracking-wider pt-1 flex items-center gap-2"
style={{ color, fontFamily: "var(--font-mono)" }}
>
<div
className="w-2 h-2 rounded-full flex-shrink-0"
style={{ background: color }}
/>
{getCategoryLabel(cat)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
{entries.map((e) => (
<div
key={`${e.category}-${e.exerciseType}`}
className="flex items-center justify-between px-3 py-2 rounded-lg"
style={{ background: "rgba(255,255,255,0.04)" }}
>
<div className="flex flex-col gap-0.5">
<span className="text-sm font-medium" style={{ color: "var(--text-primary)" }}>
{e.exerciseLabel}
</span>
<span className="text-[10px]" style={{ color: "var(--text-muted)" }}>
{e.scoredCount} scored / {e.attemptCount} total
</span>
</div>
<div className="text-right flex-shrink-0">
<div
className="text-sm font-bold"
style={{ fontFamily: "var(--font-mono)", color }}
>
{Math.round(e.bestScore * 100)}%
</div>
<div
className="text-[10px]"
style={{ color: "var(--text-muted)" }}
>
{format(new Date(e.achievedAt), "MMM d")}
</div>
</div>
</div>
))}
</div>
</div>
);
});
})()}
</motion.div>
)}
{/* ── Activity Log ── */}
<motion.div
className="glass-md rounded-2xl p-6 space-y-4"
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2, duration: 0.4 }}
>
<div className="flex items-center justify-between gap-2 flex-wrap">
<h2
className="text-lg font-bold uppercase tracking-widest"
style={{ fontFamily: "var(--font-mono)", color: "var(--text-secondary)" }}
>
Activity Log
</h2>
{activityTotal > 0 && (
<span
className="text-xs"
style={{ color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}
>
{recentActivities.length} / {activityTotal}
</span>
)}
</div>
{/* Category filter tabs */}
<div className="flex flex-wrap gap-1.5">
{(["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 (
<button
key={cat}
onClick={() => handleCategoryFilterChange(cat)}
disabled={filterLoading}
className="px-3 py-1 rounded-full text-xs font-semibold transition-all disabled:opacity-50"
style={{
background: isActive
? `${color}33`
: "rgba(255,255,255,0.05)",
color: isActive ? color : "var(--text-muted)",
border: `1px solid ${isActive ? color + "66" : "rgba(255,255,255,0.08)"}`,
}}
>
{label}
</button>
);
})}
</div>
{(recentActivities.length === 0 && !filterLoading) ? (
<div
className="py-12 text-center text-sm"
style={{ color: "var(--text-muted)" }}
>
{activityCategory === "all"
? "No activities yet."
: `No ${getCategoryLabel(activityCategory)} activities yet.`}
</div>
) : (
<>
<div
className="space-y-2 transition-opacity duration-200"
style={{ opacity: filterLoading ? 0.4 : 1 }}
>
{recentActivities.map((a) => {
const color = getCategoryColor(a.category);
return (
<div
key={a.id}
className="flex items-center gap-3 px-4 py-3 rounded-lg"
style={{ background: "rgba(255,255,255,0.03)" }}
>
{/* Category dot */}
<div
className="w-2.5 h-2.5 rounded-full flex-shrink-0"
style={{ background: color }}
/>
{/* Description */}
<div className="flex-1 min-w-0">
<div className="text-sm truncate">
{a.description}
</div>
<div
className="text-xs mt-0.5"
style={{ color: "var(--text-muted)" }}
>
{getCategoryLabel(a.category)} · {a.exerciseType}
{a.durationSecs ? ` · ${fmtDuration(a.durationSecs)}` : ""}
</div>
</div>
{/* XP */}
<div className="text-right flex-shrink-0">
<div
className="text-sm font-bold"
style={{
fontFamily: "var(--font-mono)",
color: a.isCriticalHit ? "#f59e0b" : color,
}}
>
+{a.totalXp} XP
{a.isCriticalHit && (
<span className="ml-1 text-xs">💥</span>
)}
</div>
<div
className="text-xs"
style={{ color: "var(--text-muted)" }}
>
{format(new Date(a.createdAt), "MMM d, h:mm a")}
</div>
</div>
</div>
);
})}
</div>
{/* Load More */}
{hasMoreActivities && (
<div className="pt-2 flex justify-center">
<button
onClick={loadMoreActivities}
disabled={loadingMore}
className="px-5 py-2 rounded-lg text-sm font-semibold transition-opacity disabled:opacity-50"
style={{
background: "rgba(99,102,241,0.15)",
color: "#6366f1",
border: "1px solid rgba(99,102,241,0.3)",
}}
>
{loadingMore ? "Loading…" : `Load More (${activityTotal - recentActivities.length} remaining)`}
</button>
</div>
)}
</>
)}
</motion.div>
</div>
);
}