"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  AlertCircle,
  ArrowRight,
  Briefcase,
  Building2,
  Calendar,
  CalendarDays,
  Check,
  CheckCircle2,
  Clock,
  DollarSign,
  FileText,
  HeartPulse,
  Layers,
  Lock,
  Mail,
  Phone,
  Plus,
  Search,
  ShieldAlert,
  ShieldCheck,
  Trash2,
  UserCheck,
  Users,
  X,
  XCircle,
  ChevronRight,
  Network,
  Landmark,
  RefreshCw,
} from "lucide-react";

type HrisSetting = {
  enabled: boolean;
  selfServicePortal: boolean;
  ptoTracking: boolean;
  benefitsAdministration: boolean;
  complianceMonitoring: boolean;
  orgChart: boolean;
  canManage: boolean;
  currentUser: { id: number; name: string; role: string } | null;
};

type MunisSetting = {
  enabled: boolean;
  mode: "mock" | "live";
  includeCompensation: boolean;
  includeEmergencyContact: boolean;
  includeOrganization: boolean;
};

interface Employee {
  id: number;
  employeeNumber: string;
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  departmentId: number | null;
  department: { id: number; name: string } | null;
  jobTitle: string;
  status: string;
  employmentType: string;
  hireDate: string;
  salary: number;
  ptoBalanceDays: string;
  benefitsCount: number;
  monthlyBenefitsCost: number;
  timeOffRequestsCount: number;
  timeOffPendingCount: number;
  emergencyContactName?: string;
  emergencyContactPhone?: string;
  onboardingCase?: { id: number; targetStartDate?: string | null } | null;
}

interface TimeOffRequest {
  id: number;
  employeeId: number;
  type: string;
  startDate: string;
  endDate: string;
  daysRequested: string;
  status: string;
  notes: string;
  employee: { id: number; firstName: string; lastName: string; jobTitle: string; department: { name: string } | null } | null;
  approver: { id: number; name: string } | null;
}

interface BenefitEnrollment {
  id: number;
  employeeId: number;
  planName: string;
  planType: string;
  enrollmentStatus: string;
  employerContributionMonthly: number;
  employeeContributionMonthly: number;
  employee: { id: number; firstName: string; lastName: string; jobTitle: string; department: { name: string } | null } | null;
}

export default function HrisHubPage() {
  const router = useRouter();
  const [hrisSetting, setHrisSetting] = useState<HrisSetting | null>(null);
  const [munisSetting, setMunisSetting] = useState<MunisSetting | null>(null);
  const [pushingMunis, setPushingMunis] = useState(false);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<"directory" | "time_off" | "benefits" | "org">("directory");

  // Data lists
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [timeOffRequests, setTimeOffRequests] = useState<TimeOffRequest[]>([]);
  const [benefits, setBenefits] = useState<BenefitEnrollment[]>([]);
  const [departments, setDepartments] = useState<any[]>([]);

  // Filters
  const [search, setSearch] = useState("");
  const [deptFilter, setDeptFilter] = useState("all");
  const [statusFilter, setStatusFilter] = useState("all");

  // Modals
  const [showAddEmpModal, setShowAddEmpModal] = useState(false);
  const [showTimeOffModal, setShowTimeOffModal] = useState(false);
  const [showBenefitModal, setShowBenefitModal] = useState(false);
  const [selectedEmpDetail, setSelectedEmpDetail] = useState<Employee | null>(null);
  const [saving, setSaving] = useState(false);
  const [notice, setNotice] = useState("");
  const [error, setError] = useState("");

  // Form states
  const [newEmp, setNewEmp] = useState({
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
    departmentId: "1",
    jobTitle: "",
    employmentType: "full_time",
    hireDate: new Date().toISOString().slice(0, 10),
    salary: 120000,
    ptoBalanceDays: "15.00",
  });

  const [newTimeOff, setNewTimeOff] = useState({
    employeeId: "",
    type: "vacation",
    startDate: new Date().toISOString().slice(0, 10),
    endDate: new Date().toISOString().slice(0, 10),
    daysRequested: "1.00",
    notes: "",
  });

  const [newBenefit, setNewBenefit] = useState({
    employeeId: "",
    planName: "Standard Medical + Dental PPO",
    planType: "health",
    employerContributionMonthly: 600,
    employeeContributionMonthly: 120,
  });

  async function loadAllData() {
    setLoading(true);
    try {
      const [settingRes, empsRes, timeOffRes, benefitsRes, deptsRes, munisRes] = await Promise.all([
        fetch("/api/settings/hris"),
        fetch("/api/hris/employees"),
        fetch("/api/hris/time-off"),
        fetch("/api/hris/benefits"),
        fetch("/api/departments"),
        fetch("/api/settings/munis"),
      ]);
      const [settingData, empsData, timeOffData, benefitsData, deptsData, munisData] = await Promise.all([
        settingRes.json(),
        empsRes.json(),
        timeOffRes.json(),
        benefitsRes.json(),
        deptsRes.json(),
        munisRes.json(),
      ]);

      setHrisSetting(settingData);
      if (munisRes.ok) setMunisSetting(munisData);
      if (Array.isArray(empsData)) {
        setEmployees(empsData);
        if (empsData.length > 0 && !newTimeOff.employeeId) {
          setNewTimeOff((prev) => ({ ...prev, employeeId: String(empsData[0].id) }));
          setNewBenefit((prev) => ({ ...prev, employeeId: String(empsData[0].id) }));
        }
      }
      if (Array.isArray(timeOffData)) setTimeOffRequests(timeOffData);
      if (Array.isArray(benefitsData)) setBenefits(benefitsData);
      if (Array.isArray(deptsData)) {
        setDepartments(deptsData);
        if (deptsData.length > 0 && !newEmp.departmentId) {
          setNewEmp((prev) => ({ ...prev, departmentId: String(deptsData[0].id) }));
        }
      }
    } catch (err) {
      console.error("Failed to load HRIS data:", err);
      setError("Unable to load HRIS workspace.");
    } finally {
      setLoading(false);
    }
  }

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

  async function pushWorkforceToMunis() {
    if (!confirm(`Push ${employees.filter((e) => e.status === "active").length} active employee records to Tyler Munis?`)) return;
    setPushingMunis(true);
    setError("");
    try {
      const res = await fetch("/api/hris/munis/push", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ scope: "workforce" }),
      });
      const data = await res.json();
      if (res.ok) {
        setNotice(`Workforce push complete! ${data.run?.recordsPushed || employees.length} employee record(s) sent to Tyler Munis. Reference: ${data.run?.externalReference || "created"}.`);
      } else {
        setError(data.error || "Failed to push workforce to Munis.");
      }
    } catch {
      setError("Network error while pushing workforce to Munis.");
    } finally {
      setPushingMunis(false);
    }
  }

  async function toggleOptIn(enabled: boolean) {
    if (!hrisSetting) return;
    setSaving(true);
    try {
      const res = await fetch("/api/settings/hris", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...hrisSetting, enabled }),
      });
      const data = await res.json();
      if (res.ok) {
        setHrisSetting(data);
        setNotice(enabled ? "HRIS Module activated successfully!" : "HRIS Module disabled.");
        window.dispatchEvent(new Event("hris_setting_updated"));
        await loadAllData();
      } else {
        setError(data.error || "Unable to change opt-in status.");
      }
    } catch {
      setError("Network error");
    } finally {
      setSaving(false);
    }
  }

  async function handleAddEmployee(e: React.FormEvent) {
    e.preventDefault();
    if (!newEmp.firstName || !newEmp.lastName || !newEmp.email || !newEmp.jobTitle) {
      setError("First name, last name, email, and job title are required.");
      return;
    }
    setSaving(true);
    setError("");
    try {
      const res = await fetch("/api/hris/employees", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newEmp),
      });
      const data = await res.json();
      if (res.ok) {
        setNotice(`Employee ${data.firstName} ${data.lastName} (${data.employeeNumber}) added to HRIS!`);
        setShowAddEmpModal(false);
        await loadAllData();
      } else {
        setError(data.error || "Failed to create employee.");
      }
    } catch {
      setError("Network error.");
    } finally {
      setSaving(false);
    }
  }

  async function handleTimeOffReview(reqId: number, status: "approved" | "rejected") {
    try {
      const res = await fetch(`/api/hris/time-off/${reqId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status }),
      });
      const data = await res.json();
      if (res.ok) {
        setNotice(status === "approved" ? "Time off request approved and PTO balance deducted." : "Time off request rejected.");
        await loadAllData();
      } else if (data.autoDenied) {
        setError(data.staffingMessage || "Approval was automatically denied by the minimum staffing rule.");
        await loadAllData();
      } else {
        setError(data.error || "Failed to process time off request.");
      }
    } catch {
      setError("Failed to process time off request.");
    }
  }

  async function handleCreateTimeOff(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setError("");
    try {
      const res = await fetch("/api/hris/time-off", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newTimeOff),
      });
      const data = await res.json();
      if (res.ok) {
        if (data.autoDenied) {
          setError(data.staffingMessage || "Time off was automatically denied because it would reduce staffing below the required minimum.");
        } else {
          setNotice("Time off request submitted and passed minimum staffing validation!");
        }
        setShowTimeOffModal(false);
        await loadAllData();
      } else {
        setError(data.error || "Submission failed.");
      }
    } catch {
      setError("Network error.");
    } finally {
      setSaving(false);
    }
  }

  async function handleCreateBenefit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setError("");
    try {
      const res = await fetch("/api/hris/benefits", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newBenefit),
      });
      const data = await res.json();
      if (res.ok) {
        setNotice("Employee enrolled in benefit plan!");
        setShowBenefitModal(false);
        await loadAllData();
      } else {
        setError(data.error || "Enrollment failed.");
      }
    } catch {
      setError("Network error.");
    } finally {
      setSaving(false);
    }
  }

  const filteredEmployees = useMemo(() => {
    const query = search.toLowerCase();
    return employees.filter((emp) => {
      const name = `${emp.firstName} ${emp.lastName}`.toLowerCase();
      const matchesSearch = !query || name.includes(query) || emp.jobTitle.toLowerCase().includes(query) || emp.employeeNumber.toLowerCase().includes(query);
      const matchesDept = deptFilter === "all" || String(emp.departmentId) === deptFilter;
      const matchesStatus = statusFilter === "all" || emp.status === statusFilter;
      return matchesSearch && matchesDept && matchesStatus;
    });
  }, [employees, search, deptFilter, statusFilter]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-indigo-600" />
      </div>
    );
  }

  // If not opted in, show Opt-In Gate
  if (!hrisSetting?.enabled) {
    return (
      <div className="p-6 max-w-5xl mx-auto">
        <div className="bg-gradient-to-br from-indigo-900 via-slate-900 to-blue-950 text-white rounded-3xl p-8 md:p-12 shadow-2xl border border-indigo-500/30 overflow-hidden relative">
          <div className="max-w-3xl relative z-10 space-y-6">
            <div className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full bg-indigo-500/20 text-indigo-300 border border-indigo-400/30 text-xs font-bold uppercase tracking-wider">
              <span>🏢</span> Optional Suite Module
            </div>
            <h1 className="text-3xl md:text-5xl font-extrabold tracking-tight leading-tight">
              Human Resources Information System (HRIS)
            </h1>
            <p className="text-lg text-slate-300 leading-relaxed">
              Expand your recruitment and onboarding pipeline into permanent workforce management. The HRIS component unifies your active employee directory, paid time off (PTO) balance tracking, and company benefit enrollments right inside your workspace.
            </p>

            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 pt-2">
              <div className="p-4 rounded-2xl bg-white/5 border border-white/10 space-y-2">
                <Users className="w-6 h-6 text-indigo-400" />
                <h3 className="font-bold text-white text-base">Employee Directory</h3>
                <p className="text-xs text-slate-300">
                  Convert candidates seamlessly with EMP numbers, department alignment, and salary history.
                </p>
              </div>
              <div className="p-4 rounded-2xl bg-white/5 border border-white/10 space-y-2">
                <CalendarDays className="w-6 h-6 text-emerald-400" />
                <h3 className="font-bold text-white text-base">Time Off & Leave</h3>
                <p className="text-xs text-slate-300">
                  Manage vacation requests and track real-time PTO balance deductions upon approval.
                </p>
              </div>
              <div className="p-4 rounded-2xl bg-white/5 border border-white/10 space-y-2">
                <HeartPulse className="w-6 h-6 text-pink-400" />
                <h3 className="font-bold text-white text-base">Benefits Administration</h3>
                <p className="text-xs text-slate-300">
                  Track health, dental, and 401(k) employer vs. employee monthly contribution costs.
                </p>
              </div>
            </div>

            <div className="pt-6 border-t border-white/10 flex flex-wrap items-center justify-between gap-4">
              <div>
                {hrisSetting?.canManage ? (
                  <button
                    onClick={() => toggleOptIn(true)}
                    disabled={saving}
                    className="px-8 py-4 bg-indigo-500 hover:bg-indigo-600 text-white font-extrabold rounded-2xl shadow-lg shadow-indigo-600/40 transition-all flex items-center gap-2.5 text-base disabled:opacity-50"
                  >
                    <UserCheck className="w-5 h-5" />
                    <span>{saving ? "Enabling Suite..." : "Opt-In & Activate HRIS Module Now"}</span>
                  </button>
                ) : (
                  <div className="flex items-center gap-3 p-4 bg-amber-500/10 border border-amber-500/30 rounded-2xl text-amber-200">
                    <Lock className="w-5 h-5 shrink-0 text-amber-400" />
                    <span className="text-sm font-medium">
                      Opt-in required. Only Super Administrators can turn on the HRIS section for the organization.
                    </span>
                  </div>
                )}
              </div>
              <span className="text-xs text-slate-400">
                You can toggle this section anytime in <Link href="/settings" className="underline hover:text-white">Settings → HRIS Module</Link>.
              </span>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Active HRIS Suite Workspace
  const totalPayroll = employees.reduce((sum, e) => sum + (e.salary || 0), 0);
  const avgSalary = employees.length ? Math.round(totalPayroll / employees.length) : 0;
  const totalBenefitsCost = benefits.reduce((sum, b) => sum + (b.employerContributionMonthly || 0), 0);
  const pendingLeaveCount = timeOffRequests.filter((t) => t.status === "pending").length;

  return (
    <div className="p-6 max-w-7xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-2xl border border-gray-200 shadow-sm">
        <div>
          <div className="flex items-center gap-2.5">
            <span className="p-2 bg-indigo-100 text-indigo-700 rounded-xl">
              <UserCheck className="w-6 h-6" />
            </span>
            <div>
              <h1 className="text-2xl font-bold text-gray-900">HRIS Workforce Management</h1>
              <p className="text-sm text-gray-500">
                Manage permanent employees, PTO leave requests, and employer benefit enrollments
              </p>
            </div>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <Link
            href="/settings"
            className="px-4 py-2.5 bg-gray-50 border border-gray-200 text-gray-700 rounded-xl hover:bg-gray-100 transition-colors text-sm font-semibold"
          >
            Configure Module
          </Link>
          {hrisSetting?.orgChart && (
            <Link
              href="/hris/org-chart"
              className="px-4 py-2.5 bg-white border border-indigo-200 text-indigo-700 rounded-xl hover:bg-indigo-50 transition-colors text-sm font-bold flex items-center gap-2 shadow-sm"
            >
              <Network className="w-4 h-4" /> Org Chart
            </Link>
          )}
          {munisSetting?.enabled && (
            <button
              onClick={pushWorkforceToMunis}
              disabled={pushingMunis}
              className="px-4 py-2.5 bg-sky-600 hover:bg-sky-700 text-white rounded-xl transition-colors text-sm font-bold flex items-center gap-2 shadow-sm disabled:opacity-50"
              title={munisSetting.mode === "live" ? "Push all active HRIS employees to Tyler Munis" : "Run safe demo workforce push to Tyler Munis"}
            >
              <Landmark className="w-4 h-4" />
              {pushingMunis ? "Pushing to Munis..." : "Push Workforce to Munis"}
            </button>
          )}
          <button
            onClick={() => setShowAddEmpModal(true)}
            className="px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl transition-colors text-sm font-bold flex items-center gap-2 shadow-sm"
          >
            <Plus className="w-4 h-4" /> Add Employee
          </button>
        </div>
      </div>

      {notice && (
        <div className="p-4 bg-emerald-50 border border-emerald-200 rounded-xl text-sm font-bold text-emerald-800 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <CheckCircle2 className="w-5 h-5 text-emerald-600" />
            <span>{notice}</span>
          </div>
          <button onClick={() => setNotice("")} className="text-emerald-600 hover:text-emerald-800"><X className="w-4 h-4" /></button>
        </div>
      )}

      {error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-xl text-sm font-semibold text-red-700 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <AlertCircle className="w-5 h-5 text-red-600" />
            <span>{error}</span>
          </div>
          <button onClick={() => setError("")} className="text-red-600 hover:text-red-800"><X className="w-4 h-4" /></button>
        </div>
      )}

      {/* KPI Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-white rounded-2xl border border-gray-200 p-5 shadow-sm">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2.5 bg-indigo-50 text-indigo-600 rounded-xl"><Users className="w-5 h-5" /></div>
            <span className="text-sm font-semibold text-gray-500">Active Workforce</span>
          </div>
          <p className="text-3xl font-extrabold text-gray-900">{employees.filter((e) => e.status === "active").length}</p>
          <p className="text-xs text-gray-400 mt-1">Total {employees.length} employee records</p>
        </div>

        <div className="bg-white rounded-2xl border border-gray-200 p-5 shadow-sm">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2.5 bg-emerald-50 text-emerald-600 rounded-xl"><DollarSign className="w-5 h-5" /></div>
            <span className="text-sm font-semibold text-gray-500">Average Compensation</span>
          </div>
          <p className="text-3xl font-extrabold text-gray-900">${avgSalary.toLocaleString()}</p>
          <p className="text-xs text-gray-400 mt-1">Total annual payroll: ${(totalPayroll / 1000).toFixed(0)}k</p>
        </div>

        <div className="bg-white rounded-2xl border border-gray-200 p-5 shadow-sm">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2.5 bg-amber-50 text-amber-600 rounded-xl"><CalendarDays className="w-5 h-5" /></div>
            <span className="text-sm font-semibold text-gray-500">Time Off Requests</span>
          </div>
          <p className="text-3xl font-extrabold text-gray-900">{pendingLeaveCount}</p>
          <p className="text-xs text-amber-600 font-medium mt-1">Pending manager approval</p>
        </div>

        <div className="bg-white rounded-2xl border border-gray-200 p-5 shadow-sm">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2.5 bg-pink-50 text-pink-600 rounded-xl"><HeartPulse className="w-5 h-5" /></div>
            <span className="text-sm font-semibold text-gray-500">Monthly Benefits Budget</span>
          </div>
          <p className="text-3xl font-extrabold text-gray-900">${totalBenefitsCost.toLocaleString()}</p>
          <p className="text-xs text-gray-400 mt-1">{benefits.length} active employee enrollments</p>
        </div>
      </div>

      {/* Main Tabs */}
      <div className="flex flex-wrap items-center gap-2 border-b border-gray-200 bg-white p-1 rounded-2xl shadow-sm">
        {[
          { id: "directory", label: "Workforce Directory", icon: Users, count: employees.length },
          { id: "time_off", label: "Time Off & Leaves", icon: CalendarDays, count: pendingLeaveCount },
          { id: "benefits", label: "Benefits & Compensation", icon: HeartPulse, count: benefits.length },
          { id: "org", label: "Departments Overview", icon: Building2, count: departments.length },
        ].map((tab) => {
          const Icon = tab.icon;
          const isActive = activeTab === tab.id;
          return (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id as any)}
              className={`flex items-center gap-2.5 px-5 py-3 rounded-xl text-sm font-semibold transition-all ${
                isActive ? "bg-indigo-600 text-white shadow-sm" : "text-gray-600 hover:bg-gray-50"
              }`}
            >
              <Icon className="w-4 h-4" />
              <span>{tab.label}</span>
              <span className={`text-xs px-2 py-0.5 rounded-full font-bold ${isActive ? "bg-indigo-500 text-white" : "bg-gray-100 text-gray-500"}`}>
                {tab.count}
              </span>
            </button>
          );
        })}
      </div>

      {/* Tab 1: Workforce Directory */}
      {activeTab === "directory" && (
        <div className="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden">
          <div className="p-5 border-b border-gray-200 flex flex-wrap items-center justify-between gap-4">
            <div className="relative min-w-[280px] flex-1">
              <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                placeholder="Search by name, EMP number, or job title..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none"
              />
            </div>
            <div className="flex items-center gap-3">
              <select
                value={deptFilter}
                onChange={(e) => setDeptFilter(e.target.value)}
                className="px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none"
              >
                <option value="all">All Departments</option>
                {departments.map((d) => (
                  <option key={d.id} value={String(d.id)}>{d.name}</option>
                ))}
              </select>
              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                className="px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none"
              >
                <option value="all">All Statuses</option>
                <option value="active">Active</option>
                <option value="on_leave">On Leave</option>
                <option value="terminated">Terminated</option>
              </select>
            </div>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full text-left">
              <thead className="bg-gray-50 border-b border-gray-200 text-xs font-bold uppercase text-gray-500 tracking-wider">
                <tr>
                  <th className="px-6 py-4">Employee</th>
                  <th className="px-6 py-4">EMP #</th>
                  <th className="px-6 py-4">Department & Title</th>
                  <th className="px-6 py-4">Hire Date</th>
                  <th className="px-6 py-4">Salary</th>
                  <th className="px-6 py-4">PTO Balance</th>
                  <th className="px-6 py-4">Status</th>
                  <th className="px-6 py-4 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100 text-sm">
                {filteredEmployees.length === 0 ? (
                  <tr>
                    <td colSpan={8} className="text-center py-12 text-gray-400">
                      No employees match your filter criteria.
                    </td>
                  </tr>
                ) : (
                  filteredEmployees.map((emp) => (
                    <tr
                      key={emp.id}
                      onClick={() => router.push(`/hris/${emp.id}`)}
                      className="hover:bg-indigo-50/50 transition-colors cursor-pointer group"
                    >
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 rounded-full bg-indigo-100 text-indigo-700 font-bold flex items-center justify-center shrink-0 group-hover:bg-indigo-600 group-hover:text-white transition-colors">
                            {emp.firstName[0]}{emp.lastName[0]}
                          </div>
                          <div>
                            <p className="font-bold text-gray-900 group-hover:text-indigo-600 transition-colors flex items-center gap-1.5">
                              <span>{emp.firstName} {emp.lastName}</span>
                              <ChevronRight className="w-3.5 h-3.5 opacity-0 group-hover:opacity-100 text-indigo-600 transition-opacity" />
                            </p>
                            <p className="text-xs text-gray-500">{emp.email}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4 font-mono font-semibold text-gray-700">{emp.employeeNumber}</td>
                      <td className="px-6 py-4">
                        <p className="font-medium text-gray-900">{emp.jobTitle}</p>
                        <p className="text-xs text-gray-500">{emp.department?.name || "No Department"}</p>
                      </td>
                      <td className="px-6 py-4 text-gray-600">
                        {new Date(emp.hireDate + "T00:00:00").toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                      </td>
                      <td className="px-6 py-4 font-bold text-gray-900">
                        ${emp.salary.toLocaleString()}
                        <span className="text-xs font-normal text-gray-400">/yr</span>
                      </td>
                      <td className="px-6 py-4">
                        <span className="font-bold text-indigo-700">{emp.ptoBalanceDays}</span> days
                      </td>
                      <td className="px-6 py-4">
                        <span
                          className={`text-xs px-2.5 py-1 rounded-full font-bold uppercase ${
                            emp.status === "active"
                              ? "bg-emerald-100 text-emerald-800"
                              : emp.status === "on_leave"
                              ? "bg-amber-100 text-amber-800"
                              : "bg-red-100 text-red-800"
                          }`}
                        >
                          {emp.status.replace("_", " ")}
                        </span>
                      </td>
                      <td className="px-6 py-4 text-right">
                        <Link
                          href={`/hris/${emp.id}`}
                          onClick={(e) => e.stopPropagation()}
                          className="px-3.5 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold transition-colors inline-flex items-center gap-1 shadow-sm"
                        >
                          <span>Open Folder</span>
                          <ChevronRight className="w-3 h-3" />
                        </Link>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Tab 2: Time Off & Leaves */}
      {activeTab === "time_off" && (
        <div className="space-y-6">
          <div className="flex items-center justify-between bg-white p-5 rounded-2xl border border-gray-200 shadow-sm">
            <div>
              <h3 className="font-bold text-gray-900 text-lg">Employee Time Off & Leave Requests</h3>
              <p className="text-sm text-gray-500">Approving requests automatically deducts from the employee&apos;s PTO balance.</p>
            </div>
            <button
              onClick={() => setShowTimeOffModal(true)}
              className="px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-sm font-bold flex items-center gap-2 shadow-sm"
            >
              <Plus className="w-4 h-4" /> Submit Leave Request
            </button>
          </div>

          <div className="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden">
            <table className="w-full text-left">
              <thead className="bg-gray-50 border-b border-gray-200 text-xs font-bold uppercase text-gray-500 tracking-wider">
                <tr>
                  <th className="px-6 py-4">Employee</th>
                  <th className="px-6 py-4">Leave Type</th>
                  <th className="px-6 py-4">Dates</th>
                  <th className="px-6 py-4">Days</th>
                  <th className="px-6 py-4">Notes</th>
                  <th className="px-6 py-4">Status</th>
                  <th className="px-6 py-4 text-right">Manager Action</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100 text-sm">
                {timeOffRequests.length === 0 ? (
                  <tr>
                    <td colSpan={7} className="text-center py-12 text-gray-400">No time off requests submitted yet.</td>
                  </tr>
                ) : (
                  timeOffRequests.map((req) => (
                    <tr key={req.id} className="hover:bg-gray-50/80">
                      <td className="px-6 py-4 font-bold text-gray-900">
                        {req.employee ? `${req.employee.firstName} ${req.employee.lastName}` : "Employee"}
                        <p className="text-xs font-normal text-gray-500">{req.employee?.jobTitle}</p>
                      </td>
                      <td className="px-6 py-4 capitalize font-semibold text-gray-800">{req.type}</td>
                      <td className="px-6 py-4 text-gray-600">
                        {req.startDate} → {req.endDate}
                      </td>
                      <td className="px-6 py-4 font-bold text-indigo-700">{req.daysRequested} days</td>
                      <td className="px-6 py-4 text-xs text-gray-500 max-w-xs truncate">{req.notes || "No notes provided"}</td>
                      <td className="px-6 py-4">
                        <span
                          className={`text-xs px-2.5 py-1 rounded-full font-bold uppercase ${
                            req.status === "approved"
                              ? "bg-emerald-100 text-emerald-800"
                              : req.status === "rejected"
                              ? "bg-red-100 text-red-800"
                              : "bg-amber-100 text-amber-800"
                          }`}
                        >
                          {req.status}
                        </span>
                      </td>
                      <td className="px-6 py-4 text-right space-x-2">
                        {req.status === "pending" ? (
                          <>
                            <button
                              onClick={() => handleTimeOffReview(req.id, "approved")}
                              className="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-bold transition-colors"
                            >
                              Approve
                            </button>
                            <button
                              onClick={() => handleTimeOffReview(req.id, "rejected")}
                              className="px-3 py-1.5 bg-red-600 hover:bg-red-700 text-white rounded-lg text-xs font-bold transition-colors"
                            >
                              Reject
                            </button>
                          </>
                        ) : (
                          <span className="text-xs text-gray-400 font-medium">Reviewed by {req.approver?.name || "Manager"}</span>
                        )}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Tab 3: Benefits & Compensation */}
      {activeTab === "benefits" && (
        <div className="space-y-6">
          <div className="flex items-center justify-between bg-white p-5 rounded-2xl border border-gray-200 shadow-sm">
            <div>
              <h3 className="font-bold text-gray-900 text-lg">Employee Benefit Plans & Contributions</h3>
              <p className="text-sm text-gray-500">Track monthly employer contributions vs. employee deductions.</p>
            </div>
            <button
              onClick={() => setShowBenefitModal(true)}
              className="px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-sm font-bold flex items-center gap-2 shadow-sm"
            >
              <Plus className="w-4 h-4" /> Enroll Employee
            </button>
          </div>

          <div className="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden">
            <table className="w-full text-left">
              <thead className="bg-gray-50 border-b border-gray-200 text-xs font-bold uppercase text-gray-500 tracking-wider">
                <tr>
                  <th className="px-6 py-4">Employee</th>
                  <th className="px-6 py-4">Plan Name</th>
                  <th className="px-6 py-4">Category</th>
                  <th className="px-6 py-4">Status</th>
                  <th className="px-6 py-4">Employer Cost ($/mo)</th>
                  <th className="px-6 py-4">Employee Deduction ($/mo)</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100 text-sm">
                {benefits.map((b) => (
                  <tr key={b.id} className="hover:bg-gray-50/80">
                    <td className="px-6 py-4 font-bold text-gray-900">
                      {b.employee ? `${b.employee.firstName} ${b.employee.lastName}` : "Employee"}
                    </td>
                    <td className="px-6 py-4 font-semibold text-gray-800">{b.planName}</td>
                    <td className="px-6 py-4 capitalize text-gray-600">{b.planType}</td>
                    <td className="px-6 py-4">
                      <span className="text-xs px-2.5 py-1 bg-emerald-100 text-emerald-800 rounded-full font-bold uppercase">
                        {b.enrollmentStatus}
                      </span>
                    </td>
                    <td className="px-6 py-4 font-bold text-emerald-700">${b.employerContributionMonthly.toLocaleString()}</td>
                    <td className="px-6 py-4 font-bold text-gray-700">${b.employeeContributionMonthly.toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Tab 4: Departments Overview */}
      {activeTab === "org" && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {departments.map((dept) => {
            const deptEmps = employees.filter((e) => e.departmentId === dept.id);
            const deptPayroll = deptEmps.reduce((sum, e) => sum + (e.salary || 0), 0);
            return (
              <div key={dept.id} className="bg-white rounded-2xl border border-gray-200 shadow-sm p-6 space-y-4">
                <div className="flex items-start justify-between">
                  <div>
                    <h3 className="font-extrabold text-xl text-gray-900">{dept.name}</h3>
                    <p className="text-xs text-gray-500 mt-0.5">{dept.description}</p>
                  </div>
                  <span className="px-3 py-1 bg-indigo-50 text-indigo-700 font-bold rounded-xl text-sm border border-indigo-100">
                    {deptEmps.length} Employees
                  </span>
                </div>
                <div className="p-4 bg-gray-50 rounded-xl border border-gray-100 flex items-center justify-between">
                  <span className="text-xs font-bold text-gray-500 uppercase">Annual Department Payroll</span>
                  <span className="text-lg font-extrabold text-gray-900">${deptPayroll.toLocaleString()}</span>
                </div>
                <div className="space-y-2 pt-2">
                  <p className="text-xs font-bold text-gray-400 uppercase tracking-wider">Assigned Workforce</p>
                  {deptEmps.length === 0 ? (
                    <p className="text-xs text-gray-400 italic">No active employees in this department.</p>
                  ) : (
                    deptEmps.map((emp) => (
                      <div key={emp.id} className="flex items-center justify-between p-2.5 bg-gray-50 rounded-xl text-sm">
                        <span className="font-semibold text-gray-800">{emp.firstName} {emp.lastName}</span>
                        <span className="text-xs text-gray-500 font-medium">{emp.jobTitle}</span>
                      </div>
                    ))
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Modal: Add New Employee */}
      {showAddEmpModal && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-xl overflow-hidden border border-gray-100">
            <div className="px-6 py-5 bg-indigo-600 text-white flex items-center justify-between">
              <h2 className="font-bold text-lg">Add New Employee to HRIS</h2>
              <button onClick={() => setShowAddEmpModal(false)} className="p-2 text-indigo-100 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <form onSubmit={handleAddEmployee} className="p-6 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">First Name *</label>
                  <input value={newEmp.firstName} onChange={(e) => setNewEmp({ ...newEmp, firstName: e.target.value })} required className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500" />
                </div>
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Last Name *</label>
                  <input value={newEmp.lastName} onChange={(e) => setNewEmp({ ...newEmp, lastName: e.target.value })} required className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Email Address *</label>
                  <input type="email" value={newEmp.email} onChange={(e) => setNewEmp({ ...newEmp, email: e.target.value })} required className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500" />
                </div>
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Phone Number</label>
                  <input value={newEmp.phone} onChange={(e) => setNewEmp({ ...newEmp, phone: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Job Title *</label>
                  <input value={newEmp.jobTitle} onChange={(e) => setNewEmp({ ...newEmp, jobTitle: e.target.value })} required className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500" />
                </div>
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Department</label>
                  <select value={newEmp.departmentId} onChange={(e) => setNewEmp({ ...newEmp, departmentId: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500">
                    {departments.map((d) => (
                      <option key={d.id} value={d.id}>{d.name}</option>
                    ))}
                  </select>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Annual Salary ($)</label>
                  <input type="number" value={newEmp.salary} onChange={(e) => setNewEmp({ ...newEmp, salary: Number(e.target.value) })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500" />
                </div>
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Starting PTO Days</label>
                  <input value={newEmp.ptoBalanceDays} onChange={(e) => setNewEmp({ ...newEmp, ptoBalanceDays: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500" />
                </div>
              </div>
              <div className="pt-4 border-t border-gray-100 flex justify-end gap-3">
                <button type="button" onClick={() => setShowAddEmpModal(false)} className="px-5 py-2.5 text-sm font-bold text-gray-700 hover:bg-gray-100 rounded-xl">Cancel</button>
                <button type="submit" disabled={saving} className="px-6 py-2.5 bg-indigo-600 text-white font-bold text-sm rounded-xl hover:bg-indigo-700 shadow-sm">{saving ? "Creating..." : "Create Employee Record"}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Modal: Submit Time Off */}
      {showTimeOffModal && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-lg overflow-hidden border border-gray-100">
            <div className="px-6 py-5 bg-indigo-600 text-white flex items-center justify-between">
              <h2 className="font-bold text-lg">Submit Time Off Request</h2>
              <button onClick={() => setShowTimeOffModal(false)} className="p-2 text-indigo-100 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <form onSubmit={handleCreateTimeOff} className="p-6 space-y-4">
              <div>
                <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Employee *</label>
                <select value={newTimeOff.employeeId} onChange={(e) => setNewTimeOff({ ...newTimeOff, employeeId: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm">
                  {employees.map((e) => (
                    <option key={e.id} value={e.id}>{e.firstName} {e.lastName} ({e.ptoBalanceDays} PTO days available)</option>
                  ))}
                </select>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Leave Type</label>
                  <select value={newTimeOff.type} onChange={(e) => setNewTimeOff({ ...newTimeOff, type: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm">
                    <option value="vacation">Vacation</option>
                    <option value="sick">Sick Leave</option>
                    <option value="personal">Personal Leave</option>
                    <option value="parental">Parental Leave</option>
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Days Requested</label>
                  <input type="number" step="0.5" value={newTimeOff.daysRequested} onChange={(e) => setNewTimeOff({ ...newTimeOff, daysRequested: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Start Date</label>
                  <input type="date" value={newTimeOff.startDate} onChange={(e) => setNewTimeOff({ ...newTimeOff, startDate: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm" />
                </div>
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">End Date</label>
                  <input type="date" value={newTimeOff.endDate} onChange={(e) => setNewTimeOff({ ...newTimeOff, endDate: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm" />
                </div>
              </div>
              <div>
                <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Notes / Reason</label>
                <textarea value={newTimeOff.notes} onChange={(e) => setNewTimeOff({ ...newTimeOff, notes: e.target.value })} rows={2} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm resize-none" placeholder="Reason for request..." />
              </div>
              <div className="pt-4 border-t border-gray-100 flex justify-end gap-3">
                <button type="button" onClick={() => setShowTimeOffModal(false)} className="px-5 py-2.5 text-sm font-bold text-gray-700 hover:bg-gray-100 rounded-xl">Cancel</button>
                <button type="submit" disabled={saving} className="px-6 py-2.5 bg-indigo-600 text-white font-bold text-sm rounded-xl hover:bg-indigo-700 shadow-sm">{saving ? "Submitting..." : "Submit Request"}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Modal: Enroll Benefit */}
      {showBenefitModal && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-lg overflow-hidden border border-gray-100">
            <div className="px-6 py-5 bg-indigo-600 text-white flex items-center justify-between">
              <h2 className="font-bold text-lg">Enroll Employee in Benefit Plan</h2>
              <button onClick={() => setShowBenefitModal(false)} className="p-2 text-indigo-100 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <form onSubmit={handleCreateBenefit} className="p-6 space-y-4">
              <div>
                <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Employee *</label>
                <select value={newBenefit.employeeId} onChange={(e) => setNewBenefit({ ...newBenefit, employeeId: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm">
                  {employees.map((e) => (
                    <option key={e.id} value={e.id}>{e.firstName} {e.lastName}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Plan Name *</label>
                <input value={newBenefit.planName} onChange={(e) => setNewBenefit({ ...newBenefit, planName: e.target.value })} required className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Category</label>
                  <select value={newBenefit.planType} onChange={(e) => setNewBenefit({ ...newBenefit, planType: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm">
                    <option value="health">Medical / Health</option>
                    <option value="dental">Dental Care</option>
                    <option value="vision">Vision Care</option>
                    <option value="retirement">401(k) / Retirement</option>
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Employer Cost ($/mo)</label>
                  <input type="number" value={newBenefit.employerContributionMonthly} onChange={(e) => setNewBenefit({ ...newBenefit, employerContributionMonthly: Number(e.target.value) })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm" />
                </div>
              </div>
              <div className="pt-4 border-t border-gray-100 flex justify-end gap-3">
                <button type="button" onClick={() => setShowBenefitModal(false)} className="px-5 py-2.5 text-sm font-bold text-gray-700 hover:bg-gray-100 rounded-xl">Cancel</button>
                <button type="submit" disabled={saving} className="px-6 py-2.5 bg-indigo-600 text-white font-bold text-sm rounded-xl hover:bg-indigo-700 shadow-sm">{saving ? "Enrolling..." : "Enroll Employee"}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Modal: Employee Inspect Details */}
      {selectedEmpDetail && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col border border-gray-100">
            <div className="px-6 py-5 bg-slate-900 text-white flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className="w-11 h-11 rounded-full bg-indigo-500 text-white font-bold flex items-center justify-center text-lg">
                  {selectedEmpDetail.firstName[0]}{selectedEmpDetail.lastName[0]}
                </div>
                <div>
                  <h2 className="font-bold text-lg">{selectedEmpDetail.firstName} {selectedEmpDetail.lastName}</h2>
                  <p className="text-xs text-slate-400 font-mono">{selectedEmpDetail.employeeNumber} • {selectedEmpDetail.jobTitle}</p>
                </div>
              </div>
              <button onClick={() => setSelectedEmpDetail(null)} className="p-2 text-slate-400 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <div className="p-6 overflow-y-auto flex-1 space-y-6">
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 bg-gray-50 p-4 rounded-2xl border border-gray-200/80 text-sm">
                <div><span className="text-xs text-gray-400 uppercase font-bold block">Status</span><span className="font-bold text-emerald-700 capitalize">{selectedEmpDetail.status.replace("_", " ")}</span></div>
                <div><span className="text-xs text-gray-400 uppercase font-bold block">Annual Salary</span><span className="font-bold text-gray-900">${selectedEmpDetail.salary.toLocaleString()}</span></div>
                <div><span className="text-xs text-gray-400 uppercase font-bold block">PTO Available</span><span className="font-bold text-indigo-600">{selectedEmpDetail.ptoBalanceDays} days</span></div>
                <div><span className="text-xs text-gray-400 uppercase font-bold block">Hire Date</span><span className="font-medium text-gray-800">{selectedEmpDetail.hireDate}</span></div>
              </div>

              <div>
                <h4 className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-2">Emergency Contact</h4>
                <div className="p-4 bg-gray-50 rounded-xl border border-gray-200/80 flex justify-between text-sm">
                  <span><strong>{selectedEmpDetail.firstName}&apos;s Contact:</strong> {selectedEmpDetail.emergencyContactName || "Not Recorded"}</span>
                  <span className="font-mono text-gray-600">{selectedEmpDetail.emergencyContactPhone || "—"}</span>
                </div>
              </div>

              {selectedEmpDetail.onboardingCase && (
                <div>
                  <h4 className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-2">Onboarding History</h4>
                  <div className="p-4 bg-blue-50/60 rounded-xl border border-blue-200 flex items-center justify-between">
                    <div>
                      <p className="font-bold text-blue-950 text-sm">Completed Onboarding Case #{selectedEmpDetail.onboardingCase.id}</p>
                      <p className="text-xs text-blue-700">Target start: {selectedEmpDetail.onboardingCase.targetStartDate || selectedEmpDetail.hireDate}</p>
                    </div>
                    <Link href={`/onboarding/${selectedEmpDetail.onboardingCase.id}`} className="px-3.5 py-1.5 bg-blue-600 text-white font-bold text-xs rounded-lg shadow-sm">
                      Inspect Onboarding Record
                    </Link>
                  </div>
                </div>
              )}
            </div>
            <div className="px-6 py-4 bg-gray-50 border-t border-gray-100 flex justify-end">
              <button onClick={() => setSelectedEmpDetail(null)} className="px-6 py-2.5 bg-slate-900 text-white font-bold text-sm rounded-xl">Close Profile</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
