import { useEffect, useState } from "react";
import { notifyStreakMilestone } from "@/lib/pushNotify";
import { Link, useNavigate } from "react-router-dom";
import { ExamCountdown } from "@/components/neb/ExamCountdown";
import {
  Camera, Swords, ArrowRight, Crown, Target, Users, BrainCircuit,
  Layers, Video, ChevronRight, Play,
} from "lucide-react";
import { DashboardLayout } from "@/components/layout/DashboardLayout";
import { supabase } from "@/integrations/supabase/client";
import { Skeleton } from "@/components/ui/skeleton";
import { DailyChallenges } from "@/components/gamification/DailyChallenges";
import { getLevel } from "@/hooks/useXP";
import { useUserProfile } from "@/contexts/UserProfileContext";
import { useSubscription } from "@/hooks/useSubscription";
import { differenceInDays, format, formatDistanceToNow } from "date-fns";
import { useMetaTags } from "@/hooks/useMetaTags";
import { SubjectBadge } from "@/components/ui/SubjectBadge";
import { SmartDate } from "@/components/SmartDate";
import { useCalendarPref } from "@/hooks/useCalendarPref";
import { formatByPref } from "@/lib/bs-calendar";
import { useSchoolStudent } from "@/hooks/useSchoolStudent";
import { SchoolQuickAccess } from "@/components/dashboard/SchoolQuickAccess";
import { WeakAreasWidget } from "@/components/dashboard/WeakAreasWidget";
import { resolveOnboardingState } from "@/lib/onboarding";
import { dailyPhrase, daysSince } from "@/lib/dailyPhrases";
import { StudentTrackingSection } from "@/components/dashboard/StudentTrackingSection";

import { db } from "@/lib/backend";
interface SubjectRow { id: string; name: string; color: string; }

interface LiveClassRow {
  id: string;
  title: string;
  subject: string;
  scheduled_at: string;
  instructor: string;
  meeting_url: string | null;
  status: string;
}

interface ContinueItem {
  type: "note" | "mcq";
  title: string;
  subject: string;
  href: string;
  time: string;
}

const QUICK_ACTIONS = [
  { label: "1v1 Arena",   icon: Swords,       href: "/arena",          hints: ["Find a study rival", "Quick brain-warmup", "Settle a chapter — duel time"], examHint: "Sharpen under exam pressure" },
  { label: "AI Tutor",    icon: BrainCircuit, href: "/ai-tutor",       hints: ["Stuck somewhere? Just ask", "Pick up where it gets hard", "Late-night doubts? I'm here"], examHint: "Walk me through what's not clicking" },
  { label: "Photo Solve", icon: Camera,       href: "/photo-solve",    hints: ["Snap your homework — I'll explain", "Click that tricky problem", "Show me the question, get the steps"], examHint: "Past-paper question? Snap it" },
  { label: "Flashcards",  icon: Layers,       href: "/flashcards/all", hints: ["Five minutes, big retention", "Quick recall before the bus", "Brush up while chai brews"], examHint: "Last-mile revision" },
];

const getContextHint = (action: typeof QUICK_ACTIONS[0], hour: number, examSoon: boolean) => {
  if (examSoon) return action.examHint;
  if (hour < 10) return action.hints[0];
  if (hour < 17) return action.hints[1];
  return action.hints[2];
};

const getSubjectLabel = (pct: number): string | null => {
  if (pct === 0) return null;
  if (pct < 20) return "Just getting started";
  if (pct >= 80) return "Almost there!";
  return null;
};

const Dashboard = () => {
  useMetaTags({ title: "Dashboard", description: "Your personalized study dashboard." });
  const profile = useUserProfile();
  const { isPro, isInstitutional, loading: subLoading } = useSubscription();
  const schoolStudent = useSchoolStudent();
  const [subjects, setSubjects] = useState<SubjectRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [xp, setXp] = useState(0);
  const [streakCount, setStreakCount] = useState(0);
  const [subjectProgress, setSubjectProgress] = useState<{ name: string; pct: number; lastStudied?: string }[]>([]);
  const [liveClasses, setLiveClasses] = useState<LiveClassRow[]>([]);
  const [continueItems, setContinueItems] = useState<ContinueItem[]>([]);
  const [weeklyChapters, setWeeklyChapters] = useState(0);
  const [schoolExams, setSchoolExams] = useState<any[]>([]);
  const [latestSchoolNotice, setLatestSchoolNotice] = useState<any | null>(null);
  const nav = useNavigate();
  const { pref: calendarPref } = useCalendarPref();

  // Redirect to onboarding if not completed
  useEffect(() => {
    if (profile.loading || !profile.id || profile.role !== "user") return;

    // Fast-path: if either flag is already true locally, never bounce.
    if (profile.onboarding_completed || profile.grade) return;

    resolveOnboardingState(profile.id, profile.role, {
      grade: profile.grade,
      onboarding_completed: profile.onboarding_completed,
    }).then((state) => {
      if (state.requiresOnboarding) nav("/onboarding", { replace: true });
    });
  }, [profile.loading, profile.id, profile.onboarding_completed, profile.grade, profile.role, nav]);

  // Initial offline download is now driven by <OfflineWelcomeModal /> (asks
  // the student first) and re-syncs are owned by <OfflineProvider /> — no
  // silent auto-download from the Dashboard anymore.

  useEffect(() => {
    if (profile.loading || !profile.id) return;
    const load = async () => {
      const [, freshProfileRes, subRes] = await Promise.all([
        db.rpc("update_streak", { p_user_id: profile.id }),
        db.from("profiles").select("xp, streak_count").eq("id", profile.id).maybeSingle(),
        (() => {
          let query = db.from("subjects").select("id, name, color").eq("curriculum", "nepal").eq("class", profile.grade || "10");
          if ((profile.grade === "11" || profile.grade === "12") && profile.stream) query = query.eq("stream", profile.stream);
          return query.order("sort_order").limit(6);
        })(),
      ]);

      setXp(freshProfileRes.data?.xp || 0);
      const newStreak = freshProfileRes.data?.streak_count || 0;
      setStreakCount(newStreak);
      if ([3, 7, 14, 30, 50, 100].includes(newStreak)) notifyStreakMilestone(profile.id, newStreak);

      const subData = (subRes.data || []) as SubjectRow[];
      setSubjects(subData);
      setLoading(false);

      const [continueRes, progressRes, lcRes] = await Promise.all([
        (async () => {
          const [{ data: lastNote }, { data: lastMcq }] = await Promise.all([
            (db.from("note_progress") as any)
              .select("completed_at, notes(title, chapters(subject))")
              .eq("user_id", profile.id)
              .order("completed_at", { ascending: false })
              .limit(1),
            db.from("mcq_scores")
              .select("subject, created_at, percentage")
              .eq("user_id", profile.id)
              .order("created_at", { ascending: false })
              .limit(1),
          ]);
          const items: ContinueItem[] = [];
          if (lastNote?.[0]) {
            const n = lastNote[0];
            items.push({
              type: "note",
              title: n.notes?.title || "Note",
              subject: n.notes?.chapters?.subject || "",
              href: "/study-materials",
              time: n.completed_at ? formatDistanceToNow(new Date(n.completed_at), { addSuffix: true }) : "",
            });
          }
          if (lastMcq?.[0]) {
            const m = lastMcq[0];
            items.push({
              type: "mcq",
              title: `${m.subject} MCQ — ${m.percentage}%`,
              subject: m.subject,
              href: "/mcq-practice",
              time: formatDistanceToNow(new Date(m.created_at), { addSuffix: true }),
            });
          }
          return items;
        })(),
        (async () => {
          if (subData.length === 0) return { progress: [] as { name: string; pct: number; lastStudied?: string }[], weeklyCount: 0 };
          const subjectIds = subData.map(s => s.id);
          const { data: allChapters } = await supabase
            .from("chapters").select("id, subject_id")
            .in("subject_id", subjectIds);
          if (!allChapters?.length) return { progress: subData.map(s => ({ name: s.name, pct: 0 })), weeklyCount: 0 };
          const chapterIds = allChapters.map(c => c.id);
          const chapterToSubject = new Map(allChapters.map(c => [c.id, c.subject_id]));
          const [{ data: allNotes }, { data: allProgress }] = await Promise.all([
            db.from("notes").select("id, chapter_id")
              .in("chapter_id", chapterIds).eq("is_published", true),
            db.from("note_progress").select("note_id, completed_at")
              .eq("user_id", profile.id),
          ]);
          const noteToSubject = new Map<string, string>();
          const notesPerSubject = new Map<string, number>();
          for (const note of allNotes || []) {
            const subjectId = chapterToSubject.get(note.chapter_id);
            if (!subjectId) continue;
            noteToSubject.set(note.id, subjectId);
            notesPerSubject.set(subjectId, (notesPerSubject.get(subjectId) || 0) + 1);
          }
          const donePerSubject = new Map<string, number>();
          const lastStudiedPerSubject = new Map<string, Date>();
          const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
          let weeklyCount = 0;
          for (const prog of allProgress || []) {
            const subjectId = noteToSubject.get(prog.note_id);
            if (!subjectId) continue;
            donePerSubject.set(subjectId, (donePerSubject.get(subjectId) || 0) + 1);
            if (prog.completed_at) {
              const d = new Date(prog.completed_at);
              const existing = lastStudiedPerSubject.get(subjectId);
              if (!existing || d > existing) lastStudiedPerSubject.set(subjectId, d);
              if (d >= sevenDaysAgo) weeklyCount++;
            }
          }
          return {
            progress: subData.map(sub => {
              const total = notesPerSubject.get(sub.id) || 0;
              const done = donePerSubject.get(sub.id) || 0;
              const lastDate = lastStudiedPerSubject.get(sub.id);
              return {
                name: sub.name,
                pct: total > 0 ? Math.round((done / total) * 100) : 0,
                lastStudied: lastDate ? formatDistanceToNow(lastDate, { addSuffix: true }) : undefined,
              };
            }),
            weeklyCount,
          };
        })(),
        (async () => {
          const grade = profile.grade || "10";
          const { data: lcData } = await db.from("live_classes")
            .select("id, title, subject, scheduled_at, instructor, meeting_url, status")
            .eq("grade", grade).in("status", ["upcoming", "live"])
            .order("scheduled_at").limit(3);
          return (lcData as any[]) || [];
        })(),
      ]);

      setContinueItems(continueRes);
      setSubjectProgress(progressRes.progress || []);
      setWeeklyChapters(progressRes.weeklyCount || 0);
      setLiveClasses(lcRes);
    };
    load();
  }, [profile.loading, profile.id]);

  // Load upcoming school exams + latest announcement for enrolled students
  useEffect(() => {
    if (schoolStudent.loading || !schoolStudent.isSchoolStudent || !schoolStudent.schoolId) return;
    const loadSchoolData = async () => {
      const [examsRes, noticeRes] = await Promise.all([
        db.from("exams")
          .select("id, name, subject, date, start_time, total_marks, exam_type, status")
          .eq("school_id", schoolStudent.schoolId!)
          .eq("grade", schoolStudent.grade!)
          .in("status", ["upcoming", "ongoing"])
          .order("date", { ascending: true })
          .limit(5),
        db.from("school_announcements")
          .select("id, title, body, type, created_at")
          .eq("school_id", schoolStudent.schoolId!)
          .order("created_at", { ascending: false })
          .limit(1)
          .maybeSingle(),
      ]);
      setSchoolExams(examsRes.data || []);
      setLatestSchoolNotice(noticeRes.data || null);
    };
    loadSchoolData();
  }, [schoolStudent.loading, schoolStudent.isSchoolStudent, schoolStudent.schoolId]);

  const examDaysLeft = profile.exam_date ? Math.max(0, differenceInDays(new Date(profile.exam_date), new Date())) : 0;
  const level = getLevel(xp);
  const firstName = profile.full_name?.split(" ")[0] || "Student";

  const hour = new Date().getHours();

  const contextLine =
    hour >= 22 ? "Late night? One small win before sleep — that's how streaks survive." :
    hour >= 20 ? "Evening study mode. Quiet hours are your secret weapon." :
    examDaysLeft > 0 && examDaysLeft <= 7 ? `${examDaysLeft} days left. You already know what to do — just sit and start.` :
    examDaysLeft > 0 && examDaysLeft <= 30 ? `${examDaysLeft} days to go. Steady wins, not all-nighters.` :
    examDaysLeft > 0 ? `${examDaysLeft} days until ${profile.grade === "12" ? "NEB" : "SEE"}. Plenty of time — if you start today.` :
    streakCount >= 7 ? `${streakCount}-day streak. This is what consistency feels like.` :
    streakCount >= 3 ? `${streakCount} days in a row — keep that fire alive.` :
    hour < 10 ? "Good morning. The mind is sharpest now — what shall we open first?" :
    "One chapter at a time. That's the whole secret.";

  const examSoon = examDaysLeft > 0 && examDaysLeft <= 14;
  // Day-N counter — falls back to a per-device "first seen" stamp in localStorage
  // since UserProfile context doesn't carry created_at.
  const joinIso = (() => {
    try {
      const k = "nepedu:joined_at";
      const existing = localStorage.getItem(k);
      if (existing) return existing;
      const now = new Date().toISOString();
      localStorage.setItem(k, now);
      return now;
    } catch {
      return null;
    }
  })();
  const dayN = daysSince(joinIso);
  const todaysPhrase = dailyPhrase();
  const weeklyGoalPct = Math.min(100, weeklyChapters * 15);

  const weakest = subjectProgress.length > 0
    ? [...subjectProgress].sort((a, b) => a.pct - b.pct)[0]
    : null;
  const aiMessage = weakest && weakest.pct > 0 && weakest.pct < 50
    ? `${weakest.name} is sitting at ${weakest.pct}%. Want to spend 15 minutes there together?`
    : subjectProgress.some(s => s.pct > 0)
    ? `Nice work on ${subjectProgress.find(s => s.pct > 0)?.name}. Shall we tackle the weaker spots next?`
    : "New here? Tell me where you're stuck — I'll find the right chapter.";

  if (loading || profile.loading) {
    return (
      <DashboardLayout>
        <div className="space-y-5 max-w-3xl mx-auto">
          <Skeleton className="h-24 w-full rounded-2xl" />
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
            {[1,2,3,4].map(i => <Skeleton key={i} className="h-16 rounded-2xl" />)}
          </div>
          <Skeleton className="h-48 rounded-2xl" />
        </div>
      </DashboardLayout>
    );
  }

  /* Linear/Apple-Health style — short greeting (no time icon, no emoji) */
  const shortGreeting = hour < 12 ? "Morning" : hour < 17 ? "Afternoon" : "Evening";
  const todayLabel = formatByPref(new Date(), calendarPref, (d) => format(d, "EEEE, MMMM d"));

  // Quick action accent palette — saffron / blue / emerald / crimson (Nepal warmth)
  const ACTION_ACCENTS = [
    { dot: "hsl(38 92% 52%)",  tint: "hsl(38 92% 52% / 0.10)" }, // saffron
    { dot: "hsl(213 80% 50%)", tint: "hsl(213 80% 50% / 0.10)" }, // blue
    { dot: "hsl(142 72% 42%)", tint: "hsl(142 72% 42% / 0.10)" }, // emerald
    { dot: "hsl(352 72% 48%)", tint: "hsl(352 72% 48% / 0.10)" }, // crimson
  ];

  return (
    <DashboardLayout>
      <div data-portal="student" className="w-full animate-in fade-in duration-200">

        {/* ═══════════════════════════════════════════════
            HERO — dark editorial band (matches public site)
            data-dark-section flips the navbar theme.
            ═══════════════════════════════════════════════ */}
        <header
          data-dark-section="true"
          className="dark-section relative isolate overflow-hidden rounded-[28px] border border-white/[0.06] px-7 py-8 sm:px-10 sm:py-10 mb-7"
        >
          {/* hairline rule */}
          <div className="absolute top-0 left-10 right-10 h-px bg-gradient-to-r from-transparent via-white/15 to-transparent" />

          <div className="relative flex flex-col lg:flex-row lg:items-end lg:justify-between gap-6">
            <div className="min-w-0 flex-1">
              <p className="text-[11px] font-semibold uppercase tracking-[0.24em] text-primary mb-3">
                {shortGreeting} · {todayLabel}
              </p>
              <h1 className="text-[36px] sm:text-[44px] lg:text-[52px] leading-[1.02] tracking-[-0.03em] font-semibold text-foreground">
                Hello,{" "}
                <span className="font-editorial italic text-[40px] sm:text-[48px] lg:text-[56px] text-primary">
                  {firstName}.
                </span>
              </h1>
              {schoolStudent.isSchoolStudent && schoolStudent.schoolName && (
                <div className="mt-4 inline-flex items-center gap-2 px-3 py-1.5 rounded-full border border-white/[0.10] bg-white/[0.04] text-[12.5px] text-foreground">
                  <span className="w-1.5 h-1.5 rounded-full bg-primary" />
                  <span className="text-muted-foreground">Enrolled at</span>
                  <span className="font-semibold">{schoolStudent.schoolName}</span>
                  {schoolStudent.grade && (
                    <span className="text-muted-foreground">· Grade {schoolStudent.grade}{schoolStudent.section ? ` ${schoolStudent.section}` : ""}</span>
                  )}
                </div>
              )}
              <p className="text-[15px] sm:text-[16px] text-muted-foreground mt-4 max-w-xl leading-[1.55]">
                {contextLine}
              </p>

              {/* Stats strip — inline, editorial. Always show all 4 so the dashboard never feels empty. */}
              <div className="flex items-center gap-x-7 gap-y-3 mt-7 flex-wrap text-[13.5px]">
                <div className="flex items-baseline gap-2">
                  <span className="w-1.5 h-1.5 rounded-full bg-[hsl(38_92%_56%)]" />
                  <span className="text-muted-foreground">Streak</span>
                  <span className="font-semibold text-foreground tabular-nums">{streakCount}d</span>
                  {streakCount === 0 && (
                    <span className="text-[11px] text-muted-foreground italic ml-1">start today</span>
                  )}
                </div>
                <div className="flex items-baseline gap-2">
                  <span className="w-1.5 h-1.5 rounded-full bg-primary" />
                  <span className="text-muted-foreground">XP</span>
                  <span className="font-semibold text-foreground tabular-nums">{xp.toLocaleString()}</span>
                </div>
                <div className="flex items-baseline gap-2">
                  <span className="w-1.5 h-1.5 rounded-full bg-[hsl(213_80%_60%)]" />
                  <span className="text-muted-foreground">Level</span>
                  <span className="font-editorial italic text-[16px] text-foreground">{level.title}</span>
                </div>
                <div className="flex items-baseline gap-2">
                  <span className="w-1.5 h-1.5 rounded-full bg-[hsl(352_72%_56%)]" />
                  <span className="text-muted-foreground">This week</span>
                  <span className="font-semibold text-foreground tabular-nums">{weeklyChapters} chapters</span>
                </div>
              </div>
            </div>

            {/* Exam pill — dominant right anchor */}
            {profile.exam_date && examDaysLeft > 0 && (
              <Link
                to="/settings"
                className={`shrink-0 inline-flex flex-col items-start lg:items-end px-5 py-4 rounded-2xl border transition-all hover:-translate-y-0.5
                  ${examSoon
                    ? "border-[hsl(352_72%_56%/0.40)] bg-[hsl(352_72%_56%/0.10)]"
                    : "border-white/[0.10] bg-white/[0.04]"}`}
              >
                <span className="text-[11px] font-semibold uppercase tracking-[0.24em] text-primary">Days to {profile.grade === "12" ? "NEB" : "SEE"}</span>
                <div className="flex items-baseline gap-2 mt-1">
                  <span className={`text-[40px] font-bold tabular-nums leading-none tracking-[-0.02em] ${examSoon ? "text-[hsl(352_72%_64%)]" : "text-foreground"}`}>
                    {examDaysLeft}
                  </span>
                  <span className="text-[13px] text-muted-foreground">days left</span>
                </div>
              </Link>
            )}
          </div>
        </header>

        {/* School quick-access — appears only for school-linked students */}
        {schoolStudent.isSchoolStudent && schoolStudent.schoolName && (
          <SchoolQuickAccess
            schoolName={schoolStudent.schoolName}
            grade={schoolStudent.grade}
            section={schoolStudent.section}
          />
        )}

        {/* Tracking — modern analytics block */}
        <div className="mb-8">
          <StudentTrackingSection streak={streakCount} level={level} />
        </div>

        {/* ═══════════════════════════════════════════════
            ASYMMETRIC GRID — wider main (1.6fr) + aside (1fr)
            Better balance on 1280–1600px viewports
            ═══════════════════════════════════════════════ */}
        <div className="lg:grid lg:grid-cols-[1.6fr_1fr] xl:grid-cols-[1.7fr_1fr] lg:gap-7 xl:gap-9 items-start">

          {/* ─────────── MAIN COLUMN ─────────── */}
          <div className="space-y-8 min-w-0">

            {/* Continue Learning */}
            {continueItems.length > 0 && (
              <section>
                <p className="section-overline mb-3">Pick up where you left off</p>
                <div className="rounded-2xl border border-border bg-card overflow-hidden">
                  {continueItems.map((item, i) => {
                    const subMeta = subjects.find(s => s.name === item.subject);
                    const subColor = subMeta?.color || "hsl(var(--primary))";
                    return (
                      <Link key={i} to={item.href}
                        className="flex items-center gap-3 px-4 py-4 group relative border-b border-border/60 last:border-b-0 hover:bg-muted/30 transition-colors"
                      >
                        <div className="absolute left-0 top-0 bottom-0 w-1" style={{ backgroundColor: subColor }} />
                        <div className="ml-2">
                          <SubjectBadge subject={item.subject} size="sm" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <p className="text-[14.5px] font-semibold text-foreground truncate">{item.title}</p>
                          <p className="text-[12px] text-muted-foreground mt-0.5">{item.time} · Continue {item.type === "note" ? "reading" : "practice"}</p>
                        </div>
                        <ChevronRight className="w-4 h-4 text-muted-foreground group-hover:text-foreground shrink-0 transition-colors" />
                      </Link>
                    );
                  })}
                </div>
              </section>
            )}
            {continueItems.length === 0 && !loading && (
              <section>
                <p className="section-overline mb-3">Start your journey</p>
                <Link to="/study-materials"
                  className="flex items-center gap-3 px-5 py-5 rounded-2xl border border-dashed border-border hover:border-primary/40 hover:bg-paper-warm transition-colors group"
                >
                  <div className="w-10 h-10 rounded-xl bg-[hsl(142_72%_42%/0.10)] flex items-center justify-center shrink-0">
                    <Play className="w-[18px] h-[18px] text-[hsl(142_72%_42%)]" strokeWidth={2} />
                  </div>
                  <div>
                    <p className="text-[15px] font-semibold text-foreground">Your syllabus is ready</p>
                    <p className="text-[13px] text-muted-foreground mt-0.5">Start your first chapter</p>
                  </div>
                  <ArrowRight className="w-4 h-4 text-muted-foreground ml-auto shrink-0 group-hover:text-primary transition-colors" />
                </Link>
              </section>
            )}

            {/* Quick Actions — colored 4-up tiles on desktop, 2-up on mobile */}
            <section>
              <p className="section-overline mb-3">Quick actions</p>
              <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
                {QUICK_ACTIONS.map((action, i) => {
                  const Icon = action.icon;
                  const accent = ACTION_ACCENTS[i];
                  return (
                    <Link
                      key={action.label}
                      to={action.href}
                      className="group flex flex-col gap-3 p-4 lg:p-5 rounded-2xl border border-border bg-card hover:border-foreground/15 hover:-translate-y-0.5 hover:shadow-[var(--shadow-sm)] transition-all duration-200 min-h-[112px]"
                    >
                      <div
                        className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0 transition-transform group-hover:scale-105"
                        style={{ backgroundColor: accent.tint }}
                      >
                        <Icon className="w-[18px] h-[18px]" strokeWidth={2} style={{ color: accent.dot }} />
                      </div>
                      <div className="min-w-0">
                        <p className="text-[14.5px] font-semibold text-foreground">{action.label}</p>
                        <p className="text-[12px] text-muted-foreground mt-0.5 leading-snug line-clamp-2">{getContextHint(action, hour, examSoon)}</p>
                      </div>
                    </Link>
                  );
                })}
              </div>
            </section>

            {/* Subjects — colored progress bars */}
            {subjectProgress.length > 0 && (
              <section>
                <div className="flex items-end justify-between mb-3">
                  <p className="section-overline">Your subjects</p>
                  <Link to="/study-materials" className="text-[12px] font-medium text-muted-foreground hover:text-primary transition-colors">View all →</Link>
                </div>
                <div className="rounded-2xl border border-border bg-card overflow-hidden">
                  {subjectProgress.map((sub) => {
                    const subMeta = subjects.find(s => s.name === sub.name);
                    const subColor = subMeta?.color || "hsl(var(--primary))";
                    const label = getSubjectLabel(sub.pct);
                    return (
                      <Link key={sub.name} to={`/study-materials/${encodeURIComponent(sub.name)}`}
                       className="group flex items-center gap-3 px-4 py-3.5 border-b border-border/60 last:border-b-0 hover:bg-muted/30 transition-colors relative"
                       >
                         <div className="absolute left-0 top-2 bottom-2 w-1 rounded-r" style={{ backgroundColor: subColor }} />
                         <div className="ml-2">
                           <SubjectBadge subject={sub.name} size="sm" />
                         </div>
                         <div className="flex-1 min-w-0">
                           <p className="text-[14px] font-semibold text-foreground truncate group-hover:text-primary transition-colors">{sub.name}</p>
                           {label && <p className="text-[11px] text-muted-foreground mt-0.5">{label}</p>}
                         </div>
                         <div className="flex items-center gap-3 shrink-0">
                           <div className="w-20 sm:w-28 h-1.5 rounded-full bg-muted overflow-hidden">
                             <div className="h-full transition-all rounded-full" style={{ width: `${sub.pct}%`, backgroundColor: subColor }} />
                           </div>
                           <span className="text-[12px] font-semibold tabular-nums w-9 text-right text-foreground">
                             {sub.pct}%
                           </span>
                         </div>
                      </Link>
                    );
                  })}
                </div>
              </section>
            )}

            {/* Live Classes */}
            {liveClasses.length > 0 && (
              <section>
                <p className="section-overline mb-3">Upcoming live classes</p>
                <div className="rounded-2xl border border-border bg-card overflow-hidden">
                  {liveClasses.map(lc => (
                    <div key={lc.id} className="px-4 py-3.5 flex items-center gap-3 border-b border-border/60 last:border-b-0">
                      <div className="w-9 h-9 rounded-lg bg-[hsl(213_80%_50%/0.10)] flex items-center justify-center shrink-0">
                        <Video className="w-[16px] h-[16px] text-[hsl(213_80%_50%)]" strokeWidth={2} />
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <p className="text-[14px] font-semibold text-foreground truncate">{lc.title}</p>
                          {lc.status === "live" && (
                            <span className="inline-flex items-center gap-1 text-[10px] font-bold px-1.5 py-0.5 rounded bg-destructive/12 text-destructive">
                              <span className="w-1.5 h-1.5 rounded-full bg-destructive animate-pulse" />
                              LIVE
                            </span>
                          )}
                        </div>
                        <p className="text-[12px] text-muted-foreground">{lc.subject} · {lc.instructor} · <SmartDate value={lc.scheduled_at} pattern="MMM d, h:mm a" bsVariant="short" /></p>
                      </div>
                      {lc.status === "live" ? (
                        <Link to={`/live-class/${lc.id}`} className="shrink-0 px-3 py-1.5 rounded-lg bg-primary text-primary-foreground text-xs font-semibold hover:opacity-90 transition-opacity">Join</Link>
                      ) : (
                        <Link to={`/live-class/${lc.id}`} className="shrink-0 px-3 py-1.5 rounded-lg border border-border text-foreground text-xs font-medium hover:bg-muted transition-colors">View</Link>
                      )}
                    </div>
                  ))}
                </div>
              </section>
            )}

            {/* Latest school announcement */}
            {schoolStudent.isSchoolStudent && latestSchoolNotice && (
              <section>
                <div className="flex items-end justify-between mb-3">
                  <p className="section-overline">Latest from {schoolStudent.schoolName || "your school"}</p>
                  <Link to="/notifications" className="text-[11px] font-semibold text-primary hover:underline">View all</Link>
                </div>
                <Link
                  to="/notifications"
                  className="block rounded-2xl border border-border bg-card p-5 hover:border-primary/40 transition-colors group"
                >
                  <div className="flex items-center gap-2 mb-2">
                    <span className="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-primary/10 text-primary">
                      {latestSchoolNotice.type || "announcement"}
                    </span>
                    <span className="text-[11px] text-muted-foreground">
                      {formatDistanceToNow(new Date(latestSchoolNotice.created_at), { addSuffix: true })}
                    </span>
                  </div>
                  <p className="font-semibold text-foreground text-[15px] leading-snug">{latestSchoolNotice.title}</p>
                  {latestSchoolNotice.body && (
                    <p className="text-[13px] text-muted-foreground mt-1.5 line-clamp-2 leading-relaxed">{latestSchoolNotice.body}</p>
                  )}
                </Link>
              </section>
            )}

            {/* School Exams */}
            {schoolStudent.isSchoolStudent && schoolExams.length > 0 && (
              <section>
                <div className="flex items-end justify-between mb-3">
                  <p className="section-overline">School exams</p>
                  <span className="text-[11px] text-muted-foreground font-editorial">{schoolStudent.schoolName}</span>
                </div>
                <div className="rounded-2xl border border-border bg-card overflow-hidden">
                  {schoolExams.map((exam: any) => {
                    const daysUntil = differenceInDays(new Date(exam.date), new Date());
                    const urgent = daysUntil <= 3;
                    return (
                      <div key={exam.id} className="flex items-center gap-3 px-4 py-3 border-b border-border/60 last:border-b-0 relative">
                        <div className={`absolute left-0 top-2 bottom-2 w-1 rounded-r ${urgent ? "bg-[hsl(352_72%_48%)]" : "bg-border"}`} />
                        <div className="ml-2 w-12 text-center">
                          <span className={`text-[18px] font-bold tabular-nums leading-none ${urgent ? "text-[hsl(352_72%_48%)]" : "text-foreground"}`}>
                            {daysUntil <= 0 ? "—" : daysUntil}
                          </span>
                          <p className="text-[10px] text-muted-foreground uppercase tracking-wider mt-0.5">days</p>
                        </div>
                        <div className="flex-1 min-w-0">
                          <p className="text-[14px] font-semibold text-foreground truncate">{exam.name}</p>
                          <p className="text-[12px] text-muted-foreground">{exam.subject} · <SmartDate value={exam.date} pattern="MMM d" bsVariant="short" />{exam.start_time ? ` · ${exam.start_time}` : ""}</p>
                        </div>
                        <span className="text-[11px] text-muted-foreground tabular-nums shrink-0 font-semibold">{exam.total_marks}m</span>
                      </div>
                    );
                  })}
                </div>
              </section>
            )}
          </div>

          {/* ─────────── ASIDE COLUMN ─────────── */}
          <aside className="space-y-8 mt-8 lg:mt-0 min-w-0">

            {/* Daily Challenges */}
            <section>
              <p className="section-overline mb-3">Today's missions</p>
              <div className="rounded-2xl border border-border bg-card overflow-hidden">
                <DailyChallenges />
              </div>
            </section>

            {/* AI Tutor warm nudge */}
            <section>
              <p className="section-overline mb-3">From your AI tutor</p>
              <Link
                to="/ai-tutor"
                className="block bg-paper-warm rounded-2xl border border-border/60 p-5 hover:border-[hsl(38_92%_52%/0.4)] transition-colors group"
              >
                <div className="flex items-start gap-3">
                  <div className="w-9 h-9 rounded-xl bg-[hsl(38_92%_52%/0.15)] flex items-center justify-center shrink-0">
                    <BrainCircuit className="w-[18px] h-[18px] text-[hsl(38_92%_52%)]" strokeWidth={2} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="font-editorial text-[16px] text-foreground leading-snug">
                      "{aiMessage}"
                    </p>
                    <p className="text-[12px] text-muted-foreground mt-2 group-hover:text-foreground transition-colors flex items-center gap-1">
                      Open AI Tutor <ArrowRight className="w-3 h-3" />
                    </p>
                  </div>
                </div>
              </Link>
            </section>

            {/* Exam set CTA — only when no exam */}
            {!profile.exam_date && (
              <section>
                <Link to="/settings" className="flex items-center gap-3 px-4 py-3.5 rounded-2xl border border-dashed border-border hover:border-foreground/30 hover:bg-muted/30 transition-colors">
                  <Target className="w-4 h-4 text-muted-foreground shrink-0" strokeWidth={2} />
                  <p className="text-[13px] text-foreground font-medium">When's your exam? <span className="text-muted-foreground">Set it →</span></p>
                </Link>
              </section>
            )}

            {/* Weak Areas */}
            <section>
              <p className="section-overline mb-3">Where you can improve</p>
              <WeakAreasWidget />
            </section>

            {/* Community + Pro */}
            <section>
              <p className="section-overline mb-3">More</p>
              <div className="rounded-2xl border border-border bg-card overflow-hidden">
                <Link to="/community" className="flex items-center gap-3 px-4 py-3.5 group hover:bg-muted/30 transition-colors">
                  <div className="w-8 h-8 rounded-lg bg-[hsl(213_80%_50%/0.10)] flex items-center justify-center shrink-0">
                    <Users className="w-[16px] h-[16px] text-[hsl(213_80%_50%)]" strokeWidth={2} />
                  </div>
                  <span className="text-[14px] font-semibold text-foreground">Ask 12,000+ students</span>
                  <ChevronRight className="w-4 h-4 text-muted-foreground ml-auto shrink-0 group-hover:text-foreground transition-colors" />
                </Link>
                {!isPro && !subLoading && !isInstitutional && (
                  <>
                    <div className="border-t border-border" />
                    <Link to="/pricing" className="flex items-center gap-3 px-4 py-3.5 group hover:bg-paper-warm transition-colors">
                      <div className="w-8 h-8 rounded-lg bg-[hsl(38_92%_52%/0.12)] flex items-center justify-center shrink-0">
                        <Crown className="w-[16px] h-[16px] text-[hsl(38_92%_52%)]" strokeWidth={2} />
                      </div>
                      <div className="min-w-0">
                        <p className="text-[14px] font-semibold text-foreground">Unlock everything</p>
                        <p className="text-[11px] text-muted-foreground">रू 149/mo · Cancel anytime</p>
                      </div>
                      <ChevronRight className="w-4 h-4 text-muted-foreground ml-auto shrink-0 group-hover:text-foreground transition-colors" />
                    </Link>
                  </>
                )}
              </div>
            </section>
          </aside>
        </div>
      </div>
    </DashboardLayout>
  );
};

export default Dashboard;
