import React, { useState, useEffect, useMemo } from 'react';
import { 
  Calendar, 
  Users, 
  BookOpen, 
  Layout, 
  Plus, 
  Trash2, 
  AlertCircle, 
  Printer, 
  CheckCircle,
  Clock,
  MapPin,
  ChevronRight,
  Menu,
  X,
  ShieldCheck,
  FileText,
  Search,
  AlertTriangle
} from 'lucide-react';

// --- Constants & Seed Data ---

const BRANCHES = [
  { id: 'CE', name: 'Civil Engineering', lateral: false },
  { id: 'CE-LE', name: 'Civil Engineering - Lateral Entry', lateral: true },
  { id: 'PCE', name: 'Petro Chemical Engineering', lateral: false },
  { id: 'PT', name: 'Paint Technology', lateral: false },
];

const SEMESTERS = [
  { no: 1, type: 'ODD' },
  { no: 2, type: 'EVEN' },
  { no: 3, type: 'ODD' },
  { no: 4, type: 'EVEN' },
  { no: 5, type: 'ODD' },
  { no: 6, type: 'EVEN' },
];

const DAYS = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];

const TIME_SLOTS = [
  { id: 1, label: 'Period 1', time: '10:00 - 11:00' },
  { id: 2, label: 'Period 2', time: '11:00 - 12:00' },
  { id: 3, label: 'Period 3', time: '12:00 - 13:00' },
  { id: 'LUNCH', label: 'Lunch Break', time: '13:00 - 14:00', isBreak: true },
  { id: 4, label: 'Period 4', time: '14:00 - 15:00' },
  { id: 5, label: 'Period 5', time: '15:00 - 16:00' },
  { id: 6, label: 'Period 6', time: '16:00 - 17:00' },
];

const INITIAL_FACULTY = [
  "Atul Kumar Sharma", "Namrata Pal", "Himmani Khandelwal", "Pushpendra Kumar",
  "Ashwani Kumar Mishra", "Subodh Saini", "Kanchan Kushwaha", "Bhupendra Pal Singh Yadav",
  "Anuradha Katiyar", "Vibha Verma", "Satyaveer Singh", "Vivek Kumar Singh",
  "Yatendra Kumar", "Alka Saxena", "Rajkumar Sharma", "Praveen Mishra",
  "Priya Sharma", "Shalini Rathore", "Radheshyam Sharma", "Nandkishore Saini",
  "Ambrikesh Mishra", "Lucky", "Vikas Kumar", "Ashok Kumar",
  "Hemant Kumar Sharma", "Rajkumar Kushwah", "Amit Kumar Sengar"
].map((name, i) => ({ 
  id: i + 1, 
  name, 
  designation: i === 0 ? 'Principal' : (i === 4 ? 'H.O.D' : (i === 14 ? 'Workshop Superintendent' : 'Lecturer')) 
}));

// Expanded Subjects for Phase 2 readiness
const INITIAL_SUBJECTS = [
  // Sem 1 & 2 (Common-ish)
  { id: 101, name: 'Mathematics-I', sem: 1, branches: ['CE', 'PCE', 'PT'], type: 'Theory' },
  { id: 102, name: 'Applied Physics-I', sem: 1, branches: ['CE', 'PCE', 'PT'], type: 'Theory' },
  { id: 103, name: 'Applied Chemistry', sem: 1, branches: ['CE', 'PCE', 'PT'], type: 'Theory' },
  { id: 104, name: 'Communication Skills', sem: 1, branches: ['CE', 'PCE', 'PT'], type: 'Theory' },
  { id: 105, name: 'Engineering Graphics', sem: 1, branches: ['CE', 'PCE', 'PT'], type: 'Practical' },
  { id: 201, name: 'Mathematics-II', sem: 2, branches: ['CE', 'PCE', 'PT'], type: 'Theory' },
  { id: 202, name: 'Applied Physics-II', sem: 2, branches: ['CE', 'PCE', 'PT'], type: 'Theory' },
  { id: 203, name: 'Engineering Mechanics', sem: 2, branches: ['CE', 'PCE', 'PT'], type: 'Theory' },
  
  // Sem 3 (Department Specific)
  { id: 301, name: 'Hydraulics', sem: 3, branches: ['CE', 'CE-LE'], type: 'Theory' },
  { id: 302, name: 'Surveying-I', sem: 3, branches: ['CE', 'CE-LE'], type: 'Theory' },
  { id: 303, name: 'Concrete Technology', sem: 3, branches: ['CE', 'CE-LE'], type: 'Theory' },
  { id: 304, name: 'Chemical Process Calc', sem: 3, branches: ['PCE'], type: 'Theory' },
  { id: 305, name: 'Fluid Flow', sem: 3, branches: ['PCE', 'PT'], type: 'Theory' },
  { id: 306, name: 'Resins & Polymers', sem: 3, branches: ['PT'], type: 'Theory' },
  
  // Sem 4
  { id: 401, name: 'Soil Mechanics', sem: 4, branches: ['CE', 'CE-LE'], type: 'Theory' },
  { id: 402, name: 'RCC Design', sem: 4, branches: ['CE', 'CE-LE'], type: 'Theory' },
  { id: 403, name: 'Heat Transfer', sem: 4, branches: ['PCE', 'PT'], type: 'Theory' },
  { id: 404, name: 'Mass Transfer', sem: 4, branches: ['PCE'], type: 'Theory' },
];

// --- Main App Component ---

export default function App() {
  const [activeTab, setActiveTab] = useState('dashboard');
  const [selectedBranch, setSelectedBranch] = useState(BRANCHES[0]);
  const [selectedSem, setSelectedSem] = useState(1);
  const [timetable, setTimetable] = useState([]); 
  const [notifications, setNotifications] = useState([]);

  // Filtered Subjects for current selection
  const availableSubjects = useMemo(() => {
    return INITIAL_SUBJECTS.filter(s => s.sem === selectedSem && s.branches.includes(selectedBranch.id));
  }, [selectedSem, selectedBranch]);

  const addNotification = (msg, type = 'info', details = null) => {
    const id = Date.now();
    setNotifications(prev => [...prev, { id, msg, type, details }]);
    setTimeout(() => setNotifications(prev => prev.filter(n => n.id !== id)), 6000);
  };

  const handleAddEntry = (day, slotId, subjectId, facultyId, roomId) => {
    const faculty = INITIAL_FACULTY.find(f => f.id === parseInt(facultyId));
    const subject = INITIAL_SUBJECTS.find(s => s.id === parseInt(subjectId));

    // Conflict Check 1: Faculty busy in another branch/semester?
    const facultyConflict = timetable.find(e => e.day === day && e.slotId === slotId && e.facultyId === parseInt(facultyId));
    if (facultyConflict) {
      const conflictBranch = BRANCHES.find(b => b.id === facultyConflict.branchId)?.name;
      addNotification(
        `Faculty Conflict!`, 
        'error', 
        `${faculty?.name} is already assigned to ${conflictBranch} (Sem ${facultyConflict.sem}) in this slot.`
      );
      return;
    }

    // Conflict Check 2: Room busy?
    if (roomId && roomId.trim() !== "") {
      const roomConflict = timetable.find(e => e.day === day && e.slotId === slotId && e.roomId.toLowerCase() === roomId.toLowerCase());
      if (roomConflict) {
        const conflictBranch = BRANCHES.find(b => b.id === roomConflict.branchId)?.name;
        addNotification(
          `Room Conflict!`, 
          'error', 
          `Room ${roomId} is occupied by ${conflictBranch} (Sem ${roomConflict.sem}).`
        );
        return;
      }
    }

    // Conflict Check 3: Current Branch/Sem already has a class here?
    const classOverlap = timetable.find(e => e.day === day && e.slotId === slotId && e.branchId === selectedBranch.id && e.sem === selectedSem);
    if (classOverlap) {
        addNotification(`Schedule Overlap!`, 'error', `This branch and semester already have a class scheduled for this slot.`);
        return;
    }

    const newEntry = { 
      id: Date.now(),
      branchId: selectedBranch.id, 
      sem: selectedSem, 
      day, 
      slotId, 
      subjectId: parseInt(subjectId), 
      facultyId: parseInt(facultyId), 
      roomId 
    };

    setTimetable(prev => [...prev, newEntry]);
    addNotification('Entry added successfully', 'success');
  };

  const removeEntry = (id) => {
    setTimetable(prev => prev.filter(e => e.id !== id));
  };

  // Views
  const Dashboard = () => (
    <div className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <StatCard icon={<Layout size={24} />} label="Total Branches" value={BRANCHES.length} color="bg-blue-500" />
        <StatCard icon={<Users size={24} />} label="Active Faculty" value={INITIAL_FACULTY.length} color="bg-green-500" />
        <StatCard icon={<BookOpen size={24} />} label="Current Semester" value="Odd (2025-26)" color="bg-purple-500" />
        <StatCard icon={<AlertTriangle size={24} />} label="Global Conflicts" value={0} color="bg-orange-500" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="bg-white p-6 rounded-xl shadow-sm border border-slate-200">
          <h3 className="text-lg font-bold mb-4">Branch Status</h3>
          <div className="overflow-x-auto">
            <table className="w-full text-left">
              <thead>
                <tr className="border-b border-slate-100 text-slate-500 text-sm">
                  <th className="py-3 px-4">Branch</th>
                  <th className="py-3 px-4">Type</th>
                  <th className="py-3 px-4">Classes</th>
                </tr>
              </thead>
              <tbody>
                {BRANCHES.map(b => (
                  <tr key={b.id} className="border-b border-slate-50 last:border-0 hover:bg-slate-50">
                    <td className="py-3 px-4 font-medium">{b.name}</td>
                    <td className="py-3 px-4">
                      <span className={`px-2 py-1 rounded-full text-[10px] font-bold ${b.lateral ? 'bg-amber-100 text-amber-700' : 'bg-blue-100 text-blue-700'}`}>
                        {b.lateral ? 'LATERAL' : 'REGULAR'}
                      </span>
                    </td>
                    <td className="py-3 px-4 text-sm text-slate-500">
                        {timetable.filter(e => e.branchId === b.id).length} slots filled
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <div className="bg-white p-6 rounded-xl shadow-sm border border-slate-200">
          <div className="flex justify-between items-center mb-4">
            <h3 className="text-lg font-bold">Conflict Monitor</h3>
            <span className="text-[10px] bg-green-100 text-green-700 px-2 py-1 rounded font-bold">SYSTEM STABLE</span>
          </div>
          <div className="flex flex-col items-center justify-center h-48 border-2 border-dashed border-slate-50 rounded-xl text-slate-400">
             <CheckCircle size={32} className="mb-2 text-green-500 opacity-50" />
             <p className="text-sm">No cross-departmental conflicts detected.</p>
          </div>
        </div>
      </div>
    </div>
  );

  const TimetableBuilder = () => {
    const [entryForm, setEntryForm] = useState(null);

    // Lateral Entry semester logic
    useEffect(() => {
        if (selectedBranch.lateral && selectedSem < 3) {
            setSelectedSem(3);
        }
    }, [selectedBranch]);

    return (
      <div className="space-y-4">
        {/* Controls */}
        <div className="flex flex-wrap gap-4 bg-white p-4 rounded-xl shadow-sm border border-slate-200 items-end">
          <div className="flex-1 min-w-[200px] space-y-1">
            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Select Branch</label>
            <div className="relative">
              <select 
                className="w-full p-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm font-bold focus:ring-2 focus:ring-blue-500 outline-none appearance-none cursor-pointer"
                value={selectedBranch.id}
                onChange={(e) => setSelectedBranch(BRANCHES.find(b => b.id === e.target.value))}
              >
                {BRANCHES.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
              </select>
              <ChevronRight className="absolute right-3 top-3 text-slate-400 rotate-90 pointer-events-none" size={16} />
            </div>
          </div>
          <div className="w-48 space-y-1">
            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Semester</label>
            <div className="relative">
              <select 
                className="w-full p-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm font-bold focus:ring-2 focus:ring-blue-500 outline-none appearance-none cursor-pointer"
                value={selectedSem}
                onChange={(e) => setSelectedSem(parseInt(e.target.value))}
              >
                {SEMESTERS.filter(s => selectedBranch.lateral ? s.no > 2 : true).map(s => (
                  <option key={s.no} value={s.no}>SEM {s.no} ({s.type})</option>
                ))}
              </select>
              <ChevronRight className="absolute right-3 top-3 text-slate-400 rotate-90 pointer-events-none" size={16} />
            </div>
          </div>
          <button 
            onClick={() => window.print()}
            className="bg-slate-800 text-white h-[42px] px-6 rounded-lg flex items-center gap-2 hover:bg-slate-900 transition-all font-bold text-sm shadow-lg shadow-slate-200"
          >
            <Printer size={18} /> Print
          </button>
        </div>

        {/* Grid View */}
        <div className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full border-collapse">
              <thead>
                <tr className="bg-slate-900 text-white">
                  <th className="p-5 border-r border-slate-700 w-40 text-left">
                    <div className="text-[10px] font-black opacity-50 uppercase tracking-widest mb-1">Time Slot</div>
                    <div className="text-sm font-bold">Schedule</div>
                  </th>
                  {DAYS.map(day => (
                    <th key={day} className="p-5 text-center">
                        <div className="text-xs font-black tracking-widest">{day}</div>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {TIME_SLOTS.map(slot => (
                  <tr key={slot.id} className={`border-b border-slate-100 ${slot.isBreak ? 'bg-slate-50/50' : ''}`}>
                    <td className="p-5 border-r border-slate-100 bg-slate-50/30">
                      <div className="font-black text-slate-800 text-sm leading-tight">{slot.label}</div>
                      <div className="text-[10px] text-slate-500 font-bold mt-1 flex items-center gap-1">
                        <Clock size={10} /> {slot.time}
                      </div>
                    </td>
                    {DAYS.map(day => {
                      const entry = timetable.find(e => e.day === day && e.slotId === slot.id && e.branchId === selectedBranch.id && e.sem === selectedSem);
                      
                      if (slot.isBreak) return <td key={day} className="p-5 text-center italic text-slate-300 font-black text-[10px] tracking-widest">LUNCH</td>;

                      return (
                        <td key={day} className="p-2 min-w-[160px] relative group h-24">
                          {entry ? (
                            <div className={`h-full p-3 rounded-xl border flex flex-col justify-between shadow-sm transition-all group-hover:scale-[1.02] ${entry.subjectId > 300 ? 'bg-indigo-50 border-indigo-200 text-indigo-900' : 'bg-blue-50 border-blue-200 text-blue-900'}`}>
                              <button 
                                onClick={() => removeEntry(entry.id)}
                                className="absolute -top-1 -right-1 opacity-0 group-hover:opacity-100 p-1 bg-red-500 text-white rounded-full shadow-lg hover:bg-red-600 transition-all z-10"
                              >
                                <X size={10} />
                              </button>
                              <div className="text-[11px] font-black uppercase leading-tight line-clamp-2">
                                {INITIAL_SUBJECTS.find(s => s.id === entry.subjectId)?.name}
                              </div>
                              <div className="mt-auto space-y-0.5">
                                <div className="text-[9px] font-bold opacity-60 flex items-center truncate">
                                    <Users size={8} className="mr-1 shrink-0" /> {INITIAL_FACULTY.find(f => f.id === entry.facultyId)?.name}
                                </div>
                                {entry.roomId && (
                                    <div className="text-[9px] font-bold opacity-60 flex items-center">
                                        <MapPin size={8} className="mr-1 shrink-0" /> {entry.roomId}
                                    </div>
                                )}
                              </div>
                            </div>
                          ) : (
                            <button 
                              onClick={() => setEntryForm({ day, slotId: slot.id })}
                              className="w-full h-full border-2 border-dashed border-slate-100 rounded-xl flex items-center justify-center text-slate-200 hover:border-blue-300 hover:bg-blue-50 hover:text-blue-400 transition-all"
                            >
                              <Plus size={20} />
                            </button>
                          )}
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Add Entry Modal */}
        {entryForm && (
          <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-md flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-3xl p-8 w-full max-w-md shadow-2xl animate-in fade-in zoom-in duration-300">
              <div className="flex justify-between items-center mb-8">
                <div>
                    <h3 className="text-2xl font-black text-slate-800">Schedule Slot</h3>
                    <p className="text-slate-400 text-xs font-bold uppercase tracking-widest mt-1">
                        {entryForm.day} • {TIME_SLOTS.find(s => s.id === entryForm.slotId)?.time}
                    </p>
                </div>
                <button onClick={() => setEntryForm(null)} className="p-2 bg-slate-100 rounded-full text-slate-500 hover:bg-slate-200 transition-all">
                    <X size={20} />
                </button>
              </div>
              
              <form onSubmit={(e) => {
                e.preventDefault();
                const fd = new FormData(e.target);
                handleAddEntry(entryForm.day, entryForm.slotId, fd.get('subjectId'), fd.get('facultyId'), fd.get('roomId'));
                setEntryForm(null);
              }} className="space-y-5">
                
                <div className="space-y-1.5">
                  <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Subject</label>
                  <select name="subjectId" required className="w-full p-3 bg-slate-50 border-2 border-slate-100 rounded-xl font-bold text-sm focus:border-blue-500 outline-none transition-all">
                    <option value="">Choose Subject...</option>
                    {availableSubjects.map(s => <option key={s.id} value={s.id}>{s.name} ({s.type})</option>)}
                  </select>
                </div>

                <div className="space-y-1.5">
                  <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Faculty Member</label>
                  <select name="facultyId" required className="w-full p-3 bg-slate-50 border-2 border-slate-100 rounded-xl font-bold text-sm focus:border-blue-500 outline-none transition-all">
                    <option value="">Assign Faculty...</option>
                    {INITIAL_FACULTY.map(f => <option key={f.id} value={f.id}>{f.name} ({f.designation})</option>)}
                  </select>
                </div>

                <div className="space-y-1.5">
                  <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Room / Lab</label>
                  <input name="roomId" type="text" placeholder="e.g. CR-01, Lab-A" className="w-full p-3 bg-slate-50 border-2 border-slate-100 rounded-xl font-bold text-sm focus:border-blue-500 outline-none transition-all" />
                </div>

                <button type="submit" className="w-full bg-blue-600 text-white py-4 rounded-2xl font-black text-sm shadow-xl shadow-blue-200 hover:bg-blue-700 transition-all active:scale-[0.98] mt-4 uppercase tracking-widest">
                  Confirm Schedule
                </button>
              </form>
            </div>
          </div>
        )}
      </div>
    );
  };

  const FacultyView = () => (
    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
      <div className="md:col-span-1">
        <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
          <div className="relative mb-6">
            <Search className="absolute left-3 top-3 text-slate-400" size={18} />
            <input 
                type="text" 
                placeholder="Search faculty..." 
                className="w-full pl-10 p-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div className="space-y-2 max-h-[500px] overflow-y-auto pr-2 custom-scrollbar">
            {INITIAL_FACULTY.map(f => (
              <div key={f.id} className="flex items-center p-3 rounded-xl border border-transparent hover:border-blue-100 hover:bg-blue-50/30 transition-all cursor-pointer group">
                <div className="w-10 h-10 rounded-xl bg-slate-100 text-slate-600 flex items-center justify-center font-black mr-4 group-hover:bg-blue-600 group-hover:text-white transition-all">
                  {f.name.split(' ').map(n => n[0]).join('')}
                </div>
                <div>
                  <div className="text-sm font-bold text-slate-800">{f.name}</div>
                  <div className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{f.designation}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="md:col-span-2 space-y-6">
        <div className="bg-blue-900 text-white p-10 rounded-3xl relative overflow-hidden shadow-2xl">
            <div className="relative z-10">
                <h3 className="text-3xl font-black mb-2">Workload Analysis</h3>
                <p className="text-blue-200 max-w-sm">Detailed breakdown of teaching hours, administrative duties, and laboratory oversight.</p>
                <div className="mt-8 grid grid-cols-3 gap-4">
                    <div className="bg-white/10 p-4 rounded-2xl">
                        <div className="text-xs font-bold text-blue-300 uppercase mb-1">Total Hours</div>
                        <div className="text-2xl font-black">24h</div>
                    </div>
                    <div className="bg-white/10 p-4 rounded-2xl">
                        <div className="text-xs font-bold text-blue-300 uppercase mb-1">Labs</div>
                        <div className="text-2xl font-black">06h</div>
                    </div>
                    <div className="bg-white/10 p-4 rounded-2xl">
                        <div className="text-xs font-bold text-blue-300 uppercase mb-1">Theory</div>
                        <div className="text-2xl font-black">18h</div>
                    </div>
                </div>
            </div>
            <Users size={120} className="absolute -right-10 -bottom-10 text-white/10 rotate-12" />
        </div>
      </div>
    </div>
  );

  return (
    <div className="min-h-screen bg-slate-50 flex flex-col md:flex-row font-sans text-slate-900 overflow-hidden">
      {/* Sidebar */}
      <nav className="w-full md:w-72 bg-white border-r border-slate-200 flex flex-col shrink-0 z-40">
        <div className="p-8">
          <div className="flex items-center gap-3 mb-10">
            <div className="w-10 h-10 bg-indigo-600 rounded-2xl flex items-center justify-center text-white font-black italic shadow-lg shadow-indigo-100">P</div>
            <div>
                <span className="block font-black text-xl tracking-tighter leading-none">POLY<span className="text-indigo-600">ERP</span></span>
                <span className="text-[9px] font-black text-slate-400 uppercase tracking-[0.2em]">Management</span>
            </div>
          </div>
          
          <div className="space-y-1.5">
            <NavItem active={activeTab === 'dashboard'} onClick={() => setActiveTab('dashboard')} icon={<Layout size={20}/>} label="Overview" />
            <NavItem active={activeTab === 'timetable'} onClick={() => setActiveTab('timetable')} icon={<Calendar size={20}/>} label="Master Planner" />
            <NavItem active={activeTab === 'faculty'} onClick={() => setActiveTab('faculty')} icon={<Users size={20}/>} label="Faculty Roster" />
            <NavItem active={activeTab === 'exams'} onClick={() => setActiveTab('exams')} icon={<ShieldCheck size={20}/>} label="Exams & Sessional" />
          </div>
        </div>
        
        <div className="mt-auto p-6 m-4 bg-slate-50 rounded-2xl border border-slate-100">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-white border border-slate-200 shadow-sm flex items-center justify-center font-black text-indigo-600">AS</div>
            <div className="overflow-hidden">
              <div className="text-xs font-black text-slate-800 truncate">Atul Sharma</div>
              <div className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Principal</div>
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content Area */}
      <main className="flex-1 p-8 md:p-12 overflow-y-auto h-screen print:p-0 print:h-auto print:bg-white relative">
        {/* Header */}
        <header className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-10 print:hidden">
          <div>
            <h1 className="text-4xl font-black tracking-tight text-slate-900 capitalize leading-none">
              {activeTab === 'timetable' ? 'Academic Planner' : activeTab.replace('_', ' ')}
            </h1>
            <p className="text-slate-400 font-bold text-sm mt-2">Manage institution-wide scheduling and resources.</p>
          </div>
          <div className="bg-white px-5 py-3 rounded-2xl border border-slate-200 shadow-sm flex items-center gap-4">
            <div className="text-right">
              <div className="text-[9px] font-black text-slate-400 uppercase tracking-widest">System Time</div>
              <div className="text-xs font-black text-slate-700">Feb 2026 • Cycle 1</div>
            </div>
            <div className="w-px h-8 bg-slate-100"></div>
            <div className="p-2 bg-indigo-50 text-indigo-600 rounded-xl">
                <Calendar size={18} />
            </div>
          </div>
        </header>

        {/* Improved Notification System */}
        <div className="fixed top-6 right-6 z-[100] space-y-3 max-w-sm pointer-events-none">
          {notifications.map(n => (
            <div key={n.id} className={`p-5 rounded-2xl shadow-2xl flex flex-col gap-1 border-l-4 animate-in slide-in-from-right pointer-events-auto ${n.type === 'error' ? 'bg-white border-red-500' : (n.type === 'success' ? 'bg-white border-green-500' : 'bg-white border-blue-500')}`}>
              <div className="flex items-center gap-3">
                {n.type === 'error' ? <AlertCircle size={18} className="text-red-500"/> : <CheckCircle size={18} className="text-green-500"/>}
                <span className="text-sm font-black text-slate-800">{n.msg}</span>
              </div>
              {n.details && <p className="text-[11px] text-slate-500 font-medium ml-7">{n.details}</p>}
            </div>
          ))}
        </div>

        {/* Dynamic Views */}
        <div className="animate-in fade-in slide-in-from-bottom-2 duration-700">
          {activeTab === 'dashboard' && <Dashboard />}
          {activeTab === 'timetable' && <TimetableBuilder />}
          {activeTab === 'faculty' && <FacultyView />}
          {activeTab === 'exams' && (
            <div className="flex flex-col items-center justify-center py-20 text-center">
                 <div className="w-20 h-20 bg-amber-50 rounded-3xl flex items-center justify-center text-amber-500 mb-6">
                    <ShieldCheck size={40} />
                 </div>
                 <h2 className="text-2xl font-black">Sessional Hub</h2>
                 <p className="text-slate-500 max-w-xs mt-2">Schedule mid-term assessments and final practical exams for the current semester.</p>
                 <button className="mt-8 bg-slate-900 text-white px-8 py-3 rounded-2xl font-black text-sm uppercase tracking-widest hover:bg-black transition-all">
                    Initiate Exam Drive
                 </button>
            </div>
          )}
        </div>
      </main>

      {/* Global CSS for Print and Custom UI */}
      <style>{`
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap');
        
        * { font-family: 'Inter', sans-serif; }

        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 10px; }

        @media print {
          nav, header, button, .notifications, .fixed { display: none !important; }
          main { padding: 0 !important; margin: 0 !important; width: 100% !important; height: auto !important; overflow: visible !important; }
          .bg-slate-50 { background-color: white !important; }
          .rounded-2xl, .rounded-xl { border-radius: 0 !important; border: 1px solid #eee !important; }
          table { width: 100% !important; border-collapse: collapse !important; font-size: 10px !important; }
          th, td { border: 1px solid #ddd !important; padding: 4px !important; height: auto !important; }
          .p-2, .p-3, .p-5 { padding: 4px !important; }
          .bg-slate-900 { background-color: #f8fafc !important; color: black !important; }
          .bg-blue-50, .bg-indigo-50 { background-color: transparent !important; }
        }
      `}</style>
    </div>
  );
}

// --- Sub-components ---

function NavItem({ icon, label, active, onClick }) {
  return (
    <button 
      onClick={onClick}
      className={`w-full flex items-center gap-3 px-5 py-3.5 rounded-2xl text-sm font-black transition-all ${active ? 'bg-indigo-600 text-white shadow-xl shadow-indigo-100' : 'text-slate-400 hover:text-slate-800 hover:bg-slate-50'}`}
    >
      <span className={active ? 'text-white' : 'text-slate-400'}>{icon}</span>
      {label}
    </button>
  );
}

function StatCard({ icon, label, value, color }) {
  return (
    <div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-200 hover:border-indigo-100 transition-all">
      <div className="flex items-center gap-5">
        <div className={`w-14 h-14 rounded-2xl text-white flex items-center justify-center shadow-lg ${color}`}>
          {icon}
        </div>
        <div>
          <div className="text-[10px] font-black text-slate-400 uppercase tracking-widest leading-none mb-1">{label}</div>
          <div className="text-3xl font-black text-slate-900 tracking-tighter">{value}</div>
        </div>
      </div>
    </div>
  );
}