import React, { useState } from 'react';
import { useCollege } from '../context/CollegeContext';
import {
  Users,
  FileCheck,
  CreditCard,
  Building,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Search,
  Filter,
  Plus,
  Printer,
  Calendar,
  Lock,
  Unlock,
  Receipt,
  FileText,
  Clock,
  ShieldCheck,
  QrCode,
  GraduationCap,
  Award,
  BookOpen,
  Check,
  X,
  SlidersHorizontal,
  Briefcase,
  UserCheck,
  UserX,
  Edit3,
  ExternalLink,
  ShieldAlert,
  Download,
  FileSpreadsheet,
  Layers,
  Table,
  CheckCheck,
} from 'lucide-react';
import { StudentApplication, FeePayment, User, Role, AttendanceRecord, GradeItem } from '../types';
import { StudentIDCardModal } from '../components/StudentIDCardModal';
import { BulkExportModal } from '../components/BulkExportModal';
import {
  generateStudentRegistrationsCsv,
  generateAttendanceRecordsCsv,
  triggerCsvDownload,
} from '../utils/exportCsv';

interface AdminDashboardProps {
  onOpenRegisterModal: () => void;
  onOpenCalendarSync: () => void;
  onOpenReportCard: (studentId: string) => void;
}

export const AdminDashboard: React.FC<AdminDashboardProps> = ({
  onOpenRegisterModal,
  onOpenCalendarSync,
  onOpenReportCard,
}) => {
  const {
    allUsers,
    applications,
    fees,
    courses,
    attendance,
    grades,
    approveApplication,
    rejectApplication,
    verifyBankDepositSlip,
    broadcastUrgentAlert,
    isResultsLocked,
    approveTeacherAccount,
    rejectTeacherAccount,
    updateTeacherPermissions,
    registerTeacherAccount,
    suspendTeacherAccount,
    reactivateTeacherAccount,
    switchRole,
  } = useCollege();

  const [activeTab, setActiveTab] = useState<'applications' | 'attendance' | 'teachers' | 'fees' | 'clearance'>('applications');
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedApp, setSelectedApp] = useState<StudentApplication | null>(null);
  const [viewingIdCardFee, setViewingIdCardFee] = useState<FeePayment | null>(null);
  
  // Bulk Export state
  const [showBulkExportModal, setShowBulkExportModal] = useState(false);
  const [exportSuccessMessage, setExportSuccessMessage] = useState<string | null>(null);

  // Attendance tab specific filters
  const [attCourseFilter, setAttCourseFilter] = useState('all');
  const [attStatusFilter, setAttStatusFilter] = useState('all');

  // Teacher Approval & Management states
  const [teacherStatusFilter, setTeacherStatusFilter] = useState<'all' | 'pending_approval' | 'active' | 'suspended'>('all');
  const [teacherDeptFilter, setTeacherDeptFilter] = useState<string>('all');
  const [selectedTeacherForApproval, setSelectedTeacherForApproval] = useState<User | null>(null);
  const [editingTeacherPermissions, setEditingTeacherPermissions] = useState<User | null>(null);
  const [showNewTeacherModal, setShowNewTeacherModal] = useState(false);
  const [rejectionModalUser, setRejectionModalUser] = useState<User | null>(null);
  const [rejectionReasonInput, setRejectionReasonInput] = useState('');

  // Approval form state inside modal
  const [approvalPermissions, setApprovalPermissions] = useState({
    canPrepareExams: true,
    canCreateClasswork: true,
    canEnterGrades: true,
    canUploadMaterials: true,
    assignedCourses: [] as string[],
    department: '',
    title: '',
    employmentType: 'Full-Time Lecturer' as User['employmentType'],
  });

  // New Lecturer registration form state
  const [newLecturerForm, setNewLecturerForm] = useState({
    name: '',
    email: '',
    phone: '',
    department: 'Engineering & Computing',
    title: 'Lecturer',
    qualification: '',
    employmentType: 'Full-Time Lecturer' as NonNullable<User['employmentType']>,
    assignedCourses: [] as string[],
    canPrepareExams: true,
    canCreateClasswork: true,
    canEnterGrades: true,
    canUploadMaterials: true,
    status: 'active' as const,
  });

  // Statistics
  const pendingApps = applications.filter(a => a.status === 'Pending Verification').length;
  const approvedApps = applications.filter(a => a.status === 'Approved').length;

  const allTeachers = allUsers.filter(u => u.role === 'teacher');
  const pendingTeachers = allTeachers.filter(u => u.status === 'pending_approval');
  const activeTeachers = allTeachers.filter(u => u.status === 'active');
  const examCommissionedTeachers = allTeachers.filter(u => u.status === 'active' && u.canPrepareExams);
  
  const pendingSlipsCount = fees.reduce(
    (acc, f) => acc + f.bankDepositSlips.filter(s => s.status === 'Pending Review').length,
    0
  );

  const totalCollectedMWK = fees.reduce((sum, f) => sum + f.totalPaid, 0);

  const filteredApps = applications.filter(a =>
    `${a.firstNames} ${a.surname} ${a.refNumber} ${a.firstChoiceCourseCode}`
      .toLowerCase()
      .includes(searchTerm.toLowerCase())
  );

  const filteredFees = fees.filter(f =>
    `${f.studentName} ${f.studentId} ${f.courseName}`
      .toLowerCase()
      .includes(searchTerm.toLowerCase())
  );

  const filteredTeachers = allTeachers.filter(teacher => {
    const matchesSearch = `${teacher.name} ${teacher.email} ${teacher.department || ''} ${teacher.qualification || ''} ${teacher.title || ''} ${(teacher.assignedCourses || []).join(' ')}`
      .toLowerCase()
      .includes(searchTerm.toLowerCase());

    const matchesStatus =
      teacherStatusFilter === 'all'
        ? true
        : teacher.status === teacherStatusFilter;

    const matchesDept =
      teacherDeptFilter === 'all'
        ? true
        : teacher.department === teacherDeptFilter;

    return matchesSearch && matchesStatus && matchesDept;
  });

  // Open modal to review and approve a pending teacher
  const openApprovalModal = (teacher: User) => {
    setSelectedTeacherForApproval(teacher);
    setApprovalPermissions({
      canPrepareExams: teacher.canPrepareExams ?? true,
      canCreateClasswork: teacher.canCreateClasswork ?? true,
      canEnterGrades: teacher.canEnterGrades ?? true,
      canUploadMaterials: teacher.canUploadMaterials ?? true,
      assignedCourses: teacher.assignedCourses || (courses.length > 0 ? [courses[0].code] : []),
      department: teacher.department || 'Academic Faculty',
      title: teacher.title || 'Accredited Lecturer',
      employmentType: teacher.employmentType || 'Full-Time Lecturer',
    });
  };

  // Open modal to edit permissions of an active teacher
  const openEditPermissionsModal = (teacher: User) => {
    setEditingTeacherPermissions(teacher);
    setApprovalPermissions({
      canPrepareExams: teacher.canPrepareExams ?? false,
      canCreateClasswork: teacher.canCreateClasswork ?? false,
      canEnterGrades: teacher.canEnterGrades ?? false,
      canUploadMaterials: teacher.canUploadMaterials ?? false,
      assignedCourses: teacher.assignedCourses || [],
      department: teacher.department || 'Academic Faculty',
      title: teacher.title || 'Lecturer',
      employmentType: teacher.employmentType || 'Full-Time Lecturer',
    });
  };

  const handleConfirmApproval = (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedTeacherForApproval) return;
    approveTeacherAccount(selectedTeacherForApproval.id, approvalPermissions);
    setSelectedTeacherForApproval(null);
  };

  const handleSavePermissionUpdates = (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingTeacherPermissions) return;
    updateTeacherPermissions(editingTeacherPermissions.id, {
      canPrepareExams: approvalPermissions.canPrepareExams,
      canCreateClasswork: approvalPermissions.canCreateClasswork,
      canEnterGrades: approvalPermissions.canEnterGrades,
      canUploadMaterials: approvalPermissions.canUploadMaterials,
      assignedCourses: approvalPermissions.assignedCourses,
      department: approvalPermissions.department,
      title: approvalPermissions.title,
      employmentType: approvalPermissions.employmentType,
    });
    setEditingTeacherPermissions(null);
  };

  const handleConfirmRejection = (e: React.FormEvent) => {
    e.preventDefault();
    if (!rejectionModalUser) return;
    rejectTeacherAccount(rejectionModalUser.id, rejectionReasonInput || 'Credentials not verified or incomplete requirements.');
    setRejectionModalUser(null);
    setRejectionReasonInput('');
  };

  const handleCreateNewLecturer = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newLecturerForm.name || !newLecturerForm.email) return;

    registerTeacherAccount({
      name: newLecturerForm.name,
      email: newLecturerForm.email,
      phone: newLecturerForm.phone,
      role: 'teacher',
      department: newLecturerForm.department,
      title: newLecturerForm.title,
      qualification: newLecturerForm.qualification,
      employmentType: newLecturerForm.employmentType,
      assignedCourses: newLecturerForm.assignedCourses,
      canPrepareExams: newLecturerForm.canPrepareExams,
      canCreateClasswork: newLecturerForm.canCreateClasswork,
      canEnterGrades: newLecturerForm.canEnterGrades,
      canUploadMaterials: newLecturerForm.canUploadMaterials,
      status: 'active',
      approvedBy: 'Dr. Eddie Njunga (Principal & Registrar)',
      approvedAt: new Date().toISOString(),
      avatarUrl: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=150&auto=format&fit=crop&q=80',
    });

    setShowNewTeacherModal(false);
    setNewLecturerForm({
      name: '',
      email: '',
      phone: '',
      department: 'Engineering & Computing',
      title: 'Lecturer',
      qualification: '',
      employmentType: 'Full-Time Lecturer',
      assignedCourses: [],
      canPrepareExams: true,
      canCreateClasswork: true,
      canEnterGrades: true,
      canUploadMaterials: true,
      status: 'active',
    });
  };

  const departmentsList = Array.from(
    new Set(allTeachers.map(t => t.department).filter(Boolean) as string[])
  );

  // Quick export handlers
  const handleQuickExportRegistrations = () => {
    const { csvString, count, filename } = generateStudentRegistrationsCsv(applications, courses, fees);
    triggerCsvDownload(filename, csvString);
    setExportSuccessMessage(`Downloaded ${count} student registration records (${filename}) for local filing.`);
    setTimeout(() => setExportSuccessMessage(null), 5000);
  };

  const handleQuickExportAttendance = () => {
    const { csvString, count, filename } = generateAttendanceRecordsCsv(attendance, applications, allUsers, courses);
    triggerCsvDownload(filename, csvString);
    setExportSuccessMessage(`Downloaded ${count} attendance logs (${filename}) for academic board audit.`);
    setTimeout(() => setExportSuccessMessage(null), 5000);
  };

  // Filtered attendance records for Attendance & Roll-Call tab
  const filteredAttendance = attendance.filter(rec => {
    const studentUser = allUsers.find(u => u.studentId === rec.studentId);
    const applicant = applications.find(a => a.assignedStudentId === rec.studentId);
    const studentName = studentUser
      ? studentUser.name
      : applicant
      ? `${applicant.firstNames} ${applicant.surname}`
      : `Student (${rec.studentId})`;
    const course = courses.find(c => c.code === rec.courseCode);
    const courseName = course ? course.name : '';

    const matchesSearch = `${rec.studentId} ${studentName} ${rec.courseCode} ${courseName} ${rec.sessionName} ${rec.markedBy} ${rec.remarks || ''}`
      .toLowerCase()
      .includes(searchTerm.toLowerCase());

    const matchesCourse = attCourseFilter === 'all' ? true : rec.courseCode === attCourseFilter;
    const matchesStatus = attStatusFilter === 'all' ? true : rec.status === attStatusFilter;

    return matchesSearch && matchesCourse && matchesStatus;
  });

  const totalAbsences = attendance.filter(a => a.status === 'Absent').length;
  const totalPresent = attendance.filter(a => a.status === 'Present').length;
  const overallAttendanceRate = attendance.length > 0
    ? Math.round((totalPresent / attendance.length) * 100)
    : 100;

  return (
    <div className="space-y-6">
      
      {/* Welcome Banner */}
      <div className="bg-slate-900 text-white rounded-2xl p-6 shadow-md border border-slate-800 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="space-y-1">
          <div className="flex items-center gap-2">
            <span className="bg-amber-500 text-slate-950 font-mono text-[10px] font-bold px-2 py-0.5 rounded uppercase">
              Principal & Academic Registry
            </span>
            <span className="text-xs text-slate-400 font-medium">July – December 2026 Intake Portal</span>
          </div>
          <h1 className="text-xl sm:text-2xl font-bold tracking-tight text-white">
            College Administration & Bursar Control
          </h1>
          <p className="text-xs sm:text-sm text-slate-300">
            Verify official student applications, approve & commission lecturer accounts for examinations and class works, reconcile National Bank deposits, and manage examination clearance.
          </p>
        </div>

        <div className="flex flex-wrap items-center gap-2.5">
          <button
            onClick={() => setShowBulkExportModal(true)}
            className="px-4 py-2 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-bold rounded-lg transition shadow-sm flex items-center gap-2 active:scale-95"
            title="Export CSV data for offline audit & local filing"
          >
            <FileSpreadsheet className="w-4 h-4" />
            Bulk Data Export (CSV)
          </button>
          <button
            onClick={() => setShowNewTeacherModal(true)}
            className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-bold rounded-lg transition shadow-sm flex items-center gap-2 active:scale-95"
          >
            <UserCheck className="w-4 h-4" />
            Commission Lecturer
          </button>
          <button
            onClick={onOpenRegisterModal}
            className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white text-xs font-bold rounded-lg border border-slate-700 transition shadow-sm flex items-center gap-2 active:scale-95"
          >
            <Plus className="w-4 h-4 text-emerald-400" />
            New Application
          </button>
          <button
            onClick={onOpenCalendarSync}
            className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 text-xs font-semibold rounded-lg transition flex items-center gap-2"
          >
            <Calendar className="w-4 h-4 text-emerald-400" />
            Exam Timetable
          </button>
        </div>
      </div>

      {/* Export Success Banner */}
      {exportSuccessMessage && (
        <div className="bg-emerald-50 border border-emerald-300 text-emerald-950 px-4 py-3 rounded-xl flex items-center justify-between animate-in fade-in slide-in-from-top-2 shadow-xs">
          <div className="flex items-center gap-2.5">
            <CheckCheck className="w-5 h-5 text-emerald-600 shrink-0" />
            <span className="text-xs font-semibold">{exportSuccessMessage}</span>
          </div>
          <button
            onClick={() => setExportSuccessMessage(null)}
            className="text-emerald-800 hover:text-emerald-950 p-1 text-xs font-bold"
          >
            Dismiss
          </button>
        </div>
      )}

      {/* Metrics Row */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {/* Pending Teacher Approvals */}
        <div
          onClick={() => {
            setActiveTab('teachers');
            setTeacherStatusFilter('pending_approval');
          }}
          className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs space-y-1 cursor-pointer hover:border-indigo-400 transition"
        >
          <div className="flex items-center justify-between">
            <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider block">
              Lecturer Approvals
            </span>
            <Users className="w-4 h-4 text-indigo-600" />
          </div>
          <div className="flex items-baseline justify-between">
            <span className="text-2xl font-bold font-mono text-slate-900">{pendingTeachers.length}</span>
            <span className={`text-xs font-semibold px-2 py-0.5 rounded ${
              pendingTeachers.length > 0
                ? 'bg-amber-100 text-amber-800 animate-pulse'
                : 'bg-slate-100 text-slate-600'
            }`}>
              {pendingTeachers.length > 0 ? 'Action Required' : 'All Cleared'}
            </span>
          </div>
          <p className="text-[10px] text-slate-500">Awaiting exam & classwork permissions</p>
        </div>

        {/* Pending Student Applications */}
        <div
          onClick={() => setActiveTab('applications')}
          className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs space-y-1 cursor-pointer hover:border-emerald-400 transition"
        >
          <div className="flex items-center justify-between">
            <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider block">
              Pending Admissions
            </span>
            <FileCheck className="w-4 h-4 text-emerald-600" />
          </div>
          <div className="flex items-baseline justify-between">
            <span className="text-2xl font-bold font-mono text-slate-900">{pendingApps}</span>
            <span className="text-xs font-semibold text-amber-700 bg-amber-100 px-2 py-0.5 rounded">
              Forms Review
            </span>
          </div>
          <p className="text-[10px] text-slate-500">STC/APPLFORM/01/2025 forms</p>
        </div>

        {/* Attendance & Roll-Call Audits */}
        <div
          onClick={() => setActiveTab('attendance')}
          className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs space-y-1 cursor-pointer hover:border-blue-400 transition"
        >
          <div className="flex items-center justify-between">
            <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider block">
              Attendance Audit Logs
            </span>
            <Clock className="w-4 h-4 text-blue-600" />
          </div>
          <div className="flex items-baseline justify-between">
            <span className="text-2xl font-bold font-mono text-slate-900">{attendance.length}</span>
            <span className="text-xs font-semibold text-emerald-700 bg-emerald-100 px-2 py-0.5 rounded">
              {overallAttendanceRate}% Rate
            </span>
          </div>
          <p className="text-[10px] text-slate-500">{totalAbsences} unexcused absences flagged</p>
        </div>

        {/* Exam Commissioned Lecturers */}
        <div
          onClick={() => {
            setActiveTab('teachers');
            setTeacherStatusFilter('active');
          }}
          className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs space-y-1 cursor-pointer hover:border-purple-400 transition"
        >
          <div className="flex items-center justify-between">
            <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider block">
              Exam Commissioned
            </span>
            <Award className="w-4 h-4 text-purple-600" />
          </div>
          <div className="flex items-baseline justify-between">
            <span className="text-2xl font-bold font-mono text-purple-900">
              {examCommissionedTeachers.length} <span className="text-xs font-normal text-slate-500">/ {allTeachers.length}</span>
            </span>
            <span className="text-[10px] text-emerald-700 bg-emerald-100 px-2 py-0.5 rounded font-semibold">
              Authorized
            </span>
          </div>
          <p className="text-[10px] text-slate-500">Active lecturers with exam rights</p>
        </div>
      </div>

      {/* Main Tabs Container */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-xs overflow-hidden">
        <div className="flex border-b border-slate-200 bg-slate-50 px-6 pt-3 gap-3 sm:gap-4 overflow-x-auto">
          {/* Applications Tab */}
          <button
            onClick={() => setActiveTab('applications')}
            className={`pb-3 text-xs font-bold transition border-b-2 flex items-center gap-2 whitespace-nowrap ${
              activeTab === 'applications'
                ? 'border-emerald-600 text-emerald-800'
                : 'border-transparent text-slate-500 hover:text-slate-900'
            }`}
          >
            <FileCheck className="w-4 h-4" />
            Admissions & Forms ({applications.length})
          </button>

          {/* Attendance Audit Tab */}
          <button
            onClick={() => setActiveTab('attendance')}
            className={`pb-3 text-xs font-bold transition border-b-2 flex items-center gap-2 whitespace-nowrap ${
              activeTab === 'attendance'
                ? 'border-blue-600 text-blue-800'
                : 'border-transparent text-slate-500 hover:text-slate-900'
            }`}
          >
            <Clock className="w-4 h-4 text-blue-600" />
            Attendance & Roll-Call Logs ({attendance.length})
          </button>

          {/* Teacher Approvals Tab */}
          <button
            onClick={() => setActiveTab('teachers')}
            className={`pb-3 text-xs font-bold transition border-b-2 flex items-center gap-2 whitespace-nowrap relative ${
              activeTab === 'teachers'
                ? 'border-indigo-600 text-indigo-800'
                : 'border-transparent text-slate-500 hover:text-slate-900'
            }`}
          >
            <Users className="w-4 h-4 text-indigo-600" />
            <span>Lecturer Approvals & Exam Rights ({allTeachers.length})</span>
            {pendingTeachers.length > 0 && (
              <span className="px-1.5 py-0.5 rounded-full bg-amber-500 text-white font-mono text-[10px] font-bold">
                {pendingTeachers.length} Pending
              </span>
            )}
          </button>

          {/* Fees Tab */}
          <button
            onClick={() => setActiveTab('fees')}
            className={`pb-3 text-xs font-bold transition border-b-2 flex items-center gap-2 whitespace-nowrap ${
              activeTab === 'fees'
                ? 'border-emerald-600 text-emerald-800'
                : 'border-transparent text-slate-500 hover:text-slate-900'
            }`}
          >
            <CreditCard className="w-4 h-4" />
            National Bank Slip Verification ({fees.length})
          </button>

          {/* Clearance Tab */}
          <button
            onClick={() => setActiveTab('clearance')}
            className={`pb-3 text-xs font-bold transition border-b-2 flex items-center gap-2 whitespace-nowrap ${
              activeTab === 'clearance'
                ? 'border-emerald-600 text-emerald-800'
                : 'border-transparent text-slate-500 hover:text-slate-900'
            }`}
          >
            <ShieldCheck className="w-4 h-4" />
            Exam Results Access Control
          </button>
        </div>

        {/* Search & Sub-actions Bar */}
        <div className="p-4 bg-slate-50/50 border-b border-slate-200 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
          <div className="relative flex-1">
            <Search className="w-4 h-4 text-slate-400 absolute left-3 top-2.5" />
            <input
              type="text"
              placeholder={
                activeTab === 'teachers'
                  ? 'Search lecturers by name, email, department, qualification, course code...'
                  : activeTab === 'applications'
                  ? 'Search by student name, reference number, course code or ID...'
                  : activeTab === 'attendance'
                  ? 'Search attendance logs by student ID, name, course code, lecturer, session...'
                  : 'Search by student name, student ID, course name...'
              }
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
              className="w-full pl-9 pr-3 py-2 bg-white border border-slate-300 rounded-lg text-xs focus:ring-2 focus:ring-emerald-500 focus:outline-none"
            />
          </div>

          {activeTab === 'teachers' && (
            <div className="flex items-center gap-2">
              <select
                value={teacherStatusFilter}
                onChange={e => setTeacherStatusFilter(e.target.value as any)}
                className="text-xs bg-white border border-slate-300 rounded-lg px-2.5 py-2 font-medium text-slate-700 focus:outline-none focus:ring-2 focus:ring-indigo-500"
              >
                <option value="all">All Statuses ({allTeachers.length})</option>
                <option value="pending_approval">Pending Approval ({pendingTeachers.length})</option>
                <option value="active">Active & Commissioned ({activeTeachers.length})</option>
                <option value="suspended">Suspended</option>
              </select>

              {departmentsList.length > 0 && (
                <select
                  value={teacherDeptFilter}
                  onChange={e => setTeacherDeptFilter(e.target.value)}
                  className="text-xs bg-white border border-slate-300 rounded-lg px-2.5 py-2 font-medium text-slate-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 hidden md:block"
                >
                  <option value="all">All Departments</option>
                  {departmentsList.map(dept => (
                    <option key={dept} value={dept}>{dept}</option>
                  ))}
                </select>
              )}
            </div>
          )}

          {activeTab === 'attendance' && (
            <div className="flex items-center gap-2">
              <select
                value={attCourseFilter}
                onChange={e => setAttCourseFilter(e.target.value)}
                className="text-xs bg-white border border-slate-300 rounded-lg px-2.5 py-2 font-medium text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="all">All Courses</option>
                {courses.map(c => (
                  <option key={c.code} value={c.code}>{c.code} – {c.name.slice(0, 24)}...</option>
                ))}
              </select>

              <select
                value={attStatusFilter}
                onChange={e => setAttStatusFilter(e.target.value)}
                className="text-xs bg-white border border-slate-300 rounded-lg px-2.5 py-2 font-medium text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="all">All Statuses</option>
                <option value="Present">Present Only</option>
                <option value="Absent">Absent Only</option>
                <option value="Late">Late Only</option>
                <option value="Excused">Excused</option>
              </select>

              <button
                onClick={handleQuickExportAttendance}
                className="px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-xs font-bold flex items-center gap-1.5 shadow-xs shrink-0 transition"
              >
                <Download className="w-3.5 h-3.5" />
                Export CSV
              </button>
            </div>
          )}

          {activeTab === 'applications' && (
            <div className="flex items-center gap-2">
              <button
                onClick={handleQuickExportRegistrations}
                className="px-3 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-bold flex items-center gap-1.5 shadow-xs shrink-0 transition"
                title="Download all student registration records in CSV format"
              >
                <Download className="w-3.5 h-3.5" />
                Export Registrations (CSV)
              </button>
              <button
                onClick={() => setShowBulkExportModal(true)}
                className="px-3 py-2 bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 rounded-lg text-xs font-semibold flex items-center gap-1.5 shrink-0 transition"
              >
                <Filter className="w-3.5 h-3.5" />
                Filtered Export
              </button>
            </div>
          )}
        </div>

        {/* TAB 1: APPLICATIONS */}
        {activeTab === 'applications' && (
          <div className="p-4 overflow-x-auto space-y-4">
            <div className="bg-slate-50 border border-slate-200 rounded-xl p-3 flex flex-col sm:flex-row sm:items-center justify-between gap-3 text-xs">
              <div className="flex items-center gap-2">
                <span className="font-bold text-slate-800">
                  Student Registration Register ({applications.length} total)
                </span>
                <span className="text-slate-400">•</span>
                <span className="text-emerald-700 font-semibold">{approvedApps} Approved</span>
                <span className="text-slate-400">•</span>
                <span className="text-amber-700 font-semibold">{pendingApps} Awaiting Clearance</span>
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={handleQuickExportRegistrations}
                  className="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg font-bold flex items-center gap-1.5 shadow-2xs transition"
                >
                  <Download className="w-3.5 h-3.5" />
                  Download Admissions CSV
                </button>
              </div>
            </div>

            <table className="w-full text-left text-xs">
              <thead>
                <tr className="bg-slate-100 text-slate-700 font-semibold border-b border-slate-200">
                  <th className="p-3">Ref & Date</th>
                  <th className="p-3">Applicant Name</th>
                  <th className="p-3">Course (1st Choice)</th>
                  <th className="p-3">Guardian Info</th>
                  <th className="p-3">Bank Ref (MK10,000)</th>
                  <th className="p-3">Status</th>
                  <th className="p-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-200">
                {filteredApps.map(app => {
                  const course = courses.find(c => c.code === app.firstChoiceCourseCode);
                  return (
                    <tr key={app.id} className="hover:bg-slate-50">
                      <td className="p-3">
                        <span className="font-mono font-bold text-slate-900 block">{app.refNumber}</span>
                        <span className="text-[10px] text-slate-500">{app.applicationDate}</span>
                      </td>
                      <td className="p-3 font-semibold text-slate-900">
                        {app.firstNames} {app.surname}
                        <span className="text-[10px] text-slate-500 block font-normal">{app.ownPhone}</span>
                      </td>
                      <td className="p-3">
                        <span className="font-medium text-slate-800 block">
                          {course ? course.name : app.firstChoiceCourseCode}
                        </span>
                        <span className="text-[10px] text-slate-500 font-mono">
                          {app.firstChoiceCourseCode} • {app.entryLevel}
                        </span>
                      </td>
                      <td className="p-3">
                        <span className="text-slate-800 font-medium block">{app.guardianName}</span>
                        <span className="text-[10px] text-slate-500 block">{app.guardianPhone}</span>
                      </td>
                      <td className="p-3 font-mono font-semibold text-emerald-800">
                        {app.depositSlipRef || 'NBM-DEP-002'}
                        <span className="text-[10px] text-slate-500 block font-sans">Customs Rd</span>
                      </td>
                      <td className="p-3">
                        <span
                          className={`px-2 py-0.5 rounded font-semibold text-[11px] ${
                            app.status === 'Approved'
                              ? 'bg-emerald-100 text-emerald-800 border border-emerald-300'
                              : app.status === 'Rejected'
                              ? 'bg-rose-100 text-rose-800 border border-rose-300'
                              : 'bg-amber-100 text-amber-800 border border-amber-300'
                          }`}
                        >
                          {app.status}
                        </span>
                      </td>
                      <td className="p-3 text-right">
                        {app.status === 'Pending Verification' ? (
                          <div className="flex items-center justify-end gap-1.5">
                            <button
                              onClick={() => approveApplication(app.id)}
                              className="px-2.5 py-1 bg-emerald-600 hover:bg-emerald-700 text-white rounded text-xs font-semibold flex items-center gap-1 shadow-xs"
                            >
                              <CheckCircle2 className="w-3.5 h-3.5" />
                              Approve
                            </button>
                            <button
                              onClick={() => rejectApplication(app.id, 'Did not meet MSCE requirement')}
                              className="px-2.5 py-1 bg-rose-600 hover:bg-rose-700 text-white rounded text-xs font-semibold flex items-center gap-1 shadow-xs"
                            >
                              <XCircle className="w-3.5 h-3.5" />
                              Reject
                            </button>
                          </div>
                        ) : (
                          <span className="text-xs text-slate-500 font-mono">
                            {app.assignedStudentId || 'Processed'}
                          </span>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        {/* TAB 2: ATTENDANCE & ROLL-CALL AUDIT LOGS */}
        {activeTab === 'attendance' && (
          <div className="p-6 space-y-5">
            {/* Tab Header Banner */}
            <div className="bg-blue-50/70 border border-blue-200 rounded-xl p-4 flex flex-col md:flex-row md:items-center justify-between gap-4">
              <div className="flex items-start gap-3">
                <div className="w-9 h-9 rounded-lg bg-blue-600 flex items-center justify-center text-white shrink-0 mt-0.5">
                  <Clock className="w-5 h-5" />
                </div>
                <div>
                  <h3 className="text-sm font-bold text-blue-950">
                    Institutional Attendance Register & Roll-Call Audit System
                  </h3>
                  <p className="text-xs text-blue-900/80 mt-0.5">
                    Continuous monitoring of student lecture attendance, tardiness logs, and automatic parent SMS/push notification dispatch in accordance with TEVETA Malawi 75% exam sitting threshold regulations.
                  </p>
                </div>
              </div>

              <div className="flex items-center gap-2 self-start md:self-auto shrink-0">
                <button
                  onClick={handleQuickExportAttendance}
                  className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold rounded-lg transition shadow-xs flex items-center gap-1.5"
                  title="Download all attendance records in CSV format"
                >
                  <Download className="w-4 h-4" />
                  Export Attendance CSV
                </button>
                <button
                  onClick={() => setShowBulkExportModal(true)}
                  className="px-3.5 py-2 bg-white hover:bg-slate-50 text-slate-700 border border-slate-300 text-xs font-semibold rounded-lg transition flex items-center gap-1.5"
                >
                  <Filter className="w-4 h-4 text-slate-500" />
                  Custom Filter Export
                </button>
              </div>
            </div>

            {/* Attendance Statistics Cards */}
            <div className="grid grid-cols-1 sm:grid-cols-4 gap-3">
              <div className="bg-slate-50 border border-slate-200 p-3 rounded-xl">
                <span className="text-[10px] uppercase font-bold text-slate-500 block">Total Logged Sessions</span>
                <span className="text-lg font-bold font-mono text-slate-900">{attendance.length}</span>
              </div>
              <div className="bg-emerald-50 border border-emerald-200 p-3 rounded-xl">
                <span className="text-[10px] uppercase font-bold text-emerald-700 block">Present Marks</span>
                <span className="text-lg font-bold font-mono text-emerald-800">{totalPresent} ({overallAttendanceRate}%)</span>
              </div>
              <div className="bg-rose-50 border border-rose-200 p-3 rounded-xl">
                <span className="text-[10px] uppercase font-bold text-rose-700 block">Unexcused Absences</span>
                <span className="text-lg font-bold font-mono text-rose-800">{totalAbsences}</span>
              </div>
              <div className="bg-purple-50 border border-purple-200 p-3 rounded-xl">
                <span className="text-[10px] uppercase font-bold text-purple-700 block">Parent Alerts Dispatched</span>
                <span className="text-lg font-bold font-mono text-purple-800">
                  {attendance.filter(a => a.alertSentToParent).length} Alerts
                </span>
              </div>
            </div>

            {/* Attendance Table */}
            <div className="border border-slate-200 rounded-xl overflow-hidden shadow-2xs">
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs">
                  <thead>
                    <tr className="bg-slate-100 text-slate-700 font-semibold border-b border-slate-200">
                      <th className="p-3">Date & Session</th>
                      <th className="p-3">Student Name & ID</th>
                      <th className="p-3">Course / Module</th>
                      <th className="p-3">Status</th>
                      <th className="p-3">Marked By (Lecturer)</th>
                      <th className="p-3">Notes & Parent Alert</th>
                      <th className="p-3 text-right">Academic Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-200">
                    {filteredAttendance.length > 0 ? (
                      filteredAttendance.map(record => {
                        const studentUser = allUsers.find(u => u.studentId === record.studentId);
                        const applicant = applications.find(a => a.assignedStudentId === record.studentId);
                        const studentName = studentUser
                          ? studentUser.name
                          : applicant
                          ? `${applicant.firstNames} ${applicant.surname}`
                          : `Student (${record.studentId})`;
                        const course = courses.find(c => c.code === record.courseCode);

                        return (
                          <tr key={record.id} className="hover:bg-slate-50">
                            <td className="p-3">
                              <span className="font-mono font-bold text-slate-900 block">{record.date}</span>
                              <span className="text-[10px] text-slate-500">{record.sessionName}</span>
                            </td>
                            <td className="p-3">
                              <span className="font-semibold text-slate-900 block">{studentName}</span>
                              <span className="font-mono text-[10px] text-slate-500">{record.studentId}</span>
                            </td>
                            <td className="p-3">
                              <span className="font-medium text-slate-800 block">
                                {course ? course.name : record.courseCode}
                              </span>
                              <span className="font-mono text-[10px] text-slate-500">
                                {record.courseCode} • {course ? course.examBoard : 'TEVETA'}
                              </span>
                            </td>
                            <td className="p-3">
                              <span
                                className={`px-2 py-0.5 rounded font-bold text-[10px] inline-flex items-center gap-1 ${
                                  record.status === 'Present'
                                    ? 'bg-emerald-100 text-emerald-800 border border-emerald-300'
                                    : record.status === 'Absent'
                                    ? 'bg-rose-100 text-rose-800 border border-rose-300'
                                    : record.status === 'Late'
                                    ? 'bg-amber-100 text-amber-800 border border-amber-300'
                                    : 'bg-blue-100 text-blue-800 border border-blue-300'
                                }`}
                              >
                                {record.status === 'Present' && <Check className="w-3 h-3 text-emerald-600" />}
                                {record.status === 'Absent' && <AlertTriangle className="w-3 h-3 text-rose-600" />}
                                {record.status === 'Late' && <Clock className="w-3 h-3 text-amber-600" />}
                                {record.status}
                              </span>
                            </td>
                            <td className="p-3">
                              <span className="text-slate-800 font-medium block">{record.markedBy}</span>
                              <span className="text-[10px] text-slate-500 font-mono">Registry Verified</span>
                            </td>
                            <td className="p-3">
                              <span className="text-slate-700 block text-[11px]">
                                {record.remarks || (record.status === 'Present' ? 'Full Session Attended' : 'Pending verification')}
                              </span>
                              {record.alertSentToParent && (
                                <span className="inline-flex items-center gap-1 text-[9px] font-bold text-purple-700 bg-purple-100 px-1.5 py-0.2 rounded mt-0.5 border border-purple-200">
                                  <CheckCheck className="w-2.5 h-2.5" /> SMS & App Alert Sent
                                </span>
                              )}
                            </td>
                            <td className="p-3 text-right">
                              <button
                                onClick={() => onOpenReportCard(record.studentId)}
                                className="px-2.5 py-1 bg-slate-800 hover:bg-slate-700 text-white rounded text-xs font-semibold transition"
                              >
                                Report Card
                              </button>
                            </td>
                          </tr>
                        );
                      })
                    ) : (
                      <tr>
                        <td colSpan={7} className="p-8 text-center text-slate-500 text-xs">
                          No attendance records matched your filter and search criteria.
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* TAB 2: TEACHER / LECTURER APPROVALS & EXAM/CLASSWORK AUTHORIZATION */}
        {activeTab === 'teachers' && (
          <div className="p-6 space-y-6">
            
            {/* Header info note on institutional authority */}
            <div className="bg-indigo-50/70 border border-indigo-200 rounded-xl p-4 flex flex-col md:flex-row md:items-center justify-between gap-4">
              <div className="flex items-start gap-3">
                <div className="w-9 h-9 rounded-lg bg-indigo-600 flex items-center justify-center text-white shrink-0 mt-0.5">
                  <ShieldCheck className="w-5 h-5" />
                </div>
                <div>
                  <h3 className="text-sm font-bold text-indigo-950">
                    Principal & Academic Registry Faculty Commissioning Authority
                  </h3>
                  <p className="text-xs text-indigo-900/80 mt-0.5">
                    As Principal and Registrar of Soche Technical College, you have sole authority to review instructor credentials, grant <strong>Examination Preparation</strong> privileges (final exams, midterms, scoring & grading moderation), and authorize <strong>Class Work & Coursework</strong> publishing across ABMA, City & Guilds, ICAM, and NCIC departments.
                  </p>
                </div>
              </div>

              <button
                onClick={() => setShowNewTeacherModal(true)}
                className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold rounded-lg transition shadow-sm flex items-center gap-1.5 whitespace-nowrap self-start md:self-auto shrink-0"
              >
                <Plus className="w-4 h-4" />
                Register New Lecturer
              </button>
            </div>

            {/* PENDING APPROVALS QUEUE (If any) */}
            {pendingTeachers.length > 0 && (
              <div className="border-2 border-amber-300 bg-amber-50/40 rounded-xl p-4 space-y-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <span className="inline-block w-2.5 h-2.5 rounded-full bg-amber-500 animate-ping"></span>
                    <h3 className="text-sm font-bold text-amber-950 flex items-center gap-2">
                      <Clock className="w-4 h-4 text-amber-600" />
                      Pending Lecturer Commissioning Queue ({pendingTeachers.length})
                    </h3>
                  </div>
                  <span className="text-xs font-medium text-amber-800">
                    Awaiting Academic Board Clearance
                  </span>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {pendingTeachers.map(teacher => (
                    <div
                      key={teacher.id}
                      className="bg-white p-4 rounded-xl border border-amber-200 shadow-xs flex flex-col justify-between space-y-3"
                    >
                      <div className="space-y-2">
                        <div className="flex items-start justify-between gap-3">
                          <div className="flex items-center gap-3">
                            <img
                              src={teacher.avatarUrl || 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=150&auto=format&fit=crop&q=80'}
                              alt={teacher.name}
                              className="w-11 h-11 rounded-full object-cover border-2 border-amber-300"
                            />
                            <div>
                              <h4 className="text-sm font-bold text-slate-900">{teacher.name}</h4>
                              <p className="text-xs text-indigo-700 font-medium">{teacher.title || 'Lecturer Applicant'}</p>
                              <p className="text-[11px] text-slate-500 font-mono">{teacher.email} • {teacher.phone || '+265 88X XXX XXX'}</p>
                            </div>
                          </div>
                          <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-amber-100 text-amber-800 border border-amber-300 shrink-0">
                            Pending Review
                          </span>
                        </div>

                        {/* Qualifications & Department */}
                        <div className="bg-slate-50 p-2.5 rounded-lg border border-slate-200 text-xs space-y-1">
                          <div className="flex items-start gap-1.5">
                            <Award className="w-3.5 h-3.5 text-amber-600 shrink-0 mt-0.5" />
                            <span className="text-slate-700">
                              <strong>Qualification:</strong> {teacher.qualification || 'BSc / Master Degree (Malawi / UK)'}
                            </span>
                          </div>
                          <div className="flex items-center gap-1.5 text-slate-600">
                            <Building className="w-3.5 h-3.5 text-slate-500 shrink-0" />
                            <span><strong>Dept:</strong> {teacher.department || 'Management & Hospitality'}</span>
                            <span className="text-slate-300">|</span>
                            <span>{teacher.employmentType || 'Visiting Lecturer'}</span>
                          </div>
                          {teacher.assignedCourses && teacher.assignedCourses.length > 0 && (
                            <div className="flex items-center gap-1 text-[11px] text-slate-600">
                              <BookOpen className="w-3.5 h-3.5 text-slate-500 shrink-0" />
                              <span><strong>Requested Courses:</strong></span>
                              <div className="flex flex-wrap gap-1">
                                {teacher.assignedCourses.map(c => (
                                  <span key={c} className="font-mono px-1.5 py-0.2 bg-white border border-slate-300 rounded text-[10px]">
                                    {c}
                                  </span>
                                ))}
                              </div>
                            </div>
                          )}
                        </div>
                      </div>

                      {/* Action buttons */}
                      <div className="flex items-center justify-between pt-2 border-t border-slate-100">
                        <span className="text-[10px] text-slate-400">
                          Registered: {teacher.registrationDate || '2026-07-01'}
                        </span>
                        <div className="flex items-center gap-2">
                          <button
                            onClick={() => {
                              setRejectionModalUser(teacher);
                              setRejectionReasonInput('');
                            }}
                            className="px-3 py-1.5 bg-rose-50 hover:bg-rose-100 text-rose-700 border border-rose-200 rounded-lg text-xs font-semibold transition"
                          >
                            Decline
                          </button>
                          <button
                            onClick={() => openApprovalModal(teacher)}
                            className="px-3.5 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-bold transition shadow-xs flex items-center gap-1.5 active:scale-95"
                          >
                            <ShieldCheck className="w-3.5 h-3.5" />
                            Review & Approve
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* FULL FACULTY DIRECTORY & PERMISSION CONTROLS */}
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-sm font-bold text-slate-900">
                    Teaching Staff & Examination Commission Registry
                  </h3>
                  <p className="text-xs text-slate-500">
                    Manage lecturer accreditation, assign examination rights, and control class work creation permissions.
                  </p>
                </div>
                <span className="text-xs text-slate-500 font-mono">
                  Showing {filteredTeachers.length} of {allTeachers.length} instructors
                </span>
              </div>

              {filteredTeachers.length === 0 ? (
                <div className="text-center py-10 bg-slate-50 rounded-xl border border-dashed border-slate-300 text-slate-500 text-xs">
                  No instructors found matching the filter or search criteria.
                </div>
              ) : (
                <div className="overflow-x-auto border border-slate-200 rounded-xl">
                  <table className="w-full text-left text-xs">
                    <thead>
                      <tr className="bg-slate-100 text-slate-700 font-semibold border-b border-slate-200">
                        <th className="p-3">Lecturer Profile</th>
                        <th className="p-3">Department & Title</th>
                        <th className="p-3">Assigned Courses</th>
                        <th className="p-3">Examination Preparation</th>
                        <th className="p-3">Class Works / Tasks</th>
                        <th className="p-3">Grading & Syllabus</th>
                        <th className="p-3">Status</th>
                        <th className="p-3 text-right">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-200">
                      {filteredTeachers.map(teacher => {
                        const isApproved = teacher.status === 'active';
                        const isPending = teacher.status === 'pending_approval';
                        const isSuspended = teacher.status === 'suspended';

                        return (
                          <tr key={teacher.id} className="hover:bg-slate-50">
                            {/* Lecturer Name & Avatar */}
                            <td className="p-3">
                              <div className="flex items-center gap-2.5">
                                <img
                                  src={teacher.avatarUrl || 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=100&auto=format&fit=crop&q=80'}
                                  alt={teacher.name}
                                  className="w-9 h-9 rounded-full object-cover border border-slate-200 shrink-0"
                                />
                                <div>
                                  <span className="font-bold text-slate-900 block">{teacher.name}</span>
                                  <span className="text-[10px] text-slate-500 font-mono block">{teacher.email}</span>
                                  {teacher.qualification && (
                                    <span className="text-[10px] text-indigo-700 truncate max-w-[160px] block" title={teacher.qualification}>
                                      {teacher.qualification}
                                    </span>
                                  )}
                                </div>
                              </div>
                            </td>

                            {/* Department & Title */}
                            <td className="p-3">
                              <span className="font-medium text-slate-800 block">{teacher.department || 'Academic Faculty'}</span>
                              <span className="text-[10px] text-slate-500 block">{teacher.title || 'Lecturer'}</span>
                              <span className="text-[10px] text-indigo-600 bg-indigo-50 px-1.5 py-0.2 rounded font-mono inline-block mt-0.5">
                                {teacher.employmentType || 'Full-Time'}
                              </span>
                            </td>

                            {/* Assigned Courses */}
                            <td className="p-3">
                              {teacher.assignedCourses && teacher.assignedCourses.length > 0 ? (
                                <div className="flex flex-wrap gap-1 max-w-[180px]">
                                  {teacher.assignedCourses.map(code => (
                                    <span
                                      key={code}
                                      className="font-mono text-[10px] font-semibold bg-slate-100 border border-slate-300 text-slate-800 px-1.5 py-0.5 rounded"
                                    >
                                      {code}
                                    </span>
                                  ))}
                                </div>
                              ) : (
                                <span className="text-slate-400 italic">None assigned</span>
                              )}
                            </td>

                            {/* Examination Preparation Authorization */}
                            <td className="p-3">
                              {teacher.canPrepareExams && isApproved ? (
                                <span className="inline-flex items-center gap-1 text-[11px] font-bold text-emerald-800 bg-emerald-100 border border-emerald-300 px-2 py-0.5 rounded-md">
                                  <Check className="w-3 h-3 text-emerald-700" />
                                  Authorized
                                </span>
                              ) : (
                                <span className="inline-flex items-center gap-1 text-[11px] font-semibold text-slate-600 bg-slate-100 border border-slate-300 px-2 py-0.5 rounded-md">
                                  <Lock className="w-3 h-3 text-slate-500" />
                                  Restricted
                                </span>
                              )}
                            </td>

                            {/* Class Work Creation Authorization */}
                            <td className="p-3">
                              {teacher.canCreateClasswork && isApproved ? (
                                <span className="inline-flex items-center gap-1 text-[11px] font-bold text-emerald-800 bg-emerald-100 border border-emerald-300 px-2 py-0.5 rounded-md">
                                  <Check className="w-3 h-3 text-emerald-700" />
                                  Authorized
                                </span>
                              ) : (
                                <span className="inline-flex items-center gap-1 text-[11px] font-semibold text-slate-600 bg-slate-100 border border-slate-300 px-2 py-0.5 rounded-md">
                                  <Lock className="w-3 h-3 text-slate-500" />
                                  Restricted
                                </span>
                              )}
                            </td>

                            {/* Grading & Syllabus */}
                            <td className="p-3">
                              <div className="space-y-0.5 text-[11px]">
                                <div className="flex items-center gap-1">
                                  <span className={teacher.canEnterGrades && isApproved ? 'text-emerald-700 font-semibold' : 'text-slate-400'}>
                                    • Grading: {teacher.canEnterGrades && isApproved ? 'Active' : 'Off'}
                                  </span>
                                </div>
                                <div className="flex items-center gap-1">
                                  <span className={teacher.canUploadMaterials && isApproved ? 'text-blue-700 font-semibold' : 'text-slate-400'}>
                                    • Materials: {teacher.canUploadMaterials && isApproved ? 'Active' : 'Off'}
                                  </span>
                                </div>
                              </div>
                            </td>

                            {/* Status */}
                            <td className="p-3">
                              <span
                                className={`px-2 py-0.5 rounded font-semibold text-[11px] inline-block ${
                                  isApproved
                                    ? 'bg-emerald-100 text-emerald-800 border border-emerald-300'
                                    : isPending
                                    ? 'bg-amber-100 text-amber-800 border border-amber-300 animate-pulse'
                                    : 'bg-rose-100 text-rose-800 border border-rose-300'
                                }`}
                              >
                                {isApproved ? 'Active & Approved' : isPending ? 'Pending Approval' : isSuspended ? 'Suspended' : 'Rejected'}
                              </span>
                            </td>

                            {/* Actions */}
                            <td className="p-3 text-right">
                              <div className="flex items-center justify-end gap-1.5">
                                {isPending ? (
                                  <button
                                    onClick={() => openApprovalModal(teacher)}
                                    className="px-2.5 py-1 bg-emerald-600 hover:bg-emerald-700 text-white rounded text-xs font-bold shadow-xs flex items-center gap-1"
                                  >
                                    <CheckCircle2 className="w-3.5 h-3.5" />
                                    Approve
                                  </button>
                                ) : (
                                  <>
                                    <button
                                      onClick={() => openEditPermissionsModal(teacher)}
                                      title="Edit exam & classwork permissions"
                                      className="px-2.5 py-1 bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-300 rounded text-xs font-semibold flex items-center gap-1"
                                    >
                                      <SlidersHorizontal className="w-3.5 h-3.5 text-indigo-600" />
                                      Permissions
                                    </button>

                                    {isApproved ? (
                                      <button
                                        onClick={() => suspendTeacherAccount(teacher.id, 'Account access suspended for administrative audit.')}
                                        title="Temporarily suspend access"
                                        className="p-1 text-slate-400 hover:text-rose-600 rounded"
                                      >
                                        <UserX className="w-3.5 h-3.5" />
                                      </button>
                                    ) : isSuspended ? (
                                      <button
                                        onClick={() => reactivateTeacherAccount(teacher.id)}
                                        title="Reactivate instructor"
                                        className="px-2 py-1 bg-emerald-100 text-emerald-800 border border-emerald-300 rounded text-xs font-semibold"
                                      >
                                        Reactivate
                                      </button>
                                    ) : null}

                                    <button
                                      onClick={() => switchRole('teacher', teacher.id)}
                                      title="Test viewing portal as this instructor"
                                      className="p-1 text-slate-400 hover:text-emerald-600 rounded"
                                    >
                                      <ExternalLink className="w-3.5 h-3.5" />
                                    </button>
                                  </>
                                )}
                              </div>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </div>

          </div>
        )}

        {/* TAB 3: NATIONAL BANK SLIPS */}
        {activeTab === 'fees' && (
          <div className="p-4 overflow-x-auto">
            <div className="mb-4 bg-emerald-50 border border-emerald-300 p-3 rounded-lg flex items-center justify-between text-xs text-emerald-950">
              <div>
                <strong>National Bank of Malawi Reconciled Account:</strong> 1003452219 (Customs Road Service Centre)
              </div>
              <span className="font-mono font-bold text-emerald-800">Branch Code: LIMBE-CR</span>
            </div>

            <table className="w-full text-left text-xs">
              <thead>
                <tr className="bg-slate-100 text-slate-700 font-semibold border-b border-slate-200">
                  <th className="p-3">Student & Course</th>
                  <th className="p-3">Total Due</th>
                  <th className="p-3">Total Paid</th>
                  <th className="p-3">Balance</th>
                  <th className="p-3">Deposit Slips (NBM)</th>
                  <th className="p-3">Clearance Status</th>
                  <th className="p-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-200">
                {filteredFees.map(fee => (
                  <tr key={fee.id} className="hover:bg-slate-50">
                    <td className="p-3">
                      <span className="font-semibold text-slate-900 block">{fee.studentName}</span>
                      <span className="font-mono text-[10px] text-slate-500">{fee.studentId} • {fee.courseName}</span>
                    </td>
                    <td className="p-3 font-mono">MK {fee.totalAmountDue.toLocaleString()}</td>
                    <td className="p-3 font-mono text-emerald-700 font-semibold">MK {fee.totalPaid.toLocaleString()}</td>
                    <td className="p-3 font-mono font-bold">
                      <span className={fee.balanceDue > 0 ? 'text-rose-600' : 'text-emerald-700'}>
                        MK {fee.balanceDue.toLocaleString()}
                      </span>
                    </td>
                    <td className="p-3">
                      <div className="space-y-1">
                        {fee.bankDepositSlips.map(slip => (
                          <div key={slip.id} className="flex items-center gap-1.5 text-[10px]">
                            <span className="font-mono font-semibold text-slate-800">{slip.bankRefNumber}</span>
                            <span className="text-slate-500">(MK {slip.amount.toLocaleString()})</span>
                            <span
                              className={`px-1 rounded text-[9px] font-bold ${
                                slip.status === 'Verified'
                                  ? 'bg-emerald-100 text-emerald-800'
                                  : slip.status === 'Rejected'
                                  ? 'bg-rose-100 text-rose-800'
                                  : 'bg-amber-100 text-amber-800'
                              }`}
                            >
                              {slip.status}
                            </span>
                            {slip.status === 'Pending Review' && (
                              <div className="flex gap-1 ml-1">
                                <button
                                  onClick={() => verifyBankDepositSlip(fee.id, slip.id, true)}
                                  className="px-1.5 py-0.5 bg-emerald-600 text-white rounded text-[9px] font-bold"
                                >
                                  Verify
                                </button>
                                <button
                                  onClick={() => verifyBankDepositSlip(fee.id, slip.id, false, 'Invalid transaction reference')}
                                  className="px-1.5 py-0.5 bg-rose-600 text-white rounded text-[9px] font-bold"
                                >
                                  Reject
                                </button>
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                    </td>
                    <td className="p-3">
                      <span
                        className={`px-2 py-0.5 rounded font-semibold text-[11px] ${
                          fee.status === 'Fully Cleared'
                            ? 'bg-emerald-100 text-emerald-800 border border-emerald-300'
                            : fee.status === 'Partial (70% Paid)'
                            ? 'bg-blue-100 text-blue-800 border border-blue-300'
                            : 'bg-amber-100 text-amber-800 border border-amber-300'
                        }`}
                      >
                        {fee.status}
                      </span>
                    </td>
                    <td className="p-3 text-right">
                      <button
                        onClick={() => onOpenReportCard(fee.studentId)}
                        className="px-2.5 py-1 bg-slate-800 hover:bg-slate-700 text-white rounded text-xs font-semibold"
                      >
                        Report Card
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* TAB 4: CLEARANCE & EXAM RESULTS ACCESS CONTROL */}
        {activeTab === 'clearance' && (
          <div className="p-6 space-y-4">
            <div className="bg-amber-50 border border-amber-300 rounded-xl p-4 text-xs text-amber-950 space-y-1">
              <div className="flex items-center gap-2 font-bold text-sm text-amber-900">
                <ShieldCheck className="w-5 h-5 text-amber-600" />
                Institutional Fee Clearance Policy for Examination Results
              </div>
              <p>
                As configured by college policy, students and parents can <strong>only view official semester examination marks and transcripts</strong> if their fee balance is completely cleared (MK 0.00).
              </p>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {fees.map(f => {
                const isLocked = f.balanceDue > 0;
                return (
                  <div
                    key={f.id}
                    className={`p-4 rounded-xl border flex flex-col justify-between space-y-3 ${
                      isLocked
                        ? 'bg-amber-50/60 border-amber-300'
                        : 'bg-emerald-50/60 border-emerald-300'
                    }`}
                  >
                    <div>
                      <div className="flex items-center justify-between">
                        <span className="font-bold text-slate-900 text-sm">{f.studentName}</span>
                        <span className={`px-2 py-0.5 rounded text-xs font-bold flex items-center gap-1 ${
                          isLocked
                            ? 'bg-rose-100 text-rose-800 border border-rose-300'
                            : 'bg-emerald-100 text-emerald-800 border border-emerald-300'
                        }`}>
                          {isLocked ? <Lock className="w-3 h-3" /> : <Unlock className="w-3 h-3" />}
                          {isLocked ? 'Results Restricted' : 'Results Unlocked'}
                        </span>
                      </div>
                      <p className="text-xs text-slate-600 font-mono mt-0.5">{f.studentId} • {f.courseName}</p>
                    </div>

                    <div className="bg-white p-3 rounded-lg border border-slate-200 text-xs space-y-1">
                      <div className="flex justify-between">
                        <span className="text-slate-500">Total Billed:</span>
                        <span className="font-mono font-semibold">MK {f.totalAmountDue.toLocaleString()}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-slate-500">Total Paid:</span>
                        <span className="font-mono text-emerald-700 font-semibold">MK {f.totalPaid.toLocaleString()}</span>
                      </div>
                      <div className="flex justify-between border-t border-slate-100 pt-1 font-bold">
                        <span className="text-slate-700">Balance:</span>
                        <span className={`font-mono ${isLocked ? 'text-rose-600' : 'text-slate-900'}`}>
                          MK {f.balanceDue.toLocaleString()}
                        </span>
                      </div>
                    </div>

                    <div className="flex justify-end gap-2">
                      <button
                        onClick={() => setViewingIdCardFee(f)}
                        className="px-3 py-1.5 bg-white hover:bg-slate-100 border border-slate-300 text-slate-800 rounded text-xs font-semibold flex items-center gap-1 shadow-xs"
                      >
                        <QrCode className="w-3.5 h-3.5 text-emerald-600" />
                        Digital ID
                      </button>
                      <button
                        onClick={() => onOpenReportCard(f.studentId)}
                        className="px-3 py-1.5 bg-slate-900 hover:bg-slate-800 text-white rounded text-xs font-semibold flex items-center gap-1"
                      >
                        <FileText className="w-3.5 h-3.5" />
                        Preview Transcript
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>

      {/* MODAL 1: REVIEW & APPROVE PENDING LECTURER */}
      {selectedTeacherForApproval && (
        <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto">
          <div className="bg-white rounded-2xl shadow-2xl max-w-xl w-full overflow-hidden border border-slate-200 animate-in fade-in zoom-in-95">
            {/* Modal Header */}
            <div className="bg-slate-900 text-white px-6 py-4 flex items-center justify-between border-b border-slate-800">
              <div className="flex items-center gap-2.5">
                <div className="w-9 h-9 rounded-lg bg-emerald-600 flex items-center justify-center text-white">
                  <ShieldCheck className="w-5 h-5" />
                </div>
                <div>
                  <h3 className="text-sm font-bold text-white">
                    Commission Lecturer & Approve Teaching Account
                  </h3>
                  <p className="text-[10px] text-emerald-400 font-mono">
                    Academic Board & Examination Authorization
                  </p>
                </div>
              </div>
              <button
                onClick={() => setSelectedTeacherForApproval(null)}
                className="p-1.5 text-slate-400 hover:text-white rounded-lg transition"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Modal Form */}
            <form onSubmit={handleConfirmApproval} className="p-6 space-y-4 text-xs">
              {/* Applicant Snapshot */}
              <div className="bg-slate-50 p-3.5 rounded-xl border border-slate-200 flex items-center gap-3">
                <img
                  src={selectedTeacherForApproval.avatarUrl || 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=150&auto=format&fit=crop&q=80'}
                  alt={selectedTeacherForApproval.name}
                  className="w-12 h-12 rounded-full object-cover border-2 border-emerald-400"
                />
                <div>
                  <h4 className="text-sm font-bold text-slate-900">{selectedTeacherForApproval.name}</h4>
                  <p className="text-xs text-indigo-700 font-medium">{selectedTeacherForApproval.title}</p>
                  <p className="text-[11px] text-slate-500 font-mono">{selectedTeacherForApproval.email}</p>
                  <p className="text-[11px] text-slate-600 mt-0.5">
                    <strong>Credentials:</strong> {selectedTeacherForApproval.qualification || 'Master Degree / Certified Assessor'}
                  </p>
                </div>
              </div>

              {/* Department & Role Details */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block font-semibold text-slate-700 mb-1">
                    ACADEMIC DEPARTMENT
                  </label>
                  <input
                    type="text"
                    required
                    value={approvalPermissions.department}
                    onChange={e => setApprovalPermissions({ ...approvalPermissions, department: e.target.value })}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 font-medium focus:bg-white focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block font-semibold text-slate-700 mb-1">
                    EMPLOYMENT STATUS
                  </label>
                  <select
                    value={approvalPermissions.employmentType}
                    onChange={e => setApprovalPermissions({ ...approvalPermissions, employmentType: e.target.value as any })}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 font-medium focus:bg-white focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                  >
                    <option value="Full-Time Lecturer">Full-Time Lecturer</option>
                    <option value="Visiting Lecturer">Visiting Lecturer</option>
                    <option value="Part-Time Instructor">Part-Time Instructor</option>
                    <option value="Department Head">Department Head</option>
                  </select>
                </div>
              </div>

              {/* PERMISSION CHECKBOXES - CRITICAL WORKFLOW */}
              <div className="space-y-2 pt-2 border-t border-slate-200">
                <label className="block font-bold text-slate-900 uppercase tracking-wider text-[11px]">
                  Institutional Authorizations & Rights:
                </label>

                {/* 1. Examination Preparation */}
                <label className="flex items-start gap-3 p-3 rounded-lg border border-slate-200 hover:bg-slate-50 cursor-pointer bg-white">
                  <input
                    type="checkbox"
                    checked={approvalPermissions.canPrepareExams}
                    onChange={e => setApprovalPermissions({ ...approvalPermissions, canPrepareExams: e.target.checked })}
                    className="w-4 h-4 rounded text-emerald-600 mt-0.5 focus:ring-emerald-500"
                  />
                  <div>
                    <span className="font-bold text-slate-900 block flex items-center gap-1.5">
                      <Award className="w-3.5 h-3.5 text-amber-600" />
                      Authorize Examination Preparation (Midterm, Final & Past Papers)
                    </span>
                    <span className="text-[11px] text-slate-500 block">
                      Grants permission to draft exam questions, set marking schemes, record official exam scores, and submit final grades to the Academic Board.
                    </span>
                  </div>
                </label>

                {/* 2. Class Work Creation */}
                <label className="flex items-start gap-3 p-3 rounded-lg border border-slate-200 hover:bg-slate-50 cursor-pointer bg-white">
                  <input
                    type="checkbox"
                    checked={approvalPermissions.canCreateClasswork}
                    onChange={e => setApprovalPermissions({ ...approvalPermissions, canCreateClasswork: e.target.checked })}
                    className="w-4 h-4 rounded text-emerald-600 mt-0.5 focus:ring-emerald-500"
                  />
                  <div>
                    <span className="font-bold text-slate-900 block flex items-center gap-1.5">
                      <BookOpen className="w-3.5 h-3.5 text-blue-600" />
                      Authorize Class Work & Assignment Creation
                    </span>
                    <span className="text-[11px] text-slate-500 block">
                      Grants permission to post weekly assignments, laboratory practical exercises, homework deadlines, and grade student submissions.
                    </span>
                  </div>
                </label>

                {/* 3. Continuous Assessment Grading */}
                <label className="flex items-start gap-3 p-3 rounded-lg border border-slate-200 hover:bg-slate-50 cursor-pointer bg-white">
                  <input
                    type="checkbox"
                    checked={approvalPermissions.canEnterGrades}
                    onChange={e => setApprovalPermissions({ ...approvalPermissions, canEnterGrades: e.target.checked })}
                    className="w-4 h-4 rounded text-emerald-600 mt-0.5 focus:ring-emerald-500"
                  />
                  <div>
                    <span className="font-bold text-slate-900 block flex items-center gap-1.5">
                      <FileCheck className="w-3.5 h-3.5 text-emerald-600" />
                      Authorize Continuous Assessment (CAT) & Coursework Marks
                    </span>
                    <span className="text-[11px] text-slate-500 block">
                      Allows entry and modification of student coursework scores, practical ratings, and attendance records.
                    </span>
                  </div>
                </label>

                {/* 4. Study Material Uploads */}
                <label className="flex items-start gap-3 p-3 rounded-lg border border-slate-200 hover:bg-slate-50 cursor-pointer bg-white">
                  <input
                    type="checkbox"
                    checked={approvalPermissions.canUploadMaterials}
                    onChange={e => setApprovalPermissions({ ...approvalPermissions, canUploadMaterials: e.target.checked })}
                    className="w-4 h-4 rounded text-emerald-600 mt-0.5 focus:ring-emerald-500"
                  />
                  <div>
                    <span className="font-bold text-slate-900 block flex items-center gap-1.5">
                      <FileText className="w-3.5 h-3.5 text-purple-600" />
                      Authorize Syllabus & Study Material Distribution
                    </span>
                    <span className="text-[11px] text-slate-500 block">
                      Allows publishing lecture slides, PDF modules, lab manuals, and exam revision guides to the Student Portal.
                    </span>
                  </div>
                </label>
              </div>

              {/* Course Assignment Checkboxes */}
              <div className="space-y-1.5 pt-2 border-t border-slate-200">
                <label className="block font-bold text-slate-900 uppercase tracking-wider text-[11px]">
                  Assigned Instructional Programs / Courses:
                </label>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-1.5 max-h-36 overflow-y-auto p-2 bg-slate-50 rounded-lg border border-slate-200">
                  {courses.map(course => {
                    const isAssigned = approvalPermissions.assignedCourses.includes(course.code);
                    return (
                      <label key={course.code} className="flex items-center gap-2 text-[11px] text-slate-700 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={isAssigned}
                          onChange={e => {
                            if (e.target.checked) {
                              setApprovalPermissions({
                                ...approvalPermissions,
                                assignedCourses: [...approvalPermissions.assignedCourses, course.code],
                              });
                            } else {
                              setApprovalPermissions({
                                ...approvalPermissions,
                                assignedCourses: approvalPermissions.assignedCourses.filter(c => c !== course.code),
                              });
                            }
                          }}
                          className="w-3.5 h-3.5 rounded text-emerald-600"
                        />
                        <span className="font-mono font-bold text-slate-900">{course.code}:</span>
                        <span className="truncate">{course.name}</span>
                      </label>
                    );
                  })}
                </div>
              </div>

              {/* Modal Footer Controls */}
              <div className="flex items-center justify-between pt-3 border-t border-slate-200">
                <button
                  type="button"
                  onClick={() => setSelectedTeacherForApproval(null)}
                  className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold rounded-lg transition"
                >
                  Cancel
                </button>

                <button
                  type="submit"
                  className="px-6 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg transition shadow-md flex items-center gap-2 active:scale-95"
                >
                  <CheckCircle2 className="w-4 h-4" />
                  Approve & Commission Lecturer
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL 2: EDIT PERMISSIONS FOR ACTIVE LECTURER */}
      {editingTeacherPermissions && (
        <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto">
          <div className="bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden border border-slate-200 animate-in fade-in zoom-in-95">
            {/* Header */}
            <div className="bg-slate-900 text-white px-6 py-4 flex items-center justify-between border-b border-slate-800">
              <div className="flex items-center gap-2.5">
                <div className="w-9 h-9 rounded-lg bg-indigo-600 flex items-center justify-center text-white">
                  <SlidersHorizontal className="w-5 h-5" />
                </div>
                <div>
                  <h3 className="text-sm font-bold text-white">
                    Modify Faculty Permissions & Exam Rights
                  </h3>
                  <p className="text-[10px] text-indigo-300 font-mono">
                    {editingTeacherPermissions.name} • {editingTeacherPermissions.department}
                  </p>
                </div>
              </div>
              <button
                onClick={() => setEditingTeacherPermissions(null)}
                className="p-1.5 text-slate-400 hover:text-white rounded-lg transition"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Form */}
            <form onSubmit={handleSavePermissionUpdates} className="p-6 space-y-4 text-xs">
              <div className="space-y-2">
                <label className="block font-bold text-slate-900 uppercase tracking-wider text-[11px]">
                  Institutional Permissions:
                </label>

                <label className="flex items-start gap-3 p-3 rounded-lg border border-slate-200 hover:bg-slate-50 cursor-pointer bg-white">
                  <input
                    type="checkbox"
                    checked={approvalPermissions.canPrepareExams}
                    onChange={e => setApprovalPermissions({ ...approvalPermissions, canPrepareExams: e.target.checked })}
                    className="w-4 h-4 rounded text-indigo-600 mt-0.5"
                  />
                  <div>
                    <span className="font-bold text-slate-900 block">
                      Examination Preparation & Moderation
                    </span>
                    <span className="text-[11px] text-slate-500">
                      Enables creating examination papers, setting grades, and submitting final assessment scores.
                    </span>
                  </div>
                </label>

                <label className="flex items-start gap-3 p-3 rounded-lg border border-slate-200 hover:bg-slate-50 cursor-pointer bg-white">
                  <input
                    type="checkbox"
                    checked={approvalPermissions.canCreateClasswork}
                    onChange={e => setApprovalPermissions({ ...approvalPermissions, canCreateClasswork: e.target.checked })}
                    className="w-4 h-4 rounded text-indigo-600 mt-0.5"
                  />
                  <div>
                    <span className="font-bold text-slate-900 block">
                      Class Works & Homework Tasks
                    </span>
                    <span className="text-[11px] text-slate-500">
                      Enables publishing weekly assignments and coursework instructions.
                    </span>
                  </div>
                </label>

                <label className="flex items-start gap-3 p-3 rounded-lg border border-slate-200 hover:bg-slate-50 cursor-pointer bg-white">
                  <input
                    type="checkbox"
                    checked={approvalPermissions.canEnterGrades}
                    onChange={e => setApprovalPermissions({ ...approvalPermissions, canEnterGrades: e.target.checked })}
                    className="w-4 h-4 rounded text-indigo-600 mt-0.5"
                  />
                  <div>
                    <span className="font-bold text-slate-900 block">
                      Continuous Assessment Grading
                    </span>
                    <span className="text-[11px] text-slate-500">
                      Enables recording test, coursework, and practical scores.
                    </span>
                  </div>
                </label>

                <label className="flex items-start gap-3 p-3 rounded-lg border border-slate-200 hover:bg-slate-50 cursor-pointer bg-white">
                  <input
                    type="checkbox"
                    checked={approvalPermissions.canUploadMaterials}
                    onChange={e => setApprovalPermissions({ ...approvalPermissions, canUploadMaterials: e.target.checked })}
                    className="w-4 h-4 rounded text-indigo-600 mt-0.5"
                  />
                  <div>
                    <span className="font-bold text-slate-900 block">
                      Study Materials & Syllabus
                    </span>
                    <span className="text-[11px] text-slate-500">
                      Enables uploading notes, past exam papers, and syllabus guides.
                    </span>
                  </div>
                </label>
              </div>

              {/* Course Assignment */}
              <div className="space-y-1.5 pt-2 border-t border-slate-200">
                <label className="block font-bold text-slate-900 uppercase tracking-wider text-[11px]">
                  Assigned Course Codes:
                </label>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-1.5 max-h-32 overflow-y-auto p-2 bg-slate-50 rounded-lg border border-slate-200">
                  {courses.map(course => {
                    const isAssigned = approvalPermissions.assignedCourses.includes(course.code);
                    return (
                      <label key={course.code} className="flex items-center gap-2 text-[11px] text-slate-700 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={isAssigned}
                          onChange={e => {
                            if (e.target.checked) {
                              setApprovalPermissions({
                                ...approvalPermissions,
                                assignedCourses: [...approvalPermissions.assignedCourses, course.code],
                              });
                            } else {
                              setApprovalPermissions({
                                ...approvalPermissions,
                                assignedCourses: approvalPermissions.assignedCourses.filter(c => c !== course.code),
                              });
                            }
                          }}
                          className="w-3.5 h-3.5 rounded text-indigo-600"
                        />
                        <span className="font-mono font-bold text-slate-900">{course.code}:</span>
                        <span className="truncate">{course.name}</span>
                      </label>
                    );
                  })}
                </div>
              </div>

              {/* Buttons */}
              <div className="flex items-center justify-between pt-3 border-t border-slate-200">
                <button
                  type="button"
                  onClick={() => setEditingTeacherPermissions(null)}
                  className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold rounded-lg transition"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-lg transition shadow-md flex items-center gap-2 active:scale-95"
                >
                  <Check className="w-4 h-4" />
                  Save Permission Updates
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL 3: DECLINE REASON MODAL */}
      {rejectionModalUser && (
        <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto">
          <div className="bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden border border-slate-200 animate-in fade-in zoom-in-95">
            <div className="bg-rose-900 text-white px-6 py-4 flex items-center justify-between border-b border-rose-800">
              <div className="flex items-center gap-2">
                <AlertTriangle className="w-5 h-5 text-rose-300" />
                <h3 className="text-sm font-bold text-white">Decline Lecturer Application</h3>
              </div>
              <button
                onClick={() => setRejectionModalUser(null)}
                className="p-1.5 text-rose-300 hover:text-white rounded-lg transition"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleConfirmRejection} className="p-6 space-y-4 text-xs">
              <p className="text-slate-600">
                You are declining the registration for <strong>{rejectionModalUser.name}</strong> ({rejectionModalUser.email}). Please provide an explanation for institutional records:
              </p>

              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  REASON / FEEDBACK FOR APPLICANT *
                </label>
                <textarea
                  required
                  rows={3}
                  placeholder="e.g. Teaching certificate verification pending or missing accredited academic transcripts."
                  value={rejectionReasonInput}
                  onChange={e => setRejectionReasonInput(e.target.value)}
                  className="w-full p-2.5 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 focus:bg-white focus:ring-2 focus:ring-rose-500 focus:outline-none"
                />
              </div>

              <div className="flex items-center justify-between pt-2">
                <button
                  type="button"
                  onClick={() => setRejectionModalUser(null)}
                  className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold rounded-lg transition"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-5 py-2 bg-rose-600 hover:bg-rose-700 text-white font-bold rounded-lg transition shadow-md"
                >
                  Confirm Decline
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL 4: DIRECT ONBOARD NEW LECTURER */}
      {showNewTeacherModal && (
        <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto">
          <div className="bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden border border-slate-200 animate-in fade-in zoom-in-95">
            <div className="bg-slate-900 text-white px-6 py-4 flex items-center justify-between border-b border-slate-800">
              <div className="flex items-center gap-2.5">
                <div className="w-9 h-9 rounded-lg bg-indigo-600 flex items-center justify-center text-white">
                  <UserCheck className="w-5 h-5" />
                </div>
                <div>
                  <h3 className="text-sm font-bold text-white">
                    Direct Lecturer Onboarding & Commissioning
                  </h3>
                  <p className="text-[10px] text-emerald-400 font-mono">
                    Register Teaching Staff with Pre-Approved Permissions
                  </p>
                </div>
              </div>
              <button
                onClick={() => setShowNewTeacherModal(false)}
                className="p-1.5 text-slate-400 hover:text-white rounded-lg transition"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleCreateNewLecturer} className="p-6 space-y-4 text-xs">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block font-semibold text-slate-700 mb-1">
                    LECTURER FULL NAME *
                  </label>
                  <input
                    type="text"
                    required
                    placeholder="e.g. Dr. Joyce Banda"
                    value={newLecturerForm.name}
                    onChange={e => setNewLecturerForm({ ...newLecturerForm, name: e.target.value })}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 font-medium focus:bg-white focus:ring-2 focus:ring-indigo-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block font-semibold text-slate-700 mb-1">
                    INSTITUTIONAL EMAIL *
                  </label>
                  <input
                    type="email"
                    required
                    placeholder="e.g. j.banda@sochetech.org"
                    value={newLecturerForm.email}
                    onChange={e => setNewLecturerForm({ ...newLecturerForm, email: e.target.value })}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 font-medium focus:bg-white focus:ring-2 focus:ring-indigo-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block font-semibold text-slate-700 mb-1">
                    CONTACT PHONE NUMBER
                  </label>
                  <input
                    type="text"
                    placeholder="+265 888 XXX XXX"
                    value={newLecturerForm.phone}
                    onChange={e => setNewLecturerForm({ ...newLecturerForm, phone: e.target.value })}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 font-medium focus:bg-white focus:ring-2 focus:ring-indigo-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block font-semibold text-slate-700 mb-1">
                    ACADEMIC DEPARTMENT
                  </label>
                  <select
                    value={newLecturerForm.department}
                    onChange={e => setNewLecturerForm({ ...newLecturerForm, department: e.target.value })}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 font-medium focus:bg-white focus:ring-2 focus:ring-indigo-500 focus:outline-none"
                  >
                    <option value="Engineering & Computing">Engineering & Computing</option>
                    <option value="Business & Finance">Business & Finance</option>
                    <option value="Management & Hospitality">Management & Hospitality</option>
                    <option value="Hospitality & Services">Hospitality & Services</option>
                    <option value="Construction & Civil">Construction & Civil</option>
                  </select>
                </div>
              </div>

              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  QUALIFICATIONS & CERTIFICATIONS
                </label>
                <input
                  type="text"
                  placeholder="e.g. MSc Computer Science (Chancellor College), City & Guilds Lead Assessor"
                  value={newLecturerForm.qualification}
                  onChange={e => setNewLecturerForm({ ...newLecturerForm, qualification: e.target.value })}
                  className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 font-medium focus:bg-white focus:ring-2 focus:ring-indigo-500 focus:outline-none"
                />
              </div>

              {/* Permissions Checkbox Grid */}
              <div className="space-y-2 pt-2 border-t border-slate-200">
                <label className="block font-bold text-slate-900 uppercase tracking-wider text-[11px]">
                  Grant Instant Operational Permissions:
                </label>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                  <label className="flex items-center gap-2 p-2 rounded-lg border border-slate-200 bg-slate-50 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={newLecturerForm.canPrepareExams}
                      onChange={e => setNewLecturerForm({ ...newLecturerForm, canPrepareExams: e.target.checked })}
                      className="w-4 h-4 rounded text-emerald-600"
                    />
                    <span className="font-semibold text-slate-800">Prepare Examinations</span>
                  </label>

                  <label className="flex items-center gap-2 p-2 rounded-lg border border-slate-200 bg-slate-50 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={newLecturerForm.canCreateClasswork}
                      onChange={e => setNewLecturerForm({ ...newLecturerForm, canCreateClasswork: e.target.checked })}
                      className="w-4 h-4 rounded text-emerald-600"
                    />
                    <span className="font-semibold text-slate-800">Create Class Works</span>
                  </label>

                  <label className="flex items-center gap-2 p-2 rounded-lg border border-slate-200 bg-slate-50 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={newLecturerForm.canEnterGrades}
                      onChange={e => setNewLecturerForm({ ...newLecturerForm, canEnterGrades: e.target.checked })}
                      className="w-4 h-4 rounded text-emerald-600"
                    />
                    <span className="font-semibold text-slate-800">Grade Assessments</span>
                  </label>

                  <label className="flex items-center gap-2 p-2 rounded-lg border border-slate-200 bg-slate-50 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={newLecturerForm.canUploadMaterials}
                      onChange={e => setNewLecturerForm({ ...newLecturerForm, canUploadMaterials: e.target.checked })}
                      className="w-4 h-4 rounded text-emerald-600"
                    />
                    <span className="font-semibold text-slate-800">Upload Materials</span>
                  </label>
                </div>
              </div>

              {/* Footer */}
              <div className="flex items-center justify-between pt-3 border-t border-slate-200">
                <button
                  type="button"
                  onClick={() => setShowNewTeacherModal(false)}
                  className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold rounded-lg transition"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-lg transition shadow-md flex items-center gap-2 active:scale-95"
                >
                  <CheckCircle2 className="w-4 h-4" />
                  Commission & Save Lecturer
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* STUDENT DIGITAL ID MODAL */}
      {viewingIdCardFee && (
        <StudentIDCardModal
          isOpen={!!viewingIdCardFee}
          onClose={() => setViewingIdCardFee(null)}
          user={{
            id: viewingIdCardFee.id,
            name: viewingIdCardFee.studentName,
            email: `${viewingIdCardFee.studentId.toLowerCase().replace(/[^a-z0-9]/g, '')}@student.sochetech.org`,
            role: 'student',
            studentId: viewingIdCardFee.studentId,
            title: viewingIdCardFee.courseName,
            avatarUrl: 'https://images.unsplash.com/photo-1539571696357-5a69c17a67c6?w=400&auto=format&fit=crop&q=80',
          }}
          studentFee={viewingIdCardFee}
        />
      )}

      {/* BULK DATA EXPORT MODAL FOR LOCAL FILING & REGULATORY AUDIT */}
      <BulkExportModal
        isOpen={showBulkExportModal}
        onClose={() => setShowBulkExportModal(false)}
        applications={applications}
        attendance={attendance}
        fees={fees}
        courses={courses}
        allUsers={allUsers}
        grades={grades}
      />

    </div>
  );
};
