import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useHRStore, StaffRecord, PayrollRun, LeaveRequest } from '../../store/hr';
import { Modal, ModalBody } from '../../components/ui/Modal';
import {
  Users, Briefcase, Calendar, CreditCard,
  Search, Plus, Filter, Download,
  ChevronRight, Clock, CheckCircle2, XCircle,
  Trash2, Edit2, Info, UserCheck, UserMinus,
  FileText, TrendingUp, DollarSign, PieChart,
  UserPlus, Mail, Phone, MapPin, Hash, X, Sparkles, AlertCircle,
  Building2, Lock, Landmark, Award
} from 'lucide-react';
import api from '../../store/api';

/** Trigger a CSV download of the current list state. */
function exportToCsv(filename: string, rows: Record<string, unknown>[]) {
  if (rows.length === 0) return;
  const headers = Object.keys(rows[0]);
  const escape = (v: unknown) => {
    const s = v == null ? '' : String(v);
    return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
  };
  const csv = [headers.join(','), ...rows.map(r => headers.map(h => escape(r[h])).join(','))].join('\n');
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

export default function HRManagement() {
  const navigate = useNavigate();
  const { 
    records, leaveRequests, payrollRuns, payslips, 
    leaveTypes, salaryGrades, staffRoles, departments, vacancies, applicants, loading,
    fetchRecords, fetchLeaveRequests, fetchPayrollRuns, fetchPayslips, fetchMetadata,
    fetchVacancies, fetchApplicants, updateLeaveStatus, createPayrollRun, calculatePayroll,
    payPayrollRun, cancelPayrollRun, onboardStaff, createVacancy, updateVacancy, updateVacancyStatus, deleteVacancy, updateApplicantStatus,
    createApplicant, updateStaffRecord, deleteStaffRecord
  } = useHRStore();

  const [activeTab, setActiveTab] = useState('staff'); // staff, leave, payroll, recruitment
  const [search, setSearch] = useState('');
  
  // Modals state
  const [showRunModal, setShowRunModal] = useState(false);
  const [showOnboardModal, setShowOnboardModal] = useState(false);
  const [showProfileModal, setShowProfileModal] = useState(false);
  const [showDocsModal, setShowDocsModal] = useState(false);
  const [showLeaveDetailModal, setShowLeaveDetailModal] = useState(false);
  const [showVacancyModal, setShowVacancyModal] = useState(false);
  const [showVacancyDetailModal, setShowVacancyDetailModal] = useState(false);
  const [showApplicantModal, setShowApplicantModal] = useState(false);
  const [showAddApplicantModal, setShowAddApplicantModal] = useState(false);
  
  // Selection state
  const [selectedRun, setSelectedRun] = useState<PayrollRun | null>(null);
  const [selectedStaff, setSelectedStaff] = useState<StaffRecord | null>(null);
  const [selectedLeave, setSelectedLeave] = useState<LeaveRequest | null>(null);
  const [selectedVacancy, setSelectedVacancy] = useState<any | null>(null);
  const [selectedApplicant, setSelectedApplicant] = useState<any | null>(null);

  // Forms state
  const [runForm, setRunForm] = useState({
    period_month: new Date().getMonth() + 1,
    period_year: new Date().getFullYear(),
    description: ''
  });

  const [vacancyForm, setVacancyForm] = useState({
    title: '',
    department: 'Sciences',
    description: '',
    requirements: '',
    closing_date: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
  });

  const [applicantStatusForm, setApplicantStatusForm] = useState({
    status: 'pending',
    notes: '',
    interview_date: ''
  });

  const [addApplicantForm, setAddApplicantForm] = useState({
    vacancy_id: '',
    first_name: '',
    last_name: '',
    email: '',
    phone: '',
    notes: ''
  });

  const [isEditingStaff, setIsEditingStaff] = useState(false);
  const [staffEditForm, setStaffEditForm] = useState({
    role_id: '',
    salary_grade_id: '',
    employment_type: 'full-time',
    bank_name: '',
    account_number: '',
    department: 'Sciences',
    designation: '',
    is_active: true
  });

  const [isEditingVacancy, setIsEditingVacancy] = useState(false);
  const [vacancyEditForm, setVacancyEditForm] = useState({
    title: '',
    department: 'Sciences',
    closing_date: '',
    requirements: '',
    description: ''
  });

  const [onboardForm, setOnboardForm] = useState({
    // User account
    first_name: '',
    last_name: '',
    email: '',
    password: 'staffPassword123',
    role: 'teacher',
    // Staff details
    staff_number: '',
    role_id: '',
    salary_grade_id: '',
    employment_type: 'full-time',
    appointment_date: new Date().toISOString().split('T')[0],
    department: 'Sciences',
    designation: '',
    bank_name: '',
    account_number: ''
  });

  // Load metadata and all data initially
  useEffect(() => {
    const initFetch = async () => {
      await fetchMetadata();
      // Load all data to populate stats and directories
      fetchRecords();
      fetchLeaveRequests();
      fetchPayrollRuns();
      fetchVacancies();
      fetchApplicants();
    };
    initFetch();
  }, []);

  // Poll for real-time updates silently every 5 seconds
  useEffect(() => {
    if (activeTab === 'payroll' && selectedRun) {
      fetchPayslips(selectedRun.id);
    }

    const interval = setInterval(() => {
      // Poll all HR modules silently for true realtime data flow
      fetchRecords(true);
      fetchLeaveRequests();
      fetchPayrollRuns();
      fetchVacancies();
      fetchApplicants();
      if (activeTab === 'payroll' && selectedRun) {
        fetchPayslips(selectedRun.id);
      }
    }, 5000);

    return () => clearInterval(interval);
  }, [activeTab, selectedRun]);

  const handleOnboardSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const userData = {
        first_name: onboardForm.first_name,
        last_name: onboardForm.last_name,
        email: onboardForm.email,
        password: onboardForm.password,
        role: onboardForm.role
      };

      const staffData = {
        staff_number: onboardForm.staff_number,
        role_id: parseInt(onboardForm.role_id),
        salary_grade_id: parseInt(onboardForm.salary_grade_id),
        employment_type: onboardForm.employment_type,
        appointment_date: onboardForm.appointment_date,
        department: onboardForm.department,
        designation: onboardForm.designation,
        bank_name: onboardForm.bank_name || null,
        account_number: onboardForm.account_number || null
      };

      await onboardStaff(userData, staffData);
      setShowOnboardModal(false);
      // Reset form
      setOnboardForm({
        first_name: '',
        last_name: '',
        email: '',
        password: 'staffPassword123',
        role: 'teacher',
        staff_number: '',
        role_id: '',
        salary_grade_id: '',
        employment_type: 'full-time',
        appointment_date: new Date().toISOString().split('T')[0],
        department: 'Sciences',
        designation: '',
        bank_name: '',
        account_number: ''
      });
    } catch (err) {
      alert('Failed to onboard staff member: ' + (err as any).response?.data?.error || (err as Error).message);
    }
  };

  const handleProcessPayment = async (runId: number) => {
    if (!confirm('Are you sure you want to mark this payroll run as paid?')) return;
    try {
      await payPayrollRun(runId);
      if (selectedRun && selectedRun.id === runId) {
        setSelectedRun(prev => prev ? { ...prev, status: 'paid' } : null);
      }
    } catch (err) {
      alert('Failed to process payment');
    }
  };

  const downloadMockFile = (filename: string) => {
    const dummyText = `
==================================================
DOCUMENT VERIFICATION PROFILE
==================================================
Document Type: ${filename.replace(/_/g, ' ').replace('.pdf', '')}
Employee Name: ${selectedStaff?.first_name} ${selectedStaff?.last_name}
Staff Designation: ${selectedStaff?.designation}
Employment Number: ${selectedStaff?.staff_number}
Grade Rank: ${selectedStaff?.grade_name || 'N/A'}
Department: ${selectedStaff?.department || 'N/A'}
Appointment Date: ${selectedStaff ? new Date(selectedStaff.appointment_date).toLocaleDateString() : 'N/A'}

Verification Status: VERIFIED & SEALED BY HUMAN RESOURCES
Hub ID: ${selectedStaff?.uid}
Date Generated: ${new Date().toLocaleDateString()}
==================================================
    `;
    const blob = new Blob([dummyText], { type: 'text/plain;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename.replace('.pdf', '.txt');
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const downloadMockResume = (applicant: any) => {
    const resumeText = `
==================================================
RESUME: ${applicant.first_name.toUpperCase()} ${applicant.last_name.toUpperCase()}
==================================================
Position Applied For: ${applicant.vacancy_title || 'General Vacancy'}
Email: ${applicant.email}
Phone: ${applicant.phone || 'N/A'}
Status: ${applicant.status.toUpperCase()}
Interview Date: ${applicant.interview_date ? new Date(applicant.interview_date).toLocaleString() : 'Not Scheduled'}

PROFESSIONAL SUMMARY
Experienced educator and academic administrator with a proven track record
of enhancing student performance and implementing innovative curricula.

EDUCATION
- Master of Education (M.Ed.) | University of Science and Technology
- Bachelor of Science in Education | State Teachers College

EXPERIENCE
- Senior Subject Instructor (5+ years experience)
- Curriculum Development Lead

System Notes: ${applicant.notes || 'No review comments logged yet.'}
==================================================
    `;
    const blob = new Blob([resumeText], { type: 'text/plain;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `resume_${applicant.first_name.toLowerCase()}_${applicant.last_name.toLowerCase()}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const handleCreateVacancySubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await createVacancy(vacancyForm);
      setShowVacancyModal(false);
      setVacancyForm({
        title: '',
        department: 'Sciences',
        description: '',
        requirements: '',
        closing_date: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
      });
    } catch (err) {
      alert('Failed to create vacancy listing.');
    }
  };

  const handleToggleVacancyStatus = async (id: number, currentStatus: string) => {
    const nextStatus = currentStatus === 'open' ? 'closed' : 'open';
    try {
      await updateVacancyStatus(id, nextStatus);
      if (selectedVacancy && selectedVacancy.id === id) {
        setSelectedVacancy((prev: any) => prev ? { ...prev, status: nextStatus } : null);
      }
    } catch (err) {
      alert('Failed to update vacancy status.');
    }
  };

  const handleDeleteVacancy = async (id: number) => {
    if (!confirm('Are you sure you want to delete this vacancy?')) return;
    try {
      await deleteVacancy(id);
      setShowVacancyDetailModal(false);
    } catch (err) {
      alert('Failed to delete vacancy.');
    }
  };

  const handleUpdateApplicantStatusSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedApplicant) return;
    try {
      await updateApplicantStatus(selectedApplicant.id, applicantStatusForm.status, {
        notes: applicantStatusForm.notes,
        interview_date: applicantStatusForm.interview_date || undefined
      });
      setShowApplicantModal(false);
    } catch (err) {
      alert('Failed to update applicant status.');
    }
  };

  const handleAddApplicantSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await createApplicant({
        vacancy_id: addApplicantForm.vacancy_id ? parseInt(addApplicantForm.vacancy_id) : null,
        first_name: addApplicantForm.first_name,
        last_name: addApplicantForm.last_name,
        email: addApplicantForm.email,
        phone: addApplicantForm.phone || null,
        notes: addApplicantForm.notes || null
      });
      setShowAddApplicantModal(false);
      setAddApplicantForm({
        vacancy_id: '',
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        notes: ''
      });
    } catch (err) {
      alert('Failed to add applicant.');
    }
  };

  const handleEditStaffSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedStaff) return;
    try {
      await updateStaffRecord(selectedStaff.id, {
        role_id: staffEditForm.role_id ? parseInt(staffEditForm.role_id) : null,
        salary_grade_id: staffEditForm.salary_grade_id ? parseInt(staffEditForm.salary_grade_id) : null,
        employment_type: staffEditForm.employment_type,
        bank_name: staffEditForm.bank_name || null,
        account_number: staffEditForm.account_number || null,
        department: staffEditForm.department,
        designation: staffEditForm.designation,
        is_active: staffEditForm.is_active
      });
      setIsEditingStaff(false);
      setShowProfileModal(false);
    } catch (err) {
      alert('Failed to update staff record.');
    }
  };

  const handleEditVacancySubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedVacancy) return;
    try {
      await updateVacancy(selectedVacancy.id, {
        title: vacancyEditForm.title,
        department: vacancyEditForm.department,
        closing_date: vacancyEditForm.closing_date,
        requirements: vacancyEditForm.requirements,
        description: vacancyEditForm.description
      });
      setIsEditingVacancy(false);
      setShowVacancyDetailModal(false);
    } catch (err) {
      alert('Failed to update vacancy.');
    }
  };

  const handleDeleteStaff = async (id: number) => {
    if (!confirm('Are you sure you want to remove this staff member? This will soft-delete their record.')) return;
    try {
      await deleteStaffRecord(id);
      setShowProfileModal(false);
    } catch (err) {
      alert('Failed to delete staff record.');
    }
  };

  const stats = [
    { label: 'Active Staff', value: records.length, icon: Users, color: 'blue' },
    { label: 'On Leave', value: leaveRequests.filter(r => r.status === 'approved' && new Date(r.start_date) <= new Date() && new Date(r.end_date) >= new Date()).length, icon: Calendar, color: 'orange' },
    { label: 'Open Vacancies', value: vacancies.filter(v => v.status === 'open').length || 0, icon: Briefcase, color: 'purple' },
    { label: 'Monthly Payroll', value: `$${payrollRuns[0]?.total_net?.toLocaleString() || '0'}`, icon: DollarSign, color: 'emerald' },
  ];

  const getStatColors = (color: string) => {
    switch (color) {
      case 'blue': return 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800';
      case 'emerald': return 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800';
      case 'orange': return 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-800';
      case 'purple': return 'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800';
      default: return 'bg-muted text-text-muted border-border';
    }
  };

  const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight uppercase">Human Resources</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">Staff & Payroll</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button
            onClick={() => {
              const rows = activeTab === 'staff'
                ? records.map(r => ({
                    id: r.id, name: `${r.first_name} ${r.last_name}`,
                    designation: r.designation ?? '', role: r.role_name ?? '',
                    email: r.email ?? '', staff_number: r.staff_number ?? '',
                    grade: r.grade_name ?? '', status: r.is_active ? 'active' : 'inactive'
                  }))
                : activeTab === 'leave'
                  ? leaveRequests.map(r => ({
                      id: r.id, staff: `${r.first_name} ${r.last_name}`,
                      type: r.leave_type, start: r.start_date, end: r.end_date,
                      days: r.days_count, status: r.status
                    }))
                  : activeTab === 'payroll'
                    ? payrollRuns.map(run => ({
                        id: run.id, period: `${run.period_month}/${run.period_year}`,
                        total_net: run.total_net, total_gross: run.total_gross,
                        total_deductions: run.total_deductions, status: run.status
                      }))
                    : [];
              exportToCsv(`hr_${activeTab}_${new Date().toISOString().split('T')[0]}.csv`, rows);
            }}
            className="flex items-center gap-2 px-6 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted/50 transition-all active:scale-95 shadow-sm dark:bg-zinc-900"
          >
            <Download size={18} />
            Reports
          </button>
          {activeTab === 'staff' && (
            <button 
              onClick={() => setShowOnboardModal(true)} 
              className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg active:scale-95"
            >
              <UserPlus size={18} />
              Onboard Staff
            </button>
          )}
          {activeTab === 'payroll' && (
            <button 
              onClick={() => setShowRunModal(true)} 
              className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg active:scale-95"
            >
              <Plus size={18} />
              New Payroll Run
            </button>
          )}
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 group cursor-default">
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center ${getStatColors(stat.color)} group-hover:scale-110 transition-transform`}>
              <stat.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
              <p className="text-2xl font-black text-text">{stat.value}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Tabs Control */}
      <div className="bg-card border border-border rounded-[2rem] p-2 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-4">
        <div className="flex p-1 bg-muted/50 rounded-2xl overflow-x-auto min-w-0 no-scrollbar">
          {[
            { id: 'staff', label: 'Staff Directory', icon: Users },
            { id: 'leave', label: 'Leave Portal', icon: Calendar },
            { id: 'payroll', label: 'Payroll Center', icon: CreditCard },
            { id: 'recruitment', label: 'Recruitment', icon: Briefcase },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`
                px-6 py-2.5 rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all whitespace-nowrap flex items-center justify-center gap-2
                ${activeTab === tab.id ? 'bg-card text-primary shadow-sm ring-1 ring-border dark:bg-zinc-800 dark:text-blue-400' : 'text-text-muted hover:text-text'}
              `}
            >
              <tab.icon size={14} />
              {tab.label}
            </button>
          ))}
        </div>

        <div className="relative group flex-1">
          <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
          <input 
            type="text" 
            className="w-full bg-muted/50 border border-border rounded-2xl pl-11 pr-4 py-3.5 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all text-text dark:bg-zinc-900"
            placeholder="Search records, names, or reference numbers..."
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
        </div>
      </div>

      {/* Main Content */}
      <div className="min-h-[400px]">
        {loading ? (
            <div className="py-20 text-center">
                <div className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                <p className="text-text-muted font-bold uppercase tracking-widest text-xs italic">Syncing HR data...</p>
            </div>
        ) : activeTab === 'staff' ? (
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                {records.filter(r => `${r.first_name} ${r.last_name}`.toLowerCase().includes(search.toLowerCase())).map((staff) => (
                    <div key={staff.id} className="bg-card border border-border rounded-[2.5rem] p-8 hover:shadow-xl transition-all group relative overflow-hidden flex flex-col">
                        <div className="flex justify-between items-start mb-6">
                            <div className="w-16 h-16 rounded-[1.5rem] bg-gradient-to-br from-primary to-slate-900 flex items-center justify-center text-white text-xl font-black shadow-lg">
                                {staff.first_name[0]}{staff.last_name[0]}
                            </div>
                            <span className={`px-3 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${
                                staff.is_active 
                                  ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20' 
                                  : 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/20'
                            }`}>
                                {staff.is_active ? 'Active' : 'Inactive'}
                            </span>
                        </div>
                        <div className="space-y-1 mb-6 flex-grow">
                            <h3 className="text-xl font-black text-text tracking-tight group-hover:text-primary transition-colors">{staff.first_name} {staff.last_name}</h3>
                            <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-[3px]">{staff.designation} | {staff.role_name}</p>
                        </div>
                        <div className="space-y-3 pt-6 border-t border-border">
                            <div className="flex items-center gap-3 text-sm text-text-muted">
                                <Mail size={14} className="shrink-0" /> <span className="truncate">{staff.email}</span>
                            </div>
                            <div className="flex items-center gap-3 text-sm text-text-muted">
                                <Hash size={14} className="shrink-0" /> {staff.staff_number}
                            </div>
                            <div className="flex items-center gap-3 text-sm text-text-muted">
                                <TrendingUp size={14} className="shrink-0" /> {staff.grade_name || 'No salary grade'}
                            </div>
                        </div>
                        <div className="mt-8 pt-6 border-t border-border flex gap-2">
                             <button 
                              onClick={() => { setSelectedStaff(staff); setShowProfileModal(true); }}
                              className="flex-1 py-3 bg-muted hover:bg-muted/85 dark:bg-zinc-800 dark:hover:bg-zinc-700/80 text-text rounded-xl font-bold text-xs transition-all flex items-center justify-center gap-2"
                            >
                                <Edit2 size={14} /> Profile
                            </button>
                            <button 
                              onClick={() => { setSelectedStaff(staff); setShowDocsModal(true); }}
                              className="flex-1 py-3 bg-primary text-white rounded-xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-primary/90 transition-all shadow-lg flex items-center justify-center gap-2"
                            >
                                <FileText size={14} /> Documents
                            </button>
                        </div>
                    </div>
                ))}
            </div>
        ) : activeTab === 'leave' ? (
            <div className="space-y-4">
              {/* Sprint 1b — F6: Leave approval flow moved to /hr/leave-approval.
                  Keep this tab as a read-only listing — staff user clicks the
                  "Review queue" CTA to perform approvals there. */}
              <div className="bg-card border border-border rounded-2xl p-5 shadow-sm flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                <div>
                  <p className="text-sm font-bold text-text">Leave approval queue</p>
                  <p className="text-xs text-text-muted mt-0.5">
                    Approvals happen in the dedicated Leave Approval page. This tab is read-only.
                  </p>
                </div>
                <button
                  onClick={() => navigate('/hr/leave-approval')}
                  className="flex items-center gap-2 px-5 py-2.5 rounded-xl bg-primary hover:bg-primary-dark text-white text-sm font-bold transition-all shadow-lg shadow-blue-900/10 active:scale-[0.98]"
                >
                  <Calendar size={16} />
                  <span>Review queue</span>
                </button>
              </div>
              <div className="bg-card border border-border rounded-[2.5rem] overflow-hidden shadow-sm">
                <div className="overflow-x-auto">
                  <table className="w-full text-left">
                    <thead>
                        <tr className="bg-muted/50 border-b border-border">
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Staff Member</th>
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Type & Duration</th>
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Status</th>
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                        {leaveRequests.filter(lr => `${lr.first_name} ${lr.last_name} ${lr.leave_type}`.toLowerCase().includes(search.toLowerCase())).map((req) => (
                            <tr key={req.id} className="hover:bg-muted/30 transition-colors">
                                <td className="px-8 py-5">
                                    <div className="flex items-center gap-4">
                                        <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary font-black text-sm uppercase">
                                            {req.first_name?.[0] || 'S'}{req.last_name?.[0] || 'T'}
                                        </div>
                                        <div>
                                            <p className="text-sm font-bold text-text">{req.first_name} {req.last_name}</p>
                                            <p className="text-[0.6rem] text-text-muted font-black tracking-widest uppercase mt-0.5">UID: {req.uid.substring(0, 8)}</p>
                                        </div>
                                    </div>
                                </td>
                                <td className="px-8 py-5">
                                    <p className="text-xs font-bold text-text">{req.leave_type}</p>
                                    <p className="text-[0.65rem] text-text-muted font-medium mt-1">
                                        {new Date(req.start_date).toLocaleDateString()} - {new Date(req.end_date).toLocaleDateString()} ({req.days_count} Days)
                                    </p>
                                </td>
                                <td className="px-8 py-5">
                                    <span className={`px-3 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${
                                        req.status === 'approved' ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20' :
                                        req.status === 'rejected' ? 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/20' :
                                        'bg-orange-50 text-orange-600 border-orange-100 dark:bg-orange-500/10 dark:text-orange-400 dark:border-orange-500/20'
                                    }`}>
                                        {req.status}
                                    </span>
                                </td>
                                <td className="px-8 py-5 text-right">
                                    <div className="flex justify-end items-center gap-2">
                                        <button
                                          onClick={() => { setSelectedLeave(req); setShowLeaveDetailModal(true); }}
                                          className="text-text-muted hover:text-primary transition-all text-xs font-black uppercase tracking-widest px-3 py-1.5 hover:bg-muted dark:hover:bg-zinc-800 rounded-lg"
                                        >
                                          View Detail
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
        ) : activeTab === 'payroll' ? (
            <div className="space-y-6">
                <div className="grid grid-cols-1 xl:grid-cols-12 gap-6">
                    {/* Runs List */}
                    <div className="xl:col-span-8 bg-card border border-border rounded-[2.5rem] overflow-hidden shadow-sm">
                        <div className="overflow-x-auto">
                            <table className="w-full text-left">
                                <thead>
                                    <tr className="bg-muted/50 border-b border-border">
                                        <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Period</th>
                                        <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Total Net</th>
                                        <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-center">Status</th>
                                        <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-border">
                                    {payrollRuns.filter(pr => months[pr.period_month - 1].toLowerCase().includes(search.toLowerCase()) || pr.period_year.toString().includes(search)).map((run) => (
                                        <tr key={run.id} onClick={() => { setSelectedRun(run); fetchPayslips(run.id); }} className={`hover:bg-muted/30 cursor-pointer transition-colors ${selectedRun?.id === run.id ? 'bg-primary/5' : ''}`}>
                                            <td className="px-8 py-5">
                                                <p className="text-sm font-bold text-text">{months[run.period_month - 1]} {run.period_year}</p>
                                                <p className="text-[0.6rem] text-text-muted font-black tracking-widest uppercase mt-0.5">{run.description || 'Monthly Salaries'}</p>
                                            </td>
                                            <td className="px-8 py-5">
                                                <p className="text-sm font-black text-text">${run.total_net?.toLocaleString()}</p>
                                                <p className="text-[0.6rem] text-text-muted font-bold uppercase mt-0.5">Gross: ${run.total_gross?.toLocaleString()}</p>
                                            </td>
                                            <td className="px-8 py-5 text-center">
                                                <span className={`px-3 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${
                                                    run.status === 'paid' ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20' :
                                                    run.status === 'calculated' ? 'bg-blue-50 text-blue-600 border-blue-100 dark:bg-blue-500/10 dark:text-blue-400 dark:border-blue-500/20' :
                                                    'bg-muted text-text-muted border-border dark:bg-zinc-800 dark:text-zinc-400 dark:border-zinc-700'
                                                }`}>
                                                    {run.status}
                                                </span>
                                            </td>
                                            <td className="px-8 py-5 text-right">
                                                {run.status === 'draft' && (
                                                    <button onClick={(e) => { e.stopPropagation(); calculatePayroll(run.id); }} className="px-4 py-2 bg-primary text-white rounded-lg font-black text-[0.6rem] uppercase tracking-widest shadow-lg">Calculate</button>
                                                )}
                                                {run.status === 'calculated' && (
                                                    <div className="flex gap-2 justify-end">
                                                        <button 
                                                            onClick={(e) => { e.stopPropagation(); handleProcessPayment(run.id); }} 
                                                            className="px-3 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg font-black text-[0.6rem] uppercase tracking-widest shadow-md transition-colors"
                                                        >
                                                            Process Payment
                                                        </button>
                                                        <button 
                                                            onClick={async (e) => { 
                                                                e.stopPropagation(); 
                                                                if (confirm("Are you sure you want to cancel this calculated payroll run and reset it to draft?")) {
                                                                    await cancelPayrollRun(run.id);
                                                                    if (selectedRun?.id === run.id) {
                                                                        setSelectedRun(null);
                                                                    }
                                                                }
                                                            }} 
                                                            className="px-3 py-2 bg-rose-500/10 text-rose-500 border border-rose-500/20 hover:bg-rose-500/20 rounded-lg font-black text-[0.6rem] uppercase tracking-widest transition-all"
                                                            title="Cancel calculation and reset to draft"
                                                        >
                                                            Cancel
                                                        </button>
                                                    </div>
                                                )}
                                                {run.status === 'paid' && (
                                                    <button
                                                      onClick={(e) => {
                                                        e.stopPropagation();
                                                        exportToCsv(
                                                          `payroll_run_${run.period_month}_${run.period_year}_${new Date().toISOString().split('T')[0]}.csv`,
                                                          payslips.map(p => ({
                                                            staff_number: p.staff_number,
                                                            name: `${p.first_name} ${p.last_name}`,
                                                            net_salary: p.net_salary
                                                          }))
                                                        );
                                                      }}
                                                      title="Download payslip register"
                                                      className="p-2 text-primary hover:bg-primary/10 rounded-lg transition-all"
                                                    ><Download size={18} /></button>
                                                )}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    {/* Detail Panel */}
                    <div className="xl:col-span-4 space-y-6">
                        {selectedRun ? (
                            <div className="bg-slate-900 rounded-[2.5rem] p-8 text-white shadow-2xl relative overflow-hidden group min-h-[500px]">
                                <div className="absolute right-[-40px] bottom-[-40px] opacity-10 group-hover:rotate-12 transition-transform duration-700">
                                    <PieChart size={180} strokeWidth={1} />
                                </div>
                                <div className="relative z-10">
                                    <div className="flex justify-between items-start mb-10">
                                        <div>
                                            <h4 className="text-[0.6rem] font-black uppercase tracking-[3px] text-white/40 mb-1">Payroll Summary</h4>
                                            <h2 className="text-2xl font-black">{months[selectedRun.period_month - 1]} {selectedRun.period_year}</h2>
                                        </div>
                                        <div className="p-3 bg-white/10 rounded-2xl border border-white/10 text-white">
                                            <CreditCard size={20} />
                                        </div>
                                    </div>

                                    <div className="space-y-6 mb-10">
                                        <div className="flex justify-between items-end border-b border-white/10 pb-4">
                                            <span className="text-[0.65rem] font-black uppercase tracking-widest text-white/50">Total Distribution</span>
                                            <span className="text-xl font-black">${selectedRun.total_net?.toLocaleString()}</span>
                                        </div>
                                        <div className="flex justify-between items-end border-b border-white/10 pb-4">
                                            <span className="text-[0.65rem] font-black uppercase tracking-widest text-white/50">Tax & Statutories</span>
                                            <span className="text-lg font-bold text-rose-400">-${selectedRun.total_deductions?.toLocaleString()}</span>
                                        </div>
                                        <div className="flex justify-between items-end">
                                            <span className="text-[0.65rem] font-black uppercase tracking-widest text-white/50">Status Profile</span>
                                            <span className="text-[0.6rem] font-black uppercase tracking-widest bg-emerald-500/20 text-emerald-400 px-3 py-1 rounded-lg border border-emerald-500/30">{selectedRun.status}</span>
                                        </div>
                                    </div>

                                    <div className="space-y-4">
                                        <h5 className="text-[0.6rem] font-black uppercase tracking-widest text-white/30 border-b border-white/5 pb-2">Payslip Records ({payslips.length})</h5>
                                        <div className="max-h-[250px] overflow-y-auto no-scrollbar space-y-2">
                                            {payslips.map(p => (
                                                <div key={p.id} className="p-4 bg-white/5 rounded-2xl border border-white/5 flex justify-between items-center hover:bg-white/10 transition-colors">
                                                    <div>
                                                        <p className="text-xs font-bold">{p.first_name} {p.last_name}</p>
                                                        <p className="text-[0.55rem] text-white/40 uppercase tracking-widest">{p.staff_number}</p>
                                                    </div>
                                                    <div className="text-right">
                                                        <p className="text-xs font-black text-emerald-400">${p.net_salary.toLocaleString()}</p>
                                                        <p className="text-[0.55rem] text-white/30 uppercase tracking-widest">NET</p>
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        ) : (
                            <div className="bg-card border-2 border-dashed border-border rounded-[2.5rem] p-12 text-center flex flex-col items-center justify-center min-h-[500px]">
                                <div className="w-16 h-16 rounded-3xl bg-muted flex items-center justify-center text-text-muted mb-6">
                                    <TrendingUp size={32} />
                                </div>
                                <h4 className="text-xl font-black text-text uppercase tracking-tight">Analytical View</h4>
                                <p className="text-text-muted text-sm font-medium max-w-[200px] mt-2">Select a payroll run from the list to view payslip details and distribution.</p>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        ) : (
            /* Recruitment Tab - Fully Functional */
            <div className="space-y-8">
              <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
                {/* Vacancies List */}
                <div className="lg:col-span-6 bg-card border border-border rounded-[2.5rem] p-8 shadow-sm space-y-6">
                  <div className="flex justify-between items-center pb-4 border-b border-border">
                    <div>
                      <h3 className="text-xl font-black text-text tracking-tight uppercase">Open Positions</h3>
                      <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Institutional vacancies</p>
                    </div>
                    <button 
                      onClick={() => setShowVacancyModal(true)} 
                      className="px-4 py-2 bg-primary text-white rounded-xl font-bold text-xs hover:bg-primary/90 transition-all active:scale-95"
                    >
                      Add Vacancy
                    </button>
                  </div>
                  
                  <div className="space-y-4 max-h-[500px] overflow-y-auto pr-1 custom-scrollbar">
                    {vacancies.length === 0 ? (
                      <div className="text-center py-12 text-text-muted font-bold text-sm uppercase tracking-wider">No vacancies listed</div>
                    ) : vacancies.map((vac: any) => (
                      <div key={vac.id} className="p-5 bg-muted/40 border border-border rounded-2xl hover:border-primary transition-all group relative">
                        <div className="flex justify-between items-start mb-2">
                          <h4 className="text-sm font-black text-text group-hover:text-primary transition-colors">{vac.title}</h4>
                          <span className={`px-2 py-0.5 rounded text-[0.55rem] font-black uppercase border ${
                            vac.status === 'open' 
                              ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20' 
                              : 'bg-zinc-100 text-zinc-600 border-zinc-200 dark:bg-zinc-800 dark:text-zinc-400 dark:border-zinc-700'
                          }`}>
                            {vac.status}
                          </span>
                        </div>
                        <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-wider">{vac.department || 'General Administration'}</p>
                        <p className="text-xs text-text-secondary mt-2 line-clamp-2">{vac.description || 'Details regarding core academic responsibilities and requirements.'}</p>
                        <div className="mt-3 pt-3 border-t border-border/60 flex justify-between items-center">
                          <span className="text-[0.6rem] font-bold text-text-muted uppercase">Closing: {vac.closing_date ? new Date(vac.closing_date).toLocaleDateString() : 'N/A'}</span>
                          <button 
                            onClick={() => { setSelectedVacancy(vac); setIsEditingVacancy(false); setShowVacancyDetailModal(true); }} 
                            className="text-[0.65rem] font-black text-primary hover:underline uppercase"
                          >
                            Manage Listing
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Applicants List */}
                <div className="lg:col-span-6 bg-card border border-border rounded-[2.5rem] p-8 shadow-sm space-y-6">
                  <div className="flex justify-between items-center pb-4 border-b border-border">
                    <div>
                      <h3 className="text-xl font-black text-text tracking-tight uppercase">Applicants Portal</h3>
                      <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Pending job applications</p>
                    </div>
                    <button 
                      onClick={() => setShowAddApplicantModal(true)} 
                      className="px-4 py-2 bg-primary text-white rounded-xl font-bold text-xs hover:bg-primary/90 transition-all active:scale-95 shadow-sm"
                    >
                      Add Applicant
                    </button>
                  </div>

                  <div className="space-y-4 max-h-[500px] overflow-y-auto pr-1 custom-scrollbar">
                    {applicants.length === 0 ? (
                      <div className="text-center py-12 text-text-muted font-bold text-sm uppercase tracking-wider">No applicant records found</div>
                    ) : applicants.map((app: any) => (
                      <div key={app.id} className="p-5 bg-muted/40 border border-border rounded-2xl hover:border-primary transition-all flex justify-between items-center">
                        <div>
                          <h4 className="text-sm font-black text-text">{app.first_name} {app.last_name}</h4>
                          <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-wider mt-0.5">Applied For: <span className="text-primary font-black">{app.vacancy_title || 'General Vacancy'}</span></p>
                          <p className="text-[0.65rem] text-text-muted mt-1">{app.email} | {app.phone}</p>
                        </div>
                        <div className="text-right space-y-2">
                          <span className={`inline-block px-2.5 py-0.5 rounded-full text-[0.55rem] font-black uppercase border ${
                            app.status === 'hired' ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20' :
                            app.status === 'rejected' ? 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/20' :
                            app.status === 'shortlisted' ? 'bg-blue-50 text-blue-600 border-blue-100 dark:bg-blue-500/10 dark:text-blue-400 dark:border-blue-500/20' :
                            'bg-orange-50 text-orange-600 border-orange-100 dark:bg-orange-500/10 dark:text-orange-400 dark:border-orange-500/20'
                          }`}>
                            {app.status}
                          </span>
                          <div className="flex flex-col items-end gap-1.5">
                            <button 
                              onClick={() => downloadMockResume(app)} 
                              className="text-[0.6rem] font-black text-primary hover:underline uppercase block"
                            >
                              Review Resume
                            </button>
                            <button 
                              onClick={() => {
                                setSelectedApplicant(app);
                                setApplicantStatusForm({
                                  status: app.status,
                                  notes: app.notes || '',
                                  interview_date: app.interview_date ? app.interview_date.substring(0, 16) : ''
                                });
                                setShowApplicantModal(true);
                              }} 
                              className="text-[0.6rem] font-black text-primary hover:underline uppercase block"
                            >
                              Manage Status
                            </button>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
        )}
      </div>

      {/* Onboard Staff Modal */}
      {showOnboardModal && (
        <Modal
          open={true}
          onClose={() => setShowOnboardModal(false)}
          title="Onboard Staff"
          icon={Sparkles}
          maxWidth="max-w-xl"
          zIndex={150}
        >
          <ModalBody>
            <form id="hr-onboard-form" onSubmit={handleOnboardSubmit} className="space-y-6">
              {/* Account Credentials */}
              <div className="space-y-4">
                <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-primary border-b border-border pb-2">1. Account Credentials</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">First Name</label>
                    <input 
                      type="text" 
                      required 
                      className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text" 
                      placeholder="e.g. John"
                      value={onboardForm.first_name} 
                      onChange={e => setOnboardForm({...onboardForm, first_name: e.target.value})}
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Last Name</label>
                    <input 
                      type="text" 
                      required 
                      className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text" 
                      placeholder="e.g. Doe"
                      value={onboardForm.last_name} 
                      onChange={e => setOnboardForm({...onboardForm, last_name: e.target.value})}
                    />
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Email Address</label>
                    <input 
                      type="email" 
                      required 
                      className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text" 
                      placeholder="john.doe@school.com"
                      value={onboardForm.email} 
                      onChange={e => setOnboardForm({...onboardForm, email: e.target.value})}
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">System User Role</label>
                    <select 
                      className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text"
                      value={onboardForm.role}
                      onChange={e => setOnboardForm({...onboardForm, role: e.target.value})}
                    >
                      <option value="teacher">Teacher</option>
                      <option value="hr">HR Manager</option>
                      <option value="bursar">Bursar / Accountant</option>
                      <option value="librarian">Librarian</option>
                      <option value="warden">Hostel Warden</option>
                      <option value="school_admin">School Admin</option>
                    </select>
                  </div>
                </div>
              </div>

              {/* Employment Metrics */}
              <div className="space-y-4 pt-4 border-t border-border">
                <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-primary border-b border-border pb-2">2. Employment Details</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Staff Number</label>
                    <input
                      type="text"
                      required
                      className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text"
                      placeholder="e.g. STF-2026-001"
                      value={onboardForm.staff_number}
                      onChange={e => setOnboardForm({...onboardForm, staff_number: e.target.value})}
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Designation</label>
                    <input 
                      type="text" 
                      required 
                      className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text" 
                      placeholder="e.g. Senior Physics Instructor"
                      value={onboardForm.designation} 
                      onChange={e => setOnboardForm({...onboardForm, designation: e.target.value})}
                    />
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Salary Grade</label>
                    <select 
                      required
                      className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text"
                      value={onboardForm.salary_grade_id}
                      onChange={e => setOnboardForm({...onboardForm, salary_grade_id: e.target.value})}
                    >
                      <option value="">Select Salary Grade...</option>
                      {salaryGrades.map(g => (
                        <option key={g.id} value={g.id}>{g.name} (${g.basic_salary}/mo)</option>
                      ))}
                    </select>
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Staff Role Category</label>
                    <select 
                      required
                      className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text"
                      value={onboardForm.role_id}
                      onChange={e => setOnboardForm({...onboardForm, role_id: e.target.value})}
                    >
                      <option value="">Select Role Profile...</option>
                      {staffRoles.map(r => (
                        <option key={r.id} value={r.id}>{r.name}</option>
                      ))}
                    </select>
                  </div>
                </div>
                <div className="grid grid-cols-3 gap-4">
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Department</label>
                    <select 
                      className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text"
                      value={onboardForm.department}
                      onChange={e => setOnboardForm({...onboardForm, department: e.target.value})}
                    >
                      <option value="">Select Department...</option>
                      {departments.map(d => (
                        <option key={d.id} value={d.name}>{d.name}</option>
                      ))}
                    </select>
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Type</label>
                    <select 
                      className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text"
                      value={onboardForm.employment_type}
                      onChange={e => setOnboardForm({...onboardForm, employment_type: e.target.value})}
                    >
                      <option value="full-time">Full-Time</option>
                      <option value="part-time">Part-Time</option>
                      <option value="contract">Contract</option>
                      <option value="temporary">Temporary</option>
                    </select>
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Appointment Date</label>
                    <input 
                      type="date" 
                      required 
                      className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text"
                      value={onboardForm.appointment_date}
                      onChange={e => setOnboardForm({...onboardForm, appointment_date: e.target.value})}
                    />
                  </div>
                </div>
              </div>

              {/* Financial Metrics */}
              <div className="space-y-4 pt-4 border-t border-border">
                <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-primary border-b border-border pb-2">3. Disbursement Route</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Bank Name</label>
                    <input 
                      type="text" 
                      className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text" 
                      placeholder="e.g. Standard Chartered"
                      value={onboardForm.bank_name} 
                      onChange={e => setOnboardForm({...onboardForm, bank_name: e.target.value})}
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Account Number</label>
                    <input 
                      type="text" 
                      className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text" 
                      placeholder="12-345678-90"
                      value={onboardForm.account_number} 
                      onChange={e => setOnboardForm({...onboardForm, account_number: e.target.value})}
                    />
                  </div>
                </div>
              </div>

              <button type="submit" form="hr-onboard-form" className="w-full py-4.5 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3">
                <UserCheck size={18} />
                Confirm Placement Protocol
              </button>
            </form>
          </ModalBody>
        </Modal>
      )}

      {/* Staff Profile Modal */}
      {showProfileModal && selectedStaff && (
        <Modal
          open={true}
          onClose={() => { setIsEditingStaff(false); setShowProfileModal(false); }}
          title={`${selectedStaff.first_name} ${selectedStaff.last_name}`}
          icon={Users}
          maxWidth="max-w-2xl"
          zIndex={150}
        >
          <ModalBody className="p-0">
            <form id="hr-profile-form" onSubmit={handleEditStaffSubmit}>
              <div className="p-10 space-y-8 max-h-[60vh] overflow-y-auto custom-scrollbar">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                  {/* Metrics */}
                  <div className="space-y-4">
                    <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Role Parameters</h4>
                    <div className="bg-muted/40 border border-border rounded-2xl p-5 space-y-4">
                      <div className="flex justify-between items-center text-sm">
                        <span className="text-text-muted">Staff Number</span>
                        <span className="font-bold text-text">{selectedStaff.staff_number}</span>
                      </div>
                      
                      {isEditingStaff ? (
                        <>
                          <div className="space-y-1">
                            <label className="text-[0.6rem] font-black uppercase text-text-muted">Designation</label>
                            <input 
                              type="text" 
                              required 
                              className="w-full bg-muted border border-border rounded-xl px-3 py-2 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                              value={staffEditForm.designation}
                              onChange={e => setStaffEditForm({...staffEditForm, designation: e.target.value})}
                            />
                          </div>
                          <div className="space-y-1">
                            <label className="text-[0.6rem] font-black uppercase text-text-muted">Category Profile</label>
                            <select 
                              required
                              className="w-full bg-muted border border-border rounded-xl px-3 py-2 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                              value={staffEditForm.role_id}
                              onChange={e => setStaffEditForm({...staffEditForm, role_id: e.target.value})}
                            >
                              {staffRoles.map(r => (
                                <option key={r.id} value={r.id}>{r.name}</option>
                              ))}
                            </select>
                          </div>
                          <div className="space-y-1">
                            <label className="text-[0.6rem] font-black uppercase text-text-muted">Department</label>
                            <select 
                              className="w-full bg-muted border border-border rounded-xl px-3 py-2 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                              value={staffEditForm.department}
                              onChange={e => setStaffEditForm({...staffEditForm, department: e.target.value})}
                            >
                              <option value="">Select Department...</option>
                              {departments.map(d => (
                                <option key={d.id} value={d.name}>{d.name}</option>
                              ))}
                            </select>
                          </div>
                          <div className="space-y-1">
                            <label className="text-[0.6rem] font-black uppercase text-text-muted">Salary Grade</label>
                            <select 
                              required
                              className="w-full bg-muted border border-border rounded-xl px-3 py-2 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                              value={staffEditForm.salary_grade_id}
                              onChange={e => setStaffEditForm({...staffEditForm, salary_grade_id: e.target.value})}
                            >
                              <option value="">Select Grade...</option>
                              {salaryGrades.map(g => (
                                <option key={g.id} value={g.id}>{g.name} (${g.basic_salary}/mo)</option>
                              ))}
                            </select>
                          </div>
                          <div className="space-y-1">
                            <label className="text-[0.6rem] font-black uppercase text-text-muted">Type</label>
                            <select 
                              className="w-full bg-muted border border-border rounded-xl px-3 py-2 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                              value={staffEditForm.employment_type}
                              onChange={e => setStaffEditForm({...staffEditForm, employment_type: e.target.value})}
                            >
                              <option value="full-time">Full-Time</option>
                              <option value="part-time">Part-Time</option>
                              <option value="contract">Contract</option>
                              <option value="temporary">Temporary</option>
                            </select>
                          </div>
                        </>
                      ) : (
                        <>
                          <div className="flex justify-between text-sm">
                            <span className="text-text-muted">Category Profile</span>
                            <span className="font-bold text-text">{selectedStaff.role_name}</span>
                          </div>
                          <div className="flex justify-between text-sm">
                            <span className="text-text-muted">Department</span>
                            <span className="font-bold text-text">{selectedStaff.department || 'N/A'}</span>
                          </div>
                          <div className="flex justify-between text-sm">
                            <span className="text-text-muted">Salary Grade</span>
                            <span className="font-bold text-text">{selectedStaff.grade_name || 'N/A'}</span>
                          </div>
                          <div className="flex justify-between text-sm">
                            <span className="text-text-muted">Employment Type</span>
                            <span className="font-bold text-text">{selectedStaff.employment_type}</span>
                          </div>
                          <div className="flex justify-between text-sm">
                            <span className="text-text-muted">Appointment Date</span>
                            <span className="font-bold text-text">{new Date(selectedStaff.appointment_date).toLocaleDateString()}</span>
                          </div>
                        </>
                      )}
                    </div>
                  </div>

                  {/* Account Details */}
                  <div className="space-y-4">
                    <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Contact & Financials</h4>
                    <div className="bg-muted/40 border border-border rounded-2xl p-5 space-y-4">
                      <div className="flex items-center gap-3 text-sm text-text-secondary">
                        <Mail size={16} className="text-primary shrink-0" />
                        <span className="truncate">{selectedStaff.email}</span>
                      </div>
                      
                      {isEditingStaff ? (
                        <>
                          <div className="space-y-1 border-t border-border/50 pt-3">
                            <label className="text-[0.6rem] font-black uppercase text-text-muted">Disbursement Bank</label>
                            <input 
                              type="text" 
                              className="w-full bg-muted border border-border rounded-xl px-3 py-2 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                              value={staffEditForm.bank_name}
                              onChange={e => setStaffEditForm({...staffEditForm, bank_name: e.target.value})}
                              placeholder="e.g. NMB Bank"
                            />
                          </div>
                          <div className="space-y-1">
                            <label className="text-[0.6rem] font-black uppercase text-text-muted">Account ID</label>
                            <input 
                              type="text" 
                              className="w-full bg-muted border border-border rounded-xl px-3 py-2 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                              value={staffEditForm.account_number}
                              onChange={e => setStaffEditForm({...staffEditForm, account_number: e.target.value})}
                              placeholder="e.g. 1004-9844-320"
                            />
                          </div>
                          <div className="flex items-center gap-3 border-t border-border/50 pt-3">
                            <input 
                              type="checkbox" 
                              id="staff-active-toggle" 
                              className="w-4 h-4 text-primary border-border rounded accent-primary cursor-pointer"
                              checked={staffEditForm.is_active}
                              onChange={e => setStaffEditForm({...staffEditForm, is_active: e.target.checked})}
                            />
                            <label htmlFor="staff-active-toggle" className="text-[0.6rem] font-black uppercase text-text-muted cursor-pointer select-none">Active Placement Status</label>
                          </div>
                        </>
                      ) : (
                        <>
                          <div className="flex items-center gap-3 text-sm text-text-secondary border-t border-border/50 pt-3">
                            <Landmark size={16} className="text-primary shrink-0" />
                            <div>
                              <p className="text-[0.6rem] font-black uppercase text-text-muted">Disbursement Bank</p>
                              <p className="font-bold text-text">{(selectedStaff as any).bank_name || 'Not Configured'}</p>
                            </div>
                          </div>
                          <div className="flex items-center gap-3 text-sm text-text-secondary border-t border-border/50 pt-3">
                            <Hash size={16} className="text-primary shrink-0" />
                            <div>
                              <p className="text-[0.6rem] font-black uppercase text-text-muted">Account ID</p>
                              <p className="font-bold text-text">{(selectedStaff as any).account_number || 'Not Configured'}</p>
                            </div>
                          </div>
                          <div className="flex items-center gap-3 text-sm text-text-secondary border-t border-border/50 pt-3">
                            <div className={`px-2 py-0.5 rounded text-[0.55rem] font-black uppercase border ${
                              selectedStaff.is_active 
                                ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20' 
                                : 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/20'
                            }`}>
                              {selectedStaff.is_active ? 'Active' : 'Inactive'}
                            </div>
                          </div>
                        </>
                      )}
                    </div>
                  </div>
                </div>
              </div>
              
              <div className="p-10 border-t border-border bg-muted/30 flex justify-between items-center">
                {isEditingStaff ? (
                  <>
                    <button 
                      type="button"
                      onClick={() => setIsEditingStaff(false)}
                      className="px-6 py-3 bg-muted border border-border text-text rounded-xl font-bold text-xs"
                    >
                      Cancel
                    </button>
                    <button 
                      type="submit"
                      className="px-8 py-3 bg-primary text-white rounded-xl font-black text-xs uppercase tracking-widest hover:bg-primary/95 transition-all shadow-md"
                    >
                      Save Changes
                    </button>
                  </>
                ) : (
                  <>
                    {selectedStaff.is_active === 1 && (
                      <button 
                        type="button"
                        onClick={() => {
                          setShowProfileModal(false);
                          navigate(`/admin/offboarding/wizard/${selectedStaff.id}`);
                        }}
                        className="px-5 py-3 bg-rose-600 hover:bg-rose-700 text-white rounded-xl font-black uppercase text-[0.6rem] tracking-widest transition-all flex items-center gap-1.5 shadow-md"
                      >
                        <UserMinus size={12} /> Offboard
                      </button>
                    )}
                    <button 
                      type="button"
                      onClick={() => handleDeleteStaff(selectedStaff.id)}
                      className="px-5 py-3 bg-rose-500/10 text-rose-500 border border-rose-500/20 hover:bg-rose-500/20 rounded-xl font-black uppercase text-[0.6rem] tracking-widest transition-all"
                    >
                      Remove Staff
                    </button>
                    <div className="flex gap-3">
                      <button 
                        type="button"
                        onClick={() => {
                          setStaffEditForm({
                            role_id: String(selectedStaff.role_id),
                            salary_grade_id: String(selectedStaff.salary_grade_id || ''),
                            employment_type: selectedStaff.employment_type,
                            bank_name: (selectedStaff as any).bank_name || '',
                            account_number: (selectedStaff as any).account_number || '',
                            department: selectedStaff.department || 'Sciences',
                            designation: selectedStaff.designation || '',
                            is_active: selectedStaff.is_active === 1
                          });
                          setIsEditingStaff(true);
                        }}
                        className="px-6 py-3 bg-muted border border-border text-text rounded-xl font-bold text-xs"
                      >
                        Edit Profile
                      </button>
                      <button 
                        type="button"
                        onClick={() => setShowProfileModal(false)}
                        className="px-8 py-3 bg-[#002147] hover:bg-black text-white rounded-2xl font-black text-xs uppercase tracking-widest transition-all"
                      >
                        Close
                      </button>
                    </div>
                  </>
                )}
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}

      {/* Documents Modal */}
      {showDocsModal && selectedStaff && (
        <Modal
          open={true}
          onClose={() => setShowDocsModal(false)}
          title="Staff Documents"
          maxWidth="max-w-lg"
          zIndex={150}
        >
          <ModalBody>

            <div className="p-8 space-y-4">
              {[
                { name: 'Employment_Contract.pdf', size: '2.4 MB', date: 'Appointment Date' },
                { name: 'KYC_Verification_Profile.pdf', size: '1.8 MB', date: 'Onboarding Date' },
                { name: 'Academic_Qualifications.pdf', size: '4.2 MB', date: 'Verified Credentials' }
              ].map((doc, idx) => (
                <div key={idx} className="p-4 bg-muted/40 border border-border rounded-2xl flex items-center justify-between hover:bg-muted/80 transition-colors">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                      <FileText size={20} />
                    </div>
                    <div>
                      <p className="text-xs font-bold text-text">{doc.name}</p>
                      <p className="text-[0.65rem] text-text-muted mt-0.5">{doc.size} | {doc.date === 'Appointment Date' ? new Date(selectedStaff.appointment_date).toLocaleDateString() : doc.date}</p>
                    </div>
                  </div>
                  <button 
                    onClick={() => downloadMockFile(doc.name)}
                    className="p-2 text-primary hover:bg-primary/10 rounded-xl transition-all"
                  >
                    <Download size={18} />
                  </button>
                </div>
              ))}
            </div>

            <div className="p-8 border-t border-border bg-muted/30 flex justify-end">
              <button
                onClick={() => setShowDocsModal(false)}
                className="px-8 py-3 bg-muted border border-border text-text rounded-xl font-bold text-xs"
              >
                Exit Directory
              </button>
            </div>
          </ModalBody>
        </Modal>
      )}

      {/* Leave Request Details Modal */}
      {showLeaveDetailModal && selectedLeave && (
        <Modal
          open={true}
          onClose={() => setShowLeaveDetailModal(false)}
          title="Leave Audit Intel"
          maxWidth="max-w-lg"
          zIndex={150}
        >
          <ModalBody>
            <div className="space-y-6">
              <div className="grid grid-cols-2 gap-4 bg-muted/20 p-4 border border-border rounded-2xl">
                <div>
                  <p className="text-[0.6rem] font-black uppercase text-text-muted">Leave Type</p>
                  <p className="text-sm font-bold text-text">{selectedLeave.leave_type}</p>
                </div>
                <div>
                  <p className="text-[0.6rem] font-black uppercase text-text-muted">Total Duration</p>
                  <p className="text-sm font-bold text-text">{selectedLeave.days_count} Working Days</p>
                </div>
              </div>

              <div>
                <p className="text-[0.6rem] font-black uppercase text-text-muted mb-2 px-1">Statement of Purpose</p>
                <div className="p-5 bg-muted/30 border border-border rounded-2xl text-xs text-text leading-relaxed font-semibold">
                  {selectedLeave.reason || 'No detailed reason was provided for this request.'}
                </div>
              </div>

              {selectedLeave.rejection_reason && (
                <div>
                  <p className="text-[0.6rem] font-black uppercase text-rose-500 mb-2 px-1">Audit Rejection Notes</p>
                  <div className="p-5 bg-rose-50/10 border border-rose-100/20 text-rose-600 dark:text-rose-400 rounded-2xl text-xs leading-relaxed font-semibold">
                    {selectedLeave.rejection_reason}
                  </div>
                </div>
              )}

              <div className="flex justify-between items-center text-[0.65rem] font-black uppercase text-text-muted pt-2">
                <span>Timeline: {new Date(selectedLeave.start_date).toLocaleDateString()} - {new Date(selectedLeave.end_date).toLocaleDateString()}</span>
                <span className={`px-2.5 py-0.5 rounded border ${
                  selectedLeave.status === 'approved' ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20' :
                  selectedLeave.status === 'rejected' ? 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/20' :
                  'bg-orange-50 text-orange-600 border-orange-100 dark:bg-orange-500/10 dark:text-orange-400 dark:border-orange-500/20'
                }`}>{selectedLeave.status}</span>
              </div>
            </div>

            <div className="p-8 border-t border-border bg-muted/30 flex justify-end gap-3">
              {selectedLeave.status === 'pending' && (
                <>
                  <button 
                    onClick={async () => { await updateLeaveStatus(selectedLeave.uid, 'rejected'); setShowLeaveDetailModal(false); }} 
                    className="px-6 py-3 bg-card border border-border text-rose-500 rounded-xl font-bold text-xs hover:bg-rose-50 dark:hover:bg-rose-950/20 transition-all"
                  >
                    Reject
                  </button>
                  <button 
                    onClick={async () => { await updateLeaveStatus(selectedLeave.uid, 'approved'); setShowLeaveDetailModal(false); }} 
                    className="px-6 py-3 bg-primary text-white rounded-xl font-bold text-xs hover:bg-primary/95 transition-all shadow-md"
                  >
                    Approve
                  </button>
                </>
              )}
              <button 
                onClick={() => setShowLeaveDetailModal(false)}
                className="px-6 py-3 bg-muted border border-border text-text rounded-xl font-bold text-xs"
              >
                Close Audit
              </button>
            </div>
          </ModalBody>
        </Modal>
      )}

      {/* Run Modal */}
      {showRunModal && (
        <Modal
          open={true}
          onClose={() => setShowRunModal(false)}
          title="New Payroll Run"
          maxWidth="max-w-md"
          zIndex={150}
        >
          <ModalBody>
            <div className="space-y-6">
                <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Month</label>
                        <select className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-sm font-bold outline-none text-text" value={runForm.period_month} onChange={e => setRunForm({...runForm, period_month: Number(e.target.value)})}>
                            {months.map((m, i) => <option key={m} value={i+1}>{m}</option>)}
                        </select>
                    </div>
                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Year</label>
                        <input type="number" className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-sm font-bold outline-none text-text" value={runForm.period_year} onChange={e => setRunForm({...runForm, period_year: Number(e.target.value)})} />
                    </div>
                </div>
                <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Protocol Description</label>
                    <textarea className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-sm font-bold outline-none text-text" rows={3} placeholder="e.g. June 2024 Salaries - Standard Run" value={runForm.description} onChange={e => setRunForm({...runForm, description: e.target.value})} />
                </div>
                <div className="pt-4 flex gap-3">
                    <button onClick={() => setShowRunModal(false)} className="flex-1 py-3 bg-muted border border-border rounded-xl font-black uppercase text-[0.65rem] tracking-widest text-text">Cancel</button>
                    <button onClick={async () => { await createPayrollRun(runForm); setShowRunModal(false); }} className="flex-1 py-3 bg-primary text-white rounded-xl font-black uppercase text-[0.65rem] tracking-widest shadow-lg shadow-blue-900/10 active:scale-95">Create Run</button>
                </div>
            </div>
          </ModalBody>
        </Modal>
      )}

      {/* Add Vacancy Modal */}
      {showVacancyModal && (
        <Modal
          open={true}
          onClose={() => setShowVacancyModal(false)}
          title="Create Job Vacancy"
          maxWidth="max-w-lg"
          zIndex={150}
        >
          <ModalBody>
            <form id="hr-vacancy-form" onSubmit={handleCreateVacancySubmit} className="space-y-5">
              <div className="space-y-1">
                <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Job Title</label>
                <input 
                  type="text" 
                  required 
                  className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                  placeholder="e.g. Senior Geography Instructor"
                  value={vacancyForm.title}
                  onChange={e => setVacancyForm({...vacancyForm, title: e.target.value})}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Department</label>
                  <select 
                    className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                    value={vacancyForm.department}
                    onChange={e => setVacancyForm({...vacancyForm, department: e.target.value})}
                  >
                    <option value="">Select Department...</option>
                    {departments.map(d => (
                      <option key={d.id} value={d.name}>{d.name}</option>
                    ))}
                  </select>
                </div>
                <div className="space-y-1">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Closing Date</label>
                  <input 
                    type="date" 
                    required 
                    className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                    value={vacancyForm.closing_date}
                    onChange={e => setVacancyForm({...vacancyForm, closing_date: e.target.value})}
                  />
                </div>
              </div>

              <div className="space-y-1">
                <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Requirements Profile</label>
                <textarea 
                  className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                  rows={2}
                  placeholder="e.g. Degree in Education or Geography, 3+ years lecturing experience"
                  value={vacancyForm.requirements}
                  onChange={e => setVacancyForm({...vacancyForm, requirements: e.target.value})}
                />
              </div>

              <div className="space-y-1">
                <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Responsibilities & Description</label>
                <textarea 
                  className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                  rows={3}
                  placeholder="Details regarding core academic responsibilities, lesson preparation, and grading guidelines..."
                  value={vacancyForm.description}
                  onChange={e => setVacancyForm({...vacancyForm, description: e.target.value})}
                />
              </div>

              <div className="pt-4 flex gap-3">
                <button type="button" onClick={() => setShowVacancyModal(false)} className="flex-1 py-3 bg-muted border border-border rounded-xl font-black uppercase text-[0.65rem] tracking-widest text-text">Cancel</button>
                <button type="submit" form="hr-vacancy-form" className="flex-1 py-3 bg-primary text-white rounded-xl font-black uppercase text-[0.65rem] tracking-widest shadow-lg shadow-blue-900/10 active:scale-95">Publish Opening</button>
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}

      {/* Vacancy Details Modal */}
      {showVacancyDetailModal && selectedVacancy && (
        <Modal
          open={true}
          onClose={() => { setShowVacancyDetailModal(false); setIsEditingVacancy(false); }}
          title={isEditingVacancy ? 'Edit Career Opening' : selectedVacancy.title}
          maxWidth="max-w-lg"
          zIndex={150}
        >
          <ModalBody>
            <form id="hr-vacancy-edit-form" onSubmit={handleEditVacancySubmit}>
              <div className="space-y-6">
                {isEditingVacancy ? (
                  <>
                    <div className="space-y-1">
                      <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Job Title</label>
                      <input 
                        type="text" 
                        required 
                        className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                        value={vacancyEditForm.title}
                        onChange={e => setVacancyEditForm({...vacancyEditForm, title: e.target.value})}
                      />
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1">
                        <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Department</label>
                        <select 
                          className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                          value={vacancyEditForm.department}
                          onChange={e => setVacancyEditForm({...vacancyEditForm, department: e.target.value})}
                        >
                          <option value="">Select Department...</option>
                          {departments.map(d => (
                            <option key={d.id} value={d.name}>{d.name}</option>
                          ))}
                        </select>
                      </div>
                      <div className="space-y-1">
                        <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Closing Date</label>
                        <input 
                          type="date" 
                          required 
                          className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                          value={vacancyEditForm.closing_date}
                          onChange={e => setVacancyEditForm({...vacancyEditForm, closing_date: e.target.value})}
                        />
                      </div>
                    </div>

                    <div className="space-y-1">
                      <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Candidate Requirements</label>
                      <textarea 
                        className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                        rows={2}
                        value={vacancyEditForm.requirements}
                        onChange={e => setVacancyEditForm({...vacancyEditForm, requirements: e.target.value})}
                      />
                    </div>

                    <div className="space-y-1">
                      <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Job Description</label>
                      <textarea 
                        className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                        rows={3}
                        value={vacancyEditForm.description}
                        onChange={e => setVacancyEditForm({...vacancyEditForm, description: e.target.value})}
                      />
                    </div>
                  </>
                ) : (
                  <>
                    <div className="grid grid-cols-2 gap-4 bg-muted/20 p-4 border border-border rounded-2xl text-xs font-semibold">
                      <div>
                        <p className="text-[0.6rem] font-black uppercase text-text-muted">Closing Timeline</p>
                        <p className="text-text mt-0.5">{selectedVacancy.closing_date ? new Date(selectedVacancy.closing_date).toLocaleDateString() : 'N/A'}</p>
                      </div>
                      <div>
                        <p className="text-[0.6rem] font-black uppercase text-text-muted">Listing Status</p>
                        <span className={`inline-block mt-1 px-2.5 py-0.5 rounded text-[0.55rem] font-black uppercase border ${
                          selectedVacancy.status === 'open' 
                            ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20' 
                            : 'bg-zinc-100 text-zinc-600 border-zinc-200 dark:bg-zinc-800 dark:text-zinc-400 dark:border-zinc-700'
                        }`}>{selectedVacancy.status}</span>
                      </div>
                    </div>

                    <div>
                      <p className="text-[0.6rem] font-black uppercase text-text-muted mb-2 px-1">Candidate Requirements</p>
                      <div className="p-4 bg-muted/30 border border-border rounded-2xl text-xs text-text leading-relaxed font-semibold">
                        {selectedVacancy.requirements || 'No specific educational or professional credentials listed.'}
                      </div>
                    </div>

                    <div>
                      <p className="text-[0.6rem] font-black uppercase text-text-muted mb-2 px-1">Job Description</p>
                      <div className="p-4 bg-muted/30 border border-border rounded-2xl text-xs text-text leading-relaxed font-semibold max-h-[150px] overflow-y-auto custom-scrollbar">
                        {selectedVacancy.description || 'Responsibilities encompass teaching course modules, preparing classroom aids, and assessing pupil coursework.'}
                      </div>
                    </div>
                  </>
                )}

                <div className="pt-4 border-t border-border flex justify-between items-center gap-3">
                  {isEditingVacancy ? (
                    <>
                      <button 
                        type="button" 
                        onClick={() => setIsEditingVacancy(false)} 
                        className="px-6 py-3 bg-muted border border-border text-text rounded-xl font-bold text-xs"
                      >
                        Cancel
                      </button>
                      <button 
                        type="submit" 
                        className="px-8 py-3 bg-primary text-white rounded-xl font-black text-xs uppercase tracking-widest hover:bg-primary/95 transition-all shadow-md"
                      >
                        Save Changes
                      </button>
                    </>
                  ) : (
                    <>
                      <button 
                        type="button"
                        onClick={() => handleDeleteVacancy(selectedVacancy.id)}
                        className="px-4 py-3 bg-rose-500/10 text-rose-500 border border-rose-500/20 hover:bg-rose-500/20 rounded-xl font-black uppercase text-[0.6rem] tracking-widest transition-all"
                      >
                        Delete Listing
                      </button>
                      <div className="flex gap-3">
                        <button 
                          type="button"
                          onClick={() => {
                            setVacancyEditForm({
                              title: selectedVacancy.title,
                              department: selectedVacancy.department || '',
                              closing_date: selectedVacancy.closing_date ? new Date(selectedVacancy.closing_date).toISOString().split('T')[0] : '',
                              requirements: selectedVacancy.requirements || '',
                              description: selectedVacancy.description || ''
                            });
                            setIsEditingVacancy(true);
                          }}
                          className="px-5 py-3 bg-muted border border-border rounded-xl font-black uppercase text-[0.6rem] tracking-widest text-text"
                        >
                          Edit Details
                        </button>
                        <button 
                          type="button"
                          onClick={() => handleToggleVacancyStatus(selectedVacancy.id, selectedVacancy.status)}
                          className="px-5 py-3 bg-muted border border-border rounded-xl font-black uppercase text-[0.6rem] tracking-widest text-text"
                        >
                          Toggle {selectedVacancy.status === 'open' ? 'Close' : 'Open'}
                        </button>
                        <button 
                          type="button"
                          onClick={() => setShowVacancyDetailModal(false)}
                          className="px-6 py-3 bg-primary text-white rounded-xl font-black uppercase text-[0.6rem] tracking-widest shadow-md"
                        >
                          Close
                        </button>
                      </div>
                    </>
                  )}
                </div>
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}

      {/* Applicant Status Modal */}
      {showApplicantModal && selectedApplicant && (
        <Modal
          open={true}
          onClose={() => setShowApplicantModal(false)}
          title="Review Candidate"
          maxWidth="max-w-md"
          zIndex={150}
        >
          <ModalBody>
            
            <form onSubmit={handleUpdateApplicantStatusSubmit} className="p-8 space-y-5">
              <div className="space-y-1">
                <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Placement Status</label>
                <select 
                  className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                  value={applicantStatusForm.status}
                  onChange={e => setApplicantStatusForm({...applicantStatusForm, status: e.target.value})}
                >
                  <option value="pending">Pending Review</option>
                  <option value="shortlisted">Shortlisted</option>
                  <option value="interviewed">Interviewed</option>
                  <option value="offered">Offered Placement</option>
                  <option value="hired">Hired / Placed</option>
                  <option value="rejected">Rejected</option>
                </select>
              </div>

              <div className="space-y-1">
                <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Interview Date & Time (Optional)</label>
                <input 
                  type="datetime-local" 
                  className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                  value={applicantStatusForm.interview_date}
                  onChange={e => setApplicantStatusForm({...applicantStatusForm, interview_date: e.target.value})}
                />
              </div>

              <div className="space-y-1">
                <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Review Notes & Decisions</label>
                <textarea 
                  className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                  rows={4}
                  placeholder="Record credentials feedback or interview summaries..."
                  value={applicantStatusForm.notes}
                  onChange={e => setApplicantStatusForm({...applicantStatusForm, notes: e.target.value})}
                />
              </div>

              <div className="pt-4 flex gap-3">
                <button type="button" onClick={() => setShowApplicantModal(false)} className="flex-1 py-3 bg-muted border border-border rounded-xl font-black uppercase text-[0.65rem] tracking-widest text-text">Cancel</button>
                <button type="submit" form="hr-applicant-status-form" className="flex-1 py-3 bg-primary text-white rounded-xl font-black uppercase text-[0.65rem] tracking-widest shadow-lg active:scale-95">Update Placement</button>
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}

      {/* Add Applicant Modal */}
      {showAddApplicantModal && (
        <Modal
          open={true}
          onClose={() => {
            setShowCustomCategoryInput(false);
            setShowCustomSupplierInput(false);
            setSelectedCategoryVal('');
            setSelectedSupplierVal('');
            setShowAddApplicantModal(false);
          }}
          title="Register Candidate"
          maxWidth="max-w-md"
          zIndex={150}
        >
          <ModalBody>
            <div className="p-8 border-b border-border bg-muted/50 flex justify-between items-center">
              <div>
                <h2 className="text-xl font-black text-text uppercase tracking-tight">Register Candidate</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Enter details of the applicant</p>
              </div>
              <button 
                type="button"
                onClick={() => setShowAddApplicantModal(false)} 
                className="w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all"
              >
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={handleAddApplicantSubmit} className="p-8 space-y-5">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">First Name</label>
                  <input 
                    type="text" 
                    required 
                    className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                    placeholder="e.g. John"
                    value={addApplicantForm.first_name}
                    onChange={e => setAddApplicantForm({...addApplicantForm, first_name: e.target.value})}
                  />
                </div>
                <div className="space-y-1">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Last Name</label>
                  <input 
                    type="text" 
                    required 
                    className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                    placeholder="e.g. Doe"
                    value={addApplicantForm.last_name}
                    onChange={e => setAddApplicantForm({...addApplicantForm, last_name: e.target.value})}
                  />
                </div>
              </div>

              <div className="space-y-1">
                <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Email Address</label>
                <input 
                  type="email" 
                  required 
                  className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                  placeholder="e.g. john.doe@email.com"
                  value={addApplicantForm.email}
                  onChange={e => setAddApplicantForm({...addApplicantForm, email: e.target.value})}
                />
              </div>

              <div className="space-y-1">
                <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Phone Number</label>
                <input 
                  type="text" 
                  className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                  placeholder="e.g. +263 77 123 4567"
                  value={addApplicantForm.phone}
                  onChange={e => setAddApplicantForm({...addApplicantForm, phone: e.target.value})}
                />
              </div>

              <div className="space-y-1">
                <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Vacancy Assignment</label>
                <select 
                  className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                  value={addApplicantForm.vacancy_id}
                  onChange={e => setAddApplicantForm({...addApplicantForm, vacancy_id: e.target.value})}
                >
                  <option value="">Select Open Position (Optional)...</option>
                  {vacancies.filter(v => v.status === 'open').map(v => (
                    <option key={v.id} value={v.id}>{v.title} ({v.department})</option>
                  ))}
                </select>
              </div>

              <div className="space-y-1">
                <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Application Notes / Qualifications</label>
                <textarea 
                  className="w-full bg-muted border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text dark:bg-zinc-900"
                  rows={3}
                  placeholder="Mention key qualifications, academic credentials or remarks..."
                  value={addApplicantForm.notes}
                  onChange={e => setAddApplicantForm({...addApplicantForm, notes: e.target.value})}
                />
              </div>

              <div className="pt-4 flex gap-3">
                <button 
                  type="button" 
                  onClick={() => setShowAddApplicantModal(false)} 
                  className="flex-1 py-3 bg-muted border border-border rounded-xl font-black uppercase text-[0.65rem] tracking-widest text-text"
                >
                  Cancel
                </button>
                <button 
                  type="submit" 
                  className="flex-1 py-3 bg-primary text-white rounded-xl font-black uppercase text-[0.65rem] tracking-widest shadow-lg active:scale-95"
                >
                  Add Candidate
                </button>
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}

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