import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

export default function AdminDashboard() {
  const navigate = useNavigate();
  const [token, setToken] = useState(localStorage.getItem('adminToken') || '');
  const [username, setUsername] = useState(localStorage.getItem('adminUsername') || '');
  const [isSetupNeeded, setIsSetupNeeded] = useState(false);
  const [activeTab, setActiveTab] = useState('dashboard');
  
  // Auth Form State
  const [authForm, setAuthForm] = useState({ username: '', password: '' });
  const [authError, setAuthError] = useState('');
  const [authSuccess, setAuthSuccess] = useState('');

  // Dashboard Data State
  const [notices, setNotices] = useState([]);
  const [events, setEvents] = useState([]);
  const [admissions, setAdmissions] = useState([]);
  const [contactMessages, setContactMessages] = useState([]);
  const [faculty, setFaculty] = useState([]);
  const [gallery, setGallery] = useState([]);
  const [achievements, setAchievements] = useState([]);
  const [students, setStudents] = useState([]);
  const [cmsPages, setCmsPages] = useState([]);
  const [downloads, setDownloads] = useState([]);
  const [activityLogs, setActivityLogs] = useState([]);
  const [backups, setBackups] = useState([]);
  const [settings, setSettings] = useState({
    schoolName: 'St. Andrews Academy',
    tagline: 'Where Learning Becomes an Adventure',
    logo: '',
    email: 'info@standrews.edu',
    phone: '+1 (555) 123-4567',
    address: '123 Education Lane, Learning City, LC 12345',
    facebookUrl: 'https://facebook.com',
    twitterUrl: 'https://twitter.com',
    instagramUrl: 'https://instagram.com',
    youtubeUrl: 'https://youtube.com'
  });
  
  // Stats
  const [stats, setStats] = useState({
    noticesCount: 0,
    eventsCount: 0,
    admissionsCount: 0,
    messagesCount: 0,
    facultyCount: 0,
    galleryCount: 0,
    achievementsCount: 0,
    studentsCount: 0,
    pagesCount: 0,
    downloadsCount: 0
  });

  // Modal / Form States
  const [noticeForm, setNoticeForm] = useState({ title: '', content: '', category: 'General' });
  const [eventForm, setEventForm] = useState({ title: '', description: '', category: 'Event', image: '' });
  const [facultyForm, setFacultyForm] = useState({ name: '', designation: '', department: 'Science', qualification: '', image: '' });
  const [galleryForm, setGalleryForm] = useState({ title: '', category: 'Campus', imageUrl: '' });
  const [achievementForm, setAchievementForm] = useState({
    title: '', recipient: '', category: 'Academic', year: new Date().getFullYear().toString(),
    featured: false, status: 'Published', image: '', description: ''
  });
  const [studentForm, setStudentForm] = useState({ name: '', rollNo: '', grade: 'Nursery', guardianName: '', phone: '', status: 'Active' });
  const [cmsForm, setCmsForm] = useState({ title: '', slug: '', content: '', status: 'Draft' });
  const [downloadForm, setDownloadForm] = useState({ title: '', category: 'Circular', fileUrl: '' });

  // Search & Filters for Achievements
  const [achQuery, setAchQuery] = useState('');
  const [achCatFilter, setAchCatFilter] = useState('');
  const [achStatusFilter, setAchStatusFilter] = useState('');

  const [editingId, setEditingId] = useState(null);
  const [formError, setFormError] = useState('');
  const [formSuccess, setFormSuccess] = useState('');

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

  useEffect(() => {
    if (token) {
      fetchDashboardData();
    }
  }, [token]);

  const checkSetup = async () => {
    try {
      const res = await axios.get('http://localhost:5000/api/auth/setup-check');
      setIsSetupNeeded(res.data.setupNeeded);
    } catch (err) {
      console.error(err);
    }
  };

  const fetchDashboardData = async () => {
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      const [noticesRes, eventsRes, admissionsRes, contactRes, facultyRes, galleryRes, achievementsRes, studentsRes, cmsRes, downloadsRes, logsRes, backupsRes, settingsRes] = await Promise.all([
        axios.get('http://localhost:5000/api/notices'),
        axios.get('http://localhost:5000/api/events'),
        axios.get('http://localhost:5000/api/admissions', config),
        axios.get('http://localhost:5000/api/contact', config),
        axios.get('http://localhost:5000/api/faculty'),
        axios.get('http://localhost:5000/api/gallery'),
        axios.get('http://localhost:5000/api/achievements'),
        axios.get('http://localhost:5000/api/students', config),
        axios.get('http://localhost:5000/api/cms-pages'),
        axios.get('http://localhost:5000/api/downloads'),
        axios.get('http://localhost:5000/api/activity-logs', config),
        axios.get('http://localhost:5000/api/backups', config),
        axios.get('http://localhost:5000/api/settings')
      ]);

      setNotices(noticesRes.data);
      setEvents(eventsRes.data);
      setAdmissions(admissionsRes.data);
      setContactMessages(contactRes.data);
      setFaculty(facultyRes.data);
      setGallery(galleryRes.data);
      setAchievements(achievementsRes.data);
      setStudents(studentsRes.data);
      setCmsPages(cmsRes.data);
      setDownloads(downloadsRes.data);
      setActivityLogs(logsRes.data);
      setBackups(backupsRes.data);
      setSettings(settingsRes.data);

      setStats({
        noticesCount: noticesRes.data.length,
        eventsCount: eventsRes.data.length,
        admissionsCount: admissionsRes.data.length,
        messagesCount: contactRes.data.length,
        facultyCount: facultyRes.data.length,
        galleryCount: galleryRes.data.length,
        achievementsCount: achievementsRes.data.length,
        studentsCount: studentsRes.data.length,
        pagesCount: cmsRes.data.length,
        downloadsCount: downloadsRes.data.length
      });
    } catch (err) {
      console.error("Error fetching dashboard data", err);
      if (err.response?.status === 401 || err.response?.status === 400) {
        handleLogout();
      }
    }
  };

  const handleAuthSubmit = async (e) => {
    e.preventDefault();
    setAuthError('');
    setAuthSuccess('');

    const endpoint = isSetupNeeded ? 'register' : 'login';
    try {
      const res = await axios.post(`http://localhost:5000/api/auth/${endpoint}`, authForm);
      if (isSetupNeeded) {
        setAuthSuccess('Admin account created! Please login.');
        setIsSetupNeeded(false);
        setAuthForm({ username: '', password: '' });
      } else {
        localStorage.setItem('adminToken', res.data.token);
        localStorage.setItem('adminUsername', res.data.username);
        setToken(res.data.token);
        setUsername(res.data.username);
      }
    } catch (err) {
      setAuthError(err.response?.data?.message || 'Authentication failed.');
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('adminToken');
    localStorage.removeItem('adminUsername');
    setToken('');
    setUsername('');
    setActiveTab('dashboard');
    navigate('/');
  };

  // Base64 File Reader helper
  const handleFileChange = (e, setForm, formState) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onloadend = () => {
      setForm({ ...formState, [e.target.name]: reader.result });
    };
    reader.readAsDataURL(file);
  };

  // CRUD Actions
  const handleAddNotice = async (e) => {
    e.preventDefault();
    setFormError('');
    setFormSuccess('');
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      if (editingId) {
        await axios.put(`http://localhost:5000/api/notices/${editingId}`, noticeForm, config);
        setFormSuccess('Notice updated successfully!');
      } else {
        await axios.post('http://localhost:5000/api/notices', noticeForm, config);
        setFormSuccess('Notice created successfully!');
      }
      setNoticeForm({ title: '', content: '', category: 'General' });
      setEditingId(null);
      fetchDashboardData();
    } catch (err) {
      setFormError('Failed to save notice.');
    }
  };

  const handleAddEvent = async (e) => {
    e.preventDefault();
    setFormError('');
    setFormSuccess('');
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      if (editingId) {
        await axios.put(`http://localhost:5000/api/events/${editingId}`, eventForm, config);
        setFormSuccess('Event updated successfully!');
      } else {
        await axios.post('http://localhost:5000/api/events', eventForm, config);
        setFormSuccess('Event created successfully!');
      }
      setEventForm({ title: '', description: '', category: 'Event', image: '' });
      setEditingId(null);
      fetchDashboardData();
    } catch (err) {
      setFormError('Failed to save event.');
    }
  };

  const handleAddFaculty = async (e) => {
    e.preventDefault();
    setFormError('');
    setFormSuccess('');
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      if (editingId) {
        await axios.put(`http://localhost:5000/api/faculty/${editingId}`, facultyForm, config);
        setFormSuccess('Faculty member updated!');
      } else {
        await axios.post('http://localhost:5000/api/faculty', facultyForm, config);
        setFormSuccess('Faculty member added!');
      }
      setFacultyForm({ name: '', designation: '', department: 'Science', qualification: '', image: '' });
      setEditingId(null);
      fetchDashboardData();
    } catch (err) {
      setFormError('Failed to save faculty member.');
    }
  };

  const handleAddGallery = async (e) => {
    e.preventDefault();
    setFormError('');
    setFormSuccess('');
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      await axios.post('http://localhost:5000/api/gallery', galleryForm, config);
      setFormSuccess('Gallery image uploaded successfully!');
      setGalleryForm({ title: '', category: 'Campus', imageUrl: '' });
      fetchDashboardData();
    } catch (err) {
      setFormError('Failed to upload image.');
    }
  };

  const handleAddAchievement = async (e) => {
    e.preventDefault();
    setFormError('');
    setFormSuccess('');
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      if (editingId) {
        await axios.put(`http://localhost:5000/api/achievements/${editingId}`, achievementForm, config);
        setFormSuccess('Achievement updated successfully!');
      } else {
        await axios.post('http://localhost:5000/api/achievements', achievementForm, config);
        setFormSuccess('Achievement created successfully!');
      }
      setAchievementForm({
        title: '', recipient: '', category: 'Academic', year: new Date().getFullYear().toString(),
        featured: false, status: 'Published', image: '', description: ''
      });
      setEditingId(null);
      fetchDashboardData();
    } catch (err) {
      setFormError('Failed to save achievement.');
    }
  };

  const handleAddStudent = async (e) => {
    e.preventDefault();
    setFormError('');
    setFormSuccess('');
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      if (editingId) {
        await axios.put(`http://localhost:5000/api/students/${editingId}`, studentForm, config);
        setFormSuccess('Student updated successfully!');
      } else {
        await axios.post('http://localhost:5000/api/students', studentForm, config);
        setFormSuccess('Student added successfully!');
      }
      setStudentForm({ name: '', rollNo: '', grade: 'Nursery', guardianName: '', phone: '', status: 'Active' });
      setEditingId(null);
      fetchDashboardData();
    } catch (err) {
      setFormError(err.response?.data?.message || 'Failed to save student.');
    }
  };

  const handleAddCmsPage = async (e) => {
    e.preventDefault();
    setFormError('');
    setFormSuccess('');
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      if (editingId) {
        await axios.put(`http://localhost:5000/api/cms-pages/${editingId}`, cmsForm, config);
        setFormSuccess('CMS Page updated successfully!');
      } else {
        await axios.post('http://localhost:5000/api/cms-pages', cmsForm, config);
        setFormSuccess('CMS Page created successfully!');
      }
      setCmsForm({ title: '', slug: '', content: '', status: 'Draft' });
      setEditingId(null);
      fetchDashboardData();
    } catch (err) {
      setFormError(err.response?.data?.message || 'Failed to save CMS Page.');
    }
  };

  const handleAddDownload = async (e) => {
    e.preventDefault();
    setFormError('');
    setFormSuccess('');
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      await axios.post('http://localhost:5000/api/downloads', downloadForm, config);
      setFormSuccess('Document uploaded successfully!');
      setDownloadForm({ title: '', category: 'Circular', fileUrl: '' });
      fetchDashboardData();
    } catch (err) {
      setFormError(err.response?.data?.message || 'Failed to upload document.');
    }
  };

  const handleCreateBackup = async () => {
    setFormError('');
    setFormSuccess('');
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      await axios.post('http://localhost:5000/api/backups', {}, config);
      setFormSuccess('Database backup triggered successfully!');
      fetchDashboardData();
    } catch (err) {
      setFormError('Failed to trigger backup.');
    }
  };

  const handleUpdateSettings = async (e) => {
    e.preventDefault();
    setFormError('');
    setFormSuccess('');
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      await axios.put('http://localhost:5000/api/settings', settings, config);
      setFormSuccess('Website settings published successfully!');
      fetchDashboardData();
    } catch (err) {
      setFormError('Failed to update website settings.');
    }
  };

  const handleFeaturedToggle = async (achievement) => {
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      await axios.put(`http://localhost:5000/api/achievements/${achievement._id}`, {
        featured: !achievement.featured
      }, config);
      fetchDashboardData();
    } catch (err) {
      console.error(err);
    }
  };

  const handleDelete = async (route, id) => {
    if (!window.confirm('Are you sure you want to delete this item?')) return;
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      await axios.delete(`http://localhost:5000/api/${route}/${id}`, config);
      fetchDashboardData();
    } catch (err) {
      console.error(err);
    }
  };

  const handleStatusChange = async (inquiryId, newStatus) => {
    const config = { headers: { Authorization: `Bearer ${token}` } };
    try {
      await axios.put(`http://localhost:5000/api/admissions/${inquiryId}`, { status: newStatus }, config);
      fetchDashboardData();
    } catch (err) {
      console.error(err);
    }
  };

  // Filtered achievements for list search
  const filteredAchievements = achievements.filter(ach => {
    const matchesSearch = ach.title.toLowerCase().includes(achQuery.toLowerCase()) || 
                          ach.recipient.toLowerCase().includes(achQuery.toLowerCase());
    const matchesCat = achCatFilter ? ach.category.toLowerCase() === achCatFilter.toLowerCase() : true;
    const matchesStatus = achStatusFilter ? ach.status.toLowerCase() === achStatusFilter.toLowerCase() : true;
    return matchesSearch && matchesCat && matchesStatus;
  });

  // If not logged in, render the login form
  if (!token) {
    return (
      <div className="min-h-screen bg-surface flex flex-col justify-center py-12 sm:px-6 lg:px-8 font-sans">
        <div className="sm:mx-auto sm:w-full sm:max-w-md text-center">
          <div className="w-16 h-16 mx-auto flex items-center justify-center bg-primary-container text-primary rounded-2xl shadow-inner mb-4">
            <span className="material-symbols-outlined text-[40px]" style={{ fontVariationSettings: "'FILL' 1" }}>shield_person</span>
          </div>
          <h2 className="mt-2 text-center text-3xl font-headline font-extrabold text-primary">
            {isSetupNeeded ? 'Create Admin Account' : 'Admin Console Login'}
          </h2>
          <p className="mt-2 text-sm text-on-surface-variant font-medium">
            {isSetupNeeded ? 'First time setup. Register your portal administrator credentials.' : 'Secure access for St. Andrews Portal managers.'}
          </p>
        </div>

        <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
          <div className="glass-card py-8 px-4 shadow-xl rounded-2xl border border-outline/50 sm:px-10">
            {authError && (
              <div className="mb-4 bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm font-semibold">
                {authError}
              </div>
            )}
            {authSuccess && (
              <div className="mb-4 bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg text-sm font-semibold">
                {authSuccess}
              </div>
            )}
            
            <form onSubmit={handleAuthSubmit} className="space-y-6">
              <div>
                <label className="block text-sm font-bold text-on-surface-variant mb-2">Username</label>
                <input
                  type="text"
                  required
                  value={authForm.username}
                  onChange={(e) => setAuthForm({ ...authForm, username: e.target.value })}
                  placeholder="admin"
                  className="w-full px-4 py-3 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white"
                />
              </div>

              <div>
                <label className="block text-sm font-bold text-on-surface-variant mb-2">Password</label>
                <input
                  type="password"
                  required
                  value={authForm.password}
                  onChange={(e) => setAuthForm({ ...authForm, password: e.target.value })}
                  placeholder="••••••••"
                  className="w-full px-4 py-3 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white"
                />
              </div>

              <button
                type="submit"
                className="w-full py-3 bg-primary text-white rounded-full font-headline font-bold hover:scale-[1.02] active:scale-95 transition-transform shadow-lg shadow-primary/20"
              >
                {isSetupNeeded ? 'Register Admin' : 'Login'}
              </button>
            </form>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-surface flex font-sans">
      {/* Sidebar Navigation */}
      <aside className="w-[280px] bg-white/70 backdrop-blur-md border-r border-outline-variant flex flex-col p-6 fixed h-full z-40 magical-glow">
        <div className="mb-8 flex flex-col items-center">
          <div className="w-16 h-16 mb-3 flex items-center justify-center bg-primary rounded-2xl shadow-lg shadow-primary/20">
            <span className="material-symbols-outlined text-white text-[36px]" style={{ fontVariationSettings: "'FILL' 1" }}>shield_person</span>
          </div>
          <h1 className="text-xl font-headline font-bold text-primary">EduAdmin</h1>
          <p className="text-[10px] text-on-surface-variant tracking-widest uppercase font-bold mt-0.5">Magical Portal</p>
          <p className="text-[11px] text-primary/70 font-semibold mt-2">Logged in: {username}</p>
        </div>

        <nav className="flex-grow space-y-1 overflow-y-auto scrollbar-hide">
          {[
            { id: 'dashboard', label: 'Dashboard', icon: 'dashboard' },
            { id: 'notices', label: 'Announcements', icon: 'campaign' },
            { id: 'events', label: 'News & Events', icon: 'event_note' },
            { id: 'admissions', label: 'Admissions Inquiry', icon: 'how_to_reg' },
            { id: 'students', label: 'Students Directory', icon: 'school' },
            { id: 'faculty', label: 'Faculty Directory', icon: 'group' },
            { id: 'gallery', label: 'Photo Gallery', icon: 'photo_library' },
            { id: 'achievements', label: 'Achievements', icon: 'emoji_events' },
            { id: 'cms', label: 'Website CMS Pages', icon: 'description' },
            { id: 'downloads', label: 'Circulars & Docs', icon: 'download' },
            { id: 'settings', label: 'Website Settings', icon: 'settings' },
            { id: 'messages', label: 'Inbound Messages', icon: 'mail' },
            { id: 'logs', label: 'Activity Logs', icon: 'history' },
            { id: 'backups', label: 'Backup & Restore', icon: 'dns' }
          ].map((item) => (
            <button
              key={item.id}
              onClick={() => {
                setActiveTab(item.id);
                setEditingId(null);
                setFormError('');
                setFormSuccess('');
              }}
              className={`w-full flex items-center gap-3 rounded-full px-5 py-3 text-sm font-semibold transition-all duration-300 hover:translate-x-1 ${
                activeTab === item.id
                  ? 'bg-primary text-white shadow-md shadow-primary/20'
                  : 'text-on-surface-variant hover:bg-primary-container/20 hover:text-primary'
              }`}
            >
              <span className="material-symbols-outlined text-xl">{item.icon}</span>
              {item.label}
            </button>
          ))}
        </nav>

        <button
          onClick={handleLogout}
          className="mt-6 w-full flex items-center gap-3 rounded-full px-5 py-3 text-sm font-semibold text-red-600 hover:bg-red-50 transition-colors"
        >
          <span className="material-symbols-outlined text-xl">logout</span>
          Sign Out
        </button>
      </aside>

      {/* Main Content Area */}
      <main className="ml-[280px] flex-grow min-h-screen flex flex-col p-8 bg-surface-container/10">
        
        {/* Tab contents */}
        {activeTab === 'dashboard' && (
          <div className="space-y-8 animate-fade-in">
            <div className="flex justify-between items-end px-2">
              <div>
                <h2 className="text-4xl font-bold text-on-surface tracking-tight">Institutional Overview <span className="text-primary">✨</span></h2>
                <p className="text-on-surface-variant mt-2 font-medium">Welcome back. Here is the school administrative dashboard.</p>
              </div>
            </div>

            {/* Statistics Widgets */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              <div className="custom-card glass-card p-6 rounded-2xl flex flex-col justify-between h-40 bg-gradient-to-br from-white to-blue-50/50">
                <div className="flex justify-between items-start">
                  <div className="w-12 h-12 rounded-2xl bg-primary/10 flex items-center justify-center text-primary">
                    <span className="material-symbols-outlined text-3xl">how_to_reg</span>
                  </div>
                  <div className="flex items-center gap-1 text-emerald-600 bg-emerald-50 px-3 py-1 rounded-full border border-emerald-100 text-xs font-bold">
                    Active
                  </div>
                </div>
                <div>
                  <h3 className="text-xs text-on-surface-variant font-bold uppercase tracking-widest">Admissions Inquiries</h3>
                  <p className="text-3xl font-bold text-on-surface mt-1">{stats.admissionsCount}</p>
                </div>
              </div>

              <div className="custom-card glass-card p-6 rounded-2xl flex flex-col justify-between h-40 bg-gradient-to-br from-white to-yellow-50/50">
                <div className="flex justify-between items-start">
                  <div className="w-12 h-12 rounded-2xl bg-secondary-container/30 flex items-center justify-center text-secondary">
                    <span className="material-symbols-outlined text-3xl">campaign</span>
                  </div>
                </div>
                <div>
                  <h3 className="text-xs text-on-surface-variant font-bold uppercase tracking-widest">Active Notices</h3>
                  <p className="text-3xl font-bold text-on-surface mt-1">{stats.noticesCount}</p>
                </div>
              </div>

              <div className="custom-card glass-card p-6 rounded-2xl flex flex-col justify-between h-40 bg-gradient-to-br from-white to-peach-50/50">
                <div className="flex justify-between items-start">
                  <div className="w-12 h-12 rounded-2xl bg-tertiary-container/30 flex items-center justify-center text-tertiary">
                    <span className="material-symbols-outlined text-3xl">emoji_events</span>
                  </div>
                </div>
                <div>
                  <h3 className="text-xs text-on-surface-variant font-bold uppercase tracking-widest">Achievements</h3>
                  <p className="text-3xl font-bold text-on-surface mt-1">{stats.achievementsCount}</p>
                </div>
              </div>

              <div className="custom-card glass-card p-6 rounded-2xl flex flex-col justify-between h-40 bg-gradient-to-br from-white to-red-50/50">
                <div className="flex justify-between items-start">
                  <div className="w-12 h-12 rounded-2xl bg-red-100/50 flex items-center justify-center text-red-600">
                    <span className="material-symbols-outlined text-3xl">mail</span>
                  </div>
                  <div className="flex items-center gap-1 text-red-600 bg-red-50 px-3 py-1 rounded-full border border-red-100 text-xs font-bold">
                    Urgent
                  </div>
                </div>
                <div>
                  <h3 className="text-xs text-on-surface-variant font-bold uppercase tracking-widest">Inbound Messages</h3>
                  <p className="text-3xl font-bold text-on-surface mt-1">{stats.messagesCount}</p>
                </div>
              </div>
            </div>

            {/* Quick Actions Panel */}
            <div className="glass-card p-8 rounded-2xl bg-white/40">
              <h3 className="text-xl font-headline font-bold text-primary mb-6">Spellcasting Grid (Quick Actions)</h3>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
                <button 
                  onClick={() => setActiveTab('notices')}
                  className="custom-card glass-card p-6 rounded-2xl text-center group bg-white/60 flex flex-col items-center gap-2"
                >
                  <div className="w-16 h-16 rounded-full bg-primary-container flex items-center justify-center text-primary group-hover:bg-primary group-hover:text-white transition-all shadow-sm">
                    <span className="material-symbols-outlined text-3xl">campaign</span>
                  </div>
                  <span className="text-sm font-bold text-on-surface">Add Notice</span>
                </button>
                <button 
                  onClick={() => setActiveTab('events')}
                  className="custom-card glass-card p-6 rounded-2xl text-center group bg-white/60 flex flex-col items-center gap-2"
                >
                  <div className="w-16 h-16 rounded-full bg-secondary-container flex items-center justify-center text-secondary group-hover:bg-secondary group-hover:text-white transition-all shadow-sm">
                    <span className="material-symbols-outlined text-3xl">event_note</span>
                  </div>
                  <span className="text-sm font-bold text-on-surface">Create Event</span>
                </button>
                <button 
                  onClick={() => setActiveTab('faculty')}
                  className="custom-card glass-card p-6 rounded-2xl text-center group bg-white/60 flex flex-col items-center gap-2"
                >
                  <div className="w-16 h-16 rounded-full bg-tertiary-container flex items-center justify-center text-tertiary group-hover:bg-tertiary group-hover:text-white transition-all shadow-sm">
                    <span className="material-symbols-outlined text-3xl">group</span>
                  </div>
                  <span className="text-sm font-bold text-on-surface">Add Faculty</span>
                </button>
                <button 
                  onClick={() => setActiveTab('achievements')}
                  className="custom-card glass-card p-6 rounded-2xl text-center group bg-white/60 flex flex-col items-center gap-2"
                >
                  <div className="w-16 h-16 rounded-full bg-primary-container flex items-center justify-center text-primary group-hover:bg-primary group-hover:text-white transition-all shadow-sm">
                    <span className="material-symbols-outlined text-3xl">emoji_events</span>
                  </div>
                  <span className="text-sm font-bold text-on-surface">Add Achievement</span>
                </button>
              </div>
            </div>

            {/* Chronicles */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              <div className="glass-card p-8 rounded-2xl bg-white/40 lg:col-span-2">
                <h3 className="text-xl font-bold text-on-surface mb-6">Recent Enquiries</h3>
                <div className="overflow-x-auto">
                  <table className="w-full text-left text-sm">
                    <thead>
                      <tr className="bg-primary/5">
                        <th className="px-4 py-3 text-xs font-bold text-primary uppercase">Student</th>
                        <th className="px-4 py-3 text-xs font-bold text-primary uppercase">Grade</th>
                        <th className="px-4 py-3 text-xs font-bold text-primary uppercase">Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-outline-variant/30">
                      {admissions.slice(0, 3).map((ad) => (
                        <tr key={ad._id} className="hover:bg-white/60">
                          <td className="px-4 py-4 font-bold text-on-surface">{ad.studentName}</td>
                          <td className="px-4 py-4 font-semibold">{ad.grade}</td>
                          <td className="px-4 py-4">
                            <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold ${
                              ad.status === 'Approved' ? 'bg-green-100 text-green-700' :
                              ad.status === 'Rejected' ? 'bg-red-100 text-red-700' : 'bg-yellow-100 text-yellow-700'
                            }`}>{ad.status}</span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
              
              <div className="glass-card p-8 rounded-2xl bg-white/40">
                <h3 className="text-xl font-bold text-on-surface mb-6">Portal Chronicles</h3>
                <div className="space-y-6 relative before:absolute before:left-4 before:top-2 before:bottom-2 before:w-[2px] before:bg-outline-variant">
                  <div className="relative pl-8">
                    <div className="absolute left-2 top-1 w-4 h-4 rounded-full bg-primary border-4 border-white shadow-sm z-10"></div>
                    <p className="text-sm font-bold text-on-surface">Data synced successfully</p>
                    <p className="text-[10px] text-on-surface-variant font-bold uppercase mt-0.5">Just now</p>
                  </div>
                  <div className="relative pl-8">
                    <div className="absolute left-2 top-1 w-4 h-4 rounded-full bg-secondary border-4 border-white shadow-sm z-10"></div>
                    <p className="text-sm font-bold text-on-surface">Active admin: {username}</p>
                    <p className="text-[10px] text-on-surface-variant font-bold uppercase mt-0.5">Online</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Notices tab */}
        {activeTab === 'notices' && (
          <div className="space-y-8 animate-fade-in">
            <div>
              <h2 className="text-3xl font-headline font-bold text-primary">Manage Notices</h2>
              <p className="text-on-surface-variant">Post and edit official announcements.</p>
            </div>

            {formSuccess && <div className="p-4 bg-green-50 border border-green-200 text-green-700 font-semibold rounded-lg text-sm">{formSuccess}</div>}
            {formError && <div className="p-4 bg-red-50 border border-red-200 text-red-700 font-semibold rounded-lg text-sm">{formError}</div>}

            <div className="grid lg:grid-cols-3 gap-8 items-start">
              {/* Form */}
              <div className="glass-card p-6 rounded-2xl bg-white/40 border border-outline/50">
                <h3 className="text-lg font-headline font-bold text-primary mb-4">
                  {editingId ? 'Edit Announcement' : 'Post Announcement'}
                </h3>
                <form onSubmit={handleAddNotice} className="space-y-4">
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Title</label>
                    <input 
                      type="text" 
                      required
                      value={noticeForm.title}
                      onChange={(e) => setNoticeForm({ ...noticeForm, title: e.target.value })}
                      placeholder="Enter notice title"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Category</label>
                    <select 
                      value={noticeForm.category}
                      onChange={(e) => setNoticeForm({ ...noticeForm, category: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    >
                      <option value="General">General</option>
                      <option value="Academic">Academic</option>
                      <option value="Exam">Exam</option>
                      <option value="Admissions">Admissions</option>
                      <option value="Holidays">Holidays</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Content</label>
                    <textarea 
                      required
                      value={noticeForm.content}
                      onChange={(e) => setNoticeForm({ ...noticeForm, content: e.target.value })}
                      placeholder="Write announcement body..."
                      rows="4"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    ></textarea>
                  </div>
                  <div className="flex gap-2">
                    <button type="submit" className="flex-1 bg-primary text-white py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform shadow-md shadow-primary/20 text-sm">
                      {editingId ? 'Update Notice' : 'Post Notice'}
                    </button>
                    {editingId && (
                      <button 
                        type="button" 
                        onClick={() => {
                          setEditingId(null);
                          setNoticeForm({ title: '', content: '', category: 'General' });
                        }}
                        className="bg-gray-200 text-gray-700 px-4 py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform text-sm"
                      >
                        Cancel
                      </button>
                    )}
                  </div>
                </form>
              </div>

              {/* List */}
              <div className="lg:col-span-2 glass-card rounded-2xl overflow-hidden bg-white/40">
                <table className="w-full text-left">
                  <thead className="bg-primary/5 text-xs text-primary uppercase font-bold">
                    <tr>
                      <th className="px-6 py-4">Title</th>
                      <th className="px-6 py-4">Category</th>
                      <th className="px-6 py-4">Date</th>
                      <th className="px-6 py-4 text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-outline-variant/30 text-sm">
                    {notices.map((n) => (
                      <tr key={n._id} className="hover:bg-white/60 transition-colors">
                        <td className="px-6 py-4 font-bold text-on-surface">{n.title}</td>
                        <td className="px-6 py-4">
                          <span className="px-3 py-1 bg-primary-container/20 rounded-full text-xs text-primary font-bold">{n.category}</span>
                        </td>
                        <td className="px-6 py-4 text-on-surface-variant font-medium">{new Date(n.date).toLocaleDateString()}</td>
                        <td className="px-6 py-4 text-right space-x-3">
                          <button 
                            onClick={() => {
                              setEditingId(n._id);
                              setNoticeForm({ title: n.title, content: n.content, category: n.category });
                            }} 
                            className="text-primary hover:underline font-bold"
                          >
                            Edit
                          </button>
                          <button 
                            onClick={() => handleDelete('notices', n._id)} 
                            className="text-red-500 hover:underline font-bold"
                          >
                            Delete
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* Events tab */}
        {activeTab === 'events' && (
          <div className="space-y-8 animate-fade-in">
            <div>
              <h2 className="text-3xl font-headline font-bold text-primary">Manage News &amp; Events</h2>
              <p className="text-on-surface-variant">Update the planner and showcase accomplishments.</p>
            </div>

            {formSuccess && <div className="p-4 bg-green-50 border border-green-200 text-green-700 font-semibold rounded-lg text-sm">{formSuccess}</div>}
            {formError && <div className="p-4 bg-red-50 border border-red-200 text-red-700 font-semibold rounded-lg text-sm">{formError}</div>}

            <div className="grid lg:grid-cols-3 gap-8 items-start">
              {/* Form */}
              <div className="glass-card p-6 rounded-2xl bg-white/40 border border-outline/50">
                <h3 className="text-lg font-headline font-bold text-primary mb-4">
                  {editingId ? 'Edit Event/News' : 'Create Event/News'}
                </h3>
                <form onSubmit={handleAddEvent} className="space-y-4">
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Title</label>
                    <input 
                      type="text" 
                      required
                      value={eventForm.title}
                      onChange={(e) => setEventForm({ ...eventForm, title: e.target.value })}
                      placeholder="Enter title"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Category</label>
                    <select 
                      value={eventForm.category}
                      onChange={(e) => setEventForm({ ...eventForm, category: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    >
                      <option value="Event">Event</option>
                      <option value="News">News</option>
                      <option value="Sports">Sports</option>
                      <option value="Spotlight">Spotlight</option>
                      <option value="Carnival">Carnival</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Image (Optional)</label>
                    <input 
                      type="file" 
                      name="image"
                      accept="image/*"
                      onChange={(e) => handleFileChange(e, setEventForm, eventForm)}
                      className="w-full text-xs text-on-surface-variant file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-bold file:bg-primary/10 file:text-primary hover:file:bg-primary/20"
                    />
                    {eventForm.image && (
                      <img src={eventForm.image} className="w-16 h-16 object-cover rounded-xl mt-2 border-2 border-outline" alt="Preview" />
                    )}
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Description</label>
                    <textarea 
                      required
                      value={eventForm.description}
                      onChange={(e) => setEventForm({ ...eventForm, description: e.target.value })}
                      placeholder="Describe the news or event..."
                      rows="4"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    ></textarea>
                  </div>
                  <div className="flex gap-2">
                    <button type="submit" className="flex-1 bg-primary text-white py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform shadow-md shadow-primary/20 text-sm">
                      Save
                    </button>
                    {editingId && (
                      <button 
                        type="button" 
                        onClick={() => {
                          setEditingId(null);
                          setEventForm({ title: '', description: '', category: 'Event', image: '' });
                        }}
                        className="bg-gray-200 text-gray-700 px-4 py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform text-sm"
                      >
                        Cancel
                      </button>
                    )}
                  </div>
                </form>
              </div>

              {/* List */}
              <div className="lg:col-span-2 glass-card rounded-2xl overflow-hidden bg-white/40">
                <table className="w-full text-left">
                  <thead className="bg-primary/5 text-xs text-primary uppercase font-bold">
                    <tr>
                      <th className="px-6 py-4">Title</th>
                      <th className="px-6 py-4">Category</th>
                      <th className="px-6 py-4">Date</th>
                      <th className="px-6 py-4 text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-outline-variant/30 text-sm">
                    {events.map((e) => (
                      <tr key={e._id} className="hover:bg-white/60 transition-colors">
                        <td className="px-6 py-4 font-bold text-on-surface">{e.title}</td>
                        <td className="px-6 py-4">
                          <span className="px-3 py-1 bg-secondary-container/20 rounded-full text-xs text-secondary font-bold">{e.category}</span>
                        </td>
                        <td className="px-6 py-4 text-on-surface-variant font-medium">{new Date(e.date).toLocaleDateString()}</td>
                        <td className="px-6 py-4 text-right space-x-3">
                          <button 
                            onClick={() => {
                              setEditingId(e._id);
                              setEventForm({ title: e.title, description: e.description, category: e.category, image: e.image });
                            }} 
                            className="text-primary hover:underline font-bold"
                          >
                            Edit
                          </button>
                          <button 
                            onClick={() => handleDelete('events', e._id)} 
                            className="text-red-500 hover:underline font-bold"
                          >
                            Delete
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* Admissions tab */}
        {activeTab === 'admissions' && (
          <div className="space-y-8 animate-fade-in">
            <div>
              <h2 className="text-3xl font-headline font-bold text-primary">Admission Inquiries</h2>
              <p className="text-on-surface-variant">Review registrations and application forms submitted online.</p>
            </div>

            <div className="glass-card rounded-2xl overflow-hidden bg-white/40">
              <table className="w-full text-left">
                <thead className="bg-primary/5 text-xs text-primary uppercase font-bold">
                  <tr>
                    <th className="px-6 py-4">Student</th>
                    <th className="px-6 py-4">Parent</th>
                    <th className="px-6 py-4">Contact Info</th>
                    <th className="px-6 py-4">Grade</th>
                    <th className="px-6 py-4">Status</th>
                    <th className="px-6 py-4 text-right">Action</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-outline-variant/30 text-sm">
                  {admissions.map((ad) => (
                    <tr key={ad._id} className="hover:bg-white/60 transition-colors">
                      <td className="px-6 py-4 font-bold text-primary">{ad.studentName}</td>
                      <td className="px-6 py-4 font-medium">{ad.parentName}</td>
                      <td className="px-6 py-4 text-xs text-on-surface-variant font-semibold">
                        <div>{ad.email}</div>
                        <div className="mt-0.5">{ad.phone}</div>
                      </td>
                      <td className="px-6 py-4 font-bold">{ad.grade}</td>
                      <td className="px-6 py-4">
                        <select 
                          value={ad.status}
                          onChange={(e) => handleStatusChange(ad._id, e.target.value)}
                          className={`px-3 py-1 rounded-full text-xs font-bold border-0 focus:ring-2 cursor-pointer ${
                            ad.status === 'Approved' ? 'bg-green-100 text-green-700 focus:ring-green-500' :
                            ad.status === 'Rejected' ? 'bg-red-100 text-red-700 focus:ring-red-500' :
                            ad.status === 'Contacted' ? 'bg-blue-100 text-blue-700 focus:ring-blue-500' : 'bg-yellow-100 text-yellow-700 focus:ring-yellow-500'
                          }`}
                        >
                          <option value="Pending">Pending</option>
                          <option value="Contacted">Contacted</option>
                          <option value="Approved">Approved</option>
                          <option value="Rejected">Rejected</option>
                        </select>
                      </td>
                      <td className="px-6 py-4 text-right">
                        <button 
                          onClick={() => handleDelete('admissions', ad._id)}
                          className="text-red-500 hover:underline font-bold"
                        >
                          Delete
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Faculty tab */}
        {activeTab === 'faculty' && (
          <div className="space-y-8 animate-fade-in">
            <div>
              <h2 className="text-3xl font-headline font-bold text-primary">Manage Faculty Directory</h2>
              <p className="text-on-surface-variant">Register and update teacher profiles on the portal.</p>
            </div>

            {formSuccess && <div className="p-4 bg-green-50 border border-green-200 text-green-700 font-semibold rounded-lg text-sm">{formSuccess}</div>}
            {formError && <div className="p-4 bg-red-50 border border-red-200 text-red-700 font-semibold rounded-lg text-sm">{formError}</div>}

            <div className="grid lg:grid-cols-3 gap-8 items-start">
              {/* Form */}
              <div className="glass-card p-6 rounded-2xl bg-white/40 border border-outline/50">
                <h3 className="text-lg font-headline font-bold text-primary mb-4">
                  {editingId ? 'Edit Profile' : 'Add Teacher'}
                </h3>
                <form onSubmit={handleAddFaculty} className="space-y-4">
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Name</label>
                    <input 
                      type="text" 
                      required
                      value={facultyForm.name}
                      onChange={(e) => setFacultyForm({ ...facultyForm, name: e.target.value })}
                      placeholder="e.g. Julian Vance"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Designation</label>
                    <input 
                      type="text" 
                      required
                      value={facultyForm.designation}
                      onChange={(e) => setFacultyForm({ ...facultyForm, designation: e.target.value })}
                      placeholder="e.g. Physics Teacher"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Department</label>
                    <select 
                      value={facultyForm.department}
                      onChange={(e) => setFacultyForm({ ...facultyForm, department: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    >
                      <option value="Leadership">Leadership</option>
                      <option value="Science">Science</option>
                      <option value="Languages">Languages</option>
                      <option value="Mathematics">Mathematics</option>
                      <option value="Arts">Arts</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Qualification</label>
                    <input 
                      type="text"
                      value={facultyForm.qualification}
                      onChange={(e) => setFacultyForm({ ...facultyForm, qualification: e.target.value })}
                      placeholder="e.g. PhD in Physics"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Avatar Photo</label>
                    <input 
                      type="file" 
                      name="image"
                      accept="image/*"
                      onChange={(e) => handleFileChange(e, setFacultyForm, facultyForm)}
                      className="w-full text-xs text-on-surface-variant file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-bold file:bg-primary/10 file:text-primary hover:file:bg-primary/20"
                    />
                    {facultyForm.image && (
                      <img src={facultyForm.image} className="w-16 h-16 object-cover rounded-full mt-2 border-2 border-outline" alt="Preview" />
                    )}
                  </div>
                  <div className="flex gap-2">
                    <button type="submit" className="flex-1 bg-primary text-white py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform shadow-md shadow-primary/20 text-sm">
                      Save
                    </button>
                    {editingId && (
                      <button 
                        type="button" 
                        onClick={() => {
                          setEditingId(null);
                          setFacultyForm({ name: '', designation: '', department: 'Science', qualification: '', image: '' });
                        }}
                        className="bg-gray-200 text-gray-700 px-4 py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform text-sm"
                      >
                        Cancel
                      </button>
                    )}
                  </div>
                </form>
              </div>

              {/* List */}
              <div className="lg:col-span-2 glass-card rounded-2xl overflow-hidden bg-white/40">
                <table className="w-full text-left">
                  <thead className="bg-primary/5 text-xs text-primary uppercase font-bold">
                    <tr>
                      <th className="px-6 py-4">Teacher</th>
                      <th className="px-6 py-4">Designation</th>
                      <th className="px-6 py-4">Department</th>
                      <th className="px-6 py-4 text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-outline-variant/30 text-sm">
                    {faculty.map((f) => (
                      <tr key={f._id} className="hover:bg-white/60 transition-colors">
                        <td className="px-6 py-4 flex items-center gap-3">
                          <img src={f.image || 'https://via.placeholder.com/150'} className="w-10 h-10 object-cover rounded-full border-2 border-white shadow-sm" alt="" />
                          <span className="font-bold text-on-surface">{f.name}</span>
                        </td>
                        <td className="px-6 py-4 font-semibold">{f.designation}</td>
                        <td className="px-6 py-4 text-on-surface-variant font-bold text-xs uppercase">{f.department}</td>
                        <td className="px-6 py-4 text-right space-x-3">
                          <button 
                            onClick={() => {
                              setEditingId(f._id);
                              setFacultyForm({ name: f.name, designation: f.designation, department: f.department, qualification: f.qualification, image: f.image });
                            }} 
                            className="text-primary hover:underline font-bold"
                          >
                            Edit
                          </button>
                          <button 
                            onClick={() => handleDelete('faculty', f._id)} 
                            className="text-red-500 hover:underline font-bold"
                          >
                            Delete
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* Gallery tab */}
        {activeTab === 'gallery' && (
          <div className="space-y-8 animate-fade-in">
            <div>
              <h2 className="text-3xl font-headline font-bold text-primary">Manage Photo Gallery</h2>
              <p className="text-on-surface-variant">Upload photos of campus events and student life.</p>
            </div>

            {formSuccess && <div className="p-4 bg-green-50 border border-green-200 text-green-700 font-semibold rounded-lg text-sm">{formSuccess}</div>}
            {formError && <div className="p-4 bg-red-50 border border-red-200 text-red-700 font-semibold rounded-lg text-sm">{formError}</div>}

            <div className="grid lg:grid-cols-3 gap-8 items-start">
              {/* Form */}
              <div className="glass-card p-6 rounded-2xl bg-white/40 border border-outline/50">
                <h3 className="text-lg font-headline font-bold text-primary mb-4">Upload Photo</h3>
                <form onSubmit={handleAddGallery} className="space-y-4">
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Title</label>
                    <input 
                      type="text" 
                      value={galleryForm.title}
                      onChange={(e) => setGalleryForm({ ...galleryForm, title: e.target.value })}
                      placeholder="e.g. Science Experiment"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Category</label>
                    <select 
                      value={galleryForm.category}
                      onChange={(e) => setGalleryForm({ ...galleryForm, category: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    >
                      <option value="Campus">Campus</option>
                      <option value="Classrooms">Classrooms</option>
                      <option value="Events">Events</option>
                      <option value="Sports">Sports</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Image File</label>
                    <input 
                      type="file" 
                      name="imageUrl"
                      required
                      accept="image/*"
                      onChange={(e) => handleFileChange(e, setGalleryForm, galleryForm)}
                      className="w-full text-xs text-on-surface-variant file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-bold file:bg-primary/10 file:text-primary hover:file:bg-primary/20"
                    />
                    {galleryForm.imageUrl && (
                      <img src={galleryForm.imageUrl} className="w-16 h-16 object-cover rounded-xl mt-2 border-2 border-outline" alt="Preview" />
                    )}
                  </div>
                  <button type="submit" className="w-full bg-primary text-white py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform shadow-md shadow-primary/20 text-sm">
                    Upload to Gallery
                  </button>
                </form>
              </div>

              {/* Grid List */}
              <div className="lg:col-span-2 glass-card p-6 rounded-2xl bg-white/40 border border-outline/50">
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
                  {gallery.map((item) => (
                    <div key={item._id} className="relative group rounded-xl overflow-hidden border-2 border-outline-variant shadow-sm custom-card">
                      <img src={item.imageUrl} className="w-full aspect-[4/3] object-cover" alt="" />
                      <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex flex-col justify-between p-3">
                        <span className="text-[10px] bg-primary text-white px-2.5 py-0.5 rounded-full self-start font-bold uppercase tracking-wider">{item.category}</span>
                        <div className="flex justify-between items-center text-white">
                          <p className="text-xs font-bold truncate max-w-[100px]">{item.title}</p>
                          <button 
                            onClick={() => handleDelete('gallery', item._id)} 
                            className="text-red-400 hover:text-red-500 font-bold text-xs"
                          >
                            Delete
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Achievements tab */}
        {activeTab === 'achievements' && (
          <div className="space-y-8 animate-fade-in">
            <div className="flex flex-col sm:flex-row sm:items-end justify-between gap-4 px-2">
              <div>
                <h2 className="text-3xl font-headline font-bold text-primary">Achievements Management <span className="text-secondary">✨</span></h2>
                <p className="text-on-surface-variant font-medium mt-1">Manage school awards, certificates, and student recognitions.</p>
              </div>
            </div>

            {formSuccess && <div className="p-4 bg-green-50 border border-green-200 text-green-700 font-semibold rounded-lg text-sm">{formSuccess}</div>}
            {formError && <div className="p-4 bg-red-50 border border-red-200 text-red-700 font-semibold rounded-lg text-sm">{formError}</div>}

            <div className="grid lg:grid-cols-3 gap-8 items-start">
              {/* Form */}
              <div className="glass-card p-6 rounded-2xl bg-white/40 border border-outline/50">
                <h3 className="text-lg font-headline font-bold text-primary mb-4">
                  {editingId ? 'Edit Achievement' : 'Add Achievement'}
                </h3>
                <form onSubmit={handleAddAchievement} className="space-y-4">
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Title</label>
                    <input 
                      type="text" 
                      required
                      value={achievementForm.title}
                      onChange={(e) => setAchievementForm({ ...achievementForm, title: e.target.value })}
                      placeholder="e.g. Science Olympiad Gold"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Recipient</label>
                    <input 
                      type="text" 
                      required
                      value={achievementForm.recipient}
                      onChange={(e) => setAchievementForm({ ...achievementForm, recipient: e.target.value })}
                      placeholder="e.g. Sarah Jenkins or Grade 11 Team"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-bold text-on-surface-variant mb-1">Category</label>
                      <select 
                        value={achievementForm.category}
                        onChange={(e) => setAchievementForm({ ...achievementForm, category: e.target.value })}
                        className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm cursor-pointer"
                      >
                        <option value="Academic">Academic</option>
                        <option value="Sports">Sports</option>
                        <option value="Arts & Culture">Arts & Culture</option>
                        <option value="School">School</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-xs font-bold text-on-surface-variant mb-1">Academic Year</label>
                      <input 
                        type="text" 
                        required
                        value={achievementForm.year}
                        onChange={(e) => setAchievementForm({ ...achievementForm, year: e.target.value })}
                        placeholder="e.g. 2023-2024"
                        className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4 pt-1">
                    <div>
                      <label className="block text-xs font-bold text-on-surface-variant mb-1">Status</label>
                      <select 
                        value={achievementForm.status}
                        onChange={(e) => setAchievementForm({ ...achievementForm, status: e.target.value })}
                        className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm cursor-pointer"
                      >
                        <option value="Published">Published</option>
                        <option value="Draft">Draft</option>
                      </select>
                    </div>
                    <div className="flex flex-col justify-end pb-2">
                      <label className="inline-flex items-center gap-2 cursor-pointer text-sm font-bold text-on-surface-variant">
                        <input 
                          type="checkbox"
                          checked={achievementForm.featured}
                          onChange={(e) => setAchievementForm({ ...achievementForm, featured: e.target.checked })}
                          className="rounded text-primary focus:ring-primary border-outline-variant border-2 w-4 h-4 cursor-pointer"
                        />
                        Featured Banner
                      </label>
                    </div>
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Banner Image (Optional)</label>
                    <input 
                      type="file" 
                      name="image"
                      accept="image/*"
                      onChange={(e) => handleFileChange(e, setAchievementForm, achievementForm)}
                      className="w-full text-xs text-on-surface-variant file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-bold file:bg-primary/10 file:text-primary hover:file:bg-primary/20"
                    />
                    {achievementForm.image && (
                      <img src={achievementForm.image} className="w-16 h-16 object-cover rounded-xl mt-2 border-2 border-outline" alt="Preview" />
                    )}
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Description</label>
                    <textarea 
                      value={achievementForm.description}
                      onChange={(e) => setAchievementForm({ ...achievementForm, description: e.target.value })}
                      placeholder="Describe the milestone or certificate achievements details..."
                      rows="3"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    ></textarea>
                  </div>
                  <div className="flex gap-2">
                    <button type="submit" className="flex-1 bg-primary text-white py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform shadow-md shadow-primary/20 text-sm">
                      Save
                    </button>
                    {editingId && (
                      <button 
                        type="button" 
                        onClick={() => {
                          setEditingId(null);
                          setAchievementForm({
                            title: '', recipient: '', category: 'Academic', year: new Date().getFullYear().toString(),
                            featured: false, status: 'Published', image: '', description: ''
                          });
                        }}
                        className="bg-gray-200 text-gray-700 px-4 py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform text-sm"
                      >
                        Cancel
                      </button>
                    )}
                  </div>
                </form>
              </div>

              {/* Toolbar + List */}
              <div className="lg:col-span-2 space-y-4">
                {/* Search & Filters */}
                <div className="glass-card p-4 rounded-2xl bg-white/40 border border-outline/50 flex flex-col sm:flex-row gap-4 items-center justify-between">
                  <div className="relative w-full sm:max-w-xs">
                    <span className="material-symbols-outlined absolute left-3 top-1/2 -translate-y-1/2 text-primary text-sm">search</span>
                    <input 
                      type="text" 
                      value={achQuery}
                      onChange={(e) => setAchQuery(e.target.value)}
                      placeholder="Search title/recipient..."
                      className="w-full bg-white border-2 border-outline-variant rounded-full py-1.5 pl-9 pr-4 text-xs focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all"
                    />
                  </div>
                  <div className="flex gap-2 w-full sm:w-auto">
                    <select 
                      value={achCatFilter}
                      onChange={(e) => setAchCatFilter(e.target.value)}
                      className="bg-white border-2 border-outline-variant rounded-full py-1.5 px-4 text-xs font-bold focus:outline-none cursor-pointer"
                    >
                      <option value="">All Categories</option>
                      <option value="Academic">Academic</option>
                      <option value="Sports">Sports</option>
                      <option value="Arts & Culture">Arts & Culture</option>
                      <option value="School">School</option>
                    </select>
                    <select 
                      value={achStatusFilter}
                      onChange={(e) => setAchStatusFilter(e.target.value)}
                      className="bg-white border-2 border-outline-variant rounded-full py-1.5 px-4 text-xs font-bold focus:outline-none cursor-pointer"
                    >
                      <option value="">All Status</option>
                      <option value="Published">Published</option>
                      <option value="Draft">Draft</option>
                    </select>
                  </div>
                </div>

                {/* Table */}
                <div className="glass-card rounded-2xl overflow-hidden bg-white/40 border border-outline/50">
                  <table className="w-full text-left">
                    <thead className="bg-primary/5 text-xs text-primary uppercase font-bold">
                      <tr>
                        <th className="px-6 py-4">Title</th>
                        <th className="px-6 py-4">Recipient</th>
                        <th className="px-6 py-4">Category</th>
                        <th className="px-6 py-4 text-center">Featured</th>
                        <th className="px-6 py-4">Status</th>
                        <th className="px-6 py-4 text-right">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-outline-variant/30 text-sm">
                      {filteredAchievements.map((ach) => (
                        <tr key={ach._id} className="hover:bg-white/60 transition-colors">
                          <td className="px-6 py-4">
                            <div className="flex items-center gap-3">
                              {ach.image ? (
                                <img src={ach.image} className="w-10 h-10 object-cover rounded-xl border-2 border-white shadow-sm" alt="" />
                              ) : (
                                <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                                  <span className="material-symbols-outlined text-xl">workspace_premium</span>
                                </div>
                              )}
                              <div>
                                <p className="font-bold text-on-surface">{ach.title}</p>
                                <p className="text-[10px] text-on-surface-variant font-bold">{ach.year}</p>
                              </div>
                            </div>
                          </td>
                          <td className="px-6 py-4 font-semibold text-on-surface">{ach.recipient}</td>
                          <td className="px-6 py-4">
                            <span className="px-3 py-1 bg-primary-container/20 rounded-full text-xs text-primary font-bold uppercase tracking-wider text-[10px]">{ach.category}</span>
                          </td>
                          <td className="px-6 py-4 text-center">
                            <button 
                              onClick={() => handleFeaturedToggle(ach)}
                              className={`p-1.5 rounded-full transition-colors ${
                                ach.featured ? 'text-yellow-500 bg-yellow-50 hover:bg-yellow-100' : 'text-gray-400 bg-gray-50 hover:bg-gray-100'
                              }`}
                              title={ach.featured ? 'Unfeature this achievement' : 'Feature this achievement'}
                            >
                              <span className="material-symbols-outlined text-lg" style={{ fontVariationSettings: ach.featured ? "'FILL' 1" : "'FILL' 0" }}>star</span>
                            </button>
                          </td>
                          <td className="px-6 py-4">
                            <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider ${
                              ach.status === 'Published' ? 'bg-green-50 text-green-700 border border-green-100' : 'bg-gray-50 text-gray-500 border border-gray-100'
                            }`}>
                              {ach.status}
                            </span>
                          </td>
                          <td className="px-6 py-4 text-right space-x-3">
                            <button 
                              onClick={() => {
                                setEditingId(ach._id);
                                setAchievementForm({
                                  title: ach.title, recipient: ach.recipient, category: ach.category, year: ach.year,
                                  featured: ach.featured, status: ach.status, image: ach.image || '', description: ach.description || ''
                                });
                              }} 
                              className="text-primary hover:underline font-bold"
                            >
                              Edit
                            </button>
                            <button 
                              onClick={() => handleDelete('achievements', ach._id)} 
                              className="text-red-500 hover:underline font-bold"
                            >
                              Delete
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  {filteredAchievements.length === 0 && (
                    <div className="p-8 text-center text-on-surface-variant font-medium">No achievements found matching your criteria.</div>
                  )}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Students tab */}
        {activeTab === 'students' && (
          <div className="space-y-8 animate-fade-in">
            <div>
              <h2 className="text-3xl font-headline font-bold text-primary">Student Management</h2>
              <p className="text-on-surface-variant">Register students, assign grades, and update status.</p>
            </div>

            {formSuccess && <div className="p-4 bg-green-50 border border-green-200 text-green-700 font-semibold rounded-lg text-sm">{formSuccess}</div>}
            {formError && <div className="p-4 bg-red-50 border border-red-200 text-red-700 font-semibold rounded-lg text-sm">{formError}</div>}

            <div className="grid lg:grid-cols-3 gap-8 items-start">
              {/* Form */}
              <div className="glass-card p-6 rounded-2xl bg-white/40 border border-outline/50">
                <h3 className="text-lg font-headline font-bold text-primary mb-4">
                  {editingId ? 'Edit Student Details' : 'Register New Student'}
                </h3>
                <form onSubmit={handleAddStudent} className="space-y-4">
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Student Full Name</label>
                    <input 
                      type="text" 
                      required
                      value={studentForm.name}
                      onChange={(e) => setStudentForm({ ...studentForm, name: e.target.value })}
                      placeholder="e.g. Liam Henderson"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-bold text-on-surface-variant mb-1">Roll Number</label>
                      <input 
                        type="text" 
                        required
                        disabled={!!editingId}
                        value={studentForm.rollNo}
                        onChange={(e) => setStudentForm({ ...studentForm, rollNo: e.target.value })}
                        placeholder="e.g. STU-2026-04"
                        className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm disabled:bg-gray-100"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-bold text-on-surface-variant mb-1">Grade / Class</label>
                      <select 
                        value={studentForm.grade}
                        onChange={(e) => setStudentForm({ ...studentForm, grade: e.target.value })}
                        className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm cursor-pointer"
                      >
                        <option value="Nursery">Nursery</option>
                        <option value="Kindergarten">Kindergarten</option>
                        <option value="Grade 1">Grade 1</option>
                        <option value="Grade 2">Grade 2</option>
                        <option value="Grade 3">Grade 3</option>
                        <option value="Grade 4">Grade 4</option>
                        <option value="Grade 5">Grade 5</option>
                      </select>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-bold text-on-surface-variant mb-1">Guardian Name</label>
                      <input 
                        type="text" 
                        required
                        value={studentForm.guardianName}
                        onChange={(e) => setStudentForm({ ...studentForm, guardianName: e.target.value })}
                        placeholder="Parent Name"
                        className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-bold text-on-surface-variant mb-1">Contact Phone</label>
                      <input 
                        type="text" 
                        required
                        value={studentForm.phone}
                        onChange={(e) => setStudentForm({ ...studentForm, phone: e.target.value })}
                        placeholder="Phone Number"
                        className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                      />
                    </div>
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Status</label>
                    <select 
                      value={studentForm.status}
                      onChange={(e) => setStudentForm({ ...studentForm, status: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm cursor-pointer"
                    >
                      <option value="Active">Active</option>
                      <option value="Suspended">Suspended</option>
                      <option value="Graduated">Graduated</option>
                    </select>
                  </div>
                  <div className="flex gap-2">
                    <button type="submit" className="flex-1 bg-primary text-white py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform shadow-md shadow-primary/20 text-sm">
                      {editingId ? 'Update Info' : 'Register Student'}
                    </button>
                    {editingId && (
                      <button 
                        type="button" 
                        onClick={() => {
                          setEditingId(null);
                          setStudentForm({ name: '', rollNo: '', grade: 'Nursery', guardianName: '', phone: '', status: 'Active' });
                        }}
                        className="bg-gray-200 text-gray-700 px-4 py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform text-sm"
                      >
                        Cancel
                      </button>
                    )}
                  </div>
                </form>
              </div>

              {/* List */}
              <div className="lg:col-span-2 glass-card rounded-2xl overflow-hidden bg-white/40 border border-outline/50">
                <table className="w-full text-left">
                  <thead className="bg-primary/5 text-xs text-primary uppercase font-bold">
                    <tr>
                      <th className="px-6 py-4">Student Details</th>
                      <th className="px-6 py-4">Guardian Info</th>
                      <th className="px-6 py-4">Grade</th>
                      <th className="px-6 py-4">Status</th>
                      <th className="px-6 py-4 text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-outline-variant/30 text-sm">
                    {students.map((student) => (
                      <tr key={student._id} className="hover:bg-white/60 transition-colors">
                        <td className="px-6 py-4">
                          <p className="font-bold text-on-surface">{student.name}</p>
                          <p className="text-xs text-on-surface-variant font-mono mt-0.5">{student.rollNo}</p>
                        </td>
                        <td className="px-6 py-4">
                          <p className="font-semibold">{student.guardianName}</p>
                          <p className="text-xs text-on-surface-variant mt-0.5">{student.phone}</p>
                        </td>
                        <td className="px-6 py-4 font-semibold">{student.grade}</td>
                        <td className="px-6 py-4">
                          <span className={`px-2.5 py-0.5 rounded-full text-[10px] font-bold ${
                            student.status === 'Active' ? 'bg-green-100 text-green-700' :
                            student.status === 'Suspended' ? 'bg-red-100 text-red-700' : 'bg-blue-100 text-blue-700'
                          }`}>{student.status}</span>
                        </td>
                        <td className="px-6 py-4 text-right space-x-3">
                          <button 
                            onClick={() => {
                              setEditingId(student._id);
                              setStudentForm({ name: student.name, rollNo: student.rollNo, grade: student.grade, guardianName: student.guardianName, phone: student.phone, status: student.status });
                            }} 
                            className="text-primary hover:underline font-bold"
                          >
                            Edit
                          </button>
                          <button 
                            onClick={() => handleDelete('students', student._id)} 
                            className="text-red-500 hover:underline font-bold"
                          >
                            Delete
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                {students.length === 0 && (
                  <div className="p-8 text-center text-on-surface-variant font-medium">No students registered in the system.</div>
                )}
              </div>
            </div>
          </div>
        )}

        {/* CMS Pages Tab */}
        {activeTab === 'cms' && (
          <div className="space-y-8 animate-fade-in">
            <div>
              <h2 className="text-3xl font-headline font-bold text-primary">Website Pages (CMS)</h2>
              <p className="text-on-surface-variant">Build and configure custom landing pages and static content.</p>
            </div>

            {formSuccess && <div className="p-4 bg-green-50 border border-green-200 text-green-700 font-semibold rounded-lg text-sm">{formSuccess}</div>}
            {formError && <div className="p-4 bg-red-50 border border-red-200 text-red-700 font-semibold rounded-lg text-sm">{formError}</div>}

            <div className="grid lg:grid-cols-3 gap-8 items-start">
              {/* Form */}
              <div className="glass-card p-6 rounded-2xl bg-white/40 border border-outline/50">
                <h3 className="text-lg font-headline font-bold text-primary mb-4">
                  {editingId ? 'Edit CMS Page' : 'Create Custom Page'}
                </h3>
                <form onSubmit={handleAddCmsPage} className="space-y-4">
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Page Title</label>
                    <input 
                      type="text" 
                      required
                      value={cmsForm.title}
                      onChange={(e) => setCmsForm({ ...cmsForm, title: e.target.value, slug: e.target.value.toLowerCase().replace(/[^a-z0-9 -]/g, '').replace(/\s+/g, '-') })}
                      placeholder="e.g. Winter Sports Meet"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Route Path (Slug)</label>
                    <input 
                      type="text" 
                      required
                      value={cmsForm.slug}
                      onChange={(e) => setCmsForm({ ...cmsForm, slug: e.target.value })}
                      placeholder="e.g. winter-sports"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Page Content (HTML supported)</label>
                    <textarea 
                      required
                      value={cmsForm.content}
                      onChange={(e) => setCmsForm({ ...cmsForm, content: e.target.value })}
                      placeholder="Write HTML or page content here..."
                      rows="6"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm font-mono"
                    ></textarea>
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Publish Status</label>
                    <select 
                      value={cmsForm.status}
                      onChange={(e) => setCmsForm({ ...cmsForm, status: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm cursor-pointer"
                    >
                      <option value="Draft">Draft</option>
                      <option value="Published">Published</option>
                    </select>
                  </div>
                  <div className="flex gap-2">
                    <button type="submit" className="flex-1 bg-primary text-white py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform shadow-md shadow-primary/20 text-sm">
                      {editingId ? 'Update Page' : 'Publish Page'}
                    </button>
                    {editingId && (
                      <button 
                        type="button" 
                        onClick={() => {
                          setEditingId(null);
                          setCmsForm({ title: '', slug: '', content: '', status: 'Draft' });
                        }}
                        className="bg-gray-200 text-gray-700 px-4 py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform text-sm"
                      >
                        Cancel
                      </button>
                    )}
                  </div>
                </form>
              </div>

              {/* List */}
              <div className="lg:col-span-2 glass-card rounded-2xl overflow-hidden bg-white/40 border border-outline/50">
                <table className="w-full text-left">
                  <thead className="bg-primary/5 text-xs text-primary uppercase font-bold">
                    <tr>
                      <th className="px-6 py-4">Title / Route</th>
                      <th className="px-6 py-4">Last Updated</th>
                      <th className="px-6 py-4">Status</th>
                      <th className="px-6 py-4 text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-outline-variant/30 text-sm">
                    {cmsPages.map((page) => (
                      <tr key={page._id} className="hover:bg-white/60 transition-colors">
                        <td className="px-6 py-4">
                          <p className="font-bold text-on-surface">{page.title}</p>
                          <p className="text-xs text-on-surface-variant font-mono mt-0.5">/pages/{page.slug}</p>
                        </td>
                        <td className="px-6 py-4 text-on-surface-variant font-medium">{new Date(page.lastUpdated).toLocaleDateString()}</td>
                        <td className="px-6 py-4">
                          <span className={`px-2.5 py-0.5 rounded-full text-[10px] font-bold ${
                            page.status === 'Published' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
                          }`}>{page.status}</span>
                        </td>
                        <td className="px-6 py-4 text-right space-x-3">
                          <button 
                            onClick={() => {
                              setEditingId(page._id);
                              setCmsForm({ title: page.title, slug: page.slug, content: page.content, status: page.status });
                            }} 
                            className="text-primary hover:underline font-bold"
                          >
                            Edit
                          </button>
                          <button 
                            onClick={() => handleDelete('cms-pages', page._id)} 
                            className="text-red-500 hover:underline font-bold"
                          >
                            Delete
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                {cmsPages.length === 0 && (
                  <div className="p-8 text-center text-on-surface-variant font-medium">No custom CMS pages created yet.</div>
                )}
              </div>
            </div>
          </div>
        )}

        {/* Downloads Tab */}
        {activeTab === 'downloads' && (
          <div className="space-y-8 animate-fade-in">
            <div>
              <h2 className="text-3xl font-headline font-bold text-primary">Downloads &amp; Circulars</h2>
              <p className="text-on-surface-variant">Upload curriculum syllabus sheets, calendar sheets, and registration forms.</p>
            </div>

            {formSuccess && <div className="p-4 bg-green-50 border border-green-200 text-green-700 font-semibold rounded-lg text-sm">{formSuccess}</div>}
            {formError && <div className="p-4 bg-red-50 border border-red-200 text-red-700 font-semibold rounded-lg text-sm">{formError}</div>}

            <div className="grid lg:grid-cols-3 gap-8 items-start">
              {/* Form */}
              <div className="glass-card p-6 rounded-2xl bg-white/40 border border-outline/50">
                <h3 className="text-lg font-headline font-bold text-primary mb-4">Upload Document</h3>
                <form onSubmit={handleAddDownload} className="space-y-4">
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Document Title</label>
                    <input 
                      type="text" 
                      required
                      value={downloadForm.title}
                      onChange={(e) => setDownloadForm({ ...downloadForm, title: e.target.value })}
                      placeholder="e.g. Annual Syllabus 2026"
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Category</label>
                    <select 
                      value={downloadForm.category}
                      onChange={(e) => setDownloadForm({ ...downloadForm, category: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all bg-white text-sm cursor-pointer"
                    >
                      <option value="Circular">Circular</option>
                      <option value="Syllabus">Syllabus</option>
                      <option value="Form">Form</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Upload File (PDF/Doc/Image)</label>
                    <input 
                      type="file" 
                      name="fileUrl"
                      required
                      accept=".pdf,.doc,.docx,image/*"
                      onChange={(e) => handleFileChange(e, setDownloadForm, downloadForm)}
                      className="w-full text-xs text-on-surface-variant file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-bold file:bg-primary/10 file:text-primary hover:file:bg-primary/20"
                    />
                  </div>
                  <button type="submit" className="w-full bg-primary text-white py-2.5 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform shadow-md shadow-primary/20 text-sm">
                    Upload Document
                  </button>
                </form>
              </div>

              {/* List */}
              <div className="lg:col-span-2 glass-card rounded-2xl overflow-hidden bg-white/40 border border-outline/50">
                <table className="w-full text-left">
                  <thead className="bg-primary/5 text-xs text-primary uppercase font-bold">
                    <tr>
                      <th className="px-6 py-4">Title</th>
                      <th className="px-6 py-4">Category</th>
                      <th className="px-6 py-4">Upload Date</th>
                      <th className="px-6 py-4 text-right">Action</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-outline-variant/30 text-sm">
                    {downloads.map((item) => (
                      <tr key={item._id} className="hover:bg-white/60 transition-colors">
                        <td className="px-6 py-4 font-bold text-on-surface">
                          <div className="flex items-center gap-2">
                            <span className="material-symbols-outlined text-primary">description</span>
                            {item.title}
                          </div>
                        </td>
                        <td className="px-6 py-4">
                          <span className="px-2.5 py-0.5 bg-secondary-container/20 text-secondary border border-secondary/10 rounded-full text-xs font-bold">{item.category}</span>
                        </td>
                        <td className="px-6 py-4 text-on-surface-variant font-medium">{new Date(item.date).toLocaleDateString()}</td>
                        <td className="px-6 py-4 text-right">
                          <button 
                            onClick={() => handleDelete('downloads', item._id)} 
                            className="text-red-500 hover:underline font-bold"
                          >
                            Delete
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                {downloads.length === 0 && (
                  <div className="p-8 text-center text-on-surface-variant font-medium">No documents uploaded yet.</div>
                )}
              </div>
            </div>
          </div>
        )}

        {/* Website Settings Tab */}
        {activeTab === 'settings' && (
          <div className="space-y-8 animate-fade-in">
            <div>
              <h2 className="text-3xl font-headline font-bold text-primary">Website Configuration Settings</h2>
              <p className="text-on-surface-variant">Update identity, mottos, social handles, and metadata for St. Andrews.</p>
            </div>

            {formSuccess && <div className="p-4 bg-green-50 border border-green-200 text-green-700 font-semibold rounded-lg text-sm">{formSuccess}</div>}
            {formError && <div className="p-4 bg-red-50 border border-red-200 text-red-700 font-semibold rounded-lg text-sm">{formError}</div>}

            <form onSubmit={handleUpdateSettings} className="glass-card p-8 rounded-2xl bg-white/40 border border-outline/50 space-y-6 max-w-4xl">
              <div>
                <h3 className="text-lg font-headline font-bold text-primary border-b-2 border-outline-variant/30 pb-2 mb-4">School Identity</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">School Name</label>
                    <input 
                      type="text" 
                      value={settings.schoolName}
                      onChange={(e) => setSettings({ ...settings, schoolName: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Tagline / Motto</label>
                    <input 
                      type="text" 
                      value={settings.tagline}
                      onChange={(e) => setSettings({ ...settings, tagline: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg bg-white text-sm"
                    />
                  </div>
                </div>
              </div>

              <div>
                <h3 className="text-lg font-headline font-bold text-primary border-b-2 border-outline-variant/30 pb-2 mb-4">Contact Information</h3>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Office Email</label>
                    <input 
                      type="email" 
                      value={settings.email}
                      onChange={(e) => setSettings({ ...settings, email: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Office Phone</label>
                    <input 
                      type="text" 
                      value={settings.phone}
                      onChange={(e) => setSettings({ ...settings, phone: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Campus Address</label>
                    <input 
                      type="text" 
                      value={settings.address}
                      onChange={(e) => setSettings({ ...settings, address: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg bg-white text-sm"
                    />
                  </div>
                </div>
              </div>

              <div>
                <h3 className="text-lg font-headline font-bold text-primary border-b-2 border-outline-variant/30 pb-2 mb-4">Social Media Handles</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Facebook URL</label>
                    <input 
                      type="text" 
                      value={settings.facebookUrl}
                      onChange={(e) => setSettings({ ...settings, facebookUrl: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Twitter URL</label>
                    <input 
                      type="text" 
                      value={settings.twitterUrl}
                      onChange={(e) => setSettings({ ...settings, twitterUrl: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">Instagram URL</label>
                    <input 
                      type="text" 
                      value={settings.instagramUrl}
                      onChange={(e) => setSettings({ ...settings, instagramUrl: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg bg-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-on-surface-variant mb-1">YouTube URL</label>
                    <input 
                      type="text" 
                      value={settings.youtubeUrl}
                      onChange={(e) => setSettings({ ...settings, youtubeUrl: e.target.value })}
                      className="w-full px-4 py-2 border-2 border-outline-variant rounded-lg bg-white text-sm"
                    />
                  </div>
                </div>
              </div>

              <div className="pt-4 border-t-2 border-outline-variant/30 flex justify-end">
                <button type="submit" className="bg-primary text-white px-8 py-3 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform shadow-lg shadow-primary/20">
                  Publish Website Settings
                </button>
              </div>
            </form>
          </div>
        )}

        {/* Activity Logs Tab */}
        {activeTab === 'logs' && (
          <div className="space-y-8 animate-fade-in">
            <div>
              <h2 className="text-3xl font-headline font-bold text-primary">Activity Audit Center</h2>
              <p className="text-on-surface-variant">Real-time trace of administrative read/write actions on the system.</p>
            </div>

            <div className="glass-card rounded-2xl overflow-hidden bg-white/40 border border-outline/50">
              <table className="w-full text-left">
                <thead className="bg-primary/5 text-xs text-primary uppercase font-bold">
                  <tr>
                    <th className="px-6 py-4">User</th>
                    <th className="px-6 py-4">Action</th>
                    <th className="px-6 py-4">Details</th>
                    <th className="px-6 py-4">IP Address</th>
                    <th className="px-6 py-4">Date &amp; Time</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-outline-variant/30 text-sm">
                  {activityLogs.map((log) => (
                    <tr key={log._id} className="hover:bg-white/60 transition-colors">
                      <td className="px-6 py-4 font-bold text-primary">
                        <div className="flex items-center gap-2">
                          <span className="material-symbols-outlined text-sm">account_circle</span>
                          {log.admin}
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <span className="px-2.5 py-0.5 bg-primary-container/20 text-primary border border-primary/10 rounded-full text-xs font-bold">{log.action}</span>
                      </td>
                      <td className="px-6 py-4 text-on-surface font-medium">{log.details}</td>
                      <td className="px-6 py-4 font-mono text-xs text-on-surface-variant">{log.ipAddress}</td>
                      <td className="px-6 py-4 text-on-surface-variant font-medium">{new Date(log.date).toLocaleString()}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {activityLogs.length === 0 && (
                <div className="p-8 text-center text-on-surface-variant font-medium">No activity log entries found.</div>
              )}
            </div>
          </div>
        )}

        {/* Backup & Restore Tab */}
        {activeTab === 'backups' && (
          <div className="space-y-8 animate-fade-in">
            <div className="flex justify-between items-center">
              <div>
                <h2 className="text-3xl font-headline font-bold text-primary">Backup &amp; Restore Center</h2>
                <p className="text-on-surface-variant">Create and restore snapshots of your school portal database.</p>
              </div>
              <button 
                onClick={handleCreateBackup}
                className="bg-primary text-white px-6 py-3 rounded-full font-bold hover:scale-[1.02] active:scale-95 transition-transform shadow-md flex items-center gap-2"
              >
                <span className="material-symbols-outlined">cloud_upload</span>
                Trigger Database Backup
              </button>
            </div>

            {formSuccess && <div className="p-4 bg-green-50 border border-green-200 text-green-700 font-semibold rounded-lg text-sm">{formSuccess}</div>}
            {formError && <div className="p-4 bg-red-50 border border-red-200 text-red-700 font-semibold rounded-lg text-sm">{formError}</div>}

            <div className="glass-card rounded-2xl overflow-hidden bg-white/40 border border-outline/50">
              <table className="w-full text-left">
                <thead className="bg-primary/5 text-xs text-primary uppercase font-bold">
                  <tr>
                    <th className="px-6 py-4">Backup File Name</th>
                    <th className="px-6 py-4">Snapshot Size</th>
                    <th className="px-6 py-4">Backup Status</th>
                    <th className="px-6 py-4">Date Created</th>
                    <th className="px-6 py-4 text-right">Action</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-outline-variant/30 text-sm">
                  {backups.map((item) => (
                    <tr key={item._id} className="hover:bg-white/60 transition-colors">
                      <td className="px-6 py-4 font-bold text-on-surface">
                        <div className="flex items-center gap-2">
                          <span className="material-symbols-outlined text-secondary">storage</span>
                          {item.filename}
                        </div>
                      </td>
                      <td className="px-6 py-4 font-semibold">{item.size}</td>
                      <td className="px-6 py-4">
                        <span className="px-2.5 py-0.5 bg-green-100 text-green-700 rounded-full text-xs font-bold">{item.status}</span>
                      </td>
                      <td className="px-6 py-4 text-on-surface-variant font-medium">{new Date(item.date).toLocaleString()}</td>
                      <td className="px-6 py-4 text-right">
                        <button 
                          onClick={() => handleDelete('backups', item._id)} 
                          className="text-red-500 hover:underline font-bold"
                        >
                          Delete Backup
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {backups.length === 0 && (
                <div className="p-8 text-center text-on-surface-variant font-medium">No database backup files found.</div>
              )}
            </div>
          </div>
        )}

        {/* Inbound Messages tab */}
        {activeTab === 'messages' && (
          <div className="space-y-8 animate-fade-in">
            <div>
              <h2 className="text-3xl font-headline font-bold text-primary">Inbound Messages</h2>
              <p className="text-on-surface-variant">Messages received from the website contact form.</p>
            </div>

            <div className="glass-card rounded-2xl overflow-hidden bg-white/40">
              {contactMessages.length === 0 ? (
                <div className="p-8 text-center text-on-surface-variant">No new contact messages found.</div>
              ) : (
                <table className="w-full text-left">
                  <thead className="bg-primary/5 text-xs text-primary uppercase font-bold">
                    <tr>
                      <th className="px-6 py-4">Sender</th>
                      <th className="px-6 py-4">Email</th>
                      <th className="px-6 py-4">Subject</th>
                      <th className="px-6 py-4">Message</th>
                      <th className="px-6 py-4">Date</th>
                      <th className="px-6 py-4 text-right">Action</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-outline-variant/30 text-sm">
                    {contactMessages.map((msg) => (
                      <tr key={msg._id} className="hover:bg-white/60 transition-colors">
                        <td className="px-6 py-4 font-bold text-on-surface">{msg.name}</td>
                        <td className="px-6 py-4 font-medium">{msg.email}</td>
                        <td className="px-6 py-4 font-bold text-secondary">{msg.subject}</td>
                        <td className="px-6 py-4 text-on-surface-variant max-w-xs truncate" title={msg.message}>{msg.message}</td>
                        <td className="px-6 py-4 text-on-surface-variant font-medium">{new Date(msg.date).toLocaleString()}</td>
                        <td className="px-6 py-4 text-right">
                          <button 
                            onClick={() => handleDelete('contact', msg._id)}
                            className="text-red-500 hover:underline font-bold"
                          >
                            Delete
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        )}

      </main>
    </div>
  );
}
