import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import {
  Save, Building2, Calendar, Mail, Check,
  ShieldCheck, RefreshCw, ChevronRight, Sparkles,
  Info, Bell, Database, Key, Globe, CheckCircle2,
  Lock, HardDrive, Download, Power, Webhook, Zap,
  CreditCard, MessageSquare, GraduationCap, Award, BookOpen,
  Plus, Pencil, Trash2, X, Layers, ArrowRight, AlertTriangle, ListChecks, Star,
} from 'lucide-react';
import api from '../../store/auth';
import { useAuthStore } from '../../store/auth';
import {
  useSchoolSettingsStore,
  type EducationLevelKey,
  type EducationLevelConfig,
  type EducationLevelConfigInput,
} from '../../store/schoolSettings';
import { SCALES } from '../../lib/gradeScales';
import { GradeBadge } from '../../components/GradeBadge';
import { T as Term } from '../../lib/terminology';
import LicenseSourceBanner from '../../components/LicenseSourceBanner';
import { ProgressBar } from '../../components/ui/ProgressBar';
import { createAxiosUploadProgressHandler } from '../../lib/uploadProgress';

interface SettingsForm {
  school_name: string;
  school_address?: string;
  school_motto?: string;
  academic_year: string;
  system_email: string;
  paynow_integration_id?: string;
  paynow_integration_key?: string;
  sms_gateway?: string;
  session_timeout?: string;
  mfa_enabled?: boolean;
  school_logo_url?: string;
  tenant_id?: string;
}

export default function Settings() {
  const [activeTab, setActiveTab] = useState<'general' | 'appearance' | 'academic' | 'integrations' | 'security' | 'data'>('general');
  const [form, setForm] = useState<SettingsForm>({
    school_name: '',
    school_address: '',
    school_motto: '',
    academic_year: '',
    system_email: '',
    paynow_integration_id: '',
    paynow_integration_key: '',
    sms_gateway: '',
    session_timeout: '30',
    mfa_enabled: false,
    school_logo_url: '',
    tenant_id: ''
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [uploadingLogo, setUploadingLogo] = useState(false);
  const [logoUploadProgress, setLogoUploadProgress] = useState<number | null>(null);
  const [scaleSaving, setScaleSaving] = useState(false);
  const [scaleSuccess, setScaleSuccess] = useState(false);
  const [scaleError, setScaleError] = useState<string | null>(null);
  const [tenantSaving, setTenantSaving] = useState(false);
  const [tenantSuccess, setTenantSuccess] = useState(false);
  const [tenantError, setTenantError] = useState<string | null>(null);
  // Ministry weekly push config (read from /api/settings/ministry-push)
  const [govPush, setGovPush] = useState({
    urls: '',
    auth: '',
    hmacSecret: '',
    schoolId: '',
    lastPushAt: null,
    lastPushStatus: null,
  });
  const [govPushSaving, setGovPushSaving] = useState(false);
  const [govPushSuccess, setGovPushSuccess] = useState(false);
  const [govPushError, setGovPushError] = useState<string | null>(null);
  const [govPushPushing, setGovPushPushing] = useState(false);

  const { user } = useAuthStore();
  const isScaleAdmin = !!user && (user.role === 'school_admin' || user.role === 'systems_admin');
  const {
    defaultGradingScale,
    defaultGradingScaleLabel,
    options: scaleOptionsList,
    loading: scaleLoading,
    fetchSettings: fetchSchoolSettings,
    setDefaultGradingScale,
  } = useSchoolSettingsStore();
  const [pendingScale, setPendingScale] = useState<string>(defaultGradingScale);

// School-wide settings store (feature/grading-scales + shapeshift)
const schoolSettings = useSchoolSettingsStore();

  // Education level manager state (feature/shapeshift).
  // The legacy single-dropdown flow is replaced by a CRUD manager
  // over the /education-level-configs endpoints.
  type EditorState = {
    open: boolean;
    /** null = create mode; otherwise the row being edited. */
    target: EducationLevelConfig | null;
    level: EducationLevelKey;
    grading_scale: string;
    display_name: string;
    sort_order: string;
    is_active: boolean;
    error: string | null;
    submitting: boolean;
  };
  const emptyEditor = (): EditorState => ({
    open: false,
    target: null,
    level: 'secondary',
    grading_scale: schoolSettings.defaultGradingScale,
    display_name: '',
    sort_order: '50',
    is_active: true,
    error: null,
    submitting: false,
  });
  const [editor, setEditor] = useState<EditorState>(emptyEditor);
  const [pendingDeleteUid, setPendingDeleteUid] = useState<string | null>(null);
  const [pendingDeleteLabel, setPendingDeleteLabel] = useState<string>('');

  // Unified banner for the Academic Engine tab so the Grading Scale
  // and Education Levels sections don't fight for the user's attention
  // with two stacked inline banners.
  const [academicBanner, setAcademicBanner] = useState<
    { kind: 'success' | 'error'; message: string } | null
  >(null);
  useEffect(() => {
    if (!academicBanner || academicBanner.kind !== 'success') return;
    const t = setTimeout(() => setAcademicBanner(null), 3500);
    return () => clearTimeout(t);
  }, [academicBanner]);
  const flashSuccess = (message: string) =>
    setAcademicBanner({ kind: 'success', message });
  const flashError = (message: string) =>
    setAcademicBanner({ kind: 'error', message });

  const [pulseData, setPulseData] = useState({
    dbSync: 'Synchronized',
    dbSize: 'Checking...',
    uptime: 'Checking...'
  });
  const [checkingIntegrity, setCheckingIntegrity] = useState(false);
  const [terminatingSessions, setTerminatingSessions] = useState(false);

  useEffect(() => {
    loadSettings();
    loadDiagnostics();
    schoolSettings.fetchSettings();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Keep the academic-tab grading-scale dropdown in sync with the
  // cached store value (the store updates after a successful save
// (legacy default-grading-scale useEffect removed — the picker is
// now driven by the Secondary level row in the unified card below.)

const loadSettings = async () => {
    try {
      setLoading(true);
      const res = await api.get('/settings');
      const data = res.data;
      setForm({
        school_name: data.school_name || '',
        school_address: data.school_address || '',
        school_motto: data.school_motto || '',
        academic_year: data.academic_year || '',
        system_email: data.system_email || '',
        paynow_integration_id: data.paynow_integration_id || '',
        paynow_integration_key: data.paynow_integration_key || '',
        sms_gateway: data.sms_gateway || '',
        session_timeout: data.session_timeout || '30',
        mfa_enabled: data.mfa_enabled === 'true' || data.mfa_enabled === true,
        school_logo_url: data.school_logo_url || '',
        tenant_id: data.tenant_id || ''
      });
    } catch (err) {
      console.error('Failed to load settings:', err);
      setForm({
        school_name: 'NextGen Academy',
        school_address: '',
        school_motto: '',
        academic_year: new Date().getFullYear().toString(),
        system_email: 'admin@nextgen.edu',
        session_timeout: '30',
        paynow_integration_id: '',
        paynow_integration_key: '',
        sms_gateway: '',
        mfa_enabled: false,
        school_logo_url: '',
        tenant_id: ''
      });
    } finally {
      setLoading(false);
    }
  };

  const loadDiagnostics = async () => {
    try {
      const res = await api.get('/settings/diagnostics');
      const sizeMB = (res.data.dbSize / 1024 / 1024).toFixed(2);
      const uptimeHrs = (res.data.uptime / 3600).toFixed(2);
      setPulseData({
        dbSync: 'Optimal',
        dbSize: `${sizeMB} MB`,
        uptime: `${uptimeHrs} Hrs`
      });
    } catch (err) {
      console.error('Failed to load diagnostics:', err);
      setPulseData({
        dbSync: 'Error',
        dbSize: 'N/A',
        uptime: 'N/A'
      });
    }
  };

  const handleTerminateSessions = async () => {
    if (!confirm('Are you sure you want to terminate all active user sessions? This will log out all other users.')) return;
    setTerminatingSessions(true);
    try {
      await api.post('/settings/terminate-sessions');
      alert('All active sessions have been terminated successfully.');
    } catch (err) {
      alert('Failed to terminate sessions.');
    } finally {
      setTerminatingSessions(false);
    }
  };

  const handleBackupDownload = async () => {
    try {
      const response = await api.get('/settings/backup/download', {
        responseType: 'blob'
      });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'school-backup.db');
      document.body.appendChild(link);
      link.click();
      link.parentNode?.removeChild(link);
    } catch (err) {
      alert('Failed to download database backup.');
    }
  };

  const handleIntegrityCheck = async () => {
    setCheckingIntegrity(true);
    try {
      const res = await api.post('/settings/integrity-check');
      alert(`Integrity Check Result: ${res.data.result || 'Successful'}`);
    } catch (err) {
      alert('Failed to perform integrity check.');
    } finally {
      setCheckingIntegrity(false);
    }
  };

  const handleRunDiagnosticAudit = async () => {
    await loadDiagnostics();
    alert('Diagnostics updated! Diagnostics run successfully. Check the system status sidebar for updated readings.');
  };

  const handleLogoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0];
      const formData = new FormData();
      formData.append('logo', file);

      try {
        setUploadingLogo(true);
        setLogoUploadProgress(0);
        const onUploadProgress = createAxiosUploadProgressHandler((percent) => {
          if (percent == null) return;
          setLogoUploadProgress(percent);
        });
        const res = await api.post('/settings/logo', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress,
        });

        if (res.data.success) {
          setForm(prev => ({
            ...prev,
            school_logo_url: res.data.logo_url
          }));
          alert('School logo uploaded successfully! The sync engine will publish it shortly.');
        }
      } catch (err: any) {
        alert('Failed to upload logo: ' + (err.response?.data?.error || err.message));
      } finally {
        setUploadingLogo(false);
        setLogoUploadProgress(null);
        e.target.value = '';
      }
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      setSaving(true);
      setError(null);
      await api.put('/settings', form);
      setSuccess(true);
      setTimeout(() => setSuccess(false), 3000);
    } catch (err: any) {
      setError(err.response?.data?.message || 'Failed to save settings');
    } finally {
      setSaving(false);
    }
  };

  const handleChange = (field: keyof SettingsForm, value: string | boolean) => {
    setForm(prev => ({ ...prev, [field]: value }));
  };

// (legacy handleSaveGradingScale removed — the Secondary level row
// in the unified card below handles its own scale edit. The legacy
// /default-grading-scale endpoint is still wired server-side as a
// derived view that targets the Secondary row.)

// Education Level manager handlers (feature/shapeshift)
const openCreateEditor = () => {
    const used = new Set(schoolSettings.educationLevelConfigs.map((c) => c.level));
    const nextLevel =
      (['primary', 'secondary', 'high_school', 'tertiary'] as EducationLevelKey[]).find(
        (l) => !used.has(l),
      ) || 'primary';
    setEditor({
      ...emptyEditor(),
      open: true,
      level: nextLevel,
    });
  };

  const openEditEditor = (cfg: EducationLevelConfig) => {
    setEditor({
      open: true,
      target: cfg,
      level: cfg.level,
      grading_scale: cfg.grading_scale,
      display_name: cfg.display_name || '',
      sort_order: String(cfg.sort_order ?? 0),
      is_active: cfg.is_active,
      error: null,
      submitting: false,
    });
  };

  const closeEditor = () => {
    if (editor.submitting) return;
    setEditor(emptyEditor());
  };

  const submitEditor = async (e: React.FormEvent) => {
    e.preventDefault();
    setEditor((s) => ({ ...s, error: null, submitting: true }));

    if (!editor.grading_scale) {
      setEditor((s) => ({ ...s, error: 'Please choose a grading scale.', submitting: false }));
      return;
    }
    const sort = Number(editor.sort_order);
    if (!Number.isFinite(sort)) {
      setEditor((s) => ({ ...s, error: 'Sort order must be a number.', submitting: false }));
      return;
    }

    const payload: EducationLevelConfigInput = {
      level: editor.level,
      grading_scale: editor.grading_scale,
      display_name: editor.display_name.trim() || null,
      sort_order: sort,
      is_active: editor.is_active,
    };

    try {
      if (editor.target) {
        await schoolSettings.updateEducationLevelConfig(editor.target.uid, payload);
        flashSuccess(`Updated "${payload.display_name || editor.target.level_label}".`);
      } else {
        await schoolSettings.createEducationLevelConfig(payload);
        flashSuccess(`Added "${payload.display_name || editor.level}".`);
      }
      setEditor(emptyEditor());
    } catch (err: any) {
      setEditor((s) => ({
        ...s,
        error: err?.message || 'Failed to save education level config',
        submitting: false,
      }));
    }
  };

  const confirmDelete = async () => {
    if (!pendingDeleteUid) return;
    try {
      await schoolSettings.deleteEducationLevelConfig(pendingDeleteUid);
      flashSuccess(`Removed "${pendingDeleteLabel}".`);
      setPendingDeleteUid(null);
      setPendingDeleteLabel('');
    } catch (err: any) {
      flashError(err?.message || 'Failed to remove education level config');
      setPendingDeleteUid(null);
      setPendingDeleteLabel('');
    }
  };

  const handleSaveTenantId = async () => {
    if (form.tenant_id === undefined) return;
    setTenantSaving(true);
    setTenantError(null);
    setTenantSuccess(false);
    try {
      await api.put('/settings/tenant_id', { 
        value: form.tenant_id, 
        category: 'sync', 
        description: 'Supabase Tenant ID for Cloud Sync' 
      });
      setTenantSuccess(true);
      setTimeout(() => setTenantSuccess(false), 3000);
    } catch (err: any) {
      setTenantError(err.response?.data?.error || err.message || 'Failed to save Tenant ID');
    } finally {
      setTenantSaving(false);
    }
  };

  // ----- Ministry Reporting (weekly cron push) -----
  const loadGovPush = async () => {
    try {
      const res = await api.get('/settings/ministry-push');
      const d = res.data || {};
      setGovPush((prev) => ({
        ...prev,
        urls: typeof d.weekly_gov_push_urls === 'string' ? d.weekly_gov_push_urls : '',
        // '***' = server has a secret but masked it; don't overwrite the
        // local form input with the sentinel.
        auth: d.weekly_gov_push_auth === '***' ? '' : (d.weekly_gov_push_auth || ''),
        hmacSecret: d.weekly_gov_push_hmac_secret === '***' ? '' : (d.weekly_gov_push_hmac_secret || ''),
        schoolId: d.weekly_gov_push_school_id || '',
      }));
    } catch (err: any) {
      console.warn('Failed to load Ministry push config:', err);
    }
  };

  const loadGovPushStatus = async () => {
    try {
      const res = await api.get('/audit', { params: { action: 'gov_push_ok', limit: 1 } });
      const ok = res.data?.logs?.[0];
      const res2 = await api.get('/audit', { params: { action: 'gov_push_failed', limit: 1 } });
      const fail = res2.data?.logs?.[0];
      const latest = [ok, fail]
        .filter(Boolean)
        .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0];
      if (latest) {
        setGovPush((prev) => ({
          ...prev,
          lastPushAt: latest.created_at,
          lastPushStatus: latest.action === 'gov_push_ok' ? 'ok' : 'failed',
        }));
      }
    } catch (err) {
      // /audit may not be reachable; non-fatal.
    }
  };

  const saveGovPush = async () => {
    setGovPushSaving(true);
    setGovPushError(null);
    setGovPushSuccess(false);
    try {
      const payload = {
        weekly_gov_push_urls: govPush.urls,
        weekly_gov_push_auth: govPush.auth,
        weekly_gov_push_hmac_secret: govPush.hmacSecret,
        weekly_gov_push_school_id: govPush.schoolId,
      };
      await api.put('/settings/ministry-push', payload);
      setGovPushSuccess(true);
      setTimeout(() => setGovPushSuccess(false), 3000);
      // Re-read so the masked sentinel comes back as '***' if a real
      // value is now stored.
      loadGovPush();
    } catch (err: any) {
      setGovPushError(err?.response?.data?.error || err?.message || 'Failed to save Ministry push config');
    } finally {
      setGovPushSaving(false);
    }
  };

  const pushGovPushNow = async () => {
    setGovPushPushing(true);
    setGovPushError(null);
    try {
      const res = await api.post('/api/admin/dev/run-push/now', {}, { params: { force: 1 } });
      const data = res.data || {};
      if (data.skipped) {
        setGovPushError('Push skipped: ' + (data.reason || 'unknown'));
      } else {
        // Refresh status indicator
        loadGovPushStatus();
      }
    } catch (err: any) {
      setGovPushError(err?.response?.data?.error || err?.message || 'Push trigger failed');
    } finally {
      setGovPushPushing(false);
    }
  };

  // Load Ministry push config + status when the Integrations tab is opened.
  // We piggyback on the existing loadSettings() by also triggering ours.
  useEffect(() => {
    if (activeTab === 'integrations') {
      loadGovPush();
      loadGovPushStatus();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab]);

  if (loading) return (
    <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
      <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
      <p className="font-black uppercase tracking-[3px] text-[0.6rem]">Accessing System Parameters...</p>
    </div>
  );

  const tabs = [
    { id: 'general', label: 'Core Identity', icon: Building2 },
    { id: 'academic', label: 'Academic Engine', icon: GraduationCap },
    { id: 'integrations', label: 'API & Integrations', icon: Webhook },
    { id: 'security', label: 'Security Vault', icon: ShieldCheck },
    { id: 'data', label: 'Data & Backups', icon: Database },
  ] as const;

  return (
    <div className="space-y-8 animate-in fade-in duration-700 pb-10">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight uppercase">System Control Center</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Administration</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Master Configuration</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button 
            className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary-dark transition-all shadow-lg shadow-primary/10 active:scale-95 disabled:opacity-50"
            onClick={handleSubmit}
            disabled={saving}
          >
            {saving ? <RefreshCw size={18} className="animate-spin" /> : <Save size={18} />}
            {saving ? 'Syncing...' : 'Commit Changes'}
          </button>
        </div>
      </div>

      {/* License Status & Provider Sync Control Center Banner */}
      <LicenseSourceBanner />

      {/* Tab Navigation */}
      <div className="flex overflow-x-auto gap-2 p-1.5 bg-card border border-border rounded-2xl shadow-sm">
        {tabs.map(tab => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`flex items-center gap-2 px-5 py-3 rounded-xl text-sm font-bold transition-all whitespace-nowrap ${
              activeTab === tab.id 
                ? 'bg-primary text-white shadow-md' 
                : 'text-text-muted hover:bg-background-alt hover:text-text'
            }`}
          >
            <tab.icon size={16} />
            {tab.label}
          </button>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        {/* Main Content Area (8/12) */}
        <div className="lg:col-span-8 space-y-6">
          
          {error && (
              <div className="p-4 bg-rose-50 dark:bg-rose-900/20 border border-rose-100 dark:border-rose-800 rounded-2xl flex items-center gap-3 animate-in shake-in duration-300">
                  <Info className="text-rose-600 dark:text-rose-400" size={18} />
                  <span className="text-rose-700 dark:text-rose-300 text-sm font-bold">{error}</span>
              </div>
          )}

          {success && (
              <div className="p-4 bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-100 dark:border-emerald-800 rounded-2xl flex items-center gap-3 animate-in slide-in-from-bottom-2 duration-300">
                  <CheckCircle2 className="text-emerald-600 dark:text-emerald-400" size={18} />
                  <span className="text-emerald-700 dark:text-emerald-300 text-sm font-bold uppercase tracking-widest">Environment Parameters Synchronized</span>
              </div>
          )}

          {/* GENERAL TAB */}
          {activeTab === 'general' && (
            <div className="bg-card border border-border rounded-[2.5rem] p-10 shadow-sm relative overflow-hidden animate-in fade-in zoom-in-95 duration-300">
                <div className="absolute top-0 right-0 w-48 h-48 bg-primary/5 rounded-bl-full -mr-16 -mt-16 pointer-events-none"></div>
                <div className="relative z-10 space-y-8">
                    <div className="flex items-center gap-4 mb-2">
                        <div className="p-3 rounded-2xl bg-primary/10 text-primary border border-primary/20 shadow-sm">
                            <Building2 size={24} />
                        </div>
                        <div>
                            <h3 className="text-xl font-black text-text tracking-tight uppercase">Core Identity</h3>
                            <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest mt-1">Institutional Identification Data</p>
                        </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                        <div className="space-y-2">
                            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-2">
                                Institutional Name
                            </label>
                            <input
                                className="form-input text-text"
                                type="text"
                                value={form.school_name}
                                onChange={(e) => handleChange('school_name', e.target.value)}
                                placeholder="e.g., NextGen Academy"
                            />
                        </div>

                        <div className="space-y-2">
                            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-2">
                                Academic Cycle
                            </label>
                            <input
                                className="form-input text-text"
                                type="text"
                                value={form.academic_year}
                                onChange={(e) => handleChange('academic_year', e.target.value)}
                                placeholder="e.g., 2026-2027"
                            />
                        </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                        <div className="space-y-2">
                            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-2">
                                Institutional Address
                            </label>
                            <input
                                className="form-input text-text"
                                type="text"
                                value={form.school_address}
                                onChange={(e) => handleChange('school_address', e.target.value)}
                                placeholder="e.g., 1 Africa Way, Harare"
                            />
                            <p className="text-[0.6rem] text-text-muted italic px-1 mt-1">* Printed on report cards and the system letterhead.</p>
                        </div>

                        <div className="space-y-2">
                            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-2">
                                Institutional Motto
                            </label>
                            <input
                                className="form-input text-text"
                                type="text"
                                value={form.school_motto}
                                onChange={(e) => handleChange('school_motto', e.target.value)}
                                placeholder='e.g., "Knowledge with Discipline"'
                            />
                            <p className="text-[0.6rem] text-text-muted italic px-1 mt-1">* Italicised on the report card header.</p>
                        </div>
                    </div>

                    <div className="space-y-4">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-2">
                            Institutional Logo
                        </label>
                        <div className="flex flex-col sm:flex-row items-center gap-6 p-6 bg-muted/40 rounded-3xl border border-border dark:bg-background/40">
                            <div className="w-24 h-24 rounded-2xl bg-card border border-border flex items-center justify-center overflow-hidden shadow-sm shrink-0">
                                {form.school_logo_url ? (
                                    <img 
                                      src={form.school_logo_url} 
                                      alt="School Logo" 
                                      className="w-full h-full object-contain" 
                                    />
                                ) : (
                                    <Building2 className="text-text-muted/30" size={32} />
                                )}
                            </div>
                            <div className="space-y-2 text-center sm:text-left">
                                <p className="text-xs font-bold text-text">Upload institutional emblem</p>
                                <p className="text-[0.6rem] text-text-muted">PNG, JPG, or SVG up to 5MB. Auto-synced to cloud registry.</p>
                                <input 
                                    type="file" 
                                    accept="image/*"
                                    id="logo-upload"
                                    className="hidden"
                                    onChange={handleLogoUpload}
                                    disabled={uploadingLogo}
                                />
                                <label 
                                    htmlFor="logo-upload"
                                    className={`inline-flex items-center gap-2 px-4 py-2 ${uploadingLogo ? 'bg-muted text-text-muted cursor-not-allowed' : 'bg-primary/10 hover:bg-primary/20 text-primary cursor-pointer'} rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all active:scale-95`}
                                >
                                    {uploadingLogo ? 'Uploading...' : 'Select Image'}
                                </label>
                            </div>
                        </div>
                    </div>

                    <div className="space-y-2">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-2">
                            System Communication Hub (Email)
                        </label>
                        <input
                            className="form-input text-text"
                            type="email"
                            value={form.system_email}
                            onChange={(e) => handleChange('system_email', e.target.value)}
                            placeholder="admin@nextgen.edu"
                        />
                        <p className="text-[0.6rem] font-medium text-text-muted italic px-1 mt-1">* This address will be used for all system-wide transmissions and critical alerts.</p>
                    </div>
                </div>
            </div>
          )}

          {/* ACADEMIC TAB — Academic Engine (Grading Scale + Education Levels) */}
          {activeTab === 'academic' && (
          <>
            {/* Hero / overview card */}
            <div className="bg-gradient-to-br from-card via-card to-primary/5 border border-border rounded-[2.5rem] p-8 shadow-sm relative overflow-hidden">
                <div className="absolute -top-10 -right-10 opacity-[0.05] rotate-12 pointer-events-none">
                    <Sparkles size={220} />
                </div>
                <div className="relative z-10 space-y-7">
                    {/* Title block — full width, no competing columns */}
                    <div className="flex items-start gap-4">
                        <div className="flex-shrink-0 p-4 rounded-2xl bg-primary/10 text-primary border border-primary/20 shadow-sm">
                            <GraduationCap size={28} />
                        </div>
                        <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-2 flex-wrap">
                                <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted whitespace-nowrap">
                                    Academic Engine
                                </span>
                                <span className="px-2 py-0.5 rounded-full bg-primary/10 text-primary text-[0.55rem] font-black uppercase tracking-widest border border-primary/20">
                                    Shaping
                                </span>
                            </div>
                            <h2 className="text-2xl md:text-3xl font-black text-text tracking-tight">
                                Marking &amp; Terminology
                            </h2>
                            <p className="text-sm text-text-muted mt-2 max-w-3xl leading-relaxed">
                                Bind each education level to its marking scale and custom display name.
                                Changes ripple through marks, exams, classes and dashboards instantly.
                            </p>
                        </div>
                    </div>

                    {/* Quick stats — full width row beneath the title */}
                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                        {/* Active levels */}
                        <div className="group/stat relative px-5 py-4 bg-card/80 backdrop-blur border border-border rounded-2xl hover:border-blue-500/50 transition-colors">
                            <div className="flex items-center justify-between mb-3">
                                <span className="inline-flex items-center justify-center w-9 h-9 rounded-xl bg-blue-500/10 text-blue-600 border border-blue-500/20">
                                    <Layers size={16} />
                                </span>
                                <span className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">
                                    Active
                                </span>
                            </div>
                            <div className="flex items-baseline gap-1.5">
                                <span className="text-3xl font-black text-text tracking-tight leading-none">
                                    {schoolSettings.educationLevelConfigs.filter((c) => c.is_active).length}
                                </span>
                                <span className="text-base font-bold text-text-muted">
                                    / {schoolSettings.educationLevelConfigs.length}
                                </span>
                            </div>
                            <div className="text-[0.65rem] font-bold text-text-muted uppercase tracking-wider mt-1">
                                Education Levels
                            </div>
                        </div>

                        {/* Default scale */}
                        <div className="group/stat relative px-5 py-4 bg-card/80 backdrop-blur border border-border rounded-2xl hover:border-emerald-500/50 transition-colors">
                            <div className="flex items-center justify-between mb-3">
                                <span className="inline-flex items-center justify-center w-9 h-9 rounded-xl bg-emerald-500/10 text-emerald-600 border border-emerald-500/20">
                                    <Award size={16} />
                                </span>
                                <span className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">
                                    Default
                                </span>
                            </div>
                            <div
                                className="text-lg font-black text-text leading-tight truncate"
                                title={schoolSettings.defaultGradingScaleLabel || ''}
                            >
                                {schoolSettings.defaultGradingScaleLabel || '—'}
                            </div>
                            <div className="text-[0.65rem] font-bold text-text-muted uppercase tracking-wider mt-1">
                                {Term.GRADING_SCALE}
                            </div>
                        </div>

                        {/* Scales available */}
                        <div className="group/stat relative px-5 py-4 bg-card/80 backdrop-blur border border-border rounded-2xl hover:border-primary/50 transition-colors">
                            <div className="flex items-center justify-between mb-3">
                                <span className="inline-flex items-center justify-center w-9 h-9 rounded-xl bg-primary/10 text-primary border border-primary/20">
                                    <ListChecks size={16} />
                                </span>
                                <span className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">
                                    Library
                                </span>
                            </div>
                            <div className="flex items-baseline gap-1.5">
                                <span className="text-3xl font-black text-text tracking-tight leading-none">
                                    {schoolSettings.scaleOptions.length}
                                </span>
                                <span className="text-base font-bold text-text-muted">
                                    scales
                                </span>
                            </div>
                            <div className="text-[0.65rem] font-bold text-text-muted uppercase tracking-wider mt-1">
                                Available to Pick
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Unified save banner */}
            {academicBanner && (
                <div
                    role="status"
                    className={`p-4 rounded-2xl flex items-center gap-3 border animate-in slide-in-from-top-2 duration-300 ${
                        academicBanner.kind === 'success'
                            ? 'bg-emerald-50 dark:bg-emerald-950/30 border-emerald-200 dark:border-emerald-900 text-emerald-700 dark:text-emerald-300'
                            : 'bg-rose-50 dark:bg-rose-950/30 border-rose-200 dark:border-rose-900 text-rose-700 dark:text-rose-300'
                    }`}
                >
                    {academicBanner.kind === 'success' ? <CheckCircle2 size={18} /> : <AlertTriangle size={18} />}
                    <span className="text-sm font-bold flex-1">{academicBanner.message}</span>
                    <button
                        type="button"
                        onClick={() => setAcademicBanner(null)}
                        className="text-xs font-black uppercase tracking-widest opacity-70 hover:opacity-100"
                        aria-label="Dismiss banner"
                    >
                        Dismiss
                    </button>
                </div>
            )}

            {/* ───────────────────────────  UNIFIED — Grading & Levels  ─────────────────────────── */}
            <section className="bg-card border border-border rounded-[2.5rem] shadow-sm relative overflow-hidden">
                {/* Header */}
                <div className="px-8 pt-7 pb-6 flex flex-col md:flex-row md:items-center gap-5 border-b border-border bg-gradient-to-r from-blue-500/5 via-blue-500/0 to-transparent relative">
                    <div className="absolute right-[-60px] top-[-40px] opacity-[0.04] rotate-12 pointer-events-none">
                        <BookOpen size={180} />
                    </div>
                    <div className="flex items-center gap-4 flex-1 min-w-0 relative z-10">
                        <div className="p-3 rounded-2xl bg-blue-500/10 text-blue-600 border border-blue-500/20 shadow-sm">
                            <BookOpen size={22} />
                        </div>
                        <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 flex-wrap">
                                <h3 className="text-xl font-black text-text tracking-tight">Marking &amp; Levels</h3>
                                <span className="text-[0.55rem] font-black uppercase tracking-widest text-blue-600 bg-blue-500/10 px-2 py-0.5 rounded-full border border-blue-500/20">
                                    Unified
                                </span>
                            </div>
                            <p className="text-sm text-text-muted mt-1">
                                One row per education level. Each row binds a level to its marking scale + display name — change either from here and they update together.
                            </p>
                        </div>
                    </div>
                    <button
                        type="button"
                        onClick={openCreateEditor}
                        disabled={!isScaleAdmin || schoolSettings.educationLevelConfigs.length >= 4}
                        className="group/btn relative inline-flex items-center gap-2 px-6 py-3 bg-gradient-to-br from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white rounded-2xl font-bold text-sm transition-all shadow-lg shadow-blue-500/20 hover:shadow-xl hover:shadow-blue-500/30 hover:-translate-y-0.5 active:translate-y-0 active:scale-95 disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:translate-y-0 disabled:hover:shadow-lg relative z-10"
                        title={
                            !isScaleAdmin
                                ? 'Only school admins can add levels'
                                : schoolSettings.educationLevelConfigs.length >= 4
                                ? 'All 4 canonical levels are already configured'
                                : 'Add a new education level'
                        }
                    >
                        <Plus size={18} className="transition-transform group-hover/btn:rotate-90" />
                        Add Level
                    </button>
                </div>

                <div className="p-8 space-y-6">
                    {/* Default fallback panel — mirrors the row flagged is_default = 1 */}
                    {(() => {
                      const defaultRow =
                        schoolSettings.educationLevelConfigs.find((c) => c.is_default) ||
                        schoolSettings.educationLevelConfigs.find((c) => c.is_active);
                      const defaultName = defaultRow?.display_name || defaultRow?.level_label || '—';
                      const defaultScale = defaultRow?.grading_scale_label || '—';
                      return (
                        <div className="grid grid-cols-1 lg:grid-cols-5 gap-5 p-5 bg-muted/30 border border-emerald-500/30 rounded-2xl">
                            <div className="lg:col-span-2 space-y-2">
                                <div className="flex items-center gap-2">
                                    <span className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">
                                        Default Fallback
                                    </span>
                                    <span className="text-[0.55rem] font-black uppercase tracking-widest text-emerald-600 bg-emerald-500/10 px-1.5 py-0.5 rounded-full border border-emerald-500/20">
                                        Live
                                    </span>
                                </div>
                                <div className="flex items-baseline gap-1.5 flex-wrap">
                                    <Star size={14} className="text-emerald-600 fill-emerald-500" />
                                    <span className="text-base font-black text-text">{defaultName}</span>
                                    <ArrowRight size={11} className="text-text-muted" />
                                    <span className="text-[0.7rem] font-black uppercase tracking-tight px-2 py-0.5 rounded-md bg-emerald-500/10 text-emerald-700 border border-emerald-500/20">
                                        {defaultScale}
                                    </span>
                                </div>
                                <p className="text-xs text-text-muted leading-relaxed">
                                    Used when a mark doesn't carry an explicit level assignment.
                                    Pick any level below as the default — its scale becomes the fallback.
                                </p>
                                <button
                                    type="button"
                                    onClick={() => { if (defaultRow) openEditEditor(defaultRow); }}
                                    disabled={!isScaleAdmin || !defaultRow}
                                    className="text-[0.6rem] font-black uppercase tracking-widest text-blue-600 hover:text-blue-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                                >
                                    {defaultRow ? '↗ Edit default level' : 'Add a level to set as default'}
                                </button>
                            </div>

                            <div className="lg:col-span-3 space-y-2">
                                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center justify-between">
                                    <span>Live Preview</span>
                                    <span className="text-text-muted/70 normal-case tracking-normal text-[0.6rem] font-bold">
                                        {defaultScale}
                                    </span>
                                </label>
                                <div className="p-3 bg-card rounded-2xl border border-border space-y-1.5">
                                    {[85, 65, 35].map((pct) => (
                                        <div key={pct} className="flex items-center gap-2">
                                            <span className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted w-10">
                                                {pct}%
                                            </span>
                                            <div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden">
                                                <div
                                                    className="h-full bg-gradient-to-r from-emerald-500 via-amber-500 to-rose-500 rounded-full"
                                                    style={{ width: `${pct}%` }}
                                                />
                                            </div>
                                            <GradeBadge percentage={pct} gradingScale={defaultRow?.grading_scale || schoolSettings.defaultGradingScale} size="sm" />
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                      );
                    })()}

                    {/* Terminology strip — shows every level ↔ scale binding at a glance */}
                    {schoolSettings.educationLevelConfigs.length > 0 && (
                        <div className="space-y-2">
                            <div className="flex items-center justify-between">
                                <h4 className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">
                                    Terminology Map
                                </h4>
                                <span className="text-[0.6rem] font-bold text-text-muted">
                                    {schoolSettings.educationLevelConfigs.length} of 4 levels
                                </span>
                            </div>
                            <div className="flex flex-wrap gap-2.5">
                                {schoolSettings.educationLevelConfigs.map((cfg) => (
                                    <div
                                        key={cfg.uid}
                                        className={`group/pill inline-flex items-center gap-2 px-4 py-2 rounded-2xl border text-sm font-bold transition-all ${
                                            cfg.is_active
                                                ? cfg.is_default
                                                    ? 'bg-emerald-500/10 text-emerald-700 border-emerald-500/30 hover:bg-emerald-500/15 hover:border-emerald-500/50'
                                                    : 'bg-blue-500/10 text-blue-700 border-blue-500/30 hover:bg-blue-500/15 hover:border-blue-500/50'
                                                : 'bg-muted text-text-muted border-border opacity-70'
                                        }`}
                                        title={`${cfg.display_name || cfg.level_label} · ${cfg.grading_scale_label}${cfg.is_default ? ' · Default fallback' : ''}`}
                                    >
                                        {cfg.is_default && cfg.is_active && (
                                            <Star size={12} className="text-emerald-600 fill-emerald-500" />
                                        )}
                                        <span className={cfg.is_active ? '' : 'line-through'}>
                                            {cfg.display_name || cfg.level_label}
                                        </span>
                                        <ArrowRight size={12} className="opacity-50" />
                                        <span className="text-[0.65rem] font-black uppercase tracking-widest text-text-secondary bg-card/60 px-2 py-0.5 rounded-md border border-border">
                                            {cfg.grading_scale_label}
                                        </span>
                                        {cfg.is_default && cfg.is_active && (
                                            <span className="text-[0.55rem] font-black uppercase tracking-widest text-emerald-600 bg-emerald-500/10 px-1.5 py-0.5 rounded-md border border-emerald-500/20">
                                                Default
                                            </span>
                                        )}
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}

                    {/* Configs table or empty state */}
                    {schoolSettings.educationLevelConfigs.length === 0 ? (
                        <div className="rounded-2xl border-2 border-dashed border-blue-500/30 bg-blue-500/5 p-12 text-center">
                            <div className="inline-flex p-5 rounded-3xl bg-blue-500/15 text-blue-500 mb-5 shadow-sm">
                                <BookOpen size={36} />
                            </div>
                            <h4 className="text-xl font-black text-text mb-2">
                                {schoolSettings.loading ? 'Loading education levels…' : 'No education levels yet'}
                            </h4>
                            <p className="text-sm text-text-muted max-w-md mx-auto mb-6 leading-relaxed">
                                Add the first education level (e.g. <strong>Primary</strong> or <strong>Secondary</strong>)
                                to bind it to a marking scale and shape the in-app terminology.
                            </p>
                            <button
                                type="button"
                                onClick={openCreateEditor}
                                disabled={!isScaleAdmin}
                                className="inline-flex items-center gap-2 px-6 py-3 bg-gradient-to-br from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white rounded-2xl font-bold text-sm transition-all shadow-lg shadow-blue-500/20 hover:shadow-xl hover:shadow-blue-500/30 hover:-translate-y-0.5 active:scale-95 disabled:opacity-40 disabled:cursor-not-allowed"
                            >
                                <Plus size={18} />
                                Add First Level
                            </button>
                        </div>
                    ) : (
                        <div className="rounded-2xl border border-border overflow-hidden bg-card">
                            <div className="overflow-x-auto">
                                <table className="w-full text-left text-sm">
                                    <thead className="bg-muted/50 text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">
                                        <tr>
                                            <th className="px-5 py-3.5">Level</th>
                                            <th className="px-5 py-3.5">Display Name</th>
                                            <th className="px-5 py-3.5">{Term.GRADING_SCALE}</th>
                                            <th className="px-5 py-3.5">Order</th>
                                            <th className="px-5 py-3.5">Status</th>
                                            <th className="px-5 py-3.5 text-right">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-border">
                                        {schoolSettings.educationLevelConfigs.map((cfg) => {
                                            const isDefault = cfg.is_default;
                                            return (
                                                <tr
                                                    key={cfg.uid}
                                                    className={`hover:bg-blue-500/5 transition-colors group ${isDefault ? 'bg-emerald-500/5' : ''}`}
                                                >
                                                    <td className="px-5 py-4">
                                                        <div className="flex items-center gap-3">
                                                            <span className={`p-2 rounded-xl ${cfg.is_active ? isDefault ? 'bg-emerald-500/15 text-emerald-600 border border-emerald-500/30' : 'bg-blue-500/10 text-blue-500' : 'bg-muted text-text-muted'}`}>
                                                                <BookOpen size={14} />
                                                            </span>
                                                            <div>
                                                                <div className="flex items-center gap-2">
                                                                    <span className={`font-black text-sm ${cfg.is_active ? 'text-text' : 'text-text-muted'}`}>
                                                                        {cfg.level_label}
                                                                    </span>
                                                                    {isDefault && cfg.is_active && (
                                                                        <span className="text-[0.5rem] font-black uppercase tracking-widest text-emerald-600 bg-emerald-500/10 px-1.5 py-0.5 rounded border border-emerald-500/20">
                                                                            Default
                                                                        </span>
                                                                    )}
                                                                </div>
                                                                <div className="text-[0.6rem] font-mono text-text-muted uppercase tracking-wider">
                                                                    {cfg.level}
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td className="px-5 py-4 text-text-secondary">
                                                        {cfg.display_name ? (
                                                            <span className="text-text-secondary">{cfg.display_name}</span>
                                                        ) : (
                                                            <span className="text-text-muted/60 italic text-xs">uses default</span>
                                                        )}
                                                    </td>
                                                    <td className="px-5 py-4">
                                                        <span className="inline-flex items-center gap-1.5 text-[0.7rem] font-black uppercase tracking-tight px-2.5 py-1 rounded-md bg-emerald-500/10 text-emerald-700 border border-emerald-500/20">
                                                            <Award size={11} />
                                                            {cfg.grading_scale_label}
                                                        </span>
                                                    </td>
                                                    <td className="px-5 py-4">
                                                        <span className="font-mono text-xs px-2 py-1 rounded-md bg-muted text-text-muted">
                                                            #{cfg.sort_order}
                                                        </span>
                                                    </td>
                                                    <td className="px-5 py-4">
                                                        <span className={`inline-flex items-center gap-1.5 text-[0.6rem] font-black uppercase tracking-widest px-2.5 py-1 rounded-full border ${
                                                            cfg.is_active
                                                                ? 'bg-emerald-500/10 text-emerald-600 border-emerald-500/20'
                                                                : 'bg-muted text-text-muted border-border'
                                                        }`}>
                                                            <span className={`w-1.5 h-1.5 rounded-full ${cfg.is_active ? 'bg-emerald-500 animate-pulse' : 'bg-text-muted'}`} />
                                                            {cfg.is_active ? 'Active' : 'Inactive'}
                                                        </span>
                                                    </td>
                                                    <td className="px-5 py-4 text-right whitespace-nowrap">
                                                        <div className="inline-flex items-center gap-1 opacity-50 group-hover:opacity-100 transition-opacity">
                                                            <button
                                                                type="button"
                                                                onClick={async () => {
                                                                    if (isDefault) return;
                                                                    try {
                                                                        await schoolSettings.setDefaultLevel(cfg.uid);
                                                                        // Defense-in-depth: re-hydrate from the server so every
                                                                        // mounted consumer (Nav, ClassRoom, dashboards) sees
                                                                        // the new education level on the next render. The store
                                                                        // already optimistically updates educationLevel inside
                                                                        // setDefaultLevel; this catches any server-side drift.
                                                                        await schoolSettings.fetchSettings();
                                                                        flashSuccess(`Default fallback set to "${cfg.display_name || cfg.level_label}".`);
                                                                    } catch (err: any) {
                                                                        flashError(err?.message || 'Failed to set default level');
                                                                    }
                                                                }}
                                                                disabled={!isScaleAdmin || !cfg.is_active || isDefault}
                                                                title={
                                                                    isDefault
                                                                        ? 'Currently the default'
                                                                        : 'Set this level as the default fallback'
                                                                }
                                                                aria-label={isDefault ? 'Current default' : `Set ${cfg.level_label} as default`}
                                                                className={`inline-flex items-center justify-center w-7 h-7 rounded-lg transition-all disabled:opacity-30 disabled:cursor-not-allowed ${
                                                                    isDefault
                                                                        ? 'text-emerald-600 bg-emerald-500/15 border border-emerald-500/30 cursor-default'
                                                                        : 'text-text-muted hover:bg-emerald-500/15 hover:text-emerald-600 hover:border hover:border-emerald-500/30 border border-transparent'
                                                                }`}
                                                            >
                                                                <Star size={14} className={isDefault ? 'fill-emerald-500' : ''} />
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => openEditEditor(cfg)}
                                                                disabled={!isScaleAdmin}
                                                                className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg hover:bg-primary hover:text-white text-text-muted text-xs font-bold transition-all disabled:opacity-30 disabled:cursor-not-allowed"
                                                                title="Edit level + scale"
                                                                aria-label={`Edit ${cfg.level_label}`}
                                                            >
                                                                <Pencil size={12} />
                                                                Edit
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => {
                                                                    setPendingDeleteUid(cfg.uid);
                                                                    setPendingDeleteLabel(cfg.display_name || cfg.level_label);
                                                                }}
                                                                disabled={!isScaleAdmin}
                                                                className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg hover:bg-rose-500 hover:text-white text-text-muted text-xs font-bold transition-all disabled:opacity-30 disabled:cursor-not-allowed"
                                                                title={isDefault ? 'Remove (will unset default)' : 'Remove level'}
                                                                aria-label={`Remove ${cfg.level_label}`}
                                                            >
                                                                <Trash2 size={12} />
                                                                Remove
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                            );
                                        })}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    )}

                    <p className="text-[0.65rem] font-medium text-text-muted px-1 leading-relaxed">
                        <strong>Tip:</strong> Levels are ordered by the <code className="px-1.5 py-0.5 bg-muted rounded text-[0.6rem] font-mono">Order</code> column
                        and rendered in the dashboard + reports.
                        <strong className="ml-1">Inactive</strong> rows stay in the database for audit + restore but stop shaping the UI.
                        Click the <Star size={10} className="inline text-emerald-600 fill-emerald-500 mx-0.5" /> star on any row to make it the <strong className="text-emerald-600">default fallback</strong> for marks without an explicit level.
                        {!isScaleAdmin && (
                            <span className="block mt-1 text-amber-600 font-bold">Read-only — admins only.</span>
                        )}
                    </p>
                </div>
            </section>
          </>
          )}

          {/* Education Level Editor modal */}
          {editor.open && createPortal(
            <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={closeEditor}>
                <div className="bg-card rounded-[2.5rem] w-full max-w-xl max-h-[90vh] flex flex-col shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border" onClick={(e) => e.stopPropagation()}>
                    <div className="px-10 py-8 bg-gradient-to-br from-blue-500/10 via-blue-500/5 to-transparent border-b border-border flex justify-between items-center relative overflow-hidden flex-shrink-0">
                        <div className="absolute right-[-20px] top-[-20px] opacity-[0.04] rotate-12">
                            <BookOpen size={200} />
                        </div>
                        <div className="relative z-10">
                            <div className="text-[0.6rem] font-black uppercase tracking-[3px] text-blue-600 mb-1">
                                {editor.target ? 'Edit' : 'New'}
                            </div>
                            <h2 className="text-2xl font-black text-text tracking-tight font-heading">
                                {editor.target ? 'Edit Education Level' : 'Add Education Level'}
                            </h2>
                            <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">
                                {editor.target
                                    ? `Update "${editor.target.level_label}"`
                                    : `Bind a new level to a ${Term.GRADING_SCALE.toLowerCase()}`}
                            </p>
                        </div>
                        <button
                            type="button"
                            onClick={closeEditor}
                            disabled={editor.submitting}
                            className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 hover:border-rose-500/20 hover:bg-rose-50/5 transition-all disabled:opacity-40"
                            aria-label="Close"
                        >
                            <X size={20} />
                        </button>
                    </div>

                    <form onSubmit={submitEditor} className="p-10 space-y-6 overflow-y-auto flex-1">
                        {editor.error && (
                            <div className="p-4 bg-rose-50 dark:bg-rose-950/30 border border-rose-200 dark:border-rose-900 rounded-2xl flex items-center gap-3 text-rose-700 dark:text-rose-300 animate-in shake-in duration-300">
                                <AlertTriangle size={18} />
                                <span className="text-sm font-bold">{editor.error}</span>
                            </div>
                        )}

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                            <div className="space-y-2">
                                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-2">
                                    Education Level
                                    <span className="text-rose-500">*</span>
                                    {!editor.target && (
                                        <span className="text-[0.55rem] text-text-muted/70 normal-case tracking-normal font-bold ml-auto">
                                            next unused
                                        </span>
                                    )}
                                </label>
                                <select
                                    value={editor.level}
                                    onChange={(e) => setEditor((s) => ({ ...s, level: e.target.value as EducationLevelKey }))}
                                    disabled={!!editor.target}
                                    className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/10 focus:bg-card focus:border-primary transition-all appearance-none cursor-pointer disabled:opacity-60 disabled:cursor-not-allowed"
                                >
                                    {schoolSettings.educationLevelOptions.map((opt) => {
                                        const isUsed = !editor.target &&
                                            schoolSettings.educationLevelConfigs.some((c) => c.level === opt.value);
                                        return (
                                            <option key={opt.value} value={opt.value} disabled={isUsed}>
                                                {opt.label}{isUsed ? '  (already added)' : ''}
                                            </option>
                                        );
                                    })}
                                </select>
                                <p className="text-[0.6rem] text-text-muted italic px-1 leading-relaxed">
                                    One row per canonical level. Can't be changed after creation — delete and re-add to switch levels.
                                </p>
                            </div>

                            <div className="space-y-2">
                                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1">
                                    {Term.GRADING_SCALE} <span className="text-rose-500">*</span>
                                </label>
                                <select
                                    value={editor.grading_scale}
                                    onChange={(e) => setEditor((s) => ({ ...s, grading_scale: e.target.value }))}
                                    className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/10 focus:bg-card focus:border-primary transition-all appearance-none cursor-pointer"
                                    required
                                >
                                    {schoolSettings.scaleOptions.map((opt) => (
                                        <option key={opt.key} value={opt.key}>{opt.label}</option>
                                    ))}
                                </select>
                                <p className="text-[0.6rem] text-text-muted italic px-1 leading-relaxed">
                                    Determines letter grades (A*, B, C…) and grade boundaries for this level.
                                </p>
                            </div>

                            <div className="space-y-2 sm:col-span-2">
                                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1">
                                    Display Name <span className="text-text-muted/60 normal-case tracking-normal font-bold">(optional override)</span>
                                </label>
                                <input
                                    type="text"
                                    value={editor.display_name}
                                    onChange={(e) => setEditor((s) => ({ ...s, display_name: e.target.value }))}
                                    className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/10 focus:bg-card focus:border-primary transition-all"
                                    placeholder="e.g. Lower Secondary, Junior High, Grade 8–9"
                                />
                                <p className="text-[0.6rem] text-text-muted italic px-1">
                                    Custom label shown in the UI. Falls back to the canonical name (e.g. "Secondary (O Levels)") when blank.
                                </p>
                            </div>

                            <div className="space-y-2">
                                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1">
                                    Sort Order
                                </label>
                                <input
                                    type="number"
                                    value={editor.sort_order}
                                    onChange={(e) => setEditor((s) => ({ ...s, sort_order: e.target.value }))}
                                    className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/10 focus:bg-card focus:border-primary transition-all"
                                    placeholder="50"
                                />
                                <p className="text-[0.6rem] text-text-muted italic px-1">
                                    Lower numbers render first. Primary = 10, Secondary = 20, etc.
                                </p>
                            </div>

                            <div className="space-y-2">
                                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1">
                                    Status
                                </label>
                                <label className="flex items-center gap-3 px-5 py-4 bg-muted/50 border border-border rounded-2xl cursor-pointer hover:bg-muted/70 transition-colors">
                                    <input
                                        type="checkbox"
                                        checked={editor.is_active}
                                        onChange={(e) => setEditor((s) => ({ ...s, is_active: e.target.checked }))}
                                        className="w-5 h-5 rounded border-border text-blue-500 focus:ring-blue-500 focus:ring-2 cursor-pointer"
                                    />
                                    <div className="flex-1">
                                        <div className="text-sm font-bold text-text">Active</div>
                                        <div className="text-[0.6rem] text-text-muted">Visible in the app and shapes terminology</div>
                                    </div>
                                    <span className={`text-[0.55rem] font-black uppercase tracking-widest px-2 py-0.5 rounded-full border ${
                                        editor.is_active
                                            ? 'bg-emerald-500/10 text-emerald-600 border-emerald-500/20'
                                            : 'bg-muted text-text-muted border-border'
                                    }`}>
                                        {editor.is_active ? 'On' : 'Off'}
                                    </span>
                                </label>
                            </div>
                        </div>

                        <div className="pt-2 flex items-center justify-end gap-2 border-t border-border">
                            <button
                                type="button"
                                onClick={closeEditor}
                                disabled={editor.submitting}
                                className="px-5 py-3 rounded-2xl border border-border text-text text-sm font-bold hover:bg-muted transition-all disabled:opacity-40"
                            >
                                Cancel
                            </button>
                            <button
                                type="submit"
                                disabled={editor.submitting}
                                className="flex items-center gap-2 px-6 py-3 rounded-2xl bg-gradient-to-br from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white text-sm font-bold transition-all shadow-lg shadow-blue-500/20 hover:shadow-xl hover:shadow-blue-500/30 active:scale-95 disabled:opacity-60 disabled:cursor-not-allowed"
                            >
                                {editor.submitting ? <RefreshCw size={16} className="animate-spin" /> : editor.target ? <Save size={16} /> : <Plus size={16} />}
                                <span>{editor.submitting ? 'Saving…' : (editor.target ? 'Save Changes' : 'Add Level')}</span>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
          ,
            document.body
          )}


          {/* Delete confirm modal */}
          {pendingDeleteUid && createPortal(
            <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={() => { setPendingDeleteUid(null); setPendingDeleteLabel(''); }}>
                <div className="bg-card rounded-[2.5rem] w-full max-w-md max-h-[90vh] flex flex-col shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border" onClick={(e) => e.stopPropagation()}>
                    <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden flex-shrink-0">
                        <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                            <Trash2 size={180} />
                        </div>
                        <div className="relative z-10">
                            <h2 className="text-2xl font-black text-text tracking-tight font-heading">Remove education level?</h2>
                            <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Unbind a level from its grading scale</p>
                        </div>
                        <button
                            type="button"
                            onClick={() => { setPendingDeleteUid(null); setPendingDeleteLabel(''); }}
                            className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 hover:border-rose-500/20 hover:bg-rose-50/5 transition-all"
                            aria-label="Close"
                        >
                            <X size={20} />
                        </button>
                    </div>

                    <div className="p-10 space-y-6 overflow-y-auto flex-1">
                        <p className="text-sm text-text-muted">
                            This soft-deletes <strong className="text-text">{pendingDeleteLabel}</strong>. Terminology for that level will revert to defaults until you re-add it.
                        </p>
                        <div className="flex justify-end gap-2 border-t border-border pt-5">
                            <button
                                type="button"
                                onClick={() => { setPendingDeleteUid(null); setPendingDeleteLabel(''); }}
                                className="px-5 py-3 rounded-2xl border border-border text-text text-sm font-bold hover:bg-muted transition-all"
                            >
                                Cancel
                            </button>
                            <button
                                type="button"
                                onClick={confirmDelete}
                                disabled={schoolSettings.saving}
                                className="flex items-center gap-2 px-5 py-3 rounded-2xl bg-rose-500 text-white text-sm font-bold hover:bg-rose-600 transition-all shadow-lg shadow-rose-900/10 active:scale-95 disabled:opacity-50"
                            >
                                {schoolSettings.saving ? <RefreshCw size={14} className="animate-spin" /> : <Trash2 size={14} />}
                                <span>Remove level</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
          ,
            document.body
          )}

          {/* INTEGRATIONS TAB */}
          {activeTab === 'integrations' && (
            <div className="bg-card border border-border rounded-[2.5rem] p-10 shadow-sm relative overflow-hidden animate-in fade-in zoom-in-95 duration-300">
                <div className="absolute top-0 right-0 w-48 h-48 bg-orange-500/5 rounded-bl-full -mr-16 -mt-16 pointer-events-none"></div>
                <div className="relative z-10 space-y-8">
                    <div className="flex items-center gap-4 mb-2">
                        <div className="p-3 rounded-2xl bg-orange-500/10 text-orange-500 border border-orange-500/20 shadow-sm">
                            <Webhook size={24} />
                        </div>
                        <div>
                            <h3 className="text-xl font-black text-text tracking-tight uppercase">API Gateways</h3>
                            <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest mt-1">Manage External Connections</p>
                        </div>
                    </div>


                    <div className="p-6 border border-border rounded-2xl bg-background-alt/50 space-y-6">
                        <h4 className="text-sm font-bold text-text flex items-center gap-2"><CreditCard size={16} className="text-primary"/> Paynow Payment Gateway</h4>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                           <div className="space-y-2">
                              <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Integration ID</label>
                              <input
                                  className="form-input font-mono text-xs"
                                  type="text"
                                  value={form.paynow_integration_id || ''}
                                  onChange={(e) => handleChange('paynow_integration_id', e.target.value)}
                                  placeholder="e.g. 12345"
                              />
                          </div>
                          <div className="space-y-2">
                              <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Integration Key</label>
                              <input
                                  className="form-input font-mono text-xs"
                                  type="password"
                                  value={form.paynow_integration_key || ''}
                                  onChange={(e) => handleChange('paynow_integration_key', e.target.value)}
                                  placeholder="••••••••••••••••"
                              />
                          </div>
                        </div>
                    </div>

                    <div className="p-6 border border-border rounded-2xl bg-background-alt/50 space-y-6">
                        <h4 className="text-sm font-bold text-text flex items-center gap-2"><MessageSquare size={16} className="text-emerald-500"/> SMS Communications</h4>
                        <div className="space-y-2">
                            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Gateway API Key (Twilio / BulkSMS)</label>
                            <input
                                className="form-input font-mono text-xs"
                                type="password"
                                value={form.sms_gateway || ''}
                                onChange={(e) => handleChange('sms_gateway', e.target.value)}
                                placeholder="sk_test_..."
                            />
                        </div>
                    </div>

                    <div className="p-6 border border-border rounded-2xl bg-background-alt/50 space-y-6">
                        <h4 className="text-sm font-bold text-text flex items-center gap-2"><Database size={16} className="text-blue-500"/> Supabase Cloud Sync</h4>
                        <div className="space-y-2">
                            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Supabase Tenant ID (UUID)</label>
                            <input
                                className="form-input font-mono text-xs text-text"
                                type="text"
                                value={form.tenant_id || ''}
                                onChange={(e) => handleChange('tenant_id', e.target.value)}
                                placeholder="e.g., 123e4567-e89b-12d3-a456-426614174000"
                            />
                        </div>

                        {tenantError && (
                            <div className="text-rose-500 text-xs font-bold px-1">{tenantError}</div>
                        )}
                        {tenantSuccess && (
                            <div className="text-emerald-500 text-xs font-bold px-1 uppercase tracking-widest animate-in fade-in zoom-in-95 duration-200">Tenant ID Saved & Synced</div>
                        )}

                        <div className="flex justify-end pt-2">
                            <button
                                onClick={handleSaveTenantId}
                                disabled={tenantSaving}
                                className="flex items-center gap-2 px-6 py-2 bg-blue-500 text-white rounded-xl font-bold text-xs hover:bg-blue-600 transition-all shadow-lg shadow-blue-500/10 active:scale-95 disabled:opacity-50"
                            >
                                {tenantSaving ? <RefreshCw size={12} className="animate-spin" /> : <Save size={12} />}
                                {tenantSaving ? 'Saving...' : 'Save Tenant ID'}
                            </button>
                        </div>
                    </div>

                    {/* Ministry Reporting (weekly cron push) */}
                    <div className="p-6 border border-border rounded-2xl bg-background-alt/50 space-y-6">
                        <h4 className="text-sm font-bold text-text flex items-center gap-2">
                            <Building2 size={16} className="text-primary" />
                            Ministry Reporting (Weekly Push)
                        </h4>
                        <p className="text-[0.65rem] text-text-muted leading-relaxed">
                            Overrides the <code>WEEKLY_GOV_PUSH_*</code> env vars for the cron that pushes the weekly
                            Ministry-style report every Monday at 06:00 server-local. Empty fields fall back to env.
                        </p>

                        {govPushError && (
                            <div className="text-rose-500 text-xs font-bold px-1">{govPushError}</div>
                        )}
                        {govPushSuccess && (
                            <div className="text-emerald-500 text-xs font-bold px-1 uppercase tracking-widest">Configuration saved</div>
                        )}

                        <div className="space-y-2">
                            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">
                                Endpoint URLs (one per line, or comma-separated)
                            </label>
                            <textarea
                                className="form-input font-mono text-xs"
                                rows={3}
                                value={govPush.urls}
                                onChange={(e) => setGovPush({ ...govPush, urls: e.target.value })}
                                placeholder={'https://mopse.gov.zw/api/v1/weekly\nhttps://placeholder.example.gov.zw/api/v1/weekly'}
                            />
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div className="space-y-2">
                                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">
                                    Authorization Header Value
                                </label>
                                <input
                                    className="form-input font-mono text-xs"
                                    type="password"
                                    value={govPush.auth}
                                    onChange={(e) => setGovPush({ ...govPush, auth: e.target.value })}
                                    placeholder="Bearer xxx  (leave blank to use env fallback)"
                                />
                            </div>
                            <div className="space-y-2">
                                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">
                                    HMAC Secret (optional, for X-Signature)
                                </label>
                                <input
                                    className="form-input font-mono text-xs"
                                    type="password"
                                    value={govPush.hmacSecret}
                                    onChange={(e) => setGovPush({ ...govPush, hmacSecret: e.target.value })}
                                    placeholder="(leave blank to use env fallback)"
                                />
                            </div>
                        </div>

                        <div className="space-y-2">
                            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">
                                School ID (optional, included in envelope)
                            </label>
                            <input
                                className="form-input font-mono text-xs"
                                type="text"
                                value={govPush.schoolId}
                                onChange={(e) => setGovPush({ ...govPush, schoolId: e.target.value })}
                                placeholder="e.g. ZW-MOPSE-001"
                            />
                        </div>

                        <div className="flex items-center justify-between pt-4 border-t border-border">
                            <div className="text-[0.65rem] text-text-muted">
                                Last push:{' '}
                                {govPush.lastPushAt ? (
                                    <span className={govPush.lastPushStatus === 'ok' ? 'text-emerald-500' : 'text-rose-500'}>
                                        {govPush.lastPushAt} — {govPush.lastPushStatus === 'ok' ? '✓ ok' : '✗ failed'}
                                    </span>
                                ) : (
                                    <span className="opacity-60">never</span>
                                )}
                            </div>
                            <div className="flex gap-2">
                                <button
                                    onClick={pushGovPushNow}
                                    disabled={govPushPushing}
                                    className="flex items-center gap-2 px-5 py-2 bg-amber-500 text-white rounded-xl font-bold text-xs hover:bg-amber-600 transition-all shadow-lg shadow-amber-500/10 active:scale-95 disabled:opacity-50"
                                >
                                    {govPushPushing ? <RefreshCw size={12} className="animate-spin" /> : <Zap size={12} />}
                                    {govPushPushing ? 'Pushing…' : 'Push Now'}
                                </button>
                                <button
                                    onClick={saveGovPush}
                                    disabled={govPushSaving}
                                    className="flex items-center gap-2 px-6 py-2 bg-primary text-white rounded-xl font-bold text-xs hover:bg-primary/90 transition-all shadow-lg shadow-blue-500/10 active:scale-95 disabled:opacity-50"
                                >
                                    {govPushSaving ? <RefreshCw size={12} className="animate-spin" /> : <Save size={12} />}
                                    {govPushSaving ? 'Saving...' : 'Save Configuration'}
                                </button>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
          )}

          {/* SECURITY TAB */}
          {activeTab === 'security' && (
            <div className="bg-card border border-border rounded-[2.5rem] p-10 shadow-sm relative overflow-hidden animate-in fade-in zoom-in-95 duration-300">
                <div className="absolute top-0 right-0 w-48 h-48 bg-rose-500/5 rounded-bl-full -mr-16 -mt-16 pointer-events-none"></div>
                <div className="relative z-10 space-y-8">
                    <div className="flex items-center gap-4 mb-2">
                        <div className="p-3 rounded-2xl bg-rose-500/10 text-rose-500 border border-rose-500/20 shadow-sm">
                            <Lock size={24} />
                        </div>
                        <div>
                            <h3 className="text-xl font-black text-text tracking-tight uppercase">Security Vault</h3>
                            <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest mt-1">Access Control & Policies</p>
                        </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                        <div className="space-y-2">
                            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">
                                Session Timeout (Minutes)
                            </label>
                            <select 
                              className="form-input text-text cursor-pointer"
                              value={form.session_timeout}
                              onChange={(e) => handleChange('session_timeout', e.target.value)}
                            >
                              <option value="15">15 Minutes</option>
                              <option value="30">30 Minutes</option>
                              <option value="60">1 Hour</option>
                              <option value="120">2 Hours</option>
                            </select>
                        </div>
                        
                        <div className="space-y-2">
                            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">
                                Multi-Factor Auth (Global)
                            </label>
                            <div className="flex items-center gap-3 mt-2 px-1">
                              <button 
                                type="button"
                                onClick={() => handleChange('mfa_enabled', !form.mfa_enabled)}
                                className={`w-12 h-6 rounded-full transition-colors relative ${form.mfa_enabled ? 'bg-emerald-500' : 'bg-border'}`}
                              >
                                <div className={`absolute top-1 w-4 h-4 rounded-full bg-white transition-transform ${form.mfa_enabled ? 'left-7' : 'left-1'}`}></div>
                              </button>
                              <span className="text-sm font-bold text-text">{form.mfa_enabled ? 'Enforced' : 'Optional'}</span>
                            </div>
                        </div>
                    </div>

                    <div className="pt-6 border-t border-border">
                      <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-rose-500 mb-4">Emergency Controls</h4>
                      <button 
                        onClick={handleTerminateSessions}
                        disabled={terminatingSessions}
                        className="px-5 py-2.5 bg-rose-500/10 text-rose-500 hover:bg-rose-500 hover:text-white border border-rose-500/20 rounded-xl font-bold text-sm transition-colors flex items-center gap-2 disabled:opacity-50"
                      >
                        <Power size={16} /> {terminatingSessions ? 'Terminating...' : 'Terminate All Active Sessions'}
                      </button>
                    </div>
                </div>
            </div>
          )}

          {/* DATA TAB */}
          {activeTab === 'data' && (
            <div className="bg-card border border-border rounded-[2.5rem] p-10 shadow-sm relative overflow-hidden animate-in fade-in zoom-in-95 duration-300">
                <div className="absolute top-0 right-0 w-48 h-48 bg-emerald-500/5 rounded-bl-full -mr-16 -mt-16 pointer-events-none"></div>
                <div className="relative z-10 space-y-8">
                    <div className="flex items-center gap-4 mb-2">
                        <div className="p-3 rounded-2xl bg-emerald-500/10 text-emerald-500 border border-emerald-500/20 shadow-sm">
                            <HardDrive size={24} />
                        </div>
                        <div>
                            <h3 className="text-xl font-black text-text tracking-tight uppercase">Data Management</h3>
                            <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest mt-1">Backups & Archiving</p>
                        </div>
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      <button 
                        type="button" 
                        onClick={handleBackupDownload}
                        className="p-6 bg-background-alt/50 border border-border hover:border-emerald-500/50 hover:bg-emerald-500/5 rounded-2xl text-left transition-all group cursor-pointer"
                      >
                        <div className="w-10 h-10 rounded-full bg-card border border-border flex items-center justify-center text-text-muted group-hover:text-emerald-500 mb-4 transition-colors">
                          <Download size={18} />
                        </div>
                        <h4 className="font-bold text-text mb-1">Manual Database Backup</h4>
                        <p className="text-xs text-text-muted leading-relaxed">Instantly snapshot the entire SQLite database to a local downloadable file.</p>
                      </button>
                      
                      <button 
                        type="button" 
                        onClick={handleIntegrityCheck}
                        disabled={checkingIntegrity}
                        className="p-6 bg-background-alt/50 border border-border hover:border-blue-500/50 hover:bg-blue-500/5 rounded-2xl text-left transition-all group disabled:opacity-50 cursor-pointer"
                      >
                        <div className="w-10 h-10 rounded-full bg-card border border-border flex items-center justify-center text-text-muted group-hover:text-blue-500 mb-4 transition-colors">
                          <Zap size={18} />
                        </div>
                        <h4 className="font-bold text-text mb-1">{checkingIntegrity ? 'Running Scan...' : 'Run Data Integrity Check'}</h4>
                        <p className="text-xs text-text-muted leading-relaxed">Scan the database for orphaned records and verify foreign key constraints.</p>
                      </button>
                    </div>
                </div>
            </div>
          )}

        </div>

        {/* Info Sidebar (4/12) */}
        <div className="lg:col-span-4 space-y-6">
            <div className="bg-slate-900 rounded-[2.5rem] p-10 text-white shadow-2xl relative overflow-hidden group">
                <div className="absolute right-[-40px] bottom-[-40px] opacity-10 group-hover:rotate-12 transition-transform duration-700">
                    <Sparkles size={200} strokeWidth={1} />
                </div>
                <div className="relative z-10">
                    <div className="flex items-center gap-3 mb-6">
                        <div className="p-2.5 bg-white/10 rounded-xl backdrop-blur-md text-blue-400">
                            <Database size={20} />
                        </div>
                        <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-white/40">System Status</span>
                    </div>
                    <h4 className="text-xl font-black mb-3 leading-tight tracking-tight uppercase">Platform Health: Optimal</h4>
                    <div className="space-y-4 mb-10">
                        {[
                            { label: 'Database Sync', val: pulseData.dbSync },
                            { label: 'Database Size', val: pulseData.dbSize },
                            { label: 'Server Uptime', val: pulseData.uptime },
                        ].map(m => (
                            <div key={m.label} className="flex justify-between items-center border-b border-white/5 pb-2">
                                <span className="text-[0.6rem] font-black uppercase text-white/40">{m.label}</span>
                                <span className="text-xs font-bold text-blue-400">{m.val}</span>
                            </div>
                        ))}
                    </div>
                    <button 
                        onClick={handleRunDiagnosticAudit}
                        className="w-full py-4 bg-white/10 hover:bg-white/20 text-white rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all border border-white/10 active:scale-95"
                    >
                        Run Diagnostic Audit
                    </button>
                </div>
            </div>

            <div className="bg-background-alt/50 border border-border rounded-[2rem] p-8">
                <div className="flex items-center gap-3 mb-6">
                    <Info className="text-primary" size={18} />
                    <h4 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Technical Context</h4>
                </div>
                <p className="text-xs font-medium text-text-muted leading-relaxed">
                    Changes made in the System Control Center require elevated privileges and apply globally across all active sessions instantly. Use caution when modifying integrations.
                </p>
            </div>
        </div>
      </div>
    </div>
  );
}
