import { useEffect, useState } from "react";
import { motion } from "framer-motion";
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, Sun, SunDim, Moon, BookOpen, Clock
} 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 { CalendarWidget } from "@/components/dashboard/CalendarWidget";
import { resolveOnboardingState } from "@/lib/onboarding";
import { resolveStudentSubjects } from "@/lib/neb-curriculum";
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);

      let subData = (subRes.data || []) as SubjectRow[];
      if (profile.grade === "11" || profile.grade === "12") {
        const { subjects: allowedSubjectNames } = resolveStudentSubjects({
          stream: profile.stream,
          faculty: profile.faculty,
          optionalSubject: profile.optional_subject,
        });
        if (allowedSubjectNames.length > 0) {
          subData = subData.filter((s) => allowedSubjectNames.includes(s.name));
        }
      }
      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);
    };
    // Audit B-CRITICAL: setLoading(false) lived mid-load, so a rejected fetch
    // left the skeleton hanging forever. Guarantee loading always clears.
    load().catch((e) => {
      console.error("Dashboard load failed:", e);
      setLoading(false);
    });
  }, [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>
    );
  }

  /* Conversational greetings with icons */
  const greetingData = hour < 12 
    ? { text: "Good morning", Icon: Sun } 
    : hour < 17 
    ? { text: "Good afternoon", Icon: SunDim } 
    : { text: "Good evening", Icon: Moon };
  
  const todayLabel = formatByPref(new Date(), calendarPref, (d) => format(d, "EEEE, MMMM d"));

  const containerVariants = {
    hidden: { opacity: 0 },
    show: {
      opacity: 1,
      transition: {
        staggerChildren: 0.08
      }
    }
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 40, scale: 0.98 },
    show: { 
      opacity: 1, 
      y: 0, 
      scale: 1, 
      transition: { type: "spring", stiffness: 300, damping: 28, mass: 0.8 }
    }
  };

  return (
    <DashboardLayout>
      <div data-portal="student" className="w-full max-w-[1200px] mx-auto pb-24 px-4 sm:px-6 lg:px-8">
        
        {/* Minimalist Command Center Header */}
        <motion.div 
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, ease: "easeOut" }}
          className="mt-8 mb-10 flex flex-col md:flex-row md:items-end justify-between gap-8"
        >
          <div className="max-w-2xl">
            <div className="flex items-center gap-2 mb-3">
              <greetingData.Icon className="w-5 h-5 text-muted-foreground" strokeWidth={2} />
              <p className="text-[12px] font-bold tracking-widest text-muted-foreground uppercase">
                {todayLabel}
              </p>
            </div>
            <h1 className="text-[32px] sm:text-[40px] font-bold tracking-tight text-foreground leading-tight">
              {greetingData.text}, {firstName}.
            </h1>
            <p className="text-[15px] text-muted-foreground mt-2 leading-relaxed max-w-lg">
              {contextLine}
            </p>
          </div>
          
          <div className="flex gap-4 shrink-0">
            <div className="flex flex-col items-start min-w-[80px]">
              <p className="text-[28px] font-bold text-foreground leading-none tracking-tight tabular-nums">{streakCount}</p>
              <p className="text-[11px] font-bold tracking-widest uppercase text-muted-foreground mt-1">Streak</p>
            </div>
            <div className="w-px h-12 bg-border/60 self-center hidden md:block"></div>
            <div className="flex flex-col items-start min-w-[80px]">
              <p className="text-[28px] font-bold text-foreground leading-none tracking-tight tabular-nums">{level.level}</p>
              <p className="text-[11px] font-bold tracking-widest uppercase text-muted-foreground mt-1">Level</p>
            </div>
            {profile.exam_date && examDaysLeft > 0 && (
              <>
                <div className="w-px h-12 bg-border/60 self-center hidden md:block"></div>
                <div className="flex flex-col items-start min-w-[80px]">
                  <p className="text-[28px] font-bold text-foreground leading-none tracking-tight tabular-nums">{examDaysLeft}</p>
                  <p className="text-[11px] font-bold tracking-widest uppercase text-primary mt-1">Days Left</p>
                </div>
              </>
            )}
          </div>
        </motion.div>

        <motion.div 
          variants={containerVariants}
          initial="hidden"
          animate="show"
          className="grid grid-cols-1 lg:grid-cols-12 gap-8"
        >
          {/* LEFT COLUMN */}
          <div className="lg:col-span-8 space-y-8">
            
            {/* Bookmark: Up Next */}
            <motion.section variants={itemVariants} className="rounded-xl bg-card border border-border shadow-xs overflow-hidden flex flex-col group relative">
              <div className="px-6 pt-6 pb-4 flex items-center justify-between relative z-10">
                <h2 className="text-[18px] font-bold text-foreground flex items-center gap-2 tracking-tight">
                  <Play className="w-4 h-4 text-foreground/60" strokeWidth={2.5} />
                  Up Next
                </h2>
              </div>
              <div className="flex-1 relative z-10">
                {continueItems.length > 0 ? (
                  continueItems.map((item, i) => (
                    <Link key={i} to={item.href}
                      className="group/item flex flex-col sm:flex-row sm:items-center justify-between p-6 hover:bg-secondary/40 transition-colors border-t border-border first:border-t-0 active:bg-secondary/60 relative overflow-hidden"
                    >
                      <div className="flex items-center gap-5 relative z-10">
                        <div className="w-12 h-12 rounded-lg bg-secondary border border-border flex items-center justify-center shrink-0 shadow-xs transition-colors duration-300 group-hover/item:border-foreground/20">
                          {item.type === "mcq" ? <Target className="w-5 h-5 text-foreground" strokeWidth={2} /> : <BookOpen className="w-5 h-5 text-foreground" strokeWidth={2} />}
                        </div>
                        <div>
                          <p className="text-[12px] font-bold tracking-widest text-muted-foreground uppercase mb-0.5">{item.subject}</p>
                          <h3 className="text-[16px] font-semibold text-foreground group-hover/item:text-foreground/80 transition-colors">{item.title}</h3>
                          <p className="text-[13px] font-medium text-muted-foreground mt-0.5 flex items-center gap-1.5">
                            <Clock className="w-3 h-3" /> {item.time}
                          </p>
                        </div>
                      </div>
                      <div className="hidden sm:flex w-8 h-8 rounded-full items-center justify-center bg-transparent border border-border group-hover/item:bg-foreground group-hover/item:text-background group-hover/item:border-foreground transition-all duration-200 relative z-10">
                        <ChevronRight className="w-4 h-4 transition-transform" strokeWidth={2} />
                      </div>
                    </Link>
                  ))
                ) : (
                  <div className="p-6">
                    <Link to="/study-materials" className="group/item flex items-center justify-between p-6 rounded-lg bg-secondary/30 hover:bg-secondary border border-border transition-all active:bg-secondary/80 relative overflow-hidden">
                      <div className="relative z-10">
                        <h3 className="text-[16px] font-semibold text-foreground">Start your syllabus</h3>
                        <p className="text-[14px] text-muted-foreground mt-0.5">Jump into your first chapter of the year.</p>
                      </div>
                      <div className="w-8 h-8 rounded-full bg-background flex items-center justify-center shrink-0 border border-border shadow-xs relative z-10">
                        <Play className="w-3.5 h-3.5 text-foreground ml-0.5" strokeWidth={2} />
                      </div>
                    </Link>
                  </div>
                )}
              </div>
            </motion.section>

            {/* Table of Contents: Subjects */}
            {subjectProgress.length > 0 && (
              <motion.section variants={itemVariants} className="rounded-xl bg-card border border-border shadow-xs p-6 group">
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-[18px] font-bold text-foreground flex items-center gap-2 tracking-tight">
                    <Layers className="w-4 h-4 text-foreground/60" strokeWidth={2.5} />
                    Your Progress
                  </h2>
                  <Link to="/study-materials" className="flex items-center gap-1 text-[12px] font-bold tracking-wider uppercase text-foreground/60 hover:text-foreground transition-colors">
                    View All <ChevronRight className="w-3 h-3" />
                  </Link>
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                  {subjectProgress.slice(0, 4).map((sub) => {
                    return (
                      <Link key={sub.name} to={`/study-materials/${encodeURIComponent(sub.name)}`}
                        className="group/sub h-[120px] rounded-lg overflow-hidden border border-border bg-secondary/30 relative shadow-xs hover:bg-secondary/60 transition-all duration-200 flex flex-col justify-between p-5"
                      >
                        <div className="relative z-10">
                          <h3 className="text-[14px] font-bold text-foreground tracking-wide uppercase mb-2">{sub.name}</h3>
                          <div className="w-8 h-px bg-border mb-3" />
                          <div className="flex items-center gap-3 text-white/90">
                            <div className="flex items-center gap-1.5 text-[12px] font-medium">
                              <BookOpen className="w-3.5 h-3.5" />
                              <span>{sub.pct}%</span>
                            </div>
                            <div className="flex items-center gap-1.5 text-[12px] font-medium">
                              <Play className="w-3 h-3" />
                              <span>Notes</span>
                            </div>
                          </div>
                        </div>
                      </Link>
                    );
                  })}
                </div>
              </motion.section>
            )}

            {/* Live Classes */}
            {liveClasses.length > 0 && (
               <motion.section variants={itemVariants} className="rounded-xl bg-card border border-border shadow-xs overflow-hidden group relative">
                 <div className="px-6 pt-6 pb-4 relative z-10">
                   <h2 className="text-[18px] font-bold text-foreground flex items-center gap-2 tracking-tight">
                     <Video className="w-4 h-4 text-foreground/60" strokeWidth={2.5} />
                     Live Classes
                   </h2>
                 </div>
                 <div className="p-8 pt-4 space-y-4 relative z-10">
                   {liveClasses.map(lc => (
                     <Link key={lc.id} to={`/live-class/${lc.id}`} className="group/lc flex flex-col sm:flex-row sm:items-center justify-between p-6 rounded-[24px] bg-background hover:bg-secondary/30 border border-border/60 hover:border-red-500/30 shadow-sm transition-all duration-300">
                       <div className="flex-1 mb-4 sm:mb-0">
                         <div className="flex items-center gap-3 mb-2">
                           {lc.status === "live" ? (
                             <span className="flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-widest text-red-600 bg-red-100/80 px-2.5 py-1 rounded-full animate-pulse border border-red-200">
                               <span className="w-1.5 h-1.5 rounded-full bg-red-500" /> Live Now
                             </span>
                           ) : (
                             <span className="text-[11px] font-bold tracking-widest text-primary uppercase bg-primary/10 px-2.5 py-1 rounded-full border border-primary/20">Upcoming</span>
                           )}
                           <span className="text-[13px] font-bold tracking-widest text-muted-foreground uppercase">{lc.subject}</span>
                         </div>
                         <h3 className="text-[18px] font-semibold text-foreground group-hover/lc:text-red-500 transition-colors">{lc.title}</h3>
                         <p className="text-[14px] text-muted-foreground mt-1 flex items-center gap-2">
                           <Users className="w-3.5 h-3.5" /> {lc.instructor}
                         </p>
                       </div>
                       <div className="flex items-center justify-between sm:justify-end gap-6 w-full sm:w-auto">
                         <span className="text-[15px] font-bold text-foreground bg-secondary/50 px-5 py-2.5 rounded-full border border-border/40 shadow-sm"><SmartDate value={lc.scheduled_at} pattern="h:mm a" bsVariant="short" /></span>
                         <div className="w-12 h-12 rounded-full bg-red-50 text-red-600 flex items-center justify-center shrink-0 border border-red-100 transition-transform duration-500 group-hover/lc:scale-110 group-hover/lc:bg-red-500 group-hover/lc:text-white shadow-sm">
                           <ArrowRight className="w-5 h-5" strokeWidth={2.5} />
                         </div>
                       </div>
                     </Link>
                   ))}
                 </div>
               </motion.section>
            )}

          </div>

          {/* RIGHT COLUMN */}
          <div className="lg:col-span-4 space-y-8">
            
            <CalendarWidget />
            <WeakAreasWidget />
            
            {/* Quick Actions / Study Tools */}
            <motion.section variants={itemVariants} className="rounded-xl bg-card border border-border shadow-xs p-6 relative overflow-hidden group">
              <h2 className="text-[16px] font-bold text-foreground mb-4 relative z-10 tracking-tight">Study Tools</h2>
              <div className="grid grid-cols-2 gap-4 relative z-10">
                {QUICK_ACTIONS.map((action) => {
                  const Icon = action.icon;
                  return (
                    <Link
                      key={action.label}
                      to={action.href}
                      className="group/btn flex flex-col items-center justify-center gap-3 p-4 rounded-lg bg-secondary/30 border border-border hover:bg-secondary/60 transition-colors relative"
                    >
                      <div className="w-10 h-10 rounded-full bg-background flex items-center justify-center shrink-0 border border-border relative z-10 shadow-xs">
                        <Icon className="w-4 h-4 text-foreground/80 group-hover/btn:text-foreground transition-colors" strokeWidth={2} />
                      </div>
                      <span className="text-[13px] font-medium text-foreground relative z-10">{action.label}</span>
                    </Link>
                  );
                })}
              </div>
            </motion.section>

            {/* Goals */}
            <motion.section variants={itemVariants} className="rounded-xl bg-card border border-border shadow-xs p-6">
              <h2 className="text-[16px] font-bold text-foreground mb-4 tracking-tight">Today's Focus</h2>
              <DailyChallenges />
            </motion.section>

            {/* Upcoming Exams */}
            {schoolStudent.isSchoolStudent && schoolExams.length > 0 && (
               <motion.section variants={itemVariants} className="rounded-xl bg-card border border-border shadow-xs p-6 relative overflow-hidden group">
                 <h2 className="text-[16px] font-bold text-foreground mb-4 relative z-10 flex items-center gap-2 tracking-tight">
                   <Target className="w-4 h-4 text-foreground/60" strokeWidth={2.5} />
                   School Exams
                 </h2>
                 <div className="space-y-3 relative z-10">
                   {schoolExams.map((exam: any) => {
                     const daysUntil = differenceInDays(new Date(exam.date), new Date());
                     return (
                       <div key={exam.id} className="flex items-center justify-between p-5 rounded-[24px] bg-background border border-border/60 hover:border-primary/30 shadow-sm hover:shadow-md transition-all duration-300">
                         <div className="min-w-0 pr-4">
                           <span className="block text-[17px] font-bold text-foreground truncate">{exam.name}</span>
                           <span className="block text-[14px] font-medium text-primary mt-1">{exam.subject}</span>
                         </div>
                         <div className="shrink-0 text-right bg-secondary/50 px-4 py-2 rounded-full border border-border/40">
                           <span className="block text-[22px] font-serif font-bold text-foreground leading-none">
                             {daysUntil <= 0 ? "—" : daysUntil}
                           </span>
                           <span className="block text-[10px] font-bold uppercase tracking-widest text-muted-foreground mt-1">
                             {daysUntil <= 0 ? "Today" : "Days"}
                           </span>
                         </div>
                       </div>
                     );
                   })}
                 </div>
               </motion.section>
            )}

          </div>
        </motion.div>
      </div>
    </DashboardLayout>
  );
};

export default Dashboard;
