import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useNavigate } from 'react-router-dom';
import api, { useAuthStore } from '../store/auth';
import { 
  Plus, Trash2, Edit2, BookOpen, Users, 
  Search, X, ChevronRight, Download, ExternalLink,
  Sparkles, School, Building2, LayoutGrid,
  CheckCircle2, AlertCircle, Info, MoreHorizontal,
  FileText, FolderOpen, RefreshCw
} from 'lucide-react';
import { useEducationTerms } from '../utils/educationTerms';
import CreateClassWizard from '../components/CreateClassWizard';
import { ProgressBar } from '../components/ui/ProgressBar';
import { createAxiosUploadProgressHandler } from '../lib/uploadProgress';
// okay
interface ClassSection {
  id: number;
  name: string;
  section?: string;
  capacity: number;
  student_count?: number;
  subject_count?: number;
  class_teacher_name?: string;
  chapters_count?: number;
  assignments_count?: number;
  materials_count?: number;
}

interface Subject {
  id: number;
  name: string;
  class_id: number;
  class_name?: string;
  class_section?: string;
  department_id?: number;
  department_name?: string;
  code?: string;
  credits?: number;
  teacher_id?: number;
  teacher_name?: string;
}

export default function Classes() {
  const { user } = useAuthStore();
  const navigate = useNavigate();
  const terms = useEducationTerms();
  const [classes, setClasses] = useState<ClassSection[]>([]);
  const [subjects, setSubjects] = useState<Subject[]>([]);
  const [departments, setDepartments] = useState<any[]>([]);
  const [teachers, setTeachers] = useState<any[]>([]);
  const [showClassModal, setShowClassModal] = useState(false);
  const [showSubjectModal, setShowSubjectModal] = useState(false);
  const [loading, setLoading] = useState(true);
  const [subjectForm, setSubjectForm] = useState({ 
    name: '', 
    code: '', 
    class_id: '', 
    department_id: '',
    teacher_id: '',
    syllabus: null as File | null,
    syllabus_name: ''
  });
  const [deleteSyllabus, setDeleteSyllabus] = useState(false);
  const [editingSubjectId, setEditingSubjectId] = useState<number | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  // Per-class heads-up refresh state. A class id is in this set while
  // its /classes/:id/heads-up request is in flight. Drives a small
  // spinner on the card so users can see live counts being fetched
  // via the dedicated heads-up endpoint.
  const [headsUpLoading, setHeadsUpLoading] = useState<Set<number>>(new Set());
  const [headsUpError, setHeadsUpError] = useState<string | null>(null);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    setLoading(true);
    try {
      const [classRes, subjectRes, deptRes, teacherRes] = await Promise.all([
        api.get('/classes'),
        api.get('/subjects'),
        api.get('/departments'),
        api.get('/users', { params: { role: 'teacher', limit: 100 } })
      ]);
      setClasses(classRes.data);
      setSubjects(subjectRes.data);
      setDepartments(deptRes.data);
      const teacherData = teacherRes.data.users || teacherRes.data;
      setTeachers(Array.isArray(teacherData) ? teacherData : []);
    } catch (err) {
      console.error('Failed to load academic structure');
    } finally {
      setLoading(false);
    }
  };

  // Refresh one class's HUD counts via the consolidated heads-up
  // endpoint. Merges the returned counts back into the class row so
  // the user sees fresh chapters/assignments/materials/learners
  // numbers without a full list reload.
  const refreshHeadsUp = async (classId: number) => {
    setHeadsUpLoading((prev) => {
      const next = new Set(prev);
      next.add(classId);
      return next;
    });
    setHeadsUpError(null);
    try {
      const res = await api.get(`/classes/${classId}/heads-up`);
      const { student_count, chapters_count, assignments_count, materials_count } = res.data || {};
      setClasses((prev) => prev.map((c) =>
        c.id === classId
          ? {
              ...c,
              student_count: student_count ?? c.student_count,
              chapters_count: chapters_count ?? c.chapters_count,
              assignments_count: assignments_count ?? c.assignments_count,
              materials_count: materials_count ?? c.materials_count,
            }
          : c,
      ));
    } catch (err: any) {
      const msg = err?.response?.data?.error || err?.message || 'Failed to refresh counts';
      setHeadsUpError(msg);
      console.error('Heads-up refresh failed:', err);
    } finally {
      setHeadsUpLoading((prev) => {
        const next = new Set(prev);
        next.delete(classId);
        return next;
      });
    }
  };

  const refreshAllHeadsUp = async () => {
    await Promise.all(filteredClasses.map((c) => refreshHeadsUp(c.id)));
  };

  const handleSubjectSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const formData = new FormData();
      formData.append('name', subjectForm.name);
      formData.append('code', subjectForm.code);
      formData.append('class_id', subjectForm.class_id);
      formData.append('department_id', subjectForm.department_id);
      formData.append('teacher_id', subjectForm.teacher_id);
      
      if (subjectForm.syllabus) {
        formData.append('syllabus', subjectForm.syllabus);
      }
      if (deleteSyllabus) {
        formData.append('delete_syllabus', 'true');
      }

      const config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      };

      if (editingSubjectId) {
        await api.put(`/subjects/${editingSubjectId}`, formData, config);
      } else {
        await api.post('/subjects', formData, config);
      }
      setShowSubjectModal(false);
      setSubjectForm({ 
        name: '', 
        code: '', 
        class_id: '', 
        department_id: '',
        teacher_id: '',
        syllabus: null,
        syllabus_name: ''
      });
      setDeleteSyllabus(false);
      setEditingSubjectId(null);
      loadData();
    } catch (err) {
      alert('Failed to save subject record');
    }
  };

  const openAddSubject = () => {
    setSubjectForm({ 
      name: '', 
      code: '', 
      class_id: '', 
      department_id: '',
      teacher_id: user?.role === 'teacher' ? user.id.toString() : '',
      syllabus: null,
      syllabus_name: ''
    });
    setDeleteSyllabus(false);
    setEditingSubjectId(null);
    setShowSubjectModal(true);
  };

  const openEditSubject = (sub: Subject) => {
    setSubjectForm({
      name: sub.name,
      code: sub.code || '',
      class_id: sub.class_id.toString(),
      department_id: sub.department_id?.toString() || '',
      teacher_id: sub.teacher_id?.toString() || '',
      syllabus: null,
      syllabus_name: (sub as any).syllabus_name || ''
    });
    setDeleteSyllabus(false);
    setEditingSubjectId(sub.id);
    setShowSubjectModal(true);
  };

  const deleteClass = async (id: number) => {
    if (!confirm('Archive this class section? This will affect student enrolments.')) return;
    await api.delete(`/classes/${id}`);
    loadData();
  };

  const deleteSubject = async (id: number) => {
    if (!confirm(`Archive this ${terms.subject.toLowerCase()} record?`)) return;
    await api.delete(`/subjects/${id}`);
    loadData();
  };

  const filteredClasses = classes.filter(c => 
    c.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    (c.section || '').toLowerCase().includes(searchQuery.toLowerCase())
  );

  const stats = [
    { label: 'Active Sections', value: classes.length, icon: Building2, color: 'blue', trend: 'Records' },
    { label: 'Curriculum Units', value: subjects.length, icon: BookOpen, color: 'emerald', trend: 'Live' },
    { label: 'Total Capacity', value: classes.reduce((acc, c) => acc + c.capacity, 0), icon: LayoutGrid, color: 'orange', trend: 'Volume' },
    { label: 'Avg. Class Size', value: '24.2', icon: Users, color: 'purple', trend: 'Trend' },
  ];

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Premium Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight text-capitalize uppercase">Academic Structure</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Administration</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Sections & Curriculum</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button
            onClick={() => {
              if (classes.length === 0) return;
              const headers = ['ID', 'Name', 'Section', 'Capacity', 'Student Count'];
              const rows = classes.map((c: ClassSection) => [c.id, c.name, c.section || '', c.capacity, c.student_count || 0]);
              const csv = [headers, ...rows].map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
              const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
              const url = URL.createObjectURL(blob);
              const a = document.createElement('a');
              a.href = url;
              a.download = 'academic_structure.csv';
              document.body.appendChild(a);
              a.click();
              document.body.removeChild(a);
              URL.revokeObjectURL(url);
            }}
            className="flex items-center gap-2 px-5 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted transition-all shadow-sm active:scale-95"
          >
            <Download size={18} />
            Export Scheme
          </button>
          <button 
            className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95"
            onClick={() => setShowClassModal(true)}
          >
            <Plus size={18} />
            New Section
          </button>
        </div>
      </div>

      {/* Stats Bento Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 hover:shadow-md transition-all group cursor-default">
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center border group-hover:scale-110 transition-transform
              ${stat.color === 'blue' ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-900/30' : 
                stat.color === 'emerald' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-900/30' : 
                stat.color === 'orange' ? 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-900/30' : 
                'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-900/30'}`}>
              <stat.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
              <div className="flex items-baseline gap-2">
                <p className="text-2xl font-black text-text">{stat.value}</p>
                <span className="text-[0.6rem] font-bold text-text-muted">{stat.trend}</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Directory Control Bar */}
      <div className="bg-card border border-border rounded-[2rem] p-2 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-4">
        <div className="relative group flex-1">
          <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
          <input 
            type="text" 
            className="w-full bg-muted/50 border border-border rounded-2xl pl-11 pr-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all dark:bg-background/50"
            placeholder="Search classes or sections..."
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
          />
          {searchQuery && (
            <button onClick={() => setSearchQuery('')} className="absolute right-4 top-1/2 -translate-y-1/2 text-text-muted hover:text-rose-500">
              <X size={16} />
            </button>
          )}
        </div>

        <button
            onClick={openAddSubject}
            className="px-5 py-3 bg-primary/5 hover:bg-primary/10 text-primary rounded-2xl border border-primary/10 transition-all flex items-center justify-center gap-2"
        >
            <Plus size={18} />
            <span className="text-[0.7rem] font-black uppercase tracking-widest">Add {terms.subject}</span>
        </button>
      </div>

      {/* Main Grid: Classes vs Subjects */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        
        {/* Classes Sections (Left 7/12) */}
        <div className="lg:col-span-7 space-y-6">
            <div className="flex items-center justify-between px-2">
                <h3 className="text-lg font-black text-text uppercase tracking-tight">Class Sections</h3>
                <div className="flex items-center gap-3">
                    <span className="text-[0.65rem] font-bold text-text-muted uppercase tracking-widest">{filteredClasses.length} Active Records</span>
                    <button
                        onClick={refreshAllHeadsUp}
                        disabled={headsUpLoading.size > 0 || loading || filteredClasses.length === 0}
                        className="flex items-center gap-1.5 px-3 py-1.5 bg-card border border-border text-text-muted hover:text-primary hover:border-primary/40 rounded-xl text-[0.6rem] font-black uppercase tracking-widest transition-all shadow-sm disabled:opacity-40 disabled:cursor-not-allowed"
                        title="Refresh HUD counts via /classes/:id/heads-up"
                    >
                        <RefreshCw size={12} className={headsUpLoading.size > 0 ? 'animate-spin' : ''} />
                        Refresh counts
                    </button>
                </div>
            </div>

            {headsUpError && (
                <div className="px-4 py-2 bg-rose-50 dark:bg-rose-900/20 border border-rose-100 dark:border-rose-800 rounded-2xl flex items-center gap-3">
                    <AlertCircle className="text-rose-600 dark:text-rose-400 shrink-0" size={14} />
                    <span className="text-rose-700 dark:text-rose-300 text-xs font-bold">{headsUpError}</span>
                </div>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {loading ? (
                    <div className="col-span-full py-20 text-center">
                        <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                        <p className="text-text-muted font-bold uppercase tracking-widest text-xs italic">Syncing Directory...</p>
                    </div>
                ) : filteredClasses.length === 0 ? (
                    <div className="col-span-full py-20 text-center bg-card border border-dashed border-border rounded-[2.5rem]">
                        <School size={48} className="mx-auto text-text-muted/30 mb-4" />
                        <p className="text-text-muted font-bold uppercase tracking-widest text-xs">No matching classes found</p>
                    </div>
                ) : filteredClasses.map((cls) => {
                    const isRefreshing = headsUpLoading.has(cls.id);
                    return (
                    <div key={cls.id} className="bg-card rounded-[2.5rem] border border-border p-8 hover:shadow-xl hover:shadow-blue-900/5 transition-all group relative overflow-hidden flex flex-col">
                        <div className="absolute top-0 right-0 w-32 h-32 bg-muted rounded-bl-[4rem] -mr-16 -mt-16 group-hover:bg-blue-50/10 dark:group-hover:bg-blue-900/20 transition-colors"></div>
                        
                        <div className="relative z-10 flex justify-between items-start mb-6">
                            <div className="w-14 h-14 rounded-2xl bg-primary flex items-center justify-center text-white shadow-lg shadow-blue-900/10 group-hover:scale-110 transition-transform">
                                <Building2 size={28} />
                            </div>
                            <div className="flex items-center gap-1.5">
                                <button
                                    onClick={(e) => { e.stopPropagation(); navigate(`/admin/classes/${cls.id}`); }}
                                    className="p-2 bg-card/80 backdrop-blur rounded-xl border border-border text-text-muted hover:text-primary hover:border-primary/40 transition-all shadow-sm"
                                    title="View class detail"
                                    aria-label="View class detail"
                                >
                                    <ExternalLink size={14} />
                                </button>
                                <button
                                    onClick={(e) => { e.stopPropagation(); refreshHeadsUp(cls.id); }}
                                    disabled={isRefreshing}
                                    className="p-2 bg-card/80 backdrop-blur rounded-xl border border-border text-text-muted hover:text-primary hover:border-primary/40 transition-all shadow-sm disabled:opacity-50"
                                    title="Refresh HUD counts"
                                    aria-label="Refresh HUD counts"
                                >
                                    <RefreshCw size={14} className={isRefreshing ? 'animate-spin' : ''} />
                                </button>
                                <button
                                    onClick={(e) => { e.stopPropagation(); deleteClass(cls.id); }}
                                    className="p-2 bg-card/80 backdrop-blur rounded-xl border border-border text-text-muted hover:text-rose-500 hover:border-rose-300 transition-all shadow-sm"
                                    title="Archive class"
                                    aria-label="Archive class"
                                >
                                    <Trash2 size={14} />
                                </button>
                            </div>
                        </div>

                        <div className="relative z-10 mb-8 flex-grow">
                            <h4 className="text-xl sm:text-2xl font-black text-text tracking-tighter group-hover:text-primary transition-colors line-clamp-2 break-words">
                                {cls.name}
                            </h4>
                            <p className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted mt-1">
                                Section: {cls.section || 'General'}
                            </p>
                        </div>

                        <div className="relative z-10 grid grid-cols-2 gap-3">
                            {/* Chapters/Modules Tile */}
                            <div className="bg-muted/40 p-3 rounded-2xl border border-border/80 group-hover:bg-card hover:border-primary/30 transition-all flex flex-col justify-between min-h-[64px]">
                                <div className="flex items-center gap-2 mb-1.5">
                                    <BookOpen size={12} className="text-blue-500 shrink-0" />
                                    <p className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-widest text-text-muted truncate">
                                        {terms.subject === 'Course' ? 'Modules' : 'Chapters'}
                                    </p>
                                </div>
                                <p className={`text-base sm:text-lg font-black ${(cls.chapters_count || 0) === 0 ? 'text-text-muted/50' : 'text-text'}`}>
                                    {cls.chapters_count || 0}
                                </p>
                            </div>

                            {/* Assignments Tile */}
                            <div className="bg-muted/40 p-3 rounded-2xl border border-border/80 group-hover:bg-card hover:border-primary/30 transition-all flex flex-col justify-between min-h-[64px]">
                                <div className="flex items-center gap-2 mb-1.5">
                                    <FileText size={12} className="text-indigo-500 shrink-0" />
                                    <p className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-widest text-text-muted truncate">
                                        Assignments
                                    </p>
                                </div>
                                <p className={`text-base sm:text-lg font-black ${(cls.assignments_count || 0) === 0 ? 'text-text-muted/50' : 'text-text'}`}>
                                    {cls.assignments_count || 0}
                                </p>
                            </div>

                            {/* Learning Materials Tile */}
                            <div className="bg-muted/40 p-3 rounded-2xl border border-border/80 group-hover:bg-card hover:border-primary/30 transition-all flex flex-col justify-between min-h-[64px]">
                                <div className="flex items-center gap-2 mb-1.5">
                                    <FolderOpen size={12} className="text-emerald-500 shrink-0" />
                                    <p className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-widest text-text-muted truncate">
                                        Materials
                                    </p>
                                </div>
                                <p className={`text-base sm:text-lg font-black ${(cls.materials_count || 0) === 0 ? 'text-text-muted/50' : 'text-text'}`}>
                                    {cls.materials_count || 0}
                                </p>
                            </div>

                            {/* Learners Tile */}
                            <div className="bg-muted/40 p-3 rounded-2xl border border-border/80 group-hover:bg-card hover:border-primary/30 transition-all flex flex-col justify-between min-h-[64px]">
                                <div className="flex items-center gap-2 mb-1.5">
                                    <Users size={12} className="text-amber-500 shrink-0" />
                                    <p className="text-[0.55rem] sm:text-[0.6rem] font-black uppercase tracking-widest text-text-muted truncate">
                                        Learners
                                    </p>
                                </div>
                                <p className="text-base sm:text-lg font-black text-text">
                                    {cls.student_count || 0}
                                    <span className="text-text-muted text-[0.65rem] ml-1 font-bold">/ {cls.capacity}</span>
                                </p>
                            </div>
                        </div>

                        <div className="mt-6 pt-4 border-t border-border flex items-center justify-between gap-2">
                            <span className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted truncate">
                                ID: SEC-2024-{cls.id}
                            </span>
                            <span className="text-[0.55rem] font-bold uppercase tracking-widest text-text-muted/60 inline-flex items-center gap-1 shrink-0">
                                {isRefreshing ? (
                                    <>
                                        <RefreshCw size={10} className="animate-spin text-primary" />
                                        Refreshing
                                    </>
                                ) : (
                                    <>4-tile HUD · live</>
                                )}
                            </span>
                        </div>
                    </div>
                    );
                })}
            </div>
        </div>

        {/* Subject Marks (Right 5/12) */}
        <div className="lg:col-span-5 space-y-6">
            <div className="flex items-center justify-between px-2">
                <h3 className="text-lg font-black text-text uppercase tracking-tight">Curriculum</h3>
                <button onClick={() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }} className="text-primary text-[0.7rem] font-bold hover:underline">View All Intelligence</button>
            </div>

            <div className="bg-card border border-border rounded-[2.5rem] overflow-hidden shadow-sm flex flex-col">
                <div className="p-8 bg-muted/50 border-b border-border flex justify-between items-center dark:bg-background/50">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-blue-50/10 dark:bg-blue-900/20 rounded-xl text-primary">
                            <BookOpen size={18} />
                        </div>
                        <p className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">{terms.subject} Records</p>
                    </div>
                    <span className="bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 text-[0.6rem] font-black px-2.5 py-1 rounded-full border border-emerald-100 dark:border-emerald-900/30 uppercase tracking-widest">
                        Live
                    </span>
                </div>
                
                <div className="p-2 divide-y divide-border">
                    {subjects.length === 0 ? (
                        <div className="py-20 text-center">
                            <BookOpen size={40} className="mx-auto text-text-muted/30 mb-3" />
                            <p className="text-text-muted font-bold uppercase tracking-widest text-[0.6rem]">No curriculum data recorded</p>
                        </div>
                    ) : subjects.map((s) => (
                        <div key={s.id} className="p-5 flex items-center justify-between hover:bg-muted/50 transition-colors group rounded-2xl cursor-default">
                            <div className="flex items-center gap-4">
                                <div className="w-12 h-12 rounded-2xl bg-slate-900 flex items-center justify-center text-[0.8rem] font-black text-emerald-500 shadow-sm border border-border group-hover:scale-110 transition-transform">
                                    {s.name[0]}
                                </div>
                                <div>
                                    <p className="text-sm font-black text-text tracking-tight group-hover:text-primary transition-colors">{s.name}</p>
                                    <div className="flex flex-wrap items-center gap-x-2 gap-y-1 mt-0.5">
                                        <div className="flex items-center gap-1">
                                            <School size={10} className="text-text-muted" />
                                            <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">{s.class_name || 'General'}</p>
                                        </div>
                                        {s.department_name && (
                                            <>
                                                <span className="w-1 h-1 rounded-full bg-text-muted/30"></span>
                                                <div className="flex items-center gap-1">
                                                    <Building2 size={10} className="text-primary" />
                                                    <p className="text-[0.6rem] font-black text-primary uppercase tracking-widest">{s.department_name}</p>
                                                </div>
                                            </>
                                        )}
                                        {s.teacher_name && (
                                            <>
                                                <span className="w-1 h-1 rounded-full bg-text-muted/30"></span>
                                                <div className="flex items-center gap-1">
                                                    <Users size={10} className="text-emerald-500" />
                                                    <p className="text-[0.6rem] font-black text-emerald-500 uppercase tracking-widest">{s.teacher_name}</p>
                                                </div>
                                            </>
                                        )}
                                    </div>
                                    {(s as any).syllabus_url && (
                                        <a 
                                            href={(s as any).syllabus_url} 
                                            target="_blank" 
                                            rel="noopener noreferrer" 
                                            className="inline-flex items-center gap-1 text-[0.6rem] font-black text-indigo-500 dark:text-indigo-400 hover:underline mt-1"
                                            onClick={e => e.stopPropagation()}
                                        >
                                            View Syllabus ({(s as any).syllabus_name || 'PDF'})
                                        </a>
                                    )}
                                </div>
                            </div>
                            <div className="flex items-center gap-2">
                                <button
                                    onClick={() => openEditSubject(s)}
                                    className="p-2 text-text-muted hover:text-primary hover:bg-primary/5 rounded-xl transition-all opacity-0 group-hover:opacity-100"
                                >
                                    <Edit2 size={16} />
                                </button>
                                <button 
                                    onClick={() => deleteSubject(s.id)}
                                    className="p-2 text-text-muted hover:text-rose-600 hover:bg-rose-500/5 rounded-xl transition-all opacity-0 group-hover:opacity-100"
                                >
                                    <Trash2 size={16} />
                                </button>
                            </div>
                        </div>
                    ))}
                </div>

                <button 
                    className="m-4 mt-2 py-4 bg-muted/50 hover:bg-muted text-text-muted text-[0.65rem] font-black uppercase tracking-[3px] rounded-3xl transition-all border border-border flex items-center justify-center gap-2 dark:bg-background/50"
                    onClick={openAddSubject}
                >
                    <Plus size={16} /> Add {terms.subject}
                </button>
            </div>

            {/* Support Tooltip */}
            <div className="bg-slate-900 rounded-[2.5rem] p-8 text-white shadow-2xl relative overflow-hidden group">
                <div className="absolute right-[-40px] bottom-[-40px] opacity-10 group-hover:rotate-12 transition-transform duration-700">
                    <Sparkles size={180} strokeWidth={1} />
                </div>
                <div className="relative z-10">
                    <h4 className="text-[0.6rem] font-black uppercase tracking-[3px] text-white/40 mb-4 px-1">NextGen Assist</h4>
                    <p className="text-[0.85rem] font-medium text-blue-50/80 leading-relaxed mb-6">
                        Need help organizing your curriculum? Use the {terms.subjects.toLowerCase()} table to assign courses to specific class sections.
                    </p>
                    <button onClick={() => window.open('https://github.com/techarvest/africa-alert-pwa', '_blank', 'noopener,noreferrer')} className="px-6 py-3 bg-white/10 hover:bg-white/20 text-white rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all border border-white/10">
                        View Documentation
                    </button>
                </div>
            </div>
        </div>
      </div>

      {/* Modals — portaled to document.body so the backdrop always covers the
          full viewport, regardless of any ancestor that establishes a new
          containing block (transform / filter / will-change / contain). */}
      {showClassModal && createPortal(
        <CreateClassWizard
          onClose={() => setShowClassModal(false)}
          onCreated={(cls) => {
            // Reload the list so the new class shows up immediately
            loadData();
            // Jump straight to the new class detail so the admin can
            // assign subjects / add a roster in one trip.
            navigate(`/admin/classes/${cls.id}`);
          }}
        />,
        document.body
      )}

      {showSubjectModal && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={() => setShowSubjectModal(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden">
                <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                    <Sparkles size={180} />
                </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">
                  {editingSubjectId ? `Edit ${terms.subject}` : `Add ${terms.subject}`}
                </h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">
                  {editingSubjectId ? 'Update curriculum record details' : 'Establish curriculum record'}
                </p>
              </div>
              <button onClick={() => setShowSubjectModal(false)} className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm">
                <X size={20} />
              </button>
            </div>
             <form onSubmit={handleSubjectSubmit} className="p-10 space-y-6">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">{terms.subject} Identifier (Name)</label>
                <input 
                  className="form-input disabled:opacity-60 disabled:cursor-not-allowed" 
                  value={subjectForm.name} 
                  onChange={e => setSubjectForm({...subjectForm, name: e.target.value})} 
                  placeholder="e.g., Quantum Mechanics" 
                  required 
                  disabled={user?.role === 'teacher'}
                />
              </div>
              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">{terms.subject} Code</label>
                  <input 
                    className="form-input disabled:opacity-60 disabled:cursor-not-allowed" 
                    value={subjectForm.code} 
                    onChange={e => setSubjectForm({...subjectForm, code: e.target.value})} 
                    placeholder="e.g., MATH-F3" 
                    disabled={user?.role === 'teacher'}
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Associate with Section</label>
                  <select 
                    className="form-input appearance-none cursor-pointer disabled:opacity-60 disabled:cursor-not-allowed" 
                    value={subjectForm.class_id} 
                    onChange={e => setSubjectForm({...subjectForm, class_id: e.target.value})} 
                    required
                    disabled={user?.role === 'teacher'}
                  >
                    <option value="">Select registry entry...</option>
                    {classes.map(c => <option key={c.id} value={c.id}>{c.name} {c.section ? `(${c.section})` : ''}</option>)}
                  </select>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Academic Department</label>
                  <select 
                    className="form-input appearance-none cursor-pointer disabled:opacity-60 disabled:cursor-not-allowed" 
                    value={subjectForm.department_id} 
                    onChange={e => setSubjectForm({...subjectForm, department_id: e.target.value})}
                    disabled={user?.role === 'teacher'}
                  >
                    <option value="">Select department...</option>
                    {departments.map(d => (
                      <option key={d.id} value={d.id} className="bg-card text-text dark:bg-card-elevated dark:text-text">{d.name}</option>
                    ))}
                  </select>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Assign Teacher</label>
                  <select 
                    className="form-input appearance-none cursor-pointer disabled:opacity-60 disabled:cursor-not-allowed" 
                    value={subjectForm.teacher_id} 
                    onChange={e => setSubjectForm({...subjectForm, teacher_id: e.target.value})}
                    disabled={user?.role === 'teacher'}
                  >
                    <option value="">Select teacher...</option>
                    {teachers.map(t => (
                      <option key={t.id} value={t.id} className="bg-card text-text dark:bg-card-elevated dark:text-text">{t.first_name} {t.last_name}</option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Upload Syllabus (Optional)</label>
                {subjectForm.syllabus_name && !deleteSyllabus ? (
                  <div className="flex items-center justify-between bg-muted/50 border border-border rounded-2xl p-4 dark:bg-background/50">
                    <span className="text-xs font-semibold text-text truncate max-w-[70%]">{subjectForm.syllabus_name}</span>
                    <button 
                      type="button" 
                      onClick={() => setDeleteSyllabus(true)} 
                      className="text-xs font-black uppercase text-rose-500 hover:text-rose-600 transition-colors"
                    >
                      Remove
                    </button>
                  </div>
                ) : (
                  <input 
                    type="file" 
                    accept=".pdf,.doc,.docx,.png,.jpg,.jpeg"
                    className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text file:mr-4 file:py-2 file:px-4 file:rounded-xl file:border-0 file:text-xs file:font-semibold file:bg-primary/10 file:text-primary hover:file:bg-primary/20 cursor-pointer dark:bg-background/50"
                    onChange={e => {
                      if (e.target.files && e.target.files[0]) {
                        setSubjectForm({...subjectForm, syllabus: e.target.files[0], syllabus_name: e.target.files[0].name});
                        setDeleteSyllabus(false);
                      }
                    }} 
                  />
                )}
              </div>

              <button type="submit" className="w-full py-5 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3">
                {editingSubjectId ? <CheckCircle2 size={18} /> : <Sparkles size={18} />}
                {editingSubjectId ? 'Update Curriculum Record' : 'Establish Curriculum Record'}
              </button>
            </form>
          </div>
        </div>,
        document.body
      )}

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(0, 71, 171, 0.1); border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: rgba(0, 71, 171, 0.2); }
      `}</style>
    </div>
  );
}
