"use client";

import { API, authFetch } from "@/lib/api";
import { useState, useEffect, useRef, useCallback } from "react";
import { useParams, useRouter } from "next/navigation";
import { motion } from "framer-motion";
import {
  ArrowLeft, Briefcase, Phone, FileText, Camera,
  Banknote, Clock, User, Download, LogOut, XCircle, Shield, Pencil, Check, X, ChevronDown
} from "lucide-react";
import { cn } from "@/lib/utils";
import {
  downloadEmployeeTemplatePDF,
  downloadEmploymentAppointmentFormPDF,
  downloadFullFinalSettlementPDF,
  downloadPersonalProfileChecklistPDF,
  downloadIncrementHistoryPDF,
  getCompanyName,
} from "@/lib/pdf";

interface Employee {
  id: string;
  employeeId: string;
  firstName: string;
  lastName: string;
  cnic: string;
  department: string;
  designation: string;
  joiningDate: string;
  contractType: string;
  basicSalary: number;
  profileImage?: string;
  bankName?: string;
  accountNumber?: string;
  email?: string;
  dateOfBirth?: string;
  emergencyContact?: string;
  emergencyContactPhone?: string;
  eobiNo?: string;
  pessiNo?: string;
  lastWorkingDay?: string;
  separationType?: string;
  settlementLastSalary?: string;
  settlementLeaveEncashment?: string;
  settlementGratuity?: string;
  settlementOvertime?: string;
  settlementLoanDeduction?: string;
  settlementOtherDeduction?: string;
  settlementNetPayable?: string;
  documents?: { id: string; title: string; type: string; fileUrl: string }[];
  attendances?: { id: string; date: string; status: string; overtimeHrs: number }[];
  payrolls?: { id: string; month: number; year: number; netSalary: number; status: string }[];
}

type Contract = {
  id: string;
  type: string;
  expiryDate: string | null;
  status: string;
  employee: { employeeId: string };
};

interface SalaryIncrement {
  id: string;
  year: number;
  previousSalary: number;
  newSalary: number;
  incrementRate: number;
  incrementAmount: number;
  createdAt: string;
}

const MONTHS = ["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

const CONTRACT_STYLE: Record<string, string> = {
  PERMANENT: "bg-emerald-50 text-emerald-700 ring-emerald-600/20",
  PROBATION: "bg-amber-50 text-amber-700 ring-amber-600/20",
  CONTRACT:  "bg-blue-50 text-blue-700 ring-blue-600/20",
  INTERN:    "bg-purple-50 text-purple-700 ring-purple-600/20",
};

const PAYROLL_STYLE: Record<string, string> = {
  PAID:             "bg-emerald-50 text-emerald-700 ring-emerald-600/20",
  PROCESSED:        "bg-blue-50 text-blue-700 ring-blue-600/20",
  PENDING_APPROVAL: "bg-amber-50 text-amber-700 ring-amber-600/20",
  DRAFT:            "bg-gray-100 text-gray-500 ring-gray-400/30",
};

export default function EmployeeDetailPage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const [employee, setEmployee] = useState<Employee | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isUploadingImage, setIsUploadingImage] = useState(false);
  const imageInputRef = useRef<HTMLInputElement>(null);

  const [settingsDepts, setSettingsDepts] = useState<string[]>([]);
  const [settingsDesigs, setSettingsDesigs] = useState<string[]>([]);
  const [deptOpen, setDeptOpen] = useState(false);
  const [desigOpen, setDesigOpen] = useState(false);
  const [salaryDivisor, setSalaryDivisor] = useState(26);
  const deptRef = useRef<HTMLDivElement>(null);
  const desigRef = useRef<HTMLDivElement>(null);

  const [editMode, setEditMode] = useState(false);
  const [editForm, setEditForm] = useState<Partial<Employee>>({});
  const [saving, setSaving] = useState(false);

  const startEdit = () => {
    if (!employee) return;
    setEditForm({
      firstName: employee.firstName,
      lastName: employee.lastName,
      cnic: employee.cnic,
      email: employee.email ?? "",
      joiningDate: employee.joiningDate?.slice(0, 10) ?? "",
      department: employee.department,
      designation: employee.designation,
      contractType: employee.contractType,
      basicSalary: employee.basicSalary,
      bankName: employee.bankName ?? "",
      accountNumber: employee.accountNumber ?? "",
      eobiNo: employee.eobiNo ?? "",
      pessiNo: employee.pessiNo ?? "",
      emergencyContact: employee.emergencyContact ?? "",
      emergencyContactPhone: employee.emergencyContactPhone ?? "",
    });
    setEditMode(true);
  };

  const handleSaveEdit = async () => {
    if (!employee) return;
    setSaving(true);
    try {
      const res = await authFetch(`${API}/dash/employees/${employee.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(editForm),
      });
      if (!res.ok) { alert("Failed to save changes."); return; }
      await fetchEmployee();
      setEditMode(false);
    } catch { alert("Failed to save changes."); }
    finally { setSaving(false); }
  };

  const [separationContract, setSeparationContract] = useState<Contract | null>(null);
  const [contractsRefreshKey, setContractsRefreshKey] = useState(0);
  const [separationDate, setSeparationDate] = useState(
    () => new Date().toISOString().slice(0, 10),
  );
  const [separating, setSeparating] = useState(false);
  const [increments, setIncrements] = useState<SalaryIncrement[]>([]);
  const [incrementPage, setIncrementPage] = useState(1);
  const incrementsPerPage = 10;

  const fetchIncrements = useCallback(async () => {
    try {
      const res = await authFetch(`${API}/dash/employees/${id}/increments`);
      if (res.ok) setIncrements(await res.json());
    } catch { /* ignore */ }
  }, [id]);

  const fetchEmployee = useCallback(async () => {
    try {
      const res = await authFetch(`${API}/dash/employees/${id}`);
      if (res.ok) setEmployee(await res.json());
    } catch { /* ignore */ } finally { setIsLoading(false); }
  }, [id]);

  useEffect(() => { fetchEmployee(); }, [fetchEmployee]);
  useEffect(() => { fetchIncrements(); }, [fetchIncrements]);

  useEffect(() => {
    authFetch(`${API}/dash/settings`).then(r => r.json()).then(data => {
      const parseCsv = (v: unknown): string[] => typeof v === "string" && v.trim() ? v.split(",").map((s: string) => s.trim()).filter(Boolean) : [];
      const d = parseCsv(data.departments); if (d.length) setSettingsDepts(d);
      const g = parseCsv(data.designations); if (g.length) setSettingsDesigs(g);
      if (data.salaryDivisor) setSalaryDivisor(Number(data.salaryDivisor));
    }).catch(() => {});
  }, []);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (deptRef.current && !deptRef.current.contains(e.target as Node)) setDeptOpen(false);
      if (desigRef.current && !desigRef.current.contains(e.target as Node)) setDesigOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const addToSettings = async (field: "departments" | "designations", list: string[]) => {
    try {
      await authFetch(`${API}/dash/settings`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ [field]: list }),
      });
    } catch {}
  };

  useEffect(() => {
    const run = async () => {
      if (!employee) return;
      try {
        const res = await authFetch(`${API}/dash/contracts`);
        const data = await res.json();
        if (!res.ok || !Array.isArray(data)) { setSeparationContract(null); return; }
        const list = data
          .filter((c: Contract) => c?.status === "Terminated" && c?.employee?.employeeId === employee.employeeId)
          .sort((a: Contract, b: Contract) => {
            const da = a.expiryDate ? new Date(a.expiryDate).getTime() : 0;
            const db = b.expiryDate ? new Date(b.expiryDate).getTime() : 0;
            return db - da;
          });
        setSeparationContract(list[0] ?? null);
      } catch { setSeparationContract(null); }
    };
    run();
  }, [employee, id, contractsRefreshKey]);

  const handleSeparation = async (separationType: "Resigned" | "Terminated") => {
    if (!employee) return;
    if (!separationDate) { alert("Please select a date."); return; }
    if (!confirm(`Mark ${employee.firstName} ${employee.lastName} as ${separationType}?\nDate: ${separationDate}`)) return;
    setSeparating(true);
    try {
      const res = await authFetch(`${API}/dash/employees/${employee.id}/terminate`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ expiryDate: separationDate, separationType }),
      });
      if (!res.ok) { const msg = await res.text().catch(() => ""); alert(`Failed.\n${msg || `Status ${res.status}`}`); return; }
      setContractsRefreshKey((k) => k + 1);
      alert(`Employee marked as ${separationType}.`);
    } catch { alert("Failed to save separation."); }
    finally { setSeparating(false); }
  };

  const handleCancelSeparation = async () => {
    if (!employee || !separationContract) { alert("No separation record to cancel."); return; }
    if (!confirm(`Remove separation record for ${employee.firstName} ${employee.lastName}?`)) return;
    setSeparating(true);
    try {
      const res = await authFetch(`${API}/dash/contracts/${separationContract.id}`, { method: "DELETE" });
      if (!res.ok) { alert("Failed to cancel separation."); return; }
      setContractsRefreshKey((k) => k + 1);
      alert("Separation record removed.");
    } catch { alert("Failed."); }
    finally { setSeparating(false); }
  };

  const buildSettlementData = async () => {
    if (!employee || !separationContract) return null;
    const leavingDate = separationContract.expiryDate ? new Date(separationContract.expiryDate) : new Date();
    const monthStart = new Date(leavingDate); monthStart.setDate(1); monthStart.setHours(0,0,0,0);
    
    const [attRes, settingsRes, loansRes] = await Promise.all([
      authFetch(`${API}/dash/attendance`),
      authFetch(`${API}/dash/settings`),
      authFetch(`${API}/dash/loans`),
    ]);
    
    const attendance = attRes.ok ? await attRes.json() : [];
    const settings = settingsRes.ok ? await settingsRes.json() : {};
    const loansData = loansRes.ok ? await loansRes.json() : [];
    
    const annualLeaveDays = Number(settings.annualLeaveDays ?? 14);
    const empAttend = Array.isArray(attendance)
      ? attendance.filter((a: any) => { 
          if (a?.employeeId !== employee.id) return false; 
          const d = new Date(a?.date); d.setHours(0,0,0,0);
          const s = new Date(monthStart); s.setHours(0,0,0,0);
          const e = new Date(leavingDate); e.setHours(23,59,59,999);
          return d >= s && d <= e; 
        })
      : [];

    const calendarDays: string[] = [];
    const tDate = new Date(monthStart);
    while (tDate <= leavingDate) {
      calendarDays.push(tDate.toISOString().split('T')[0]);
      tDate.setDate(tDate.getDate() + 1);
    }
    const unpaidAbsences = empAttend.filter((a: any) => a?.status === "ABSENT").length;
    const workDays = Math.max(0, calendarDays.length - unpaidAbsences);
    const overtimeHrs = empAttend.reduce((s: number, a: any) => s + (a?.overtimeHrs ?? 0), 0);
    const overtimeAmount = empAttend.reduce((s: number, a: any) => s + (a?.overtimeAmount ?? 0), 0);
    const lateEarlyDeduction = empAttend.reduce((s: number, a: any) => s + (a?.deductionAmount ?? 0), 0);
    
    // Outstanding Loans: Include ACTIVE loans OR COMPLETED loans that still have a balance (likely from recent separation)
    const activeLoans = Array.isArray(loansData) ? loansData.filter((l: any) => 
      l.employeeId === employee.id && (l.status === "ACTIVE" || (l.status === "COMPLETED" && (l.remainingBalance ?? 0) > 0))
    ) : [];
    const loanDeduction = activeLoans.reduce((s: number, l: any) => s + (l.remainingBalance ?? 0), 0);

    const joining = employee.joiningDate ? new Date(employee.joiningDate) : null;
    const gratuityYears = joining ? Math.floor((leavingDate.getTime() - joining.getTime()) / (1000*60*60*24*365.25)) : 0;
    const isEligibleForGratuity = gratuityYears >= 1; // Compliance Rule: 1 year minimum
    const gratuityAmount = isEligibleForGratuity ? (employee.basicSalary ?? 0) * gratuityYears : 0;
    
    const dailyRate = (employee.basicSalary ?? 0) / 26;
    const salaryEarned = dailyRate * workDays;
    const leaveEncashmentDays = annualLeaveDays;
    const leaveEncashment = dailyRate * leaveEncashmentDays;
    
    const totalEarning = gratuityAmount + salaryEarned + overtimeAmount + leaveEncashment;
    const totalPayable = totalEarning - loanDeduction - lateEarlyDeduction;
    
    return { leavingDate, workDays, overtimeHrs, overtimeAmount, lateEarlyDeduction, loanDeduction, gratuityYears, gratuityAmount, salaryEarned, leaveEncashmentDays, leaveEncashment, totalEarning, totalPayable };
  };

  const handleDownloadDoc = async (file: string, language: "english" | "urdu") => {
    if (!employee) return;
    if (file === "final-settlement-letter") {
      if (!separationContract) { alert("No separation record found."); return; }
      try {
        const s = await buildSettlementData();
        if (!s) return;
        const fmt = (n: number) => n.toLocaleString("en-PK", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        const companyName = await getCompanyName();
        await downloadEmployeeTemplatePDF({
          emp: {
            ...employee,
            lastWorkingDay: separationContract.expiryDate ?? undefined,
            separationType: separationContract.type ?? undefined,
            settlementLastSalary: fmt(s.salaryEarned),
            settlementLeaveEncashment: fmt(s.leaveEncashment),
            settlementGratuity: fmt(s.gratuityAmount),
            settlementOvertime: fmt(s.overtimeAmount),
            settlementLoanDeduction: fmt(s.loanDeduction),
            settlementOtherDeduction: fmt(s.lateEarlyDeduction),
            settlementNetPayable: fmt(s.totalPayable),
            companyName,
          },
          templateFileName: file,
          language,
        });
      } catch { alert("Failed to generate settlement PDF."); }
      return;
    }
    if (file === "personal-profile-checklist") {
      const companyName = await getCompanyName();
      await downloadPersonalProfileChecklistPDF(employee, language, companyName);
      return;
    }
    (async () => {
      const companyName = await getCompanyName();
      downloadEmployeeTemplatePDF({ emp: { ...employee, lastWorkingDay: separationContract?.expiryDate ?? undefined, separationType: separationContract?.type ?? undefined, companyName }, templateFileName: file, language });
    })();
  };

  const handleDownloadFullFinal = async () => {
    if (!employee || !separationContract) return;
    try {
      const s = await buildSettlementData();
      if (!s) return;
      const fmt = (n: number) => n.toLocaleString("en-PK", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
      
      const companyName = await getCompanyName();
      await downloadEmployeeTemplatePDF({
        emp: {
          ...employee,
          lastWorkingDay: separationContract.expiryDate ?? undefined,
          separationType: separationContract.type ?? undefined,
          settlementLastSalary: fmt(s.salaryEarned),
          settlementLeaveEncashment: fmt(s.leaveEncashment),
          settlementGratuity: fmt(s.gratuityAmount),
          settlementOvertime: fmt(s.overtimeAmount),
          settlementLoanDeduction: fmt(s.loanDeduction),
          settlementOtherDeduction: fmt(s.lateEarlyDeduction),
          settlementNetPayable: fmt(s.totalPayable),
          companyName,
        },
        templateFileName: "final-settlement-letter",
        language: "urdu"
      });
      
      await downloadEmployeeTemplatePDF({
        emp: {
          ...employee,
          lastWorkingDay: separationContract.expiryDate ?? undefined,
          separationType: separationContract.type ?? undefined,
          settlementLastSalary: fmt(s.salaryEarned),
          settlementLeaveEncashment: fmt(s.leaveEncashment),
          settlementGratuity: fmt(s.gratuityAmount),
          settlementOvertime: fmt(s.overtimeAmount),
          settlementLoanDeduction: fmt(s.loanDeduction),
          settlementOtherDeduction: fmt(s.lateEarlyDeduction),
          settlementNetPayable: fmt(s.totalPayable),
          companyName,
        },
        templateFileName: "final-settlement-letter",
        language: "english"
      });

      // Also trigger the detailed breakdown
      await downloadFullFinalSettlementPDF({
        employee: {
          employeeId: employee.employeeId,
          firstName: employee.firstName,
          lastName: employee.lastName,
          designation: employee.designation,
          department: employee.department,
          joiningDate: employee.joiningDate,
          basicSalary: employee.basicSalary,
        },
        leavingDate: separationContract.expiryDate || new Date(),
        workDays: s.workDays,
        overtimeHrs: s.overtimeHrs,
        overtimeAmount: s.overtimeAmount,
        gratuityYears: s.gratuityYears,
        gratuityAmount: s.gratuityAmount,
        noticePeriodDays: 0,
        noticePeriodAmount: 0,
        canteen: 0,
        advance: 0,
        totalEarning: s.totalEarning,
        totalDeduction: s.loanDeduction + s.lateEarlyDeduction,
        totalPayable: s.totalPayable,
        salaryEarned: s.salaryEarned,
        alDays: s.leaveEncashmentDays,
        alAmount: s.leaveEncashment,
        paymentMode: "CASH",
        expectedPaidDate: new Date(),
      });
    } catch { alert("Failed to generate settlement PDFs."); }
  };

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || !employee) return;
    setIsUploadingImage(true);
    try {
      const form = new FormData();
      form.append("image", file);
      const res = await authFetch(`${API}/dash/employees/${employee.id}/profile-image`, { method: "POST", body: form });
      if (res.ok) await fetchEmployee();
    } catch { /* ignore */ } finally { setIsUploadingImage(false); }
  };

  const handleDeleteDoc = async (docId: string) => {
    if (!confirm("Delete this document?")) return;
    await authFetch(`${API}/dash/employees/${id}/documents/${docId}`, { method: "DELETE" });
    fetchEmployee();
  };

  const handleDownloadAppointmentLetter = async (language: "english" | "urdu") => {
    if (!employee) return;
    const companyName = await getCompanyName();
    await downloadEmployeeTemplatePDF({
      emp: {
        employeeId: employee.employeeId,
        firstName: employee.firstName,
        lastName: employee.lastName,
        cnic: employee.cnic,
        department: employee.department,
        designation: employee.designation,
        joiningDate: employee.joiningDate,
        contractType: employee.contractType,
        basicSalary: employee.basicSalary,
        email: employee.email,
        bankName: employee.bankName,
        accountNumber: employee.accountNumber,
        emergencyContact: employee.emergencyContact,
        emergencyContactPhone: employee.emergencyContactPhone,
        companyName,
      },
      templateFileName: "Appointment_Letter_Rpt.pdf",
      language,
    });
  };

  const handleDownloadInquiryLetter = async (language: "english" | "urdu") => {
    if (!employee) return;
    const companyName = await getCompanyName();
    await downloadEmploymentAppointmentFormPDF({
      companyName,
      language,
      employee: {
        employeeId: employee.employeeId,
        firstName: employee.firstName,
        lastName: employee.lastName,
        department: employee.department,
        designation: employee.designation,
      },
      applicantName: "Dost Muhammad",
      inquiryNumber: "66240",
      letterDate: new Date(),
    });
  };

  if (isLoading) return (
    <div className="flex items-center justify-center h-72">
      <p className="text-sm text-gray-400 animate-pulse">Loading profile…</p>
    </div>
  );

  if (!employee) return (
    <div className="flex flex-col items-center justify-center h-72 gap-3">
      <p className="text-gray-500 font-medium">Employee not found.</p>
      <button onClick={() => router.back()} className="text-sm text-brand-600 hover:underline">← Go back</button>
    </div>
  );

  const initials = `${employee.firstName.charAt(0)}${employee.lastName.charAt(0)}`.toUpperCase();
  const joinDate  = new Date(employee.joiningDate);
  const yearsOfService = ((Date.now() - joinDate.getTime()) / (1000 * 60 * 60 * 24 * 365)).toFixed(1);
  const presentDays = employee.attendances?.filter(a => a.status === "PRESENT" || a.status === "LATE").length ?? 0;
  const totalOT     = (employee.attendances?.reduce((s, a) => s + (a.overtimeHrs ?? 0), 0) ?? 0).toFixed(1);

  return (
    <div className="space-y-8 pb-10">

      {/* ── Breadcrumb ── */}
      <button
        onClick={() => router.push("/dash/employees")}
        className="inline-flex items-center gap-1.5 text-sm font-medium text-gray-400 hover:text-brand-600 transition-colors"
      >
        <ArrowLeft className="h-4 w-4" />
        Employee Directory
      </button>

      {/* ── Hero Card ── */}
      <motion.div
        initial={{ opacity: 0, y: 16 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.35 }}
        className="rounded-3xl bg-white shadow-sm border border-gray-100 overflow-hidden"
      >
        {/* Banner */}
        <div
          className="h-20 bg-gradient-to-br from-brand-600 via-brand-500 to-violet-500"
          style={{
            backgroundImage: "radial-gradient(circle, rgba(255,255,255,0.12) 1px, transparent 1px)",
            backgroundSize: "22px 22px",
          }}
        />

        <div className="px-8 pt-0 pb-8">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-6 -mt-10">

            {/* Avatar block */}
            <div className="flex items-center gap-5">
              <div className="relative flex-shrink-0">
                <div className="h-28 w-28 rounded-2xl ring-4 ring-white shadow-xl overflow-hidden bg-gradient-to-br from-brand-100 to-brand-200 flex items-center justify-center">
                  {employee.profileImage
                    ? <img src={employee.profileImage} alt={employee.firstName} className="h-full w-full object-cover" />
                    : <span className="text-4xl font-extrabold text-brand-500 tracking-tight">{initials}</span>
                  }
                </div>
                <button
                  onClick={() => imageInputRef.current?.click()}
                  disabled={isUploadingImage}
                  className="absolute -bottom-1.5 -right-1.5 h-9 w-9 rounded-full bg-brand-600 text-white flex items-center justify-center shadow-lg hover:bg-brand-700 transition-colors border-2 border-white"
                  title="Change photo"
                >
                  <Camera className="h-4 w-4" />
                </button>
                <input ref={imageInputRef} type="file" accept="image/*" className="hidden" onChange={handleImageUpload} />
              </div>

              {/* Name & role */}
              <div>
                <h1 className="text-2xl font-extrabold text-gray-900 leading-tight">
                  {employee.firstName} {employee.lastName}
                </h1>
                <p className="text-sm text-gray-500 mt-0.5 font-medium">
                  {employee.designation}
                  <span className="mx-2 text-gray-300">·</span>
                  {employee.department}
                </p>
                <div className="flex items-center gap-2 mt-2">
                  <span className="text-xs font-mono text-gray-400 bg-gray-100 px-2 py-0.5 rounded-md">
                    #{employee.employeeId}
                  </span>
                  <span className={cn("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-bold ring-1 ring-inset", CONTRACT_STYLE[employee.contractType] ?? "bg-gray-50 text-gray-600 ring-gray-400/20")}>
                    {employee.contractType}
                  </span>
                  {separationContract && (
                    <span className={cn(
                      "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-bold ring-1 ring-inset",
                      separationContract.type === "Resigned"
                        ? "bg-amber-50 text-amber-700 ring-amber-600/20"
                        : "bg-red-50 text-red-700 ring-red-600/20"
                    )}>
                      {separationContract.type === "Resigned" ? "Resigned" : "Terminated"}
                    </span>
                  )}
                </div>
              </div>
            </div>

            {/* Stat chips */}
            <div className="flex gap-3">
              {[
                { label: "Years", value: yearsOfService + "y", color: "text-brand-600", bg: "bg-brand-50" },
                { label: "Present", value: String(presentDays), color: "text-emerald-600", bg: "bg-emerald-50" },
                { label: "OT Hrs", value: totalOT + "h", color: "text-amber-600", bg: "bg-amber-50" },
              ].map(s => (
                <div key={s.label} className={cn("flex flex-col items-center justify-center rounded-2xl px-5 py-3 min-w-[72px]", s.bg)}>
                  <span className={cn("text-xl font-extrabold leading-none", s.color)}>{s.value}</span>
                  <span className="text-xs text-gray-500 mt-1 font-medium">{s.label}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </motion.div>

      {/* ── Info Grid ── */}
      <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.05 }}
        className="rounded-2xl bg-white shadow-sm border border-gray-100 overflow-hidden"
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
          <div className="flex items-center gap-2">
            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-50 text-brand-600">
              <User className="h-4 w-4" />
            </div>
            <h2 className="text-sm font-bold text-gray-900">Employee Information</h2>
          </div>
          {!editMode ? (
            <button onClick={startEdit}
              className="inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold text-gray-600 bg-gray-50 hover:bg-gray-100 border border-gray-200 transition-colors"
            >
              <Pencil className="h-3.5 w-3.5" /> Edit
            </button>
          ) : (
            <div className="flex items-center gap-2">
              <button onClick={() => setEditMode(false)} disabled={saving}
                className="inline-flex items-center gap-1 rounded-lg px-3 py-1.5 text-xs font-semibold text-gray-500 bg-white hover:bg-gray-50 border border-gray-200 transition-colors"
              >
                <X className="h-3.5 w-3.5" /> Cancel
              </button>
              <button onClick={handleSaveEdit} disabled={saving}
                className="inline-flex items-center gap-1 rounded-lg px-3 py-1.5 text-xs font-semibold text-white bg-brand-600 hover:bg-brand-700 transition-colors disabled:opacity-50"
              >
                <Check className="h-3.5 w-3.5" /> {saving ? "Saving…" : "Save"}
              </button>
            </div>
          )}
        </div>

        {/* Fields */}
        <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-5">
          {/* helper */}
          {(() => {
            const ef = (label: string, key: keyof Employee, type: "text"|"email"|"number"|"date" = "text") => (
              <div key={key}>
                <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">{label}</p>
                {editMode ? (
                  <input
                    type={type}
                    value={String(editForm[key] ?? "")}
                    onChange={e => setEditForm(f => ({ ...f, [key]: type === "number" ? Number(e.target.value) : e.target.value }))}
                    className="w-full rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-brand-600/30"
                  />
                ) : (
                  <p className={cn("text-sm font-medium", !employee[key] ? "text-gray-400 italic" : "text-gray-900")}>
                    {type === "date" && employee[key]
                      ? new Date(employee[key] as string).toLocaleDateString("en-PK", { day: "2-digit", month: "short", year: "numeric" })
                      : String(employee[key] || "Not provided")}
                  </p>
                )}
              </div>
            );
            const sel = (label: string, key: keyof Employee, options: string[]) => (
              <div key={key}>
                <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">{label}</p>
                {editMode ? (
                  <select
                    value={String(editForm[key] ?? "")}
                    onChange={e => setEditForm(f => ({ ...f, [key]: e.target.value }))}
                    className="w-full rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-brand-600/30"
                  >
                    {options.map(o => <option key={o} value={o}>{o}</option>)}
                  </select>
                ) : (
                  <p className="text-sm font-medium text-gray-900">{String(employee[key] || "—")}</p>
                )}
              </div>
            );
            return (
              <>
                {ef("First Name",     "firstName")}
                {ef("Last Name",      "lastName")}
                {ef("CNIC",           "cnic")}
                {ef("Email",          "email", "email")}
                {ef("Joining Date",   "joiningDate", "date")}
                {ef("Date of Birth",  "dateOfBirth", "date")}
                {/* Department combobox */}
                <div ref={deptRef}>
                  <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">Department</p>
                  {editMode ? (
                    <div className="relative">
                      <input
                        type="text"
                        value={String(editForm.department ?? "")}
                        onChange={e => { setEditForm(f => ({ ...f, department: e.target.value })); setDeptOpen(true); }}
                        onFocus={() => setDeptOpen(true)}
                        placeholder="Select or type new..."
                        className="w-full rounded-lg border border-gray-200 px-3 py-1.5 pr-8 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-brand-600/30"
                      />
                      <button type="button" onClick={() => setDeptOpen(o => !o)} tabIndex={-1} className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400">
                        <ChevronDown className="h-3.5 w-3.5" />
                      </button>
                      {deptOpen && (
                        <div className="absolute z-50 mt-1 w-full rounded-lg bg-white shadow-lg ring-1 ring-gray-200 max-h-40 overflow-y-auto">
                          {[...new Set([...settingsDepts, ...(editForm.department && !settingsDepts.includes(String(editForm.department)) ? [String(editForm.department)] : [])])]
                            .filter(d => d.toLowerCase().includes(String(editForm.department ?? "").toLowerCase()))
                            .map(d => (
                              <button key={d} type="button"
                                onMouseDown={() => { setEditForm(f => ({ ...f, department: d })); setDeptOpen(false); }}
                                className={`w-full text-left px-3 py-2 text-sm hover:bg-brand-50 hover:text-brand-700 ${editForm.department === d ? "bg-brand-50 text-brand-700 font-medium" : "text-gray-700"}`}
                              >{d}</button>
                            ))}
                          {String(editForm.department ?? "").trim() && !settingsDepts.map(d => d.toLowerCase()).includes(String(editForm.department ?? "").trim().toLowerCase()) && (
                            <button type="button"
                              onMouseDown={() => {
                                const val = String(editForm.department ?? "").trim();
                                const updated = [...settingsDepts, val];
                                setSettingsDepts(updated);
                                addToSettings("departments", updated);
                                setDeptOpen(false);
                              }}
                              className="w-full text-left px-3 py-2 text-sm text-brand-600 font-semibold hover:bg-brand-50 border-t border-gray-100"
                            >+ Add &ldquo;{String(editForm.department ?? "").trim()}&rdquo; to departments</button>
                          )}
                        </div>
                      )}
                    </div>
                  ) : (
                    <p className={cn("text-sm font-medium", !employee.department ? "text-gray-400 italic" : "text-gray-900")}>{employee.department || "Not provided"}</p>
                  )}
                </div>
                {/* Designation combobox */}
                <div ref={desigRef}>
                  <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">Designation</p>
                  {editMode ? (
                    <div className="relative">
                      <input
                        type="text"
                        value={String(editForm.designation ?? "")}
                        onChange={e => { setEditForm(f => ({ ...f, designation: e.target.value })); setDesigOpen(true); }}
                        onFocus={() => setDesigOpen(true)}
                        placeholder="Select or type new..."
                        className="w-full rounded-lg border border-gray-200 px-3 py-1.5 pr-8 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-brand-600/30"
                      />
                      <button type="button" onClick={() => setDesigOpen(o => !o)} tabIndex={-1} className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400">
                        <ChevronDown className="h-3.5 w-3.5" />
                      </button>
                      {desigOpen && (
                        <div className="absolute z-50 mt-1 w-full rounded-lg bg-white shadow-lg ring-1 ring-gray-200 max-h-40 overflow-y-auto">
                          {[...new Set([...settingsDesigs, ...(editForm.designation && !settingsDesigs.includes(String(editForm.designation)) ? [String(editForm.designation)] : [])])]
                            .filter(d => d.toLowerCase().includes(String(editForm.designation ?? "").toLowerCase()))
                            .map(d => (
                              <button key={d} type="button"
                                onMouseDown={() => { setEditForm(f => ({ ...f, designation: d })); setDesigOpen(false); }}
                                className={`w-full text-left px-3 py-2 text-sm hover:bg-brand-50 hover:text-brand-700 ${editForm.designation === d ? "bg-brand-50 text-brand-700 font-medium" : "text-gray-700"}`}
                              >{d}</button>
                            ))}
                          {String(editForm.designation ?? "").trim() && !settingsDesigs.map(d => d.toLowerCase()).includes(String(editForm.designation ?? "").trim().toLowerCase()) && (
                            <button type="button"
                              onMouseDown={() => {
                                const val = String(editForm.designation ?? "").trim();
                                const updated = [...settingsDesigs, val];
                                setSettingsDesigs(updated);
                                addToSettings("designations", updated);
                                setDesigOpen(false);
                              }}
                              className="w-full text-left px-3 py-2 text-sm text-brand-600 font-semibold hover:bg-brand-50 border-t border-gray-100"
                            >+ Add &ldquo;{String(editForm.designation ?? "").trim()}&rdquo; to designations</button>
                          )}
                        </div>
                      )}
                    </div>
                  ) : (
                    <p className={cn("text-sm font-medium", !employee.designation ? "text-gray-400 italic" : "text-gray-900")}>{employee.designation || "Not provided"}</p>
                  )}
                </div>
                {sel("Contract Type", "contractType", ["PERMANENT","CONTRACT","PROBATION","INTERN"])}
                {ef("Basic Salary",   "basicSalary", "number")}
                {ef("Bank Name",      "bankName")}
                {ef("Account No.",    "accountNumber")}
                {ef("EOBI No.",       "eobiNo")}
                {ef("PESSI No.",      "pessiNo")}
                {ef("Emergency Contact",       "emergencyContact")}
                {ef("Emergency Contact Phone", "emergencyContactPhone")}
              </>
            );
          })()}
        </div>
      </motion.div>

      {/* ── Payroll History ── */}
      {employee.payrolls && employee.payrolls.length > 0 && (
        <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.25 }}
          className="rounded-2xl bg-white shadow-sm border border-gray-100 overflow-hidden"
        >
          <div className="flex items-center gap-2 px-6 py-5 border-b border-gray-100">
            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-50 text-brand-600">
              <Clock className="h-4 w-4" />
            </div>
            <h2 className="text-sm font-bold text-gray-900">Payroll History</h2>
            <span className="ml-auto text-xs text-gray-400">Last {Math.min(employee.payrolls.length, 6)} months</span>
          </div>
          <div className="overflow-x-auto">
            <table className="min-w-full">
              <thead>
                <tr className="bg-gray-50">
                  <th className="py-3 pl-6 pr-3 text-left text-xs font-bold text-gray-400 uppercase tracking-wider">Period</th>
                  <th className="px-3 py-3 text-left text-xs font-bold text-gray-400 uppercase tracking-wider">Net Salary</th>
                  <th className="px-6 py-3 text-right text-xs font-bold text-gray-400 uppercase tracking-wider">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {employee.payrolls.slice(0, 6).map((p) => (
                  <tr key={p.id} className="hover:bg-gray-50/70 transition-colors">
                    <td className="py-4 pl-6 pr-3 text-sm font-medium text-gray-700">{MONTHS[p.month]} {p.year}</td>
                    <td className="px-3 py-4 text-sm font-bold text-brand-600">
                      Rs. {p.netSalary.toLocaleString("en-PK", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                    </td>
                    <td className="px-6 py-4 text-right">
                      <span className={cn("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold ring-1 ring-inset",
                        PAYROLL_STYLE[p.status] ?? PAYROLL_STYLE.DRAFT
                      )}>
                        {p.status.replace(/_/g, " ")}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </motion.div>
      )}

      {/* ── Salary Increments ── */}
      <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.28 }}
        className="rounded-2xl bg-white shadow-sm border border-gray-100 overflow-hidden"
      >
        <div className="flex items-center gap-2 px-6 py-5 border-b border-gray-100">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-emerald-50 text-emerald-600">
            <Banknote className="h-4 w-4" />
          </div>
          <h2 className="text-sm font-bold text-gray-900">Salary Increments</h2>
          <span className="ml-auto text-xs text-gray-400">{increments.length} year(s) of increments</span>
          {increments.length > 0 && (
            <div className="flex items-center gap-1.5 ml-4">
              <button
                onClick={() => downloadIncrementHistoryPDF(employee, increments, "english")}
                className="inline-flex items-center gap-1 rounded-lg px-2.5 py-1.5 text-xs font-semibold text-white bg-brand-600 hover:bg-brand-700 transition-colors"
              >
                <Download className="h-3 w-3" /> EN
              </button>
              <button
                onClick={() => downloadIncrementHistoryPDF(employee, increments, "urdu")}
                className="inline-flex items-center gap-1 rounded-lg px-2.5 py-1.5 text-xs font-semibold text-brand-700 bg-brand-50 hover:bg-brand-100 transition-colors border border-brand-100"
              >
                <Download className="h-3 w-3" /> UR
              </button>
            </div>
          )}
        </div>
        <div className="overflow-x-auto">
          {increments.length > 0 ? (
            <>
              <table className="min-w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="py-3 pl-6 pr-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Year</th>
                    <th className="px-3 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Previous Salary</th>
                    <th className="px-3 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Increment %</th>
                    <th className="px-3 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Increment Amount</th>
                    <th className="py-3 pl-3 pr-6 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">New Salary</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-50">
                  {increments
                    .slice((incrementPage - 1) * incrementsPerPage, incrementPage * incrementsPerPage)
                    .map((inc) => (
                    <tr key={inc.id} className="hover:bg-gray-50/70 transition-colors">
                      <td className="py-4 pl-6 pr-3 text-sm font-medium text-gray-700">{inc.year}</td>
                      <td className="px-3 py-4 text-sm text-gray-600">PKR {inc.previousSalary.toLocaleString()}</td>
                      <td className="px-3 py-4 text-sm text-emerald-600 font-medium">{(inc.incrementRate * 100).toFixed(0)}%</td>
                      <td className="px-3 py-4 text-sm text-emerald-600">+PKR {inc.incrementAmount.toLocaleString()}</td>
                      <td className="py-4 pl-3 pr-6 text-sm font-bold text-gray-900">PKR {inc.newSalary.toLocaleString()}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {/* Pagination */}
              {increments.length > incrementsPerPage && (
                <div className="flex items-center justify-between px-6 py-4 border-t border-gray-100">
                  <p className="text-xs text-black">
                    Showing {(incrementPage - 1) * incrementsPerPage + 1} - {Math.min(incrementPage * incrementsPerPage, increments.length)} of {increments.length} years
                  </p>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => setIncrementPage(p => Math.max(1, p - 1))}
                      disabled={incrementPage === 1}
                      className="px-3 py-1.5 text-xs font-medium text-black rounded-lg border border-gray-200 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
                    >
                      Previous
                    </button>
                    <span className="text-xs text-black font-medium">
                      Page {incrementPage} of {Math.ceil(increments.length / incrementsPerPage)}
                    </span>
                    <button
                      onClick={() => setIncrementPage(p => Math.min(Math.ceil(increments.length / incrementsPerPage), p + 1))}
                      disabled={incrementPage >= Math.ceil(increments.length / incrementsPerPage)}
                      className="px-3 py-1.5 text-xs font-medium text-black rounded-lg border border-gray-200 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
                    >
                      Next
                    </button>
                  </div>
                </div>
              )}
            </>
          ) : (
            <div className="px-6 py-8 text-center">
              <p className="text-sm text-gray-500">No increments yet. Employee has less than 1 year of service.</p>
              <p className="text-xs text-gray-400 mt-1">10% annual increments start after completing 1 year.</p>
            </div>
          )}
        </div>
      </motion.div>

      {/* ── Documents & Letters ── */}
      <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.3 }}
        className="rounded-2xl bg-white shadow-sm border border-gray-100 overflow-hidden"
      >
        <div className="flex items-center gap-2 px-6 py-5 border-b border-gray-100">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-50 text-brand-600">
            <FileText className="h-4 w-4" />
          </div>
          <h2 className="text-sm font-bold text-gray-900">Documents & Letters</h2>
          <span className="ml-2 text-xs text-gray-400">Generate and download official HR documents</span>
        </div>
        <div className="p-6 grid grid-cols-1 sm:grid-cols-2 gap-3">
          {[
            { label: "Appointment Letter",          file: "appointment-letter",         color: "brand" },
            { label: "Confirmation Letter",         file: "confirmation-letter",        color: "brand" },
            { label: "Employee Bio Data Form",      file: "employee-bio-data-form",     color: "brand" },
            { label: "Hygiene Card",                file: "hygiene-card",               color: "brand" },
            { label: "Increment Letter",            file: "increment-letter",           color: "emerald" },
            { label: "Medical Fitness Certificate", file: "medical-fitness-certificate",color: "brand" },
            { label: "Orientation Checklist",       file: "orientation-checklist",      color: "brand" },
            { label: "Personal Profile Checklist",  file: "personal-profile-checklist", color: "brand" },
            { label: "Pre Training Form",           file: "pre-training-form",          color: "brand" },
            { label: "Promotion Letter",            file: "promotion-letter",           color: "emerald" },
            { label: "Employee Quit Letter",        file: "employee-quit-letter",       color: "amber" },
            { label: "Final Settlement Letter",     file: "final-settlement-letter",    color: "amber" },
          ].map((doc) => (
            <div key={doc.file} className="flex items-center justify-between rounded-xl border border-gray-100 bg-gray-50/60 px-4 py-3">
              <div className="flex items-center gap-3">
                <div className={`h-8 w-8 rounded-lg flex items-center justify-center flex-shrink-0 ${
                  doc.color === "emerald" ? "bg-emerald-50 text-emerald-600" :
                  doc.color === "amber"   ? "bg-amber-50 text-amber-600" :
                  "bg-brand-50 text-brand-600"
                }`}>
                  <FileText className="h-4 w-4" />
                </div>
                <span className="text-sm font-medium text-gray-800">{doc.label}</span>
              </div>
              <div className="flex items-center gap-1.5 ml-4 flex-shrink-0">
                <button
                  onClick={() => handleDownloadDoc(doc.file, "english")}
                  className="inline-flex items-center gap-1 rounded-lg px-2.5 py-1.5 text-xs font-semibold text-white bg-brand-600 hover:bg-brand-700 transition-colors"
                >
                  <Download className="h-3 w-3" /> EN
                </button>
                <button
                  onClick={() => handleDownloadDoc(doc.file, "urdu")}
                  className="inline-flex items-center gap-1 rounded-lg px-2.5 py-1.5 text-xs font-semibold text-brand-700 bg-brand-50 hover:bg-brand-100 transition-colors border border-brand-100"
                >
                  <Download className="h-3 w-3" /> UR
                </button>
              </div>
            </div>
          ))}
        </div>
      </motion.div>

      {/* ── Separation ── */}
      <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.35 }}
        className="rounded-2xl bg-white shadow-sm border border-gray-100 overflow-hidden"
      >
        <div className="flex items-center gap-2 px-6 py-5 border-b border-gray-100">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-50 text-brand-600">
            <LogOut className="h-4 w-4" />
          </div>
          <h2 className="text-sm font-bold text-gray-900">Employee Separation</h2>
          {separationContract && (
            <span className="ml-2 inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold ring-1 ring-inset bg-gray-100 text-gray-600 ring-gray-400/30">
              {separationContract.type === "Resigned" ? "Resigned" : "Terminated"}
            </span>
          )}
        </div>
        <div className="px-6 py-5 space-y-4">
          {separationContract ? (
            <div className="rounded-xl bg-gray-50 border border-gray-100 p-4 flex items-center justify-between">
              <div>
                <p className="text-sm font-semibold text-gray-800">
                  {separationContract.type === "Resigned" ? "Resigned" : "Terminated by Company"}
                </p>
                <p className="text-xs text-gray-500 mt-0.5">
                  Effective: {separationContract.expiryDate
                    ? new Date(separationContract.expiryDate).toLocaleDateString("en-PK", { day: "2-digit", month: "short", year: "numeric" })
                    : "—"}
                </p>
              </div>
              <div className="flex gap-2">
                <button
                  onClick={handleDownloadFullFinal}
                  className="inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold text-brand-600 bg-brand-50 hover:bg-brand-100 border border-brand-100 transition-colors"
                >
                  <FileText className="h-3.5 w-3.5" /> Full Settlement
                </button>
                <button
                  onClick={handleCancelSeparation}
                  disabled={separating}
                  className="inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold text-gray-600 bg-white hover:bg-red-50 hover:text-red-600 border border-gray-200 transition-colors disabled:opacity-50"
                >
                  <XCircle className="h-3.5 w-3.5" /> Remove Record
                </button>
              </div>
            </div>
          ) : (
            <div className="space-y-3">
              <div>
                <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1.5">Separation Date</label>
                <input
                  type="date"
                  value={separationDate}
                  onChange={(e) => setSeparationDate(e.target.value)}
                  className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-brand-600/40"
                />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <button
                  onClick={() => handleSeparation("Resigned")}
                  disabled={separating}
                  className="inline-flex items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-semibold text-gray-700 bg-white hover:bg-gray-50 border border-gray-200 transition-colors disabled:opacity-50"
                >
                  <LogOut className="h-4 w-4" />
                  {separating ? "Saving..." : "Mark as Resigned"}
                </button>
                <button
                  onClick={() => handleSeparation("Terminated")}
                  disabled={separating}
                  className="inline-flex items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-semibold text-white bg-brand-600 hover:bg-brand-700 transition-colors disabled:opacity-50"
                >
                  <XCircle className="h-4 w-4" />
                  {separating ? "Saving..." : "Terminate Employee"}
                </button>
              </div>
            </div>
          )}
        </div>
      </motion.div>

    </div>
  );
}




