"use client" import { useState, useEffect } from "react" import { useRouter } from "next/navigation" import { authClient } from "@/lib/auth-client" import { MetricCard } from "@/components/parent/metric-card" import { WeeklyActivityChart } from "@/components/parent/weekly-activity-chart" import { SkillMasteryChart } from "@/components/parent/skill-mastery-chart" import { MilestonesList } from "@/components/parent/milestones-list" import ErrorPatternsChart from "@/components/parent/error-patterns-chart" interface ChildSummary { id: string name: string | null } interface DashboardData { totalSessions: number todaySessions: number todayMinutes: number masteryPercent: number masteredSkills: number totalSkills: number milestones: number milestoneData: { skillCode: string; reachedAt: string }[] streak: number weeklyData: { date: string; minutes: number }[] skillBreakdown: { skillCode: string; stability: number; reps: number }[] stageProgress: { topic: string; stage: number; completedAt: string | null }[] errorTypeCount: Record totalErrors: number lastSession: { startedAt: string durationSec: number skillsPracticed: string correctCount: number totalAttempts: number } | null } export default function ParentDashboard() { const { data: session, isPending } = authClient.useSession() const router = useRouter() const [children, setChildren] = useState([]) const [selectedChildId, setSelectedChildId] = useState("") const [data, setData] = useState(null) const [loading, setLoading] = useState(true) const [creating, setCreating] = useState(false) const [newChildName, setNewChildName] = useState("") const [pairingCode, setPairingCode] = useState("") useEffect(() => { fetch("/api/children") .then((r) => r.json()) .then((list) => { if (Array.isArray(list)) { setChildren(list) if (list.length > 0) setSelectedChildId(list[0].id) } }) .catch(() => {}) }, []) useEffect(() => { if (!selectedChildId) { setLoading(false) return } setLoading(true) fetch(`/api/dashboard/summary?childId=${selectedChildId}`) .then((r) => r.json()) .then(setData) .catch(() => {}) .finally(() => setLoading(false)) }, [selectedChildId]) const handleCreateChild = async () => { if (!newChildName.trim()) return setCreating(true) const res = await fetch("/api/children", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: newChildName.trim() }), }) if (res.ok) { const child = await res.json() setChildren((prev) => [...prev, child]) setSelectedChildId(child.id) setNewChildName("") } setCreating(false) } const handleGeneratePairingCode = async () => { if (!selectedChildId) return const res = await fetch("/api/pairing", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "generate", childId: selectedChildId }), }) const data = await res.json() if (data.pairingCode) { setPairingCode(data.pairingCode) } } useEffect(() => { if (!isPending && !session) { router.push("/parent/auth/login") } }, [session, isPending, router]) if (isPending || !session) { return (
Cargando...
) } const selectedChild = children.find((c) => c.id === selectedChildId) return (

Dashboard

Bienvenida, {session.user?.name || "Mamá"}

{children.length === 0 ? (

Agregar un niño

setNewChildName(e.target.value)} placeholder="Nombre de la nena" className="flex-1 rounded-xl border border-border bg-white px-4 py-3 text-base focus:outline-none focus:ring-2 focus:ring-primary" />
) : ( <>
{children.map((c) => ( ))}
{loading ? (
Cargando...
) : data ? (
0 ? `${data.todaySessions} sesiones` : undefined} variant="success" />

Actividad semanal

Maestría por skill

Logros

{data.stageProgress.length > 0 && (

Progreso curricular

{data.stageProgress.map((sp) => (
{sp.topic === "lectura" ? "Lectura" : "Números"} — Etapa {sp.stage} {sp.completedAt ? "✅ Completada" : "🔵 En curso"}
))}
)} {data.totalErrors > 0 && (

Patrones de error

)} {data.lastSession && (

Última sesión

{new Date(data.lastSession.startedAt).toLocaleDateString("es-AR")}

{Math.round((data.lastSession.durationSec ?? 0) / 60)} min ·{" "} {data.lastSession.correctCount}/{data.lastSession.totalAttempts} correctas

Skills: {data.lastSession.skillsPracticed || "—"}

)}
) : (
Seleccioná un niño para ver su progreso
)} )} {pairingCode && (

Código de emparejamiento

Ingresá este código en el iPad de la nena

{pairingCode}

)}
) }