"use client";

import React, { useState, useMemo } from "react";
import Link from "next/link";
import {
  CalendarDays,
  Clock,
  Users,
  CheckCircle2,
  FileSpreadsheet,
  BookCheck,
  ArrowRight,
  Sparkles,
  MapPin,
  Award,
  Layers,
  Calendar,
  AlertCircle,
  Eye,
  BookOpen,
  Download,
  Send,
  Lock,
  Unlock,
  FileText,
  Search,
  Filter,
  Check,
  X,
  ChevronRight,
  AlertTriangle,
  Printer,
  RefreshCw,
  History,
  BarChart3,
  HelpCircle,
  BadgeCheck,
  ShieldCheck,
  Flame,
  GraduationCap,
  Bell,
  CheckCheck,
  Info,
  SlidersHorizontal,
  FileDown,
} from "lucide-react";
import { toast } from "sonner";

// =========================================================================
// 1. DATA MODELS & COMPREHENSIVE INSTITUTIONAL MOCK DATA
// =========================================================================

interface TodaySessionItem {
  id: string;
  code: string;
  name: string;
  type: "PRACTICAL" | "THEORY";
  time: string;
  duration: string;
  room: string;
  batch: string;
  semester: string;
  totalStudents: number;
  presentCount?: number;
  status: "OPEN" | "SCHEDULED" | "COMPLETED";
  editWindowHoursRemaining?: number;
}

const todayClassesData: TodaySessionItem[] = [
  {
    id: "session_1042",
    code: "BHM201",
    name: "Food Production Operations Practical (Kitchen B)",
    type: "PRACTICAL",
    time: "09:00 AM - 01:00 PM",
    duration: "4.0 Contact Hours",
    room: "Basic Training Kitchen B",
    batch: "Batch B1 (Practical)",
    semester: "Semester III",
    totalStudents: 30,
    presentCount: 28,
    status: "COMPLETED",
    editWindowHoursRemaining: 20,
  },
  {
    id: "session_1043",
    code: "BHM202",
    name: "Food & Beverage Service Theory",
    type: "THEORY",
    time: "02:00 PM - 03:00 PM",
    duration: "1.0 Contact Hour",
    room: "Lecture Hall 101",
    batch: "Semester III (Whole Cohort)",
    semester: "Semester III",
    totalStudents: 65,
    status: "OPEN",
    editWindowHoursRemaining: 24,
  },
  {
    id: "session_1044",
    code: "BHM301",
    name: "Advanced Culinary Techniques & Garde Manger",
    type: "PRACTICAL",
    time: "03:30 PM - 05:30 PM",
    duration: "2.0 Contact Hours",
    room: "Quantity Training Kitchen",
    batch: "Batch A1 (Specialization)",
    semester: "Semester V",
    totalStudents: 28,
    status: "SCHEDULED",
    editWindowHoursRemaining: 24,
  },
];

interface RecentEditableSession {
  id: string;
  code: string;
  name: string;
  date: string;
  time: string;
  batch: string;
  semester: string;
  type: "PRACTICAL" | "THEORY";
  conductedHours: number;
  presentCount: number;
  totalStudents: number;
  status: "OPEN_EDIT" | "LOCKED";
  hoursRemaining: number;
  lockedAt?: string;
  attendanceUnits: number;
}

const initialEditableSessions: RecentEditableSession[] = [
  {
    id: "session_1042",
    code: "BHM201",
    name: "Food Production Operations Practical",
    date: "13-Oct-2026 (Today)",
    time: "09:00 AM - 01:00 PM",
    batch: "Batch B1",
    semester: "Sem III",
    type: "PRACTICAL",
    conductedHours: 4.0,
    presentCount: 28,
    totalStudents: 30,
    status: "OPEN_EDIT",
    hoursRemaining: 20,
    attendanceUnits: 4.0,
  },
  {
    id: "session_1038",
    code: "BHM201",
    name: "Classical Stocks, Glazes & Liaison Practical",
    date: "12-Oct-2026 (Yesterday)",
    time: "09:00 AM - 01:00 PM",
    batch: "Batch B1",
    semester: "Sem III",
    type: "PRACTICAL",
    conductedHours: 4.0,
    presentCount: 29,
    totalStudents: 30,
    status: "OPEN_EDIT",
    hoursRemaining: 6,
    attendanceUnits: 4.0,
  },
  {
    id: "session_1035",
    code: "BHM202",
    name: "Beverage Service Protocol Theory",
    date: "11-Oct-2026",
    time: "02:00 PM - 03:00 PM",
    batch: "Semester III",
    semester: "Sem III",
    type: "THEORY",
    conductedHours: 1.0,
    presentCount: 61,
    totalStudents: 65,
    status: "LOCKED",
    hoursRemaining: 0,
    lockedAt: "11-Oct-2026 15:45",
    attendanceUnits: 1.0,
  },
  {
    id: "session_1030",
    code: "BHM203",
    name: "Bakery & Viennoiserie Practice",
    date: "09-Oct-2026",
    time: "09:00 AM - 01:00 PM",
    batch: "Batch B2",
    semester: "Sem III",
    type: "PRACTICAL",
    conductedHours: 4.0,
    presentCount: 27,
    totalStudents: 28,
    status: "LOCKED",
    hoursRemaining: 0,
    lockedAt: "09-Oct-2026 14:10",
    attendanceUnits: 4.0,
  },
  {
    id: "session_1025",
    code: "BHM301",
    name: "Quantity Food Costing & Purchasing Theory",
    date: "08-Oct-2026",
    time: "02:00 PM - 03:00 PM",
    batch: "Semester V",
    semester: "Sem V",
    type: "THEORY",
    conductedHours: 1.0,
    presentCount: 29,
    totalStudents: 31,
    status: "LOCKED",
    hoursRemaining: 0,
    lockedAt: "08-Oct-2026 15:30",
    attendanceUnits: 1.0,
  },
];

interface TimetableSlot {
  id: string;
  day: string;
  time: string;
  code: string;
  name: string;
  room: string;
  batch: string;
  semester: string;
  type: "PRACTICAL" | "THEORY";
  hours: number;
}

const fullWeeklyTimetable: Record<string, TimetableSlot[]> = {
  Monday: [
    {
      id: "tt-mon-1",
      day: "Monday",
      time: "09:00 AM - 01:00 PM",
      code: "BHM201",
      name: "Food Production Operations Practical",
      room: "Basic Training Kitchen B",
      batch: "Batch B1",
      semester: "Sem III",
      type: "PRACTICAL",
      hours: 4.0,
    },
    {
      id: "tt-mon-2",
      day: "Monday",
      time: "02:00 PM - 03:00 PM",
      code: "BHM202",
      name: "Food & Beverage Service Theory",
      room: "Lecture Hall 101",
      batch: "Whole Batch",
      semester: "Sem III",
      type: "THEORY",
      hours: 1.0,
    },
    {
      id: "tt-mon-3",
      day: "Monday",
      time: "03:30 PM - 04:30 PM",
      code: "BHM101",
      name: "Culinary Foundation & Sanitation Theory",
      room: "Smart Room 204",
      batch: "Section A",
      semester: "Sem I",
      type: "THEORY",
      hours: 1.0,
    },
  ],
  Tuesday: [
    {
      id: "tt-tue-1",
      day: "Tuesday",
      time: "09:00 AM - 01:00 PM",
      code: "BHM201",
      name: "Food Production Operations Practical",
      room: "Basic Training Kitchen B",
      batch: "Batch B2",
      semester: "Sem III",
      type: "PRACTICAL",
      hours: 4.0,
    },
    {
      id: "tt-tue-2",
      day: "Tuesday",
      time: "02:00 PM - 03:00 PM",
      code: "BHM301",
      name: "Advanced Culinary Techniques Theory",
      room: "Lecture Hall 102",
      batch: "Section A",
      semester: "Sem V",
      type: "THEORY",
      hours: 1.0,
    },
  ],
  Wednesday: [
    {
      id: "tt-wed-1",
      day: "Wednesday",
      time: "10:00 AM - 01:00 PM",
      code: "BHM203",
      name: "Bakery & Confectionery Practical",
      room: "Advanced Bakery Lab",
      batch: "Batch B1",
      semester: "Sem III",
      type: "PRACTICAL",
      hours: 3.0,
    },
    {
      id: "tt-wed-2",
      day: "Wednesday",
      time: "02:00 PM - 03:00 PM",
      code: "BHM201",
      name: "Culinary Science & Nutrition Theory",
      room: "Smart Room 204",
      batch: "Whole Batch",
      semester: "Sem III",
      type: "THEORY",
      hours: 1.0,
    },
    {
      id: "tt-wed-3",
      day: "Wednesday",
      time: "03:30 PM - 04:30 PM",
      code: "FAC-DEV",
      name: "Department Faculty Coordination & Curriculum Sync",
      room: "Faculty Room F-04",
      batch: "Faculty Body",
      semester: "Academic Cell",
      type: "THEORY",
      hours: 1.0,
    },
  ],
  Thursday: [
    {
      id: "tt-thu-1",
      day: "Thursday",
      time: "09:00 AM - 01:00 PM",
      code: "BHM201",
      name: "Food Production Operations Practical",
      room: "Basic Training Kitchen B",
      batch: "Batch B3",
      semester: "Sem III",
      type: "PRACTICAL",
      hours: 4.0,
    },
    {
      id: "tt-thu-2",
      day: "Thursday",
      time: "02:00 PM - 03:00 PM",
      code: "BHM202",
      name: "Food & Beverage Service Theory",
      room: "Lecture Hall 101",
      batch: "Whole Batch",
      semester: "Sem III",
      type: "THEORY",
      hours: 1.0,
    },
  ],
  Friday: [
    {
      id: "tt-fri-1",
      day: "Friday",
      time: "09:00 AM - 12:00 PM",
      code: "BHM203",
      name: "Bakery & Confectionery Practical",
      room: "Advanced Bakery Lab",
      batch: "Batch B2",
      semester: "Sem III",
      type: "PRACTICAL",
      hours: 3.0,
    },
    {
      id: "tt-fri-2",
      day: "Friday",
      time: "02:00 PM - 03:00 PM",
      code: "BHM301",
      name: "Menu Planning & Culinary Cost Control",
      room: "Lecture Hall 102",
      batch: "Whole Batch",
      semester: "Sem V",
      type: "THEORY",
      hours: 1.0,
    },
  ],
  Saturday: [
    {
      id: "tt-sat-1",
      day: "Saturday",
      time: "10:00 AM - 01:00 PM",
      code: "BHM201",
      name: "Masterclass Workshop & Regional Indian Heritage Cuisine",
      room: "Amphitheatre Demo Kitchen",
      batch: "All Batches B1/B2/B3",
      semester: "Sem III",
      type: "PRACTICAL",
      hours: 3.0,
    },
  ],
};

interface AssignedCourse {
  code: string;
  name: string;
  type: "PRACTICAL" | "THEORY";
  batch: string;
  semester: string;
  credits: number;
  enrolledStudents: number;
  totalPlannedHours: number;
  conductedHours: number;
  classesHeld: number;
  avgAttendancePct: number;
  defaultersCount: number;
  syllabusUnitsCompleted: number;
  totalSyllabusUnits: number;
}

const assignedCoursesList: AssignedCourse[] = [
  {
    code: "BHM201",
    name: "Food Production Operations Practical (Kitchen B)",
    type: "PRACTICAL",
    batch: "Batch B1, B2 & B3",
    semester: "Semester III",
    credits: 4.0,
    enrolledStudents: 30,
    totalPlannedHours: 60.0,
    conductedHours: 36.0,
    classesHeld: 9,
    avgAttendancePct: 92.4,
    defaultersCount: 1,
    syllabusUnitsCompleted: 3,
    totalSyllabusUnits: 5,
  },
  {
    code: "BHM202",
    name: "Food & Beverage Service Theory",
    type: "THEORY",
    batch: "Whole Cohort (Section A & B)",
    semester: "Semester III",
    credits: 2.0,
    enrolledStudents: 65,
    totalPlannedHours: 30.0,
    conductedHours: 18.0,
    classesHeld: 18,
    avgAttendancePct: 88.5,
    defaultersCount: 3,
    syllabusUnitsCompleted: 3,
    totalSyllabusUnits: 4,
  },
  {
    code: "BHM203",
    name: "Bakery & Confectionery Practical",
    type: "PRACTICAL",
    batch: "Batch B1 & B2",
    semester: "Semester III",
    credits: 3.0,
    enrolledStudents: 28,
    totalPlannedHours: 40.0,
    conductedHours: 20.0,
    classesHeld: 5,
    avgAttendancePct: 94.1,
    defaultersCount: 0,
    syllabusUnitsCompleted: 2,
    totalSyllabusUnits: 4,
  },
  {
    code: "BHM301",
    name: "Advanced Food Production Operations & Garde Manger",
    type: "PRACTICAL",
    batch: "Culinary Specialization A",
    semester: "Semester V",
    credits: 4.0,
    enrolledStudents: 31,
    totalPlannedHours: 50.0,
    conductedHours: 24.0,
    classesHeld: 6,
    avgAttendancePct: 91.0,
    defaultersCount: 1,
    syllabusUnitsCompleted: 2,
    totalSyllabusUnits: 5,
  },
];

interface RosterStudent {
  id: string;
  rollNumber: string;
  name: string;
  batch: string;
  semester: string;
  email: string;
  phone: string;
  attended: number;
  total: number;
  pct: number;
  condonedUnits: number;
  status: "REGULAR" | "WARNING" | "DEFAULTER";
}

const institutionalStudentsRoster: RosterStudent[] = [
  { id: "s-101", rollNumber: "2441112001", name: "Aaron Smith", batch: "Batch B1", semester: "Sem III", email: "aaron.smith@ihmkolkata.edu.in", phone: "+91 98301 23456", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-102", rollNumber: "2441112002", name: "Bethany Roy", batch: "Batch B1", semester: "Sem III", email: "bethany.roy@ihmkolkata.edu.in", phone: "+91 98301 23457", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-103", rollNumber: "2441112003", name: "Chirag Banerjee", batch: "Batch B1", semester: "Sem III", email: "chirag.b@ihmkolkata.edu.in", phone: "+91 98301 23458", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-104", rollNumber: "2441112004", name: "Devika Sharma", batch: "Batch B1", semester: "Sem III", email: "devika.s@ihmkolkata.edu.in", phone: "+91 98301 23459", attended: 6, total: 9, pct: 66.7, condonedUnits: 4, status: "DEFAULTER" },
  { id: "s-105", rollNumber: "2441112005", name: "Farhan Ahmed", batch: "Batch B1", semester: "Sem III", email: "farhan.a@ihmkolkata.edu.in", phone: "+91 98301 23460", attended: 7, total: 9, pct: 77.8, condonedUnits: 0, status: "REGULAR" },
  { id: "s-106", rollNumber: "2441112006", name: "Gautam Sen", batch: "Batch B1", semester: "Sem III", email: "gautam.s@ihmkolkata.edu.in", phone: "+91 98301 23461", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-107", rollNumber: "2441112007", name: "Harshavardhan Rao", batch: "Batch B1", semester: "Sem III", email: "harsha.rao@ihmkolkata.edu.in", phone: "+91 98301 23462", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-108", rollNumber: "2441112008", name: "Isha Mukherjee", batch: "Batch B1", semester: "Sem III", email: "isha.m@ihmkolkata.edu.in", phone: "+91 98301 23463", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-109", rollNumber: "2441112009", name: "Jayant Verma", batch: "Batch B1", semester: "Sem III", email: "jayant.v@ihmkolkata.edu.in", phone: "+91 98301 23464", attended: 7, total: 9, pct: 77.8, condonedUnits: 0, status: "REGULAR" },
  { id: "s-110", rollNumber: "2441112010", name: "Kritika Das", batch: "Batch B1", semester: "Sem III", email: "kritika.d@ihmkolkata.edu.in", phone: "+91 98301 23465", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-111", rollNumber: "2441112011", name: "Lalit Mohan", batch: "Batch B1", semester: "Sem III", email: "lalit.m@ihmkolkata.edu.in", phone: "+91 98301 23466", attended: 6, total: 9, pct: 66.7, condonedUnits: 0, status: "DEFAULTER" },
  { id: "s-112", rollNumber: "2441112012", name: "Meera Nair", batch: "Batch B1", semester: "Sem III", email: "meera.n@ihmkolkata.edu.in", phone: "+91 98301 23467", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-113", rollNumber: "2441112013", name: "Nikhil Joshi", batch: "Batch B1", semester: "Sem III", email: "nikhil.j@ihmkolkata.edu.in", phone: "+91 98301 23468", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-114", rollNumber: "2441112014", name: "Oindrila Ghosh", batch: "Batch B1", semester: "Sem III", email: "oindrila.g@ihmkolkata.edu.in", phone: "+91 98301 23469", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-115", rollNumber: "2441112015", name: "Prateek Saxena", batch: "Batch B1", semester: "Sem III", email: "prateek.s@ihmkolkata.edu.in", phone: "+91 98301 23470", attended: 7, total: 9, pct: 77.8, condonedUnits: 0, status: "REGULAR" },
  { id: "s-116", rollNumber: "2441112016", name: "Qasim Ali", batch: "Batch B1", semester: "Sem III", email: "qasim.ali@ihmkolkata.edu.in", phone: "+91 98301 23471", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-117", rollNumber: "2441112017", name: "Rhea Chawla", batch: "Batch B1", semester: "Sem III", email: "rhea.c@ihmkolkata.edu.in", phone: "+91 98301 23472", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-118", rollNumber: "2441112018", name: "Sourav Ganguly", batch: "Batch B1", semester: "Sem III", email: "sourav.g@ihmkolkata.edu.in", phone: "+91 98301 23473", attended: 7, total: 9, pct: 77.8, condonedUnits: 0, status: "REGULAR" },
  { id: "s-119", rollNumber: "2441112019", name: "Tanvi Kulkarni", batch: "Batch B1", semester: "Sem III", email: "tanvi.k@ihmkolkata.edu.in", phone: "+91 98301 23474", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-120", rollNumber: "2441112020", name: "Utkarsh Gupta", batch: "Batch B1", semester: "Sem III", email: "utkarsh.g@ihmkolkata.edu.in", phone: "+91 98301 23475", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-121", rollNumber: "2441112021", name: "Varun Mehta", batch: "Batch B1", semester: "Sem III", email: "varun.m@ihmkolkata.edu.in", phone: "+91 98301 23476", attended: 7, total: 9, pct: 77.8, condonedUnits: 0, status: "REGULAR" },
  { id: "s-122", rollNumber: "2441112022", name: "William D'Souza", batch: "Batch B1", semester: "Sem III", email: "william.d@ihmkolkata.edu.in", phone: "+91 98301 23477", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-123", rollNumber: "2441112023", name: "Xavier Pinto", batch: "Batch B1", semester: "Sem III", email: "xavier.p@ihmkolkata.edu.in", phone: "+91 98301 23478", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-124", rollNumber: "2441112024", name: "Yashasvi Paul", batch: "Batch B1", semester: "Sem III", email: "yashasvi.p@ihmkolkata.edu.in", phone: "+91 98301 23479", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-125", rollNumber: "2441112025", name: "Zoya Khan", batch: "Batch B1", semester: "Sem III", email: "zoya.khan@ihmkolkata.edu.in", phone: "+91 98301 23480", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-126", rollNumber: "2441112026", name: "Abhinav Mishra", batch: "Batch B1", semester: "Sem III", email: "abhinav.m@ihmkolkata.edu.in", phone: "+91 98301 23481", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-127", rollNumber: "2441112027", name: "Bhavya Aggarwal", batch: "Batch B1", semester: "Sem III", email: "bhavya.a@ihmkolkata.edu.in", phone: "+91 98301 23482", attended: 7, total: 9, pct: 77.8, condonedUnits: 0, status: "REGULAR" },
  { id: "s-128", rollNumber: "2441112028", name: "Chetan Bhagat", batch: "Batch B1", semester: "Sem III", email: "chetan.b@ihmkolkata.edu.in", phone: "+91 98301 23483", attended: 8, total: 9, pct: 88.9, condonedUnits: 0, status: "REGULAR" },
  { id: "s-129", rollNumber: "2441112029", name: "Deepak Chopra", batch: "Batch B1", semester: "Sem III", email: "deepak.c@ihmkolkata.edu.in", phone: "+91 98301 23484", attended: 9, total: 9, pct: 100.0, condonedUnits: 0, status: "REGULAR" },
  { id: "s-130", rollNumber: "2441112030", name: "Esha Deol", batch: "Batch B1", semester: "Sem III", email: "esha.d@ihmkolkata.edu.in", phone: "+91 98301 23485", attended: 6, total: 9, pct: 66.7, condonedUnits: 0, status: "DEFAULTER" },
];

export default function FacultyDashboardPage() {
  // Navigation tabs
  const [activeTab, setActiveTab] = useState<
    "overview" | "attendance" | "timetable" | "courses" | "progress" | "reports" | "apr"
  >("overview");

  // Timetable selected day and filter
  const [selectedDay, setSelectedDay] = useState("Monday");
  const [timetableTypeFilter, setTimetableTypeFilter] = useState<"ALL" | "PRACTICAL" | "THEORY">("ALL");

  // Student Roster Modal state
  const [showRosterModal, setShowRosterModal] = useState(false);
  const [selectedCourseForRoster, setSelectedCourseForRoster] = useState<AssignedCourse>(assignedCoursesList[0]);
  const [rosterSearch, setRosterSearch] = useState("");
  const [rosterFilter, setRosterFilter] = useState<"ALL" | "REGULAR" | "DEFAULTER">("ALL");

  // Editable Sessions & Lock Confirmation Modal
  const [editableSessions, setEditableSessions] = useState<RecentEditableSession[]>(initialEditableSessions);
  const [showLockModal, setShowLockModal] = useState(false);
  const [sessionToLock, setSessionToLock] = useState<RecentEditableSession | null>(null);

  // APR Submission State
  const [aprSubmitted, setAprSubmitted] = useState(false);
  const [showAprSubmitModal, setShowAprSubmitModal] = useState(false);
  const [aprSubmitting, setAprSubmitting] = useState(false);
  const [aprReceipt, setAprReceipt] = useState<string | null>(null);

  // Roster Filter logic
  const filteredRoster = useMemo(() => {
    return institutionalStudentsRoster.filter((student) => {
      const matchesSearch =
        student.name.toLowerCase().includes(rosterSearch.toLowerCase()) ||
        student.rollNumber.includes(rosterSearch);
      const matchesFilter =
        rosterFilter === "ALL" ? true : student.status === rosterFilter;
      return matchesSearch && matchesFilter;
    });
  }, [rosterSearch, rosterFilter]);

  // Timetable Slot Filter logic
  const currentDaySlots = useMemo(() => {
    const slots = fullWeeklyTimetable[selectedDay] || [];
    if (timetableTypeFilter === "ALL") return slots;
    return slots.filter((s) => s.type === timetableTypeFilter);
  }, [selectedDay, timetableTypeFilter]);

  // Handler: Lock Session
  const handleConfirmLock = (sessionId: string) => {
    setEditableSessions((prev) =>
      prev.map((s) =>
        s.id === sessionId
          ? {
              ...s,
              status: "LOCKED",
              hoursRemaining: 0,
              lockedAt: new Date().toLocaleDateString("en-GB") + " " + new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
            }
          : s
      )
    );
    setShowLockModal(false);
    toast.success(`Session ${sessionToLock?.code} successfully finalized and locked into institutional registers.`);
  };

  // Handler: Submit APR
  const handleSubmitApr = () => {
    setAprSubmitting(true);
    setTimeout(() => {
      setAprSubmitting(false);
      setAprSubmitted(true);
      setShowAprSubmitModal(false);
      const generatedRef = `APR-2026-10-FAC101-${Math.floor(1000 + Math.random() * 9000)}`;
      setAprReceipt(generatedRef);
      toast.success("October APR successfully submitted to HOD & Academic Cell for digital sign-off!");
    }, 1200);
  };

  return (
    <div className="space-y-6 pb-14 font-sans bg-[#F8FAFC]">
      {/* ============================================================== */}
      {/* 1. TOP HEADER BAR WITH INSTRUCTOR IDENTITY & INSTITUTIONAL PILL */}
      {/* ============================================================== */}
      <div>
        <div className="flex items-center gap-2 text-xs text-[#64748B] mb-2 font-medium">
          <Link href="/faculty/dashboard" className="hover:text-[#1769E8] transition-colors">
            Faculty Console
          </Link>
          <span>&gt;</span>
          <span className="text-[#071A4D] font-semibold">Teacher Dashboard</span>
          <span>&gt;</span>
          <span className="text-amber-600 font-bold capitalize">{activeTab}</span>
        </div>

        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <div className="flex items-center gap-2.5">
              <h1 className="text-3xl font-bold font-heading text-[#071A4D] tracking-tight">
                Welcome back, Chef Rajesh Sharma
              </h1>
              <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold bg-[#DCFCE7] text-[#15803D] border border-[#BBF7D0]">
                Active Instructor
              </span>
            </div>
            <p className="text-[14px] text-[#64748B] mt-1 font-normal flex flex-wrap items-center gap-2">
              <span className="font-semibold text-[#071A4D]">Senior Lecturer &amp; HOD</span>
              <span>•</span>
              <span>Department of Food Production &amp; Culinary Arts</span>
              <span>•</span>
              <span className="text-[#1769E8] font-mono font-bold">Session 2026–2027 (Autumn Term)</span>
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-2.5">
            <button
              onClick={() => setActiveTab("timetable")}
              className="px-3.5 py-2 bg-white border border-[#E2E8F0] rounded-lg text-xs font-semibold text-[#334155] hover:bg-slate-50 transition-colors flex items-center gap-1.5 shadow-2xs"
            >
              <Calendar className="w-3.5 h-3.5 text-[#1769E8]" />
              <span>Personalized Timetable</span>
            </button>
            <button
              onClick={() => setActiveTab("apr")}
              className="px-3.5 py-2 bg-purple-50 border border-purple-200 text-purple-700 hover:bg-purple-100 rounded-lg text-xs font-semibold transition-colors flex items-center gap-1.5 shadow-2xs"
            >
              <Award className="w-3.5 h-3.5 text-purple-600" />
              <span>APR Records</span>
            </button>
            <Link
              href="/faculty/classes/today"
              className="px-4 py-2 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-xs font-semibold transition-colors flex items-center gap-2 shadow-xs"
            >
              <CheckCircle2 className="w-3.5 h-3.5" />
              <span>Record Daily Attendance</span>
            </Link>
          </div>
        </div>
      </div>

      {/* ============================================================== */}
      {/* 2. TOP ACADEMIC KPI SUMMARIES (5 METRICS LOADED WITH REAL DATA) */}
      {/* ============================================================== */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3.5">
        {/* KPI 1: Today's Classes */}
        <div
          onClick={() => setActiveTab("attendance")}
          className="bg-white rounded-xl border border-[#E5EAF0] p-4 shadow-xs hover:border-[#1769E8]/50 transition-all cursor-pointer flex items-center justify-between"
        >
          <div>
            <span className="text-[11px] font-bold text-[#64748B] uppercase tracking-wider block">
              Today's Teaching
            </span>
            <div className="text-2xl font-bold font-heading text-[#071A4D] mt-0.5">
              3 Sessions
            </div>
            <span className="text-[11px] text-[#1769E8] font-semibold mt-0.5 block">
              7.0 Contact Hours (Kitchen &amp; Th)
            </span>
          </div>
          <div className="w-10 h-10 rounded-xl bg-blue-50 text-[#1769E8] flex items-center justify-center shrink-0 border border-blue-100">
            <Clock className="w-5 h-5" />
          </div>
        </div>

        {/* KPI 2: Assigned Courses */}
        <div
          onClick={() => setActiveTab("courses")}
          className="bg-white rounded-xl border border-[#E5EAF0] p-4 shadow-xs hover:border-[#1769E8]/50 transition-all cursor-pointer flex items-center justify-between"
        >
          <div>
            <span className="text-[11px] font-bold text-[#64748B] uppercase tracking-wider block">
              Assigned Courses
            </span>
            <div className="text-2xl font-bold font-heading text-[#071A4D] mt-0.5">
              4 Subjects
            </div>
            <span className="text-[11px] text-emerald-600 font-semibold mt-0.5 block">
              154 Enrolled Students Roster
            </span>
          </div>
          <div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0 border border-emerald-100">
            <Users className="w-5 h-5" />
          </div>
        </div>

        {/* KPI 3: Syllabus Delivery Progress */}
        <div
          onClick={() => setActiveTab("progress")}
          className="bg-white rounded-xl border border-[#E5EAF0] p-4 shadow-xs hover:border-[#1769E8]/50 transition-all cursor-pointer flex items-center justify-between"
        >
          <div>
            <span className="text-[11px] font-bold text-[#64748B] uppercase tracking-wider block">
              Syllabus Delivery
            </span>
            <div className="text-2xl font-bold font-heading text-[#071A4D] mt-0.5">
              56.9%
            </div>
            <span className="text-[11px] text-indigo-600 font-semibold mt-0.5 block">
              98.0 / 180 hrs Completed
            </span>
          </div>
          <div className="w-10 h-10 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center shrink-0 border border-indigo-100">
            <BookCheck className="w-5 h-5" />
          </div>
        </div>

        {/* KPI 4: Attendance Average & Defaulters */}
        <div
          onClick={() => setActiveTab("progress")}
          className="bg-white rounded-xl border border-[#E5EAF0] p-4 shadow-xs hover:border-[#1769E8]/50 transition-all cursor-pointer flex items-center justify-between"
        >
          <div>
            <span className="text-[11px] font-bold text-[#64748B] uppercase tracking-wider block">
              Avg Attendance
            </span>
            <div className="text-2xl font-bold font-heading text-[#071A4D] mt-0.5">
              91.5%
            </div>
            <span className="text-[11px] text-amber-600 font-semibold mt-0.5 block">
              5 Defaulters (&lt;75%) Alert
            </span>
          </div>
          <div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center shrink-0 border border-amber-100">
            <BarChart3 className="w-5 h-5" />
          </div>
        </div>

        {/* KPI 5: Monthly APR Submission */}
        <div
          onClick={() => setActiveTab("apr")}
          className="bg-white rounded-xl border border-[#E5EAF0] p-4 shadow-xs hover:border-[#1769E8]/50 transition-all cursor-pointer flex items-center justify-between"
        >
          <div>
            <span className="text-[11px] font-bold text-[#64748B] uppercase tracking-wider block">
              Monthly APR
            </span>
            <div className="text-sm font-bold font-heading text-[#071A4D] mt-1.5 flex items-center gap-1.5">
              {aprSubmitted ? (
                <span className="text-emerald-700 flex items-center gap-1">
                  <BadgeCheck className="w-4 h-4 text-emerald-600" /> Submitted
                </span>
              ) : (
                <span className="text-purple-700">Oct 2026 Ready</span>
              )}
            </div>
            <span className="text-[11px] text-slate-500 font-semibold mt-0.5 block">
              {aprSubmitted ? `Ref: ${aprReceipt}` : "32 Periods Logged"}
            </span>
          </div>
          <div className="w-10 h-10 rounded-xl bg-purple-50 text-purple-600 flex items-center justify-center shrink-0 border border-purple-100">
            <Award className="w-5 h-5" />
          </div>
        </div>
      </div>

      {/* ============================================================== */}
      {/* 3. PRIMARY FEATURE NAVIGATION TABS (ALL 10 FEATURES)          */}
      {/* ============================================================== */}
      <div className="border-b border-[#E2E8F0] bg-white rounded-xl shadow-2xs px-2 pt-2 flex items-center gap-1 overflow-x-auto">
        <button
          onClick={() => setActiveTab("overview")}
          className={`px-4 py-2.5 text-xs font-bold border-b-2 transition-all flex items-center gap-2 whitespace-nowrap ${
            activeTab === "overview"
              ? "border-[#1769E8] text-[#1769E8] bg-blue-50/50 rounded-t-lg"
              : "border-transparent text-[#64748B] hover:text-[#071A4D] hover:bg-slate-50 rounded-t-lg"
          }`}
        >
          <Layers className="w-4 h-4" />
          <span>Dashboard Overview</span>
        </button>

        <button
          onClick={() => setActiveTab("attendance")}
          className={`px-4 py-2.5 text-xs font-bold border-b-2 transition-all flex items-center gap-2 whitespace-nowrap ${
            activeTab === "attendance"
              ? "border-[#1769E8] text-[#1769E8] bg-blue-50/50 rounded-t-lg"
              : "border-transparent text-[#64748B] hover:text-[#071A4D] hover:bg-slate-50 rounded-t-lg"
          }`}
        >
          <CheckCircle2 className="w-4 h-4" />
          <span>Daily Attendance &amp; Lock</span>
          <span className="px-1.5 py-0.2 rounded-full text-[10px] bg-blue-100 text-[#1769E8] font-bold">
            3
          </span>
        </button>

        <button
          onClick={() => setActiveTab("timetable")}
          className={`px-4 py-2.5 text-xs font-bold border-b-2 transition-all flex items-center gap-2 whitespace-nowrap ${
            activeTab === "timetable"
              ? "border-[#1769E8] text-[#1769E8] bg-blue-50/50 rounded-t-lg"
              : "border-transparent text-[#64748B] hover:text-[#071A4D] hover:bg-slate-50 rounded-t-lg"
          }`}
        >
          <Calendar className="w-4 h-4" />
          <span>Personalized Timetable</span>
        </button>

        <button
          onClick={() => setActiveTab("courses")}
          className={`px-4 py-2.5 text-xs font-bold border-b-2 transition-all flex items-center gap-2 whitespace-nowrap ${
            activeTab === "courses"
              ? "border-[#1769E8] text-[#1769E8] bg-blue-50/50 rounded-t-lg"
              : "border-transparent text-[#64748B] hover:text-[#071A4D] hover:bg-slate-50 rounded-t-lg"
          }`}
        >
          <Users className="w-4 h-4" />
          <span>Courses &amp; Student Rosters</span>
          <span className="px-1.5 py-0.2 rounded-full text-[10px] bg-emerald-100 text-emerald-800 font-bold">
            154
          </span>
        </button>

        <button
          onClick={() => setActiveTab("progress")}
          className={`px-4 py-2.5 text-xs font-bold border-b-2 transition-all flex items-center gap-2 whitespace-nowrap ${
            activeTab === "progress"
              ? "border-[#1769E8] text-[#1769E8] bg-blue-50/50 rounded-t-lg"
              : "border-transparent text-[#64748B] hover:text-[#071A4D] hover:bg-slate-50 rounded-t-lg"
          }`}
        >
          <BookCheck className="w-4 h-4" />
          <span>Subject Attendance &amp; Teaching Progress</span>
        </button>

        <button
          onClick={() => setActiveTab("reports")}
          className={`px-4 py-2.5 text-xs font-bold border-b-2 transition-all flex items-center gap-2 whitespace-nowrap ${
            activeTab === "reports"
              ? "border-[#1769E8] text-[#1769E8] bg-blue-50/50 rounded-t-lg"
              : "border-transparent text-[#64748B] hover:text-[#071A4D] hover:bg-slate-50 rounded-t-lg"
          }`}
        >
          <FileSpreadsheet className="w-4 h-4" />
          <span>Attendance Reports &amp; Registers</span>
        </button>

        <button
          onClick={() => setActiveTab("apr")}
          className={`px-4 py-2.5 text-xs font-bold border-b-2 transition-all flex items-center gap-2 whitespace-nowrap ${
            activeTab === "apr"
              ? "border-purple-600 text-purple-700 bg-purple-50/50 rounded-t-lg"
              : "border-transparent text-[#64748B] hover:text-[#071A4D] hover:bg-slate-50 rounded-t-lg"
          }`}
        >
          <Award className="w-4 h-4 text-purple-600" />
          <span>APR Generator &amp; Submit</span>
        </button>
      </div>

      {/* ============================================================== */}
      {/* 4. TAB 1: RECORD DAILY ATTENDANCE & AUTHORIZED TIME WINDOW      */}
      {/* ============================================================== */}
      {(activeTab === "overview" || activeTab === "attendance") && (
        <div className="space-y-6">
          {/* SECTION 1: RECORD DAILY ATTENDANCE LAUNCHPAD */}
          <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
            <div className="p-4 border-b border-[#E5EAF0] flex flex-col sm:flex-row sm:items-center justify-between gap-3">
              <div className="flex items-center gap-2.5">
                <CalendarDays className="w-5 h-5 text-[#1769E8]" />
                <div>
                  <h2 className="font-heading font-bold text-lg text-[#071A4D]">
                    Today's Scheduled Classes ({todayClassesData.length} Sessions)
                  </h2>
                  <p className="text-xs text-[#64748B]">
                    Record live attendance, sync biometric student registers, and submit directly to database.
                  </p>
                </div>
              </div>
              <Link
                href="/faculty/classes/today"
                className="text-xs font-semibold text-[#1769E8] hover:underline flex items-center gap-1"
              >
                <span>View Full Today Roster</span>
                <ArrowRight className="w-3.5 h-3.5" />
              </Link>
            </div>

            <div className="p-5 grid grid-cols-1 md:grid-cols-3 gap-4">
              {todayClassesData.map((item) => (
                <div
                  key={item.id}
                  className="p-4 rounded-xl border border-[#E2E8F0] bg-white hover:border-[#1769E8]/40 hover:shadow-xs transition-all flex flex-col justify-between"
                >
                  <div>
                    <div className="flex items-center justify-between gap-2 mb-2">
                      <div className="flex items-center gap-1.5">
                        <span className="font-mono font-bold text-xs bg-[#F1F6FC] text-[#1769E8] px-2 py-0.5 rounded border border-[#D0E2FF]">
                          {item.code}
                        </span>
                        <span
                          className={`text-[10px] font-bold px-2 py-0.5 rounded-full border ${
                            item.type === "PRACTICAL"
                              ? "bg-amber-50 text-amber-700 border-amber-200"
                              : "bg-blue-50 text-blue-700 border-blue-200"
                          }`}
                        >
                          {item.type}
                        </span>
                      </div>

                      <span
                        className={`text-[10px] font-bold px-2.5 py-0.5 rounded-full border ${
                          item.status === "OPEN"
                            ? "bg-[#DCFCE7] text-[#15803D] border-[#BBF7D0]"
                            : item.status === "COMPLETED"
                            ? "bg-slate-100 text-slate-700 border-slate-200"
                            : "bg-blue-50 text-blue-700 border-blue-200"
                        }`}
                      >
                        {item.status === "OPEN"
                          ? "● Ready to Mark"
                          : item.status === "COMPLETED"
                          ? "✓ Completed"
                          : "Scheduled"}
                      </span>
                    </div>

                    <h3 className="font-heading font-bold text-sm text-[#071A4D] mb-1.5 leading-snug">
                      {item.name}
                    </h3>

                    <div className="space-y-1.5 text-xs text-[#64748B] mb-3">
                      <div className="flex items-center gap-1.5">
                        <Clock className="w-3.5 h-3.5 text-[#94A3B8]" />
                        <span className="font-medium text-[#334155]">{item.time} ({item.duration})</span>
                      </div>
                      <div className="flex items-center gap-1.5">
                        <MapPin className="w-3.5 h-3.5 text-[#94A3B8]" />
                        <span className="truncate">{item.room}</span>
                      </div>
                      <div className="flex items-center gap-1.5">
                        <Users className="w-3.5 h-3.5 text-[#94A3B8]" />
                        <span>{item.batch} • {item.semester}</span>
                      </div>
                    </div>
                  </div>

                  <div className="pt-3 border-t border-[#F1F5F9] flex items-center justify-between">
                    <span className="text-xs text-[#64748B]">
                      Students: <strong className="text-[#071A4D]">{item.totalStudents}</strong>
                      {item.presentCount !== undefined && (
                        <span className="text-emerald-600 font-semibold ml-1">({item.presentCount} P)</span>
                      )}
                    </span>
                    <Link
                      href={`/faculty/classes/${item.id}/mark`}
                      className={`px-3 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition-colors shadow-2xs ${
                        item.status === "OPEN"
                          ? "bg-[#1769E8] hover:bg-[#1255be] text-white"
                          : item.status === "COMPLETED"
                          ? "bg-slate-100 hover:bg-slate-200 text-slate-800"
                          : "bg-[#071A4D] hover:bg-[#0b2773] text-white"
                      }`}
                    >
                      <CheckCircle2 className="w-3.5 h-3.5" />
                      <span>{item.status === "OPEN" ? "Mark Attendance" : item.status === "COMPLETED" ? "Review Register" : "Open Pad"}</span>
                    </Link>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* SECTION 2: UPDATE ATTENDANCE RECORDS WITHIN AUTHORIZED TIMEFRAMES & FINALIZE / LOCK */}
          <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
            <div className="p-4 border-b border-[#E5EAF0] flex flex-col sm:flex-row sm:items-center justify-between gap-3">
              <div className="flex items-center gap-2.5">
                <Clock className="w-5 h-5 text-amber-600" />
                <div>
                  <h2 className="font-heading font-bold text-lg text-[#071A4D]">
                    Authorized Update Window &amp; Finalization Lock
                  </h2>
                  <p className="text-xs text-[#64748B]">
                    Update attendance records within authorized 24-hour post-class timeframe or finalize tamper-proof lock.
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-xs text-amber-800 bg-amber-50 px-2.5 py-1 rounded-md border border-amber-200 font-semibold flex items-center gap-1">
                  <ShieldCheck className="w-3.5 h-3.5 text-amber-600" />
                  Authorized Window: 24h Post-Class
                </span>
              </div>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs border-collapse">
                <thead>
                  <tr className="bg-[#F8FAFC] border-b border-[#E5EAF0] text-[#64748B] font-semibold">
                    <th className="py-3 px-3.5 font-bold text-[#071A4D]">Session Details</th>
                    <th className="py-3 px-3.5 font-bold text-[#071A4D]">Conducted Date</th>
                    <th className="py-3 px-3.5 font-bold text-[#071A4D]">Cohort Batch</th>
                    <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Tally</th>
                    <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Authorized Status</th>
                    <th className="py-3 px-4 font-bold text-[#071A4D] text-right">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#E5EAF0]">
                  {editableSessions.map((session) => (
                    <tr key={session.id} className="hover:bg-[#F8FAFC] transition-colors">
                      <td className="py-3.5 px-3.5">
                        <div className="flex items-center gap-2">
                          <span className="font-mono font-bold text-[10px] bg-[#F1F6FC] text-[#1769E8] px-1.5 py-0.5 rounded border border-[#D0E2FF]">
                            {session.code}
                          </span>
                          <span className="font-bold text-[#071A4D] text-xs">
                            {session.name}
                          </span>
                        </div>
                        <div className="text-[11px] text-[#64748B] mt-0.5">
                          {session.time} • {session.type} ({session.attendanceUnits} Contact Units)
                        </div>
                      </td>
                      <td className="py-3.5 px-3.5 font-semibold text-[#071A4D]">
                        {session.date}
                      </td>
                      <td className="py-3.5 px-3.5 font-medium text-[#334155]">
                        {session.batch} ({session.semester})
                      </td>
                      <td className="py-3.5 px-3.5 text-center font-mono font-bold text-[#071A4D]">
                        {session.presentCount} / {session.totalStudents} ({((session.presentCount / session.totalStudents) * 100).toFixed(0)}%)
                      </td>
                      <td className="py-3.5 px-3.5 text-center">
                        {session.status === "OPEN_EDIT" ? (
                          <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-amber-50 text-amber-800 border border-amber-200">
                            <Clock className="w-3 h-3 text-amber-600" />
                            Editable ({session.hoursRemaining}h remaining)
                          </span>
                        ) : (
                          <div className="inline-flex flex-col items-center">
                            <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-[#DCFCE7] text-[#15803D] border border-[#BBF7D0]">
                              <Lock className="w-3 h-3 text-emerald-600" />
                              Finalized &amp; Locked
                            </span>
                            {session.lockedAt && (
                              <span className="text-[9px] text-slate-400 font-mono mt-0.5">
                                Sealed: {session.lockedAt}
                              </span>
                            )}
                          </div>
                        )}
                      </td>
                      <td className="py-3.5 px-4 text-right">
                        <div className="flex items-center justify-end gap-2">
                          {session.status === "OPEN_EDIT" ? (
                            <>
                              <Link
                                href={`/faculty/classes/${session.id}/mark`}
                                className="px-2.5 py-1.5 rounded bg-white border border-[#E2E8F0] hover:bg-slate-50 text-[#1769E8] font-semibold text-xs transition-colors shadow-2xs"
                              >
                                Update Attendance
                              </Link>
                              <button
                                onClick={() => {
                                  setSessionToLock(session);
                                  setShowLockModal(true);
                                }}
                                className="px-2.5 py-1.5 rounded bg-emerald-600 hover:bg-emerald-700 text-white font-semibold text-xs transition-colors shadow-2xs flex items-center gap-1"
                              >
                                <Lock className="w-3 h-3" />
                                <span>Finalize &amp; Lock</span>
                              </button>
                            </>
                          ) : (
                            <Link
                              href={`/faculty/classes/${session.id}/review`}
                              className="px-2.5 py-1.5 rounded bg-slate-50 border border-slate-200 text-slate-700 hover:bg-slate-100 font-semibold text-xs transition-colors"
                            >
                              View Locked Register
                            </Link>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* ============================================================== */}
      {/* 5. TAB 2: PERSONALIZED CLASS TIMETABLES (MON–SAT COMPLETE)      */}
      {/* ============================================================== */}
      {(activeTab === "overview" || activeTab === "timetable") && (
        <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
          <div className="p-4 border-b border-[#E5EAF0] flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div className="flex items-center gap-2.5">
              <Calendar className="w-5 h-5 text-[#1769E8]" />
              <div>
                <h2 className="font-heading font-bold text-lg text-[#071A4D]">
                  Personalized Class Timetable (Weekly Schedule Matrix)
                </h2>
                <p className="text-xs text-[#64748B]">
                  Access scheduled kitchen practicals, theory lectures, allocated training venues, and contact hours.
                </p>
              </div>
            </div>

            <div className="flex items-center gap-2">
              <div className="flex items-center gap-1 bg-slate-100 p-1 rounded-lg">
                <button
                  onClick={() => setTimetableTypeFilter("ALL")}
                  className={`px-2.5 py-1 rounded-md text-xs font-semibold transition-colors ${
                    timetableTypeFilter === "ALL" ? "bg-white text-[#071A4D] shadow-2xs" : "text-slate-600 hover:text-slate-900"
                  }`}
                >
                  All Types
                </button>
                <button
                  onClick={() => setTimetableTypeFilter("PRACTICAL")}
                  className={`px-2.5 py-1 rounded-md text-xs font-semibold transition-colors ${
                    timetableTypeFilter === "PRACTICAL" ? "bg-white text-amber-700 shadow-2xs" : "text-slate-600 hover:text-slate-900"
                  }`}
                >
                  Practicals
                </button>
                <button
                  onClick={() => setTimetableTypeFilter("THEORY")}
                  className={`px-2.5 py-1 rounded-md text-xs font-semibold transition-colors ${
                    timetableTypeFilter === "THEORY" ? "bg-white text-blue-700 shadow-2xs" : "text-slate-600 hover:text-slate-900"
                  }`}
                >
                  Theories
                </button>
              </div>

              <button
                onClick={() => toast.success("Exported Personalized Weekly Timetable PDF.")}
                className="px-3 py-1.5 bg-white border border-[#E2E8F0] hover:bg-slate-50 text-slate-700 rounded-lg text-xs font-semibold flex items-center gap-1.5 shadow-2xs"
              >
                <Download className="w-3.5 h-3.5 text-[#1769E8]" />
                <span>Export PDF</span>
              </button>
            </div>
          </div>

          {/* Day Selector Navigation Pills */}
          <div className="p-3 bg-[#F8FAFC] border-b border-[#E5EAF0] flex items-center gap-2 overflow-x-auto">
            {Object.keys(fullWeeklyTimetable).map((day) => {
              const count = fullWeeklyTimetable[day].length;
              return (
                <button
                  key={day}
                  onClick={() => setSelectedDay(day)}
                  className={`px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center gap-1.5 ${
                    selectedDay === day
                      ? "bg-[#071A4D] text-white shadow-xs"
                      : "bg-white border border-[#E2E8F0] text-[#64748B] hover:text-[#071A4D] hover:bg-slate-50"
                  }`}
                >
                  <span>{day}</span>
                  <span className={`px-1.5 py-0.2 rounded-full text-[10px] ${selectedDay === day ? "bg-white/20 text-white" : "bg-slate-100 text-slate-600"}`}>
                    {count}
                  </span>
                </button>
              );
            })}
          </div>

          {/* Timetable Session Slots Display */}
          <div className="p-5">
            <div className="space-y-3">
              {currentDaySlots.length === 0 ? (
                <div className="p-8 text-center bg-slate-50 rounded-xl border border-dashed border-slate-200 text-xs text-slate-500">
                  No sessions match the selected filter for {selectedDay}.
                </div>
              ) : (
                currentDaySlots.map((slot) => (
                  <div
                    key={slot.id}
                    className="p-4 rounded-xl border border-[#E2E8F0] bg-white hover:border-[#1769E8]/40 hover:shadow-2xs transition-all flex flex-col md:flex-row md:items-center justify-between gap-4"
                  >
                    <div className="flex items-start gap-4">
                      <div className="p-3 rounded-xl bg-blue-50 border border-blue-100 text-[#1769E8] shrink-0 text-center min-w-[95px]">
                        <span className="text-[10px] font-bold uppercase block text-[#1769E8]">
                          Timing
                        </span>
                        <span className="font-mono font-bold text-xs text-[#071A4D] block mt-0.5">
                          {slot.time.split(" - ")[0]}
                        </span>
                        <span className="text-[10px] text-slate-400 block">
                          to {slot.time.split(" - ")[1]}
                        </span>
                      </div>

                      <div className="space-y-1">
                        <div className="flex items-center gap-2">
                          <span className="font-mono font-bold text-xs bg-[#F1F6FC] text-[#1769E8] px-2 py-0.5 rounded border border-[#D0E2FF]">
                            {slot.code}
                          </span>
                          <span
                            className={`text-[10px] font-bold px-2 py-0.5 rounded-full border ${
                              slot.type === "PRACTICAL"
                                ? "bg-amber-50 text-amber-700 border-amber-200"
                                : "bg-blue-50 text-blue-700 border-blue-200"
                            }`}
                          >
                            {slot.type} • {slot.hours}h Contact
                          </span>
                          <span className="text-xs text-slate-500 font-medium">
                            {slot.batch} ({slot.semester})
                          </span>
                        </div>

                        <h4 className="font-heading font-bold text-sm text-[#071A4D]">
                          {slot.name}
                        </h4>

                        <div className="flex flex-wrap items-center gap-4 text-xs text-[#64748B]">
                          <span className="flex items-center gap-1 font-medium text-[#334155]">
                            <MapPin className="w-3.5 h-3.5 text-[#94A3B8]" />
                            Venue: {slot.room}
                          </span>
                          <span className="flex items-center gap-1">
                            <Clock className="w-3.5 h-3.5 text-[#94A3B8]" />
                            Duration: {slot.time}
                          </span>
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center gap-2 pt-2 md:pt-0 border-t md:border-t-0 border-slate-100">
                      <button
                        onClick={() => {
                          const matched = assignedCoursesList.find((c) => c.code === slot.code);
                          if (matched) {
                            setSelectedCourseForRoster(matched);
                          }
                          setShowRosterModal(true);
                        }}
                        className="px-3 py-1.5 rounded-lg border border-[#E2E8F0] hover:bg-slate-50 text-[#334155] text-xs font-semibold transition-colors flex items-center gap-1.5 shadow-2xs"
                      >
                        <Users className="w-3.5 h-3.5 text-[#1769E8]" />
                        <span>View Roster</span>
                      </button>
                      <Link
                        href="/faculty/classes/today"
                        className="px-3 py-1.5 rounded-lg bg-[#1769E8] hover:bg-[#1255be] text-white text-xs font-semibold transition-colors flex items-center gap-1.5 shadow-2xs"
                      >
                        <CheckCircle2 className="w-3.5 h-3.5" />
                        <span>Take Attendance</span>
                      </Link>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      )}

      {/* ============================================================== */}
      {/* 6. TAB 3: ASSIGNED COURSES & STUDENT ROSTERS (FULL DATABASE)   */}
      {/* ============================================================== */}
      {(activeTab === "overview" || activeTab === "courses") && (
        <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
          <div className="p-4 border-b border-[#E5EAF0] flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div className="flex items-center gap-2.5">
              <Users className="w-5 h-5 text-[#1769E8]" />
              <div>
                <h2 className="font-heading font-bold text-lg text-[#071A4D]">
                  Assigned Courses &amp; Enrolled Student Rosters (4 Courses • 154 Students)
                </h2>
                <p className="text-xs text-[#64748B]">
                  Inspect curriculum allocations, individual student attendance metrics, and condonation compliance.
                </p>
              </div>
            </div>
            <button
              onClick={() => {
                setSelectedCourseForRoster(assignedCoursesList[0]);
                setShowRosterModal(true);
              }}
              className="px-3 py-1.5 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-xs font-semibold flex items-center gap-1.5 shadow-2xs"
            >
              <Users className="w-3.5 h-3.5" />
              <span>Open Student Roster (30)</span>
            </button>
          </div>

          <div className="p-5 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {assignedCoursesList.map((course) => (
              <div
                key={course.code}
                className="p-4 rounded-xl border border-[#E2E8F0] bg-white hover:border-[#1769E8]/40 hover:shadow-xs transition-all flex flex-col justify-between"
              >
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-mono font-bold text-xs bg-[#F1F6FC] text-[#1769E8] px-2 py-0.5 rounded border border-[#D0E2FF]">
                      {course.code}
                    </span>
                    <span className="text-[11px] font-semibold text-[#64748B]">
                      {course.credits} Credits • {course.type}
                    </span>
                  </div>

                  <h3 className="font-heading font-bold text-sm text-[#071A4D] mb-1 leading-snug">
                    {course.name}
                  </h3>
                  <p className="text-xs text-[#64748B] mb-3">
                    {course.batch} ({course.semester})
                  </p>

                  <div className="space-y-2 py-3 border-y border-[#F1F5F9] text-xs">
                    <div className="flex items-center justify-between">
                      <span className="text-[#64748B]">Enrolled Students:</span>
                      <strong className="text-[#071A4D]">{course.enrolledStudents} Students</strong>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-[#64748B]">Conducted Hours:</span>
                      <strong className="text-[#071A4D] font-mono">
                        {course.conductedHours} / {course.totalPlannedHours} hrs
                      </strong>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-[#64748B]">Average Attendance:</span>
                      <strong className="text-emerald-600 font-mono font-bold">
                        {course.avgAttendancePct}%
                      </strong>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-[#64748B]">Shortage Defaulters:</span>
                      <span className={`font-bold ${course.defaultersCount > 0 ? "text-amber-600" : "text-emerald-600"}`}>
                        {course.defaultersCount} Students (&lt;75%)
                      </span>
                    </div>
                  </div>
                </div>

                <div className="pt-3">
                  <button
                    onClick={() => {
                      setSelectedCourseForRoster(course);
                      setShowRosterModal(true);
                    }}
                    className="w-full py-2 bg-slate-50 hover:bg-slate-100 border border-[#E2E8F0] text-[#071A4D] rounded-lg text-xs font-semibold transition-colors flex items-center justify-center gap-1.5"
                  >
                    <Eye className="w-3.5 h-3.5 text-[#1769E8]" />
                    <span>View Student Roster</span>
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ============================================================== */}
      {/* 7. TAB 4: TEACHING DELIVERY PROGRESS & SYLLABUS TRACKING       */}
      {/* ============================================================== */}
      {(activeTab === "overview" || activeTab === "progress") && (
        <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
          <div className="p-4 border-b border-[#E5EAF0] flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div className="flex items-center gap-2.5">
              <BookCheck className="w-5 h-5 text-[#1769E8]" />
              <div>
                <h2 className="font-heading font-bold text-lg text-[#071A4D]">
                  Curriculum Contact Hours &amp; Teaching Delivery Progress
                </h2>
                <p className="text-xs text-[#64748B]">
                  Monitor conducted teaching hours against NCHMCT planned curriculum guidelines and syllabus milestones.
                </p>
              </div>
            </div>

            <Link
              href="/faculty/teaching-roster"
              className="text-xs font-semibold text-[#1769E8] hover:underline flex items-center gap-1"
            >
              <span>Full Curriculum Roster</span>
              <ArrowRight className="w-3.5 h-3.5" />
            </Link>
          </div>

          <div className="p-5 space-y-4">
            {assignedCoursesList.map((course) => {
              const progressPct = ((course.conductedHours / course.totalPlannedHours) * 100).toFixed(0);
              return (
                <div
                  key={course.code}
                  className="p-4 rounded-xl border border-[#E2E8F0] bg-white hover:border-[#1769E8]/30 transition-all space-y-3"
                >
                  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-mono font-bold text-xs bg-[#F1F6FC] text-[#1769E8] px-2 py-0.5 rounded border border-[#D0E2FF]">
                          {course.code}
                        </span>
                        <h4 className="font-heading font-bold text-sm text-[#071A4D]">
                          {course.name}
                        </h4>
                        <span className="text-xs text-slate-500 font-medium">
                          ({course.batch} • {course.semester})
                        </span>
                      </div>
                    </div>

                    <div className="flex items-center gap-3">
                      <span className="text-xs font-mono font-bold text-[#071A4D]">
                        {course.conductedHours} / {course.totalPlannedHours} Hours ({progressPct}%)
                      </span>
                      <span className="px-2 py-0.5 rounded-full text-[10px] font-bold bg-[#DCFCE7] text-[#15803D] border border-[#BBF7D0]">
                        On Target ({course.classesHeld} Sessions)
                      </span>
                    </div>
                  </div>

                  {/* Progress Bar */}
                  <div>
                    <div className="w-full bg-slate-100 h-2.5 rounded-full overflow-hidden">
                      <div
                        className="bg-[#1769E8] h-full rounded-full transition-all"
                        style={{ width: `${progressPct}%` }}
                      />
                    </div>
                  </div>

                  {/* Syllabus Modules Breakdown */}
                  <div className="grid grid-cols-1 sm:grid-cols-4 gap-2 pt-1 text-xs text-[#64748B]">
                    <div className="p-2 rounded bg-slate-50 border border-slate-100 flex items-center justify-between">
                      <span>Unit 1: Classical Cuts &amp; Stocks</span>
                      <span className="text-emerald-700 font-bold flex items-center gap-1">
                        <Check className="w-3 h-3" /> Done
                      </span>
                    </div>
                    <div className="p-2 rounded bg-slate-50 border border-slate-100 flex items-center justify-between">
                      <span>Unit 2: Sauces, Soups &amp; Stews</span>
                      <span className="text-emerald-700 font-bold flex items-center gap-1">
                        <Check className="w-3 h-3" /> Done
                      </span>
                    </div>
                    <div className="p-2 rounded bg-slate-50 border border-slate-100 flex items-center justify-between">
                      <span>Unit 3: Meat Cookery &amp; Poultry</span>
                      <span className="text-blue-700 font-bold">Active (75%)</span>
                    </div>
                    <div className="p-2 rounded bg-slate-50 border border-slate-100 flex items-center justify-between">
                      <span>Unit 4: Regional Specialities</span>
                      <span className="text-slate-400 font-medium">Upcoming (Nov)</span>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* ============================================================== */}
      {/* 8. TAB 5: ATTENDANCE REPORTS & REGISTER GENERATION             */}
      {/* ============================================================== */}
      {(activeTab === "overview" || activeTab === "reports") && (
        <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
          <div className="p-4 border-b border-[#E5EAF0] flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div className="flex items-center gap-2.5">
              <FileSpreadsheet className="w-5 h-5 text-[#1769E8]" />
              <div>
                <h2 className="font-heading font-bold text-lg text-[#071A4D]">
                  Generate Attendance Reports &amp; Registers
                </h2>
                <p className="text-xs text-[#64748B]">
                  Download monthly subject registers, NCHMCT Form 4 compliance sheets, and defaulter summaries.
                </p>
              </div>
            </div>

            <Link
              href="/faculty/reports"
              className="text-xs font-semibold text-[#1769E8] hover:underline flex items-center gap-1"
            >
              <span>Dedicated Reports Console</span>
              <ArrowRight className="w-3.5 h-3.5" />
            </Link>
          </div>

          <div className="p-5 grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="p-4 rounded-xl border border-[#E2E8F0] bg-slate-50/50 flex flex-col justify-between space-y-3">
              <div>
                <div className="w-10 h-10 rounded-lg bg-blue-100 text-[#1769E8] flex items-center justify-center mb-2">
                  <FileSpreadsheet className="w-5 h-5" />
                </div>
                <h4 className="font-heading font-bold text-sm text-[#071A4D]">
                  Monthly Subject Register (Form 4)
                </h4>
                <p className="text-xs text-[#64748B] mt-1">
                  Complete day-by-day attendance ledger for all 30 students in BHM201 with contact hour unit credits.
                </p>
              </div>
              <button
                onClick={() => toast.success("Exported Monthly Subject Register (Form 4) PDF.")}
                className="w-full py-2 bg-white hover:bg-slate-100 border border-[#E2E8F0] text-[#071A4D] rounded-lg text-xs font-semibold transition-colors flex items-center justify-center gap-1.5 shadow-2xs"
              >
                <Download className="w-3.5 h-3.5 text-[#1769E8]" />
                <span>Export PDF Register</span>
              </button>
            </div>

            <div className="p-4 rounded-xl border border-[#E2E8F0] bg-slate-50/50 flex flex-col justify-between space-y-3">
              <div>
                <div className="w-10 h-10 rounded-lg bg-amber-100 text-amber-700 flex items-center justify-center mb-2">
                  <AlertCircle className="w-5 h-5" />
                </div>
                <h4 className="font-heading font-bold text-sm text-[#071A4D]">
                  Attendance Shortage Defaulters List
                </h4>
                <p className="text-xs text-[#64748B] mt-1">
                  Official list of students falling below 75% mandatory threshold requiring condonation or warning letters.
                </p>
              </div>
              <button
                onClick={() => toast.success("Exported Shortage Defaulters List (.xlsx).")}
                className="w-full py-2 bg-white hover:bg-slate-100 border border-[#E2E8F0] text-[#071A4D] rounded-lg text-xs font-semibold transition-colors flex items-center justify-center gap-1.5 shadow-2xs"
              >
                <Download className="w-3.5 h-3.5 text-amber-600" />
                <span>Export Defaulter List</span>
              </button>
            </div>

            <div className="p-4 rounded-xl border border-[#E2E8F0] bg-slate-50/50 flex flex-col justify-between space-y-3">
              <div>
                <div className="w-10 h-10 rounded-lg bg-emerald-100 text-emerald-700 flex items-center justify-center mb-2">
                  <BarChart3 className="w-5 h-5" />
                </div>
                <h4 className="font-heading font-bold text-sm text-[#071A4D]">
                  Cumulative Term Matrix
                </h4>
                <p className="text-xs text-[#64748B] mt-1">
                  Cross-subject percentage matrix across Food Production, F&amp;B Service, and Bakery for Autumn 2026.
                </p>
              </div>
              <button
                onClick={() => toast.success("Generated Cumulative Term Matrix (.xlsx).")}
                className="w-full py-2 bg-white hover:bg-slate-100 border border-[#E2E8F0] text-[#071A4D] rounded-lg text-xs font-semibold transition-colors flex items-center justify-center gap-1.5 shadow-2xs"
              >
                <Download className="w-3.5 h-3.5 text-emerald-600" />
                <span>Download Matrix</span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ============================================================== */}
      {/* 9. TAB 6: GENERATE & SUBMIT APR (ACADEMIC PERFORMANCE REGISTER) */}
      {/* ============================================================== */}
      {(activeTab === "overview" || activeTab === "apr") && (
        <div className="bg-white rounded-xl border border-purple-200 shadow-xs overflow-hidden">
          <div className="p-4 bg-purple-50/40 border-b border-purple-100 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div className="flex items-center gap-2.5">
              <Award className="w-5 h-5 text-purple-700" />
              <div>
                <h2 className="font-heading font-bold text-lg text-[#071A4D]">
                  Generate and Submit APR (Academic Performance Register)
                </h2>
                <p className="text-xs text-[#64748B]">
                  Official monthly instructional report submitted by faculty to HOD and Academic Cell.
                </p>
              </div>
            </div>

            <div className="flex items-center gap-2">
              {aprSubmitted ? (
                <span className="px-3 py-1.5 rounded-lg bg-emerald-50 text-emerald-800 border border-emerald-200 text-xs font-bold flex items-center gap-1.5">
                  <BadgeCheck className="w-4 h-4 text-emerald-600" />
                  Submitted &amp; Acknowledged
                </span>
              ) : (
                <button
                  onClick={() => setShowAprSubmitModal(true)}
                  className="px-4 py-2 bg-purple-700 hover:bg-purple-800 text-white rounded-lg text-xs font-semibold transition-colors flex items-center gap-1.5 shadow-2xs"
                >
                  <Send className="w-3.5 h-3.5" />
                  <span>Review &amp; Submit October APR</span>
                </button>
              )}
            </div>
          </div>

          <div className="p-5">
            <div className="p-4 rounded-xl border border-purple-100 bg-white space-y-4">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 pb-3 border-b border-slate-100">
                <div>
                  <h3 className="font-heading font-bold text-base text-[#071A4D]">
                    Monthly APR Ledger: October 2026
                  </h3>
                  <p className="text-xs text-[#64748B]">
                    Faculty: Chef Rajesh Sharma (FAC-101) • Department of Food Production &amp; Culinary Arts
                  </p>
                </div>
                <div className="text-right">
                  <span className="text-[11px] font-mono text-purple-700 font-bold block">
                    {aprReceipt ? `Ref ID: ${aprReceipt}` : "Status: Draft Ready for Final Submission"}
                  </span>
                  <span className="text-[10px] text-slate-400">NCHMCT Academic Compliance Form APR-4</span>
                </div>
              </div>

              {/* Aggregated Performance Metric Grid */}
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs">
                <div className="p-3 rounded-lg bg-slate-50 border border-slate-200">
                  <span className="text-slate-500 block">Weekly Load Met</span>
                  <span className="text-base font-bold text-[#071A4D] font-mono">18 / 18 Hours</span>
                  <span className="text-[10px] text-emerald-600 font-semibold block">100% Target Met</span>
                </div>
                <div className="p-3 rounded-lg bg-slate-50 border border-slate-200">
                  <span className="text-slate-500 block">Classes Conducted</span>
                  <span className="text-base font-bold text-[#071A4D] font-mono">32 Sessions</span>
                  <span className="text-[10px] text-emerald-600 font-semibold block">0 Cancellations</span>
                </div>
                <div className="p-3 rounded-lg bg-slate-50 border border-slate-200">
                  <span className="text-slate-500 block">Contact Hours</span>
                  <span className="text-base font-bold text-[#071A4D] font-mono">74.0 Hours</span>
                  <span className="text-[10px] text-blue-600 font-semibold block">Kitchen &amp; Theory</span>
                </div>
                <div className="p-3 rounded-lg bg-slate-50 border border-slate-200">
                  <span className="text-slate-500 block">Average Attendance</span>
                  <span className="text-base font-bold text-[#071A4D] font-mono">91.8%</span>
                  <span className="text-[10px] text-emerald-600 font-semibold block">Compliant</span>
                </div>
              </div>

              {/* Actions Footer */}
              <div className="pt-2 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                <div className="flex items-center gap-2 text-xs text-slate-600">
                  <ShieldCheck className="w-4 h-4 text-purple-600" />
                  <span>
                    Digitally validated against biometric turnstile logs and room occupancy sensors.
                  </span>
                </div>

                <div className="flex items-center gap-2">
                  <button
                    onClick={() => toast.success("Draft APR record printed to official PDF template.")}
                    className="px-3 py-1.5 bg-white border border-[#E2E8F0] hover:bg-slate-50 text-slate-700 rounded-lg text-xs font-semibold flex items-center gap-1.5"
                  >
                    <Printer className="w-3.5 h-3.5 text-slate-600" />
                    <span>Print APR Preview</span>
                  </button>
                  {!aprSubmitted && (
                    <button
                      onClick={() => setShowAprSubmitModal(true)}
                      className="px-4 py-1.5 bg-purple-700 hover:bg-purple-800 text-white rounded-lg text-xs font-semibold transition-colors flex items-center gap-1.5"
                    >
                      <Send className="w-3.5 h-3.5" />
                      <span>Submit to HOD</span>
                    </button>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ============================================================== */}
      {/* 10. MODAL: INTERACTIVE STUDENT ROSTER VIEWER                   */}
      {/* ============================================================== */}
      {showRosterModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-2xs p-4">
          <div className="bg-white rounded-2xl border border-slate-200 shadow-xl w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden animate-in fade-in zoom-in-95 duration-150">
            {/* Modal Header */}
            <div className="p-4 border-b border-slate-200 flex items-center justify-between bg-slate-50">
              <div className="flex items-center gap-2.5">
                <Users className="w-5 h-5 text-[#1769E8]" />
                <div>
                  <h3 className="font-heading font-bold text-base text-[#071A4D]">
                    Enrolled Student Roster — {selectedCourseForRoster?.code}: {selectedCourseForRoster?.name}
                  </h3>
                  <p className="text-xs text-slate-500">
                    Cohort: {selectedCourseForRoster?.batch} ({selectedCourseForRoster?.semester}) • {institutionalStudentsRoster.length} Students Enrolled
                  </p>
                </div>
              </div>
              <button
                onClick={() => setShowRosterModal(false)}
                className="p-1 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-200 transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Modal Filter Bar */}
            <div className="p-4 border-b border-slate-200 bg-white flex flex-col sm:flex-row sm:items-center justify-between gap-3">
              <div className="relative flex-1 max-w-sm">
                <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
                <input
                  type="text"
                  placeholder="Search student by name or NCHM roll..."
                  value={rosterSearch}
                  onChange={(e) => setRosterSearch(e.target.value)}
                  className="w-full pl-9 pr-3 py-1.5 text-xs bg-slate-50 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#1769E8] focus:bg-white transition-colors"
                />
              </div>

              <div className="flex items-center gap-2">
                <button
                  onClick={() => setRosterFilter("ALL")}
                  className={`px-3 py-1 rounded-lg text-xs font-semibold transition-colors ${
                    rosterFilter === "ALL"
                      ? "bg-[#071A4D] text-white"
                      : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                  }`}
                >
                  All ({institutionalStudentsRoster.length})
                </button>
                <button
                  onClick={() => setRosterFilter("REGULAR")}
                  className={`px-3 py-1 rounded-lg text-xs font-semibold transition-colors ${
                    rosterFilter === "REGULAR"
                      ? "bg-emerald-700 text-white"
                      : "bg-emerald-50 text-emerald-700 hover:bg-emerald-100 border border-emerald-200"
                  }`}
                >
                  Regular &ge;75%
                </button>
                <button
                  onClick={() => setRosterFilter("DEFAULTER")}
                  className={`px-3 py-1 rounded-lg text-xs font-semibold transition-colors ${
                    rosterFilter === "DEFAULTER"
                      ? "bg-amber-600 text-white"
                      : "bg-amber-50 text-amber-700 hover:bg-amber-100 border border-amber-200"
                  }`}
                >
                  Defaulters &lt;75%
                </button>
              </div>
            </div>

            {/* Modal Body: Roster Table */}
            <div className="flex-1 overflow-y-auto p-4">
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs border-collapse min-w-[600px]">
                <thead>
                  <tr className="bg-slate-50 border-b border-slate-200 text-slate-500 font-semibold">
                    <th className="py-2.5 px-3">Roll Number</th>
                    <th className="py-2.5 px-3">Student Full Name</th>
                    <th className="py-2.5 px-3">Batch Group</th>
                    <th className="py-2.5 px-3 text-center">Classes Attended</th>
                    <th className="py-2.5 px-3 text-center">Attendance %</th>
                    <th className="py-2.5 px-3 text-center">Eligibility Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {filteredRoster.map((student) => (
                    <tr key={student.id} className="hover:bg-slate-50 transition-colors">
                      <td className="py-2.5 px-3 font-mono font-bold text-[#1769E8]">
                        {student.rollNumber}
                      </td>
                      <td className="py-2.5 px-3 font-semibold text-[#071A4D]">
                        {student.name}
                      </td>
                      <td className="py-2.5 px-3 text-slate-600">
                        {student.batch}
                      </td>
                      <td className="py-2.5 px-3 text-center font-mono font-bold text-slate-800">
                        {student.attended} / {student.total}
                      </td>
                      <td className="py-2.5 px-3 text-center font-mono font-bold">
                        <span
                          className={
                            student.pct >= 75 ? "text-emerald-600" : "text-amber-600"
                          }
                        >
                          {student.pct.toFixed(1)}%
                        </span>
                      </td>
                      <td className="py-2.5 px-3 text-center">
                        <span
                          className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold border ${
                            student.status === "REGULAR"
                              ? "bg-emerald-50 text-emerald-700 border-emerald-200"
                              : "bg-amber-50 text-amber-700 border-amber-200"
                          }`}
                        >
                          {student.status === "REGULAR" ? "Eligible" : "Attendance Shortage"}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              </div>
            </div>

            {/* Modal Footer */}
            <div className="p-3 bg-slate-50 border-t border-slate-200 flex items-center justify-between">
              <span className="text-xs text-slate-500">
                Showing {filteredRoster.length} of {institutionalStudentsRoster.length} students enrolled
              </span>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => toast.success("Exported roster to Excel format.")}
                  className="px-3 py-1.5 bg-white border border-slate-200 hover:bg-slate-100 text-slate-700 rounded-lg text-xs font-semibold flex items-center gap-1.5 shadow-2xs"
                >
                  <Download className="w-3.5 h-3.5 text-[#1769E8]" />
                  <span>Download Roster</span>
                </button>
                <button
                  onClick={() => setShowRosterModal(false)}
                  className="px-4 py-1.5 bg-[#071A4D] hover:bg-[#0b2773] text-white rounded-lg text-xs font-semibold transition-colors"
                >
                  Close Roster
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ============================================================== */}
      {/* 11. MODAL: FINALIZE & LOCK SESSION CONFIRMATION                */}
      {/* ============================================================== */}
      {showLockModal && sessionToLock && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-2xs p-4">
          <div className="bg-white rounded-2xl border border-slate-200 shadow-xl w-full max-w-md p-6 space-y-4 animate-in fade-in zoom-in-95 duration-150">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-emerald-50 border border-emerald-200 text-emerald-600 flex items-center justify-center shrink-0">
                <Lock className="w-5 h-5" />
              </div>
              <div>
                <h3 className="font-heading font-bold text-base text-[#071A4D]">
                  Finalize &amp; Lock Attendance Session?
                </h3>
                <p className="text-xs text-slate-500">
                  {sessionToLock.code} • {sessionToLock.name} ({sessionToLock.date})
                </p>
              </div>
            </div>

            <div className="p-3 bg-amber-50 rounded-xl border border-amber-200 text-xs text-amber-900 space-y-1">
              <p className="font-bold flex items-center gap-1">
                <AlertTriangle className="w-4 h-4 text-amber-600 shrink-0" />
                Permanent Record Commitment Notice
              </p>
              <p className="text-amber-800 leading-relaxed">
                Finalizing will immediately lock attendance records for <strong>{sessionToLock.totalStudents} students</strong> ({sessionToLock.presentCount} Present). Once locked, subsequent modifications will require administrative authorization.
              </p>
            </div>

            <div className="flex items-center justify-end gap-2 pt-2">
              <button
                onClick={() => setShowLockModal(false)}
                className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-xs font-semibold hover:bg-slate-50 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={() => handleConfirmLock(sessionToLock.id)}
                className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-semibold transition-colors flex items-center gap-1.5 shadow-2xs"
              >
                <Lock className="w-3.5 h-3.5" />
                <span>Confirm &amp; Lock Session</span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ============================================================== */}
      {/* 12. MODAL: SUBMIT APR CONFIRMATION MODAL                       */}
      {/* ============================================================== */}
      {showAprSubmitModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-2xs p-4">
          <div className="bg-white rounded-2xl border border-purple-200 shadow-xl w-full max-w-lg p-6 space-y-4 animate-in fade-in zoom-in-95 duration-150">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-purple-50 border border-purple-200 text-purple-700 flex items-center justify-center shrink-0">
                <Award className="w-5 h-5" />
              </div>
              <div>
                <h3 className="font-heading font-bold text-base text-[#071A4D]">
                  Submit Academic Performance Register (APR)
                </h3>
                <p className="text-xs text-slate-500">
                  Month of October 2026 • Form NCHMCT/APR-4
                </p>
              </div>
            </div>

            <div className="p-3 bg-purple-50/60 rounded-xl border border-purple-100 text-xs text-purple-950 space-y-2">
              <p className="font-bold">Faculty Declaration &amp; Certification:</p>
              <p className="text-slate-600 leading-relaxed italic">
                &ldquo;I hereby certify that all 32 lecture and practical periods recorded in this register were conducted strictly in compliance with NCHMCT syllabus standards, and student biometric records have been duly scrutinized.&rdquo;
              </p>
              <div className="pt-2 border-t border-purple-200/60 flex items-center justify-between font-mono font-bold text-[11px] text-purple-900">
                <span>Total Workload: 18h/week</span>
                <span>Contact Hours: 74.0h</span>
                <span>Avg Attendance: 91.8%</span>
              </div>
            </div>

            <div className="flex items-center justify-end gap-2 pt-2">
              <button
                onClick={() => setShowAprSubmitModal(false)}
                disabled={aprSubmitting}
                className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-xs font-semibold hover:bg-slate-50 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleSubmitApr}
                disabled={aprSubmitting}
                className="px-5 py-2 bg-purple-700 hover:bg-purple-800 text-white rounded-lg text-xs font-semibold transition-colors flex items-center gap-1.5 shadow-2xs"
              >
                {aprSubmitting ? (
                  <>
                    <RefreshCw className="w-3.5 h-3.5 animate-spin" />
                    <span>Submitting to HOD...</span>
                  </>
                ) : (
                  <>
                    <Send className="w-3.5 h-3.5" />
                    <span>Certify &amp; Submit APR</span>
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
