"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import {
  AlertCircle,
  ArrowLeft,
  Award,
  Briefcase,
  Building2,
  Calendar,
  CalendarDays,
  Landmark,
  CheckCircle2,
  ChevronRight,
  Clock,
  DollarSign,
  Download,
  ExternalLink,
  FileCheck2,
  FileText,
  Folder,
  HeartPulse,
  History,
  Lock,
  Mail,
  Pencil,
  Phone,
  Plus,
  RefreshCw,
  ShieldCheck,
  Star,
  Trash2,
  TrendingUp,
  Upload,
  User,
  UserCheck,
  Users,
  X,
} from "lucide-react";

interface MunisSetting {
  enabled: boolean;
  mode: "mock" | "live";
  autoPushOnHire: boolean;
  includeCompensation: boolean;
  includeEmergencyContact: boolean;
  includeOrganization: boolean;
  lastPushAt?: string | null;
}

interface EmployeeFolderData {
  id: number;
  employeeNumber: string;
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  personalEmail: string;
  alternatePhone: string;
  departmentId: number | null;
  department: { id: number; name: string } | null;
  jobTitle: string;
  status: string;
  employmentType: string;
  hireDate: string;
  salary: number;
  ptoBalanceDays: string;
  addressLine1: string;
  addressLine2: string;
  city: string;
  state: string;
  zipCode: string;
  country: string;
  emergencyContactName: string;
  emergencyContactRelationship: string;
  emergencyContactPhone: string;
  emergencyContactEmail: string;
  emergencyContactAddress: string;
  manager: { id: number; name: string; jobTitle: string } | null;
  candidate: { id: number; firstName: string; lastName: string; email: string; summary: string } | null;
  onboardingCase: { id: number; targetStartDate: string; status: string } | null;
  jobHistory: Array<{
    id: number;
    jobTitle: string;
    department: { name: string } | null;
    effectiveDate: string;
    changeReason: string;
    employmentType: string;
    notes: string;
  }>;
  payHistory: Array<{
    id: number;
    salary: number;
    payType: string;
    effectiveDate: string;
    changeReason: string;
    notes: string;
    approver: { name: string } | null;
  }>;
  documents: Array<{
    id: number;
    label: string;
    fileName: string;
    mimeType: string;
    fileSize: number;
    category: string;
    createdAt: string;
  }>;
  timeOffRequests: Array<{
    id: number;
    type: string;
    startDate: string;
    endDate: string;
    daysRequested: string;
    status: string;
    notes: string;
    approver: { name: string } | null;
  }>;
  benefits: Array<{
    id: number;
    planName: string;
    planType: string;
    enrollmentStatus: string;
    employerContributionMonthly: number;
    employeeContributionMonthly: number;
  }>;
}

export default function EmployeeFolderPage() {
  const params = useParams();
  const router = useRouter();
  const employeeId = String(params.id);

  const [folder, setFolder] = useState<EmployeeFolderData | null>(null);
  const [munisSetting, setMunisSetting] = useState<MunisSetting | null>(null);
  const [showMunisPushModal, setShowMunisPushModal] = useState(false);
  const [pushingMunis, setPushingMunis] = useState(false);
  const [departments, setDepartments] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<"overview" | "job_history" | "pay_history" | "documents" | "time_off" | "benefits" | "recruitment">("overview");

  // Modals
  const [showDocUploadModal, setShowDocUploadModal] = useState(false);
  const [showJobHistoryModal, setShowJobHistoryModal] = useState(false);
  const [showPayHistoryModal, setShowPayHistoryModal] = useState(false);
  const [viewDoc, setViewDoc] = useState<any | null>(null);

  // Edit permissions & inline edit states
  const [currentUserRole, setCurrentUserRole] = useState<string | null>(null);
  const [canEditHR, setCanEditHR] = useState(false);
  const [editingContact, setEditingContact] = useState(false);
  const [editingAddress, setEditingAddress] = useState(false);
  const [editingEmergency, setEditingEmergency] = useState(false);
  const [contactForm, setContactForm] = useState({ phone: "", alternatePhone: "", email: "", personalEmail: "" });
  const [addressForm, setAddressForm] = useState({ addressLine1: "", addressLine2: "", city: "", state: "", zipCode: "", country: "" });
  const [emergencyForm, setEmergencyForm] = useState({ emergencyContactName: "", emergencyContactRelationship: "", emergencyContactPhone: "", emergencyContactEmail: "", emergencyContactAddress: "" });

  // Status/Feedback
  const [saving, setSaving] = useState(false);
  const [notice, setNotice] = useState("");
  const [error, setError] = useState("");

  // New Record Forms
  const [docFile, setDocFile] = useState<File | null>(null);
  const [docLabel, setDocLabel] = useState("");
  const [docCategory, setDocCategory] = useState("Contracts & Agreements");

  const [newJobEntry, setNewJobEntry] = useState({
    jobTitle: "",
    departmentId: "1",
    effectiveDate: new Date().toISOString().slice(0, 10),
    changeReason: "Promotion",
    employmentType: "full_time",
    notes: "",
    updateCurrentTitle: true,
  });

  const [newPayEntry, setNewPayEntry] = useState({
    salary: 130000,
    payType: "Annual Salary",
    effectiveDate: new Date().toISOString().slice(0, 10),
    changeReason: "Annual Merit Increase",
    notes: "",
    updateCurrentSalary: true,
  });

  async function loadFolderData() {
    setLoading(true);
    try {
      const [empRes, deptsRes, meRes, munisRes] = await Promise.all([
        fetch(`/api/hris/employees/${employeeId}`),
        fetch("/api/departments"),
        fetch("/api/me"),
        fetch("/api/settings/munis"),
      ]);
      const [empData, deptsData, meData, munisData] = await Promise.all([empRes.json(), deptsRes.json(), meRes.json(), munisRes.json()]);

      if (!empRes.ok) throw new Error(empData.error || "Failed to load employee folder");

      setFolder(empData);
      if (munisRes.ok) setMunisSetting(munisData);
      if (Array.isArray(deptsData)) setDepartments(deptsData);

      const role = meData?.user?.role || "interviewer";
      setCurrentUserRole(role);
      const allowed = ["super_admin", "admin", "hr", "hr_manager", "people_ops", "recruiter"].includes(role);
      setCanEditHR(allowed);

      // Pre-fill forms
      setNewJobEntry((prev) => ({
        ...prev,
        jobTitle: empData.jobTitle,
        departmentId: String(empData.departmentId || deptsData[0]?.id || "1"),
      }));
      setNewPayEntry((prev) => ({
        ...prev,
        salary: empData.salary || 130000,
      }));

      setContactForm({
        phone: empData.phone || "",
        alternatePhone: empData.alternatePhone || "",
        email: empData.email || "",
        personalEmail: empData.personalEmail || "",
      });

      setAddressForm({
        addressLine1: empData.addressLine1 || "",
        addressLine2: empData.addressLine2 || "",
        city: empData.city || "",
        state: empData.state || "",
        zipCode: empData.zipCode || "",
        country: empData.country || "United States",
      });

      setEmergencyForm({
        emergencyContactName: empData.emergencyContactName || "",
        emergencyContactRelationship: empData.emergencyContactRelationship || "",
        emergencyContactPhone: empData.emergencyContactPhone || "",
        emergencyContactEmail: empData.emergencyContactEmail || "",
        emergencyContactAddress: empData.emergencyContactAddress || "",
      });
    } catch (err: any) {
      setError(err.message || "Unable to load employee folder.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    loadFolderData();
  }, [employeeId]);

  async function pushEmployeeToMunis() {
    setPushingMunis(true);
    setError("");
    try {
      const res = await fetch("/api/hris/munis/push", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ scope: "employee", employeeId: Number(employeeId) }),
      });
      const data = await res.json();
      if (res.ok) {
        setNotice(`Employee record pushed to Tyler Munis successfully. Reference: ${data.run?.externalReference || "created"}.`);
        setShowMunisPushModal(false);
        await loadFolderData();
      } else {
        setError(data.error || "Failed to push employee to Munis.");
      }
    } catch {
      setError("Network error while pushing to Munis.");
    } finally {
      setPushingMunis(false);
    }
  }

  async function saveEmployeeUpdates(payload: Record<string, any>, successMsg: string) {
    setSaving(true);
    setError("");
    try {
      const res = await fetch(`/api/hris/employees/${employeeId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      if (res.ok) {
        setNotice(successMsg);
        await loadFolderData();
        return true;
      } else {
        setError(data.error || "Failed to update employee record.");
        return false;
      }
    } catch {
      setError("Network error while saving employee file.");
      return false;
    } finally {
      setSaving(false);
    }
  }

  // Handle Document Upload
  async function handleUploadDoc(e: React.FormEvent) {
    e.preventDefault();
    if (!docFile) {
      setError("Please select a document file.");
      return;
    }
    setSaving(true);
    setError("");
    try {
      const formData = new FormData();
      formData.append("file", docFile);
      formData.append("label", docLabel || docFile.name);
      formData.append("category", docCategory);

      const res = await fetch(`/api/hris/employees/${employeeId}/documents`, {
        method: "POST",
        body: formData,
      });
      const data = await res.json();
      if (res.ok) {
        setNotice(`Document "${docFile.name}" uploaded to employee folder.`);
        setShowDocUploadModal(false);
        setDocFile(null);
        setDocLabel("");
        await loadFolderData();
      } else {
        setError(data.error || "Upload failed.");
      }
    } catch {
      setError("Network error during upload.");
    } finally {
      setSaving(false);
    }
  }

  // Handle Document Delete
  async function handleDeleteDoc(docId: number, label: string) {
    if (!confirm(`Delete "${label}" from employee folder?`)) return;
    try {
      const res = await fetch(`/api/hris/employees/${employeeId}/documents/${docId}`, {
        method: "DELETE",
      });
      if (res.ok) {
        setNotice("Document removed.");
        await loadFolderData();
      }
    } catch {
      setError("Failed to delete document.");
    }
  }

  // Handle New Job History Entry
  async function handleAddJobHistory(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setError("");
    try {
      const res = await fetch(`/api/hris/employees/${employeeId}/job-history`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newJobEntry),
      });
      const data = await res.json();
      if (res.ok) {
        setNotice("Job history record added!");
        setShowJobHistoryModal(false);
        await loadFolderData();
      } else {
        setError(data.error || "Failed to add job history.");
      }
    } catch {
      setError("Network error.");
    } finally {
      setSaving(false);
    }
  }

  // Handle New Pay History Entry
  async function handleAddPayHistory(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setError("");
    try {
      const res = await fetch(`/api/hris/employees/${employeeId}/pay-history`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newPayEntry),
      });
      const data = await res.json();
      if (res.ok) {
        setNotice("Compensation change recorded!");
        setShowPayHistoryModal(false);
        await loadFolderData();
      } else {
        setError(data.error || "Failed to record compensation change.");
      }
    } catch {
      setError("Network error.");
    } finally {
      setSaving(false);
    }
  }

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

  if (!folder) {
    return (
      <div className="p-8 max-w-4xl mx-auto text-center space-y-4">
        <AlertCircle className="w-12 h-12 text-red-500 mx-auto" />
        <h2 className="text-2xl font-bold text-gray-900">Employee Folder Not Found</h2>
        <p className="text-gray-500">{error || "The requested employee record could not be located in HRIS."}</p>
        <Link
          href="/hris"
          className="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 text-white rounded-xl font-bold text-sm"
        >
          <ArrowLeft className="w-4 h-4" /> Return to HRIS Directory
        </Link>
      </div>
    );
  }

  // Calculations for compensation progression
  const initialPay = folder.payHistory.length > 0 ? folder.payHistory[folder.payHistory.length - 1].salary : folder.salary;
  const currentPay = folder.salary;
  const payDiff = currentPay - initialPay;
  const payPercentGrowth = initialPay > 0 ? Math.round((payDiff / initialPay) * 100) : 0;

  return (
    <div className="p-6 max-w-7xl mx-auto space-y-6">
      {/* Top Navigation */}
      <div className="flex items-center gap-2 text-sm text-gray-500">
        <Link href="/hris" className="hover:text-indigo-600 transition-colors flex items-center gap-1">
          <ArrowLeft className="w-4 h-4" /> HRIS Directory
        </Link>
        <ChevronRight className="w-4 h-4 text-gray-400" />
        <span className="text-gray-900 font-bold">{folder.firstName} {folder.lastName}</span>
      </div>

      {notice && (
        <div className="p-4 bg-emerald-50 border border-emerald-200 rounded-2xl text-sm font-bold text-emerald-800 flex items-center justify-between shadow-sm">
          <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-2xl text-sm font-semibold text-red-700 flex items-center justify-between shadow-sm">
          <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>
      )}

      {/* Main Employee Folder Banner Card */}
      <div className="bg-white rounded-3xl border border-gray-200 p-6 md:p-8 shadow-sm space-y-6">
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 border-b border-gray-100 pb-6">
          <div className="flex items-start gap-4">
            <div className="w-16 h-16 rounded-3xl bg-indigo-600 text-white font-black text-2xl flex items-center justify-center shadow-md shrink-0">
              {folder.firstName[0]}{folder.lastName[0]}
            </div>
            <div>
              <div className="flex flex-wrap items-center gap-2.5">
                <h1 className="text-2xl md:text-3xl font-extrabold text-gray-900">
                  {folder.firstName} {folder.lastName}
                </h1>
                <span className="font-mono text-xs font-extrabold px-3 py-1 bg-indigo-50 text-indigo-700 rounded-lg border border-indigo-100">
                  {folder.employeeNumber}
                </span>
                <span
                  className={`text-xs px-3 py-1 rounded-full font-extrabold uppercase tracking-wide ${
                    folder.status === "active"
                      ? "bg-emerald-100 text-emerald-800"
                      : folder.status === "on_leave"
                      ? "bg-amber-100 text-amber-800"
                      : "bg-red-100 text-red-800"
                  }`}
                >
                  {folder.status.replace("_", " ")}
                </span>
              </div>

              <p className="text-base font-semibold text-indigo-600 mt-1">
                {folder.jobTitle}
                <span className="text-gray-400 font-normal"> • {folder.department?.name || "Corporate"}</span>
              </p>

              <div className="flex flex-wrap items-center gap-x-4 gap-y-1 mt-2 text-xs text-gray-500 font-medium">
                <span className="flex items-center gap-1"><Mail className="w-3.5 h-3.5 text-gray-400" />{folder.email}</span>
                {folder.phone && <span className="flex items-center gap-1"><Phone className="w-3.5 h-3.5 text-gray-400" />{folder.phone}</span>}
                <span className="flex items-center gap-1">
                  <Calendar className="w-3.5 h-3.5 text-gray-400" />
                  Hired {new Date(folder.hireDate + "T00:00:00").toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                </span>
              </div>
            </div>
          </div>

           {/* Quick Folder Actions */}
           <div className="flex flex-wrap items-center gap-2.5 shrink-0">
             {munisSetting?.enabled && (
               <button
                 onClick={() => setShowMunisPushModal(true)}
                 className="px-4 py-2.5 bg-sky-600 hover:bg-sky-700 text-white rounded-xl transition-colors text-xs font-bold flex items-center gap-1.5 shadow-sm"
               >
                 <Landmark className="w-4 h-4" /> Push to Munis
               </button>
             )}
             <button
               onClick={() => setShowDocUploadModal(true)}
               className="px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl transition-colors text-xs font-bold flex items-center gap-1.5 shadow-sm"
             >
               <Upload className="w-4 h-4" /> Upload Document
             </button>
            <button
              onClick={() => setShowJobHistoryModal(true)}
              className="px-4 py-2.5 bg-white border border-gray-300 text-gray-800 hover:bg-gray-50 rounded-xl transition-colors text-xs font-bold flex items-center gap-1.5 shadow-sm"
            >
              <Briefcase className="w-4 h-4 text-indigo-600" /> Role Promotion
            </button>
            <button
              onClick={() => setShowPayHistoryModal(true)}
              className="px-4 py-2.5 bg-white border border-gray-300 text-gray-800 hover:bg-gray-50 rounded-xl transition-colors text-xs font-bold flex items-center gap-1.5 shadow-sm"
            >
              <DollarSign className="w-4 h-4 text-emerald-600" /> Adjust Salary
            </button>
          </div>
        </div>

        {/* Top Summary Metrics Strip */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
          <div className="p-4 bg-gray-50 rounded-2xl border border-gray-100 space-y-1">
            <p className="text-xs font-bold uppercase text-gray-400">Current Compensation</p>
            <p className="text-xl font-black text-gray-900">${folder.salary.toLocaleString()}<span className="text-xs text-gray-400 font-normal">/yr</span></p>
            {payDiff > 0 && (
              <p className="text-[11px] font-bold text-emerald-600 flex items-center gap-1">
                <TrendingUp className="w-3 h-3" /> +{payPercentGrowth}% growth since hire
              </p>
            )}
          </div>

          <div className="p-4 bg-gray-50 rounded-2xl border border-gray-100 space-y-1">
            <p className="text-xs font-bold uppercase text-gray-400">PTO Leave Available</p>
            <p className="text-xl font-black text-indigo-700">{folder.ptoBalanceDays} <span className="text-xs text-gray-500 font-normal">Days</span></p>
            <p className="text-[11px] font-medium text-gray-500">{folder.timeOffRequests.length} total request records</p>
          </div>

          <div className="p-4 bg-gray-50 rounded-2xl border border-gray-100 space-y-1">
            <p className="text-xs font-bold uppercase text-gray-400">HR Folder Files</p>
            <p className="text-xl font-black text-gray-900">{folder.documents.length} <span className="text-xs text-gray-500 font-normal">Documents</span></p>
            <p className="text-[11px] font-medium text-gray-500">Stored in employee dossier</p>
          </div>

          <div className="p-4 bg-gray-50 rounded-2xl border border-gray-100 space-y-1">
            <p className="text-xs font-bold uppercase text-gray-400">Career Changes</p>
            <p className="text-xl font-black text-gray-900">{folder.jobHistory.length} <span className="text-xs text-gray-500 font-normal">Role Entries</span></p>
            <p className="text-[11px] font-medium text-gray-500">{folder.payHistory.length} compensation reviews</p>
          </div>
        </div>
      </div>

      {/* Folder Tabs Navigation */}
      <div className="flex flex-wrap items-center gap-2 border-b border-gray-200 bg-white p-1 rounded-2xl shadow-sm">
        {[
          { id: "overview", label: "Overview & Profile", icon: User },
          { id: "job_history", label: "Job & Career History", icon: History, count: folder.jobHistory.length },
          { id: "pay_history", label: "Pay & Compensation", icon: DollarSign, count: folder.payHistory.length },
          { id: "documents", label: "Documents Repository", icon: Folder, count: folder.documents.length },
          { id: "time_off", label: "Time Off & Leave Log", icon: CalendarDays, count: folder.timeOffRequests.length },
          { id: "benefits", label: "Benefits Enrollment", icon: HeartPulse, count: folder.benefits.length },
          { id: "recruitment", label: "Recruitment Pedigree", icon: Award },
        ].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 px-4 py-2.5 rounded-xl text-xs md:text-sm font-bold 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>
              {typeof tab.count === "number" && (
                <span className={`text-[11px] px-2 py-0.5 rounded-full font-extrabold ${isActive ? "bg-indigo-500 text-white" : "bg-gray-100 text-gray-500"}`}>
                  {tab.count}
                </span>
              )}
            </button>
          );
        })}
      </div>

      {/* ── TAB 1: OVERVIEW & PROFILE ── */}
      {activeTab === "overview" && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div className="lg:col-span-2 space-y-6">
            <div className="bg-white rounded-3xl border border-gray-200 p-6 shadow-sm space-y-4">
              <div className="flex items-center justify-between border-b border-gray-100 pb-3">
                <h3 className="font-extrabold text-gray-900 text-lg">
                  Employment & Organizational Record
                </h3>
                {!canEditHR && (
                  <span className="text-[10px] px-2 py-1 bg-gray-100 text-gray-500 rounded-full font-bold uppercase flex items-center gap-1"><Lock className="w-3 h-3" /> View Only</span>
                )}
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
                <div className="p-4 bg-gray-50 rounded-2xl border border-gray-100 space-y-0.5">
                  <p className="text-xs font-bold uppercase text-gray-400">Legal Name</p>
                  <p className="font-bold text-gray-900">{folder.firstName} {folder.lastName}</p>
                </div>
                <div className="p-4 bg-gray-50 rounded-2xl border border-gray-100 space-y-0.5">
                  <p className="text-xs font-bold uppercase text-gray-400">Employee Identification</p>
                  <p className="font-mono font-bold text-gray-900">{folder.employeeNumber}</p>
                </div>
                <div className="p-4 bg-gray-50 rounded-2xl border border-gray-100 space-y-0.5">
                  <p className="text-xs font-bold uppercase text-gray-400">Employment Type</p>
                  <p className="font-semibold text-gray-900 capitalize">{folder.employmentType.replace("_", " ")}</p>
                </div>
                <div className="p-4 bg-gray-50 rounded-2xl border border-gray-100 space-y-0.5">
                  <p className="text-xs font-bold uppercase text-gray-400">Assigned Manager</p>
                  <p className="font-semibold text-gray-900">{folder.manager?.name || "Direct Executive Leadership"}</p>
                </div>
              </div>
            </div>

            {/* Contact & Phone Numbers - Editable by super_admin, admin, hr */}
            <div className="bg-white rounded-3xl border border-gray-200 p-6 shadow-sm space-y-4">
              <div className="flex items-center justify-between border-b border-gray-100 pb-3">
                <h3 className="font-extrabold text-gray-900 text-lg flex items-center gap-2">
                  <Phone className="w-5 h-5 text-indigo-600" /> Contact & Phone Numbers
                </h3>
                {canEditHR ? (
                  !editingContact ? (
                    <button onClick={() => setEditingContact(true)} className="px-3 py-1.5 bg-indigo-50 text-indigo-700 hover:bg-indigo-100 rounded-xl text-xs font-bold flex items-center gap-1.5 transition-colors"><Pencil className="w-3.5 h-3.5" /> Edit</button>
                  ) : (
                    <div className="flex items-center gap-2">
                      <button onClick={() => { setEditingContact(false); setContactForm({ phone: folder.phone || "", alternatePhone: folder.alternatePhone || "", email: folder.email || "", personalEmail: folder.personalEmail || "" }); }} className="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl text-xs font-bold">Cancel</button>
                      <button onClick={async () => { const ok = await saveEmployeeUpdates(contactForm, "Contact information updated!"); if (ok) setEditingContact(false); }} disabled={saving} className="px-3 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold flex items-center gap-1.5 disabled:opacity-50"><CheckCircle2 className="w-3.5 h-3.5" /> Save</button>
                    </div>
                  )
                ) : (
                  <span className="text-[10px] px-2 py-1 bg-gray-100 text-gray-500 rounded-full font-bold uppercase flex items-center gap-1"><Lock className="w-3 h-3" /> HR Only</span>
                )}
              </div>

              {!editingContact ? (
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
                  <div className="p-4 bg-gray-50 rounded-2xl border border-gray-100 space-y-1">
                    <p className="text-xs font-bold uppercase text-gray-400">Work Email</p>
                    <p className="font-semibold text-gray-900 flex items-center gap-2"><Mail className="w-3.5 h-3.5 text-gray-400" />{folder.email}</p>
                  </div>
                  <div className="p-4 bg-gray-50 rounded-2xl border border-gray-100 space-y-1">
                    <p className="text-xs font-bold uppercase text-gray-400">Personal Email</p>
                    <p className="font-semibold text-gray-900">{folder.personalEmail || "Not on file"}</p>
                  </div>
                  <div className="p-4 bg-gray-50 rounded-2xl border border-gray-100 space-y-1">
                    <p className="text-xs font-bold uppercase text-gray-400">Primary Phone</p>
                    <p className="font-semibold text-gray-900 flex items-center gap-2"><Phone className="w-3.5 h-3.5 text-gray-400" />{folder.phone || "—"}</p>
                  </div>
                  <div className="p-4 bg-gray-50 rounded-2xl border border-gray-100 space-y-1">
                    <p className="text-xs font-bold uppercase text-gray-400">Alternate Phone</p>
                    <p className="font-semibold text-gray-900">{folder.alternatePhone || "—"}</p>
                  </div>
                </div>
              ) : (
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-bold uppercase text-gray-500 mb-1">Work Email *</label>
                    <input value={contactForm.email} onChange={(e) => setContactForm({ ...contactForm, email: 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 focus:outline-none" placeholder="work@company.com" />
                  </div>
                  <div>
                    <label className="block text-xs font-bold uppercase text-gray-500 mb-1">Personal Email</label>
                    <input value={contactForm.personalEmail} onChange={(e) => setContactForm({ ...contactForm, personalEmail: 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 focus:outline-none" placeholder="personal@gmail.com" />
                  </div>
                  <div>
                    <label className="block text-xs font-bold uppercase text-gray-500 mb-1">Primary Phone</label>
                    <input value={contactForm.phone} onChange={(e) => setContactForm({ ...contactForm, 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 focus:outline-none" placeholder="+1 (555) 123-4567" />
                  </div>
                  <div>
                    <label className="block text-xs font-bold uppercase text-gray-500 mb-1">Alternate Phone</label>
                    <input value={contactForm.alternatePhone} onChange={(e) => setContactForm({ ...contactForm, alternatePhone: 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 focus:outline-none" placeholder="+1 (555) 987-6543" />
                  </div>
                </div>
              )}
            </div>

            {/* Address - Editable by super_admin, admin, hr */}
            <div className="bg-white rounded-3xl border border-gray-200 p-6 shadow-sm space-y-4">
              <div className="flex items-center justify-between border-b border-gray-100 pb-3">
                <h3 className="font-extrabold text-gray-900 text-lg flex items-center gap-2">
                  <Building2 className="w-5 h-5 text-indigo-600" /> Home Address
                </h3>
                {canEditHR ? (
                  !editingAddress ? (
                    <button onClick={() => setEditingAddress(true)} className="px-3 py-1.5 bg-indigo-50 text-indigo-700 hover:bg-indigo-100 rounded-xl text-xs font-bold flex items-center gap-1.5 transition-colors"><Pencil className="w-3.5 h-3.5" /> Edit</button>
                  ) : (
                    <div className="flex items-center gap-2">
                      <button onClick={() => { setEditingAddress(false); setAddressForm({ addressLine1: folder.addressLine1 || "", addressLine2: folder.addressLine2 || "", city: folder.city || "", state: folder.state || "", zipCode: folder.zipCode || "", country: folder.country || "United States" }); }} className="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl text-xs font-bold">Cancel</button>
                      <button onClick={async () => { const ok = await saveEmployeeUpdates(addressForm, "Home address updated!"); if (ok) setEditingAddress(false); }} disabled={saving} className="px-3 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold flex items-center gap-1.5 disabled:opacity-50"><CheckCircle2 className="w-3.5 h-3.5" /> Save</button>
                    </div>
                  )
                ) : (
                  <span className="text-[10px] px-2 py-1 bg-gray-100 text-gray-500 rounded-full font-bold uppercase flex items-center gap-1"><Lock className="w-3 h-3" /> HR Only</span>
                )}
              </div>

              {!editingAddress ? (
                <div className="p-5 bg-gray-50/80 border border-gray-200 rounded-2xl text-sm space-y-1">
                  {folder.addressLine1 || folder.city ? (
                    <>
                      <p className="font-semibold text-gray-900">{folder.addressLine1}{folder.addressLine2 ? `, ${folder.addressLine2}` : ""}</p>
                      <p className="text-gray-700">{folder.city}{folder.city && folder.state ? `, ${folder.state}` : folder.state} {folder.zipCode}</p>
                      <p className="text-gray-500 text-xs">{folder.country || "United States"}</p>
                    </>
                  ) : (
                    <p className="text-gray-400 italic">No home address on file. Click Edit to add.</p>
                  )}
                </div>
              ) : (
                <div className="grid grid-cols-1 gap-4">
                  <div>
                    <label className="block text-xs font-bold uppercase text-gray-500 mb-1">Street Address Line 1 *</label>
                    <input value={addressForm.addressLine1} onChange={(e) => setAddressForm({ ...addressForm, addressLine1: 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 focus:outline-none" placeholder="123 Main Street, Apt 4B" />
                  </div>
                  <div>
                    <label className="block text-xs font-bold uppercase text-gray-500 mb-1">Street Address Line 2</label>
                    <input value={addressForm.addressLine2} onChange={(e) => setAddressForm({ ...addressForm, addressLine2: 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 focus:outline-none" placeholder="Suite, Floor, Building (optional)" />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-bold uppercase text-gray-500 mb-1">City *</label>
                      <input value={addressForm.city} onChange={(e) => setAddressForm({ ...addressForm, city: 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 focus:outline-none" placeholder="San Francisco" />
                    </div>
                    <div>
                      <label className="block text-xs font-bold uppercase text-gray-500 mb-1">State / Province *</label>
                      <input value={addressForm.state} onChange={(e) => setAddressForm({ ...addressForm, state: 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 focus:outline-none" placeholder="CA" />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-bold uppercase text-gray-500 mb-1">ZIP / Postal Code *</label>
                      <input value={addressForm.zipCode} onChange={(e) => setAddressForm({ ...addressForm, zipCode: 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 focus:outline-none" placeholder="94105" />
                    </div>
                    <div>
                      <label className="block text-xs font-bold uppercase text-gray-500 mb-1">Country</label>
                      <input value={addressForm.country} onChange={(e) => setAddressForm({ ...addressForm, country: 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 focus:outline-none" placeholder="United States" />
                    </div>
                  </div>
                </div>
              )}
            </div>

            <div className="bg-white rounded-3xl border border-gray-200 p-6 shadow-sm space-y-4">
              <div className="flex items-center justify-between border-b border-gray-100 pb-3">
                <h3 className="font-extrabold text-gray-900 text-lg flex items-center gap-2">
                  <ShieldCheck className="w-5 h-5 text-blue-600" /> Emergency Contact Details
                </h3>
                {canEditHR ? (
                  !editingEmergency ? (
                    <button onClick={() => setEditingEmergency(true)} className="px-3 py-1.5 bg-blue-50 text-blue-700 hover:bg-blue-100 rounded-xl text-xs font-bold flex items-center gap-1.5 transition-colors"><Pencil className="w-3.5 h-3.5" /> Edit</button>
                  ) : (
                    <div className="flex items-center gap-2">
                      <button onClick={() => { setEditingEmergency(false); setEmergencyForm({ emergencyContactName: folder.emergencyContactName || "", emergencyContactRelationship: folder.emergencyContactRelationship || "", emergencyContactPhone: folder.emergencyContactPhone || "", emergencyContactEmail: folder.emergencyContactEmail || "", emergencyContactAddress: folder.emergencyContactAddress || "" }); }} className="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl text-xs font-bold">Cancel</button>
                      <button onClick={async () => { const ok = await saveEmployeeUpdates(emergencyForm, "Emergency contact updated!"); if (ok) setEditingEmergency(false); }} disabled={saving} className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl text-xs font-bold flex items-center gap-1.5 disabled:opacity-50"><CheckCircle2 className="w-3.5 h-3.5" /> Save</button>
                    </div>
                  )
                ) : (
                  <span className="text-[10px] px-2 py-1 bg-gray-100 text-gray-500 rounded-full font-bold uppercase flex items-center gap-1"><Lock className="w-3 h-3" /> HR Only</span>
                )}
              </div>

              {!editingEmergency ? (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="p-5 bg-blue-50/60 border border-blue-100 rounded-2xl space-y-2 text-sm">
                    <p className="text-xs font-bold uppercase text-blue-800">Primary Contact Person</p>
                    <p className="font-bold text-gray-900 text-base">{folder.emergencyContactName || "Not on file"}</p>
                    <p className="text-xs text-blue-700">{folder.emergencyContactRelationship ? `Relationship: ${folder.emergencyContactRelationship}` : "Relationship not specified"}</p>
                  </div>
                  <div className="p-5 bg-gray-50 border border-gray-200 rounded-2xl space-y-2 text-sm">
                    <p className="text-xs font-bold uppercase text-gray-400">Contact Methods</p>
                    <p className="font-semibold text-gray-900 flex items-center gap-2"><Phone className="w-3.5 h-3.5 text-gray-400" />{folder.emergencyContactPhone || "No phone on file"}</p>
                    <p className="font-semibold text-gray-900 flex items-center gap-2"><Mail className="w-3.5 h-3.5 text-gray-400" />{folder.emergencyContactEmail || "No email on file"}</p>
                    {folder.emergencyContactAddress && <p className="text-xs text-gray-500 pt-1">Address: {folder.emergencyContactAddress}</p>}
                  </div>
                </div>
              ) : (
                <div className="grid grid-cols-1 gap-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-bold uppercase text-gray-500 mb-1">Full Name *</label>
                      <input value={emergencyForm.emergencyContactName} onChange={(e) => setEmergencyForm({ ...emergencyForm, emergencyContactName: 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-blue-500 focus:outline-none" placeholder="Jane Doe" />
                    </div>
                    <div>
                      <label className="block text-xs font-bold uppercase text-gray-500 mb-1">Relationship</label>
                      <select value={emergencyForm.emergencyContactRelationship} onChange={(e) => setEmergencyForm({ ...emergencyForm, emergencyContactRelationship: 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-blue-500 focus:outline-none">
                        <option value="">Select relationship</option>
                        <option value="Spouse">Spouse</option>
                        <option value="Partner">Partner</option>
                        <option value="Parent">Parent</option>
                        <option value="Mother">Mother</option>
                        <option value="Father">Father</option>
                        <option value="Sibling">Sibling</option>
                        <option value="Sister">Sister</option>
                        <option value="Brother">Brother</option>
                        <option value="Child">Child</option>
                        <option value="Friend">Friend</option>
                        <option value="Other">Other</option>
                      </select>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-bold uppercase text-gray-500 mb-1">Phone *</label>
                      <input value={emergencyForm.emergencyContactPhone} onChange={(e) => setEmergencyForm({ ...emergencyForm, emergencyContactPhone: 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-blue-500 focus:outline-none" placeholder="+1 (555) 123-4567" />
                    </div>
                    <div>
                      <label className="block text-xs font-bold uppercase text-gray-500 mb-1">Email</label>
                      <input type="email" value={emergencyForm.emergencyContactEmail} onChange={(e) => setEmergencyForm({ ...emergencyForm, emergencyContactEmail: 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-blue-500 focus:outline-none" placeholder="emergency@example.com" />
                    </div>
                  </div>
                  <div>
                    <label className="block text-xs font-bold uppercase text-gray-500 mb-1">Emergency Contact Address</label>
                    <input value={emergencyForm.emergencyContactAddress} onChange={(e) => setEmergencyForm({ ...emergencyForm, emergencyContactAddress: 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-blue-500 focus:outline-none" placeholder="123 Emergency St, City, State ZIP" />
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Sidebar Info */}
          <div className="space-y-6">
            <div className="bg-white rounded-3xl border border-gray-200 p-6 shadow-sm space-y-4">
              <h3 className="font-extrabold text-gray-900 text-base border-b border-gray-100 pb-3">
                Quick Heritage Snapshot
              </h3>
              {folder.candidate ? (
                <div className="space-y-3">
                  <div className="p-3.5 bg-emerald-50 border border-emerald-100 rounded-2xl text-xs space-y-1">
                    <p className="font-bold text-emerald-950 flex items-center gap-1">
                      <UserCheck className="w-3.5 h-3.5 text-emerald-600" /> Hired from ATS Candidate Pipeline
                    </p>
                    <p className="text-emerald-800">Originally applied as candidate #{folder.candidate.id}</p>
                  </div>
                  <Link
                    href={`/candidates/${folder.candidate.id}`}
                    className="flex items-center justify-between p-3 bg-gray-50 hover:bg-gray-100 rounded-xl text-xs font-bold text-indigo-700 transition-colors"
                  >
                    <span>Inspect Original ATS Application</span>
                    <ExternalLink className="w-3.5 h-3.5" />
                  </Link>
                </div>
              ) : (
                <p className="text-xs text-gray-400 italic">Direct HRIS hire (not converted from ATS pipeline).</p>
              )}

              {folder.onboardingCase && (
                <div className="space-y-2 pt-2 border-t border-gray-100">
                  <p className="text-xs font-bold text-gray-400 uppercase">Onboarding Reference</p>
                  <Link
                    href={`/onboarding/${folder.onboardingCase.id}`}
                    className="flex items-center justify-between p-3 bg-blue-50 hover:bg-blue-100 rounded-xl text-xs font-bold text-blue-800 transition-colors"
                  >
                    <span>Onboarding Case #{folder.onboardingCase.id}</span>
                    <ExternalLink className="w-3.5 h-3.5" />
                  </Link>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* ── TAB 2: JOB & CAREER HISTORY ── */}
      {activeTab === "job_history" && (
        <div className="space-y-6">
          <div className="flex items-center justify-between bg-white p-6 rounded-3xl border border-gray-200 shadow-sm">
            <div>
              <h3 className="font-extrabold text-gray-900 text-xl">Job & Role Progression History</h3>
              <p className="text-sm text-gray-500">Timeline of all job titles, department transfers, and promotions for this employee.</p>
            </div>
            <button
              onClick={() => setShowJobHistoryModal(true)}
              className="px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold flex items-center gap-1.5 shadow-sm"
            >
              <Plus className="w-4 h-4" /> Record Role Change
            </button>
          </div>

          <div className="bg-white rounded-3xl border border-gray-200 p-6 shadow-sm">
            <div className="relative border-l-2 border-indigo-100 ml-4 pl-6 space-y-8 py-2">
              {folder.jobHistory.length === 0 ? (
                <p className="text-sm text-gray-400 italic">No historical role changes logged yet. Current role: {folder.jobTitle}.</p>
              ) : (
                folder.jobHistory.map((item, index) => (
                  <div key={item.id} className="relative group">
                    {/* Circle marker */}
                    <div className="absolute -left-[31px] top-1.5 w-4 h-4 rounded-full bg-indigo-600 ring-4 ring-indigo-50" />
                    
                    <div className="bg-gray-50 p-5 rounded-2xl border border-gray-200/80 space-y-2">
                      <div className="flex flex-wrap items-center justify-between gap-2">
                        <h4 className="font-extrabold text-gray-900 text-lg">{item.jobTitle}</h4>
                        <span className="text-xs font-bold px-3 py-1 bg-indigo-100 text-indigo-800 rounded-full">
                          {item.changeReason}
                        </span>
                      </div>
                      <div className="flex items-center gap-4 text-xs font-medium text-gray-500">
                        <span>Department: <strong className="text-gray-800">{item.department?.name || "Corporate"}</strong></span>
                        <span>•</span>
                        <span>Effective Date: <strong className="text-gray-800">{item.effectiveDate}</strong></span>
                        <span>•</span>
                        <span className="capitalize">{item.employmentType.replace("_", " ")}</span>
                      </div>
                      {item.notes && (
                        <p className="text-xs text-gray-600 italic bg-white p-3 rounded-xl border border-gray-200/60 mt-2">
                          &quot;{item.notes}&quot;
                        </p>
                      )}
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      )}

      {/* ── TAB 3: PAY & COMPENSATION HISTORY ── */}
      {activeTab === "pay_history" && (
        <div className="space-y-6">
          <div className="flex items-center justify-between bg-white p-6 rounded-3xl border border-gray-200 shadow-sm">
            <div>
              <h3 className="font-extrabold text-gray-900 text-xl">Pay & Compensation History</h3>
              <p className="text-sm text-gray-500">Comprehensive audit record of salary increases, merit adjustments, and starting base offers.</p>
            </div>
            <button
              onClick={() => setShowPayHistoryModal(true)}
              className="px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-xs font-bold flex items-center gap-1.5 shadow-sm"
            >
              <Plus className="w-4 h-4" /> Adjust Compensation
            </button>
          </div>

          <div className="bg-white rounded-3xl 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">Effective Date</th>
                  <th className="px-6 py-4">Annual Base Salary</th>
                  <th className="px-6 py-4">Adjustment Reason</th>
                  <th className="px-6 py-4">Approved By</th>
                  <th className="px-6 py-4">Notes</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100 text-sm">
                {folder.payHistory.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="text-center py-12 text-gray-400">
                      No compensation history records logged. Current base salary: ${folder.salary.toLocaleString()}.
                    </td>
                  </tr>
                ) : (
                  folder.payHistory.map((item) => (
                    <tr key={item.id} className="hover:bg-gray-50/80">
                      <td className="px-6 py-4 font-bold text-gray-900">{item.effectiveDate}</td>
                      <td className="px-6 py-4 font-extrabold text-emerald-700 text-base">
                        ${item.salary.toLocaleString()}
                        <span className="text-xs font-normal text-gray-400"> /yr ({item.payType})</span>
                      </td>
                      <td className="px-6 py-4 font-semibold text-gray-800">{item.changeReason}</td>
                      <td className="px-6 py-4 text-xs text-gray-600">{item.approver?.name || "HR Compensation Executive"}</td>
                      <td className="px-6 py-4 text-xs text-gray-500 italic max-w-xs">{item.notes || "—"}</td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* ── TAB 4: HR DOCUMENTS REPOSITORY ── */}
      {activeTab === "documents" && (
        <div className="space-y-6">
          <div className="flex items-center justify-between bg-white p-6 rounded-3xl border border-gray-200 shadow-sm">
            <div>
              <h3 className="font-extrabold text-gray-900 text-xl">Employee Document Repository</h3>
              <p className="text-sm text-gray-500">Securely store employment contracts, tax documentation, and annual reviews in the employee dossier.</p>
            </div>
            <button
              onClick={() => setShowDocUploadModal(true)}
              className="px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold flex items-center gap-1.5 shadow-sm"
            >
              <Upload className="w-4 h-4" /> Add Document to Dossier
            </button>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {folder.documents.length === 0 ? (
              <div className="col-span-2 bg-white rounded-3xl border border-dashed border-gray-300 p-12 text-center text-gray-400 space-y-2">
                <Folder className="w-12 h-12 mx-auto text-gray-300" />
                <p className="font-bold text-gray-700">No documents stored in this employee folder yet.</p>
                <p className="text-xs">Click &quot;Add Document to Dossier&quot; above to upload agreements or tax forms.</p>
              </div>
            ) : (
              folder.documents.map((doc) => (
                <div key={doc.id} className="bg-white rounded-2xl border border-gray-200 p-5 shadow-sm flex items-center justify-between gap-4 hover:border-indigo-300 transition-all">
                  <div className="flex items-center gap-3.5 min-w-0">
                    <div className="p-3 bg-indigo-50 text-indigo-600 rounded-2xl shrink-0">
                      <FileText className="w-6 h-6" />
                    </div>
                    <div className="min-w-0">
                      <span className="text-[10px] uppercase font-extrabold px-2 py-0.5 bg-gray-100 text-gray-600 rounded-md">
                        {doc.category}
                      </span>
                      <p className="font-bold text-gray-900 text-sm truncate mt-1">{doc.label}</p>
                      <p className="text-xs text-gray-400 font-mono truncate mt-0.5">
                        {doc.fileName} • {(doc.fileSize / 1024).toFixed(0)} KB
                      </p>
                    </div>
                  </div>

                  <div className="flex items-center gap-1.5 shrink-0">
                    <button
                      onClick={() => setViewDoc(doc)}
                      className="p-2 text-indigo-600 hover:bg-indigo-50 rounded-xl transition-colors font-bold text-xs flex items-center gap-1"
                      title="View Inline"
                    >
                      <FileText className="w-4 h-4" />
                    </button>
                    <a
                      href={`/api/hris/employees/${employeeId}/documents/${doc.id}`}
                      className="p-2 text-gray-600 hover:bg-gray-100 rounded-xl transition-colors"
                      title="Download File"
                    >
                      <Download className="w-4 h-4" />
                    </a>
                    <button
                      onClick={() => handleDeleteDoc(doc.id, doc.label)}
                      className="p-2 text-red-400 hover:text-red-700 hover:bg-red-50 rounded-xl transition-colors"
                      title="Delete Document"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      )}

      {/* ── TAB 5: TIME OFF RECORD ── */}
      {activeTab === "time_off" && (
        <div className="space-y-6">
          <div className="bg-white rounded-3xl border border-gray-200 p-6 shadow-sm space-y-4">
            <div className="flex items-center justify-between border-b border-gray-100 pb-4">
              <div>
                <h3 className="font-extrabold text-gray-900 text-xl">Paid Time Off (PTO) & Leave Log</h3>
                <p className="text-sm text-gray-500">Employee leave requests and historical approvals.</p>
              </div>
              <div className="p-4 bg-indigo-50 rounded-2xl border border-indigo-100 text-right">
                <p className="text-xs text-indigo-700 font-bold uppercase">Current PTO Balance</p>
                <p className="text-2xl font-black text-indigo-900">{folder.ptoBalanceDays} Days</p>
              </div>
            </div>

            <div className="space-y-3">
              {folder.timeOffRequests.length === 0 ? (
                <p className="text-sm text-gray-400 italic text-center py-6">No leave requests submitted for this employee.</p>
              ) : (
                folder.timeOffRequests.map((req) => (
                  <div key={req.id} className="p-4 bg-gray-50 rounded-2xl border border-gray-200/80 flex items-center justify-between gap-4">
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-bold text-gray-900 capitalize text-base">{req.type} Leave</span>
                        <span className={`text-xs px-2.5 py-0.5 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>
                      </div>
                      <p className="text-xs text-gray-500 mt-1">{req.startDate} to {req.endDate} ({req.daysRequested} Days)</p>
                      {req.notes && <p className="text-xs text-gray-600 mt-1 italic">&quot;{req.notes}&quot;</p>}
                    </div>
                    <div className="text-right text-xs text-gray-400">
                      Approved by: {req.approver?.name || "Pending Management Review"}
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      )}

      {/* ── TAB 6: BENEFITS & INSURANCE ── */}
      {activeTab === "benefits" && (
        <div className="space-y-6">
          <div className="bg-white rounded-3xl border border-gray-200 p-6 shadow-sm space-y-4">
            <h3 className="font-extrabold text-gray-900 text-xl border-b border-gray-100 pb-3">
              Enrolled Benefit Plans & Monthly Costs
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {folder.benefits.map((plan) => (
                <div key={plan.id} className="p-5 bg-gray-50 rounded-2xl border border-gray-200/80 space-y-3">
                  <div className="flex items-start justify-between">
                    <div>
                      <span className="text-[10px] uppercase font-extrabold px-2 py-0.5 bg-indigo-100 text-indigo-800 rounded-md">
                        {plan.planType}
                      </span>
                      <h4 className="font-bold text-gray-900 text-base mt-1">{plan.planName}</h4>
                    </div>
                    <span className="text-xs px-2.5 py-1 bg-emerald-100 text-emerald-800 font-bold rounded-full uppercase">
                      {plan.enrollmentStatus}
                    </span>
                  </div>
                  <div className="grid grid-cols-2 gap-2 text-xs border-t border-gray-200/60 pt-3">
                    <div><span className="text-gray-400 font-medium block">Employer Monthly Cost</span><span className="font-bold text-emerald-700 text-sm">${plan.employerContributionMonthly}/mo</span></div>
                    <div><span className="text-gray-400 font-medium block">Employee Deduction</span><span className="font-bold text-gray-800 text-sm">${plan.employeeContributionMonthly}/mo</span></div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* ── TAB 7: RECRUITMENT & ONBOARDING PEDIGREE ── */}
      {activeTab === "recruitment" && (
        <div className="bg-white rounded-3xl border border-gray-200 p-6 shadow-sm space-y-6">
          <h3 className="font-extrabold text-gray-900 text-xl border-b border-gray-100 pb-3">
            Recruitment Lineage & Handoff Pedigree
          </h3>

          {folder.candidate ? (
            <div className="space-y-4">
              <div className="p-5 bg-blue-50/70 border border-blue-100 rounded-2xl space-y-2 text-sm">
                <p className="font-bold text-blue-950 text-base">Converted Candidate Record #{folder.candidate.id}</p>
                <p className="text-blue-800">FullName: {folder.candidate.firstName} {folder.candidate.lastName} ({folder.candidate.email})</p>
                <p className="text-xs text-blue-700 leading-relaxed italic">&quot;{folder.candidate.summary}&quot;</p>
              </div>

              <div className="flex items-center gap-3 pt-2">
                <Link
                  href={`/candidates/${folder.candidate.id}`}
                  className="px-5 py-2.5 bg-indigo-600 text-white font-bold text-xs rounded-xl shadow-sm hover:bg-indigo-700 flex items-center gap-2"
                >
                  <ExternalLink className="w-4 h-4" /> Open Full ATS Candidate Profile
                </Link>
                {folder.onboardingCase && (
                  <Link
                    href={`/onboarding/${folder.onboardingCase.id}`}
                    className="px-5 py-2.5 bg-emerald-600 text-white font-bold text-xs rounded-xl shadow-sm hover:bg-emerald-700 flex items-center gap-2"
                  >
                    <ExternalLink className="w-4 h-4" /> Open Candidate Onboarding Workspace
                  </Link>
                )}
              </div>
            </div>
          ) : (
            <p className="text-sm text-gray-400 italic">No ATS candidate record associated with this employee.</p>
          )}
        </div>
      )}

      {/* Modal: Document Upload */}
      {showDocUploadModal && (
        <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">Upload Document to Employee Dossier</h2>
              <button onClick={() => setShowDocUploadModal(false)} className="p-2 text-indigo-100 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <form onSubmit={handleUploadDoc} className="p-6 space-y-4">
              <div>
                <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Document Label *</label>
                <input
                  value={docLabel}
                  onChange={(e) => setDocLabel(e.target.value)}
                  placeholder="e.g. Signed Employment Agreement 2024"
                  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">Category</label>
                <select
                  value={docCategory}
                  onChange={(e) => setDocCategory(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"
                >
                  <option value="Contracts & Agreements">Contracts & Agreements</option>
                  <option value="Tax & Legal">Tax & Legal</option>
                  <option value="Payroll & Banking">Payroll & Banking</option>
                  <option value="Performance & Reviews">Performance & Reviews</option>
                  <option value="Identification">Identification</option>
                  <option value="General">General</option>
                </select>
              </div>
              <div>
                <label className="block text-xs font-bold text-gray-700 uppercase mb-1">File Upload *</label>
                <input
                  type="file"
                  onChange={(e) => setDocFile(e.target.files?.[0] || null)}
                  required
                  className="w-full text-xs text-gray-600 file:mr-4 file:py-2 file:px-4 file:rounded-xl file:border-0 file:text-xs file:font-bold file:bg-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100"
                />
              </div>
              <div className="pt-4 border-t border-gray-100 flex justify-end gap-3">
                <button type="button" onClick={() => setShowDocUploadModal(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 || !docFile} className="px-6 py-2.5 bg-indigo-600 text-white font-bold text-sm rounded-xl hover:bg-indigo-700 shadow-sm">{saving ? "Uploading..." : "Save to Dossier"}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Modal: Job Change Entry */}
      {showJobHistoryModal && (
        <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">Record Job Promotion or Role Change</h2>
              <button onClick={() => setShowJobHistoryModal(false)} className="p-2 text-indigo-100 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <form onSubmit={handleAddJobHistory} className="p-6 space-y-4">
              <div>
                <label className="block text-xs font-bold text-gray-700 uppercase mb-1">New Job Title *</label>
                <input
                  value={newJobEntry.jobTitle}
                  onChange={(e) => setNewJobEntry({ ...newJobEntry, 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 className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Department</label>
                  <select
                    value={newJobEntry.departmentId}
                    onChange={(e) => setNewJobEntry({ ...newJobEntry, 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>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Effective Date *</label>
                  <input
                    type="date"
                    value={newJobEntry.effectiveDate}
                    onChange={(e) => setNewJobEntry({ ...newJobEntry, effectiveDate: 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>
                <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Change Reason</label>
                <select
                  value={newJobEntry.changeReason}
                  onChange={(e) => setNewJobEntry({ ...newJobEntry, changeReason: 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"
                >
                  <option value="Promotion">Promotion</option>
                  <option value="Internal Transfer">Internal Transfer</option>
                  <option value="Title Adjustment">Title Adjustment</option>
                  <option value="Reorganization">Reorganization</option>
                </select>
              </div>
              <div>
                <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Notes / Rationale</label>
                <textarea
                  value={newJobEntry.notes}
                  onChange={(e) => setNewJobEntry({ ...newJobEntry, 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 promotion or transfer..."
                />
              </div>
              <div className="pt-4 border-t border-gray-100 flex justify-end gap-3">
                <button type="button" onClick={() => setShowJobHistoryModal(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 ? "Recording..." : "Record Role Change"}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Modal: Pay History Entry */}
      {showPayHistoryModal && (
        <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-emerald-600 text-white flex items-center justify-between">
              <h2 className="font-bold text-lg">Adjust Annual Salary / Compensation</h2>
              <button onClick={() => setShowPayHistoryModal(false)} className="p-2 text-emerald-100 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <form onSubmit={handleAddPayHistory} 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">New Base Salary ($/yr) *</label>
                  <input
                    type="number"
                    value={newPayEntry.salary}
                    onChange={(e) => setNewPayEntry({ ...newPayEntry, salary: Number(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-emerald-500 font-bold"
                  />
                </div>
                <div>
                  <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Effective Date *</label>
                  <input
                    type="date"
                    value={newPayEntry.effectiveDate}
                    onChange={(e) => setNewPayEntry({ ...newPayEntry, effectiveDate: 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-emerald-500"
                  />
                </div>
              </div>
              <div>
                <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Increase / Adjustment Reason</label>
                <select
                  value={newPayEntry.changeReason}
                  onChange={(e) => setNewPayEntry({ ...newPayEntry, changeReason: 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-emerald-500"
                >
                  <option value="Annual Merit Increase">Annual Merit Increase</option>
                  <option value="Promotion Adjustment">Promotion Adjustment</option>
                  <option value="Market Adjustment">Market Adjustment</option>
                  <option value="Equity Balance Alignment">Equity Balance Alignment</option>
                </select>
              </div>
              <div>
                <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Notes</label>
                <textarea
                  value={newPayEntry.notes}
                  onChange={(e) => setNewPayEntry({ ...newPayEntry, 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="Notes from performance review or compensation committee..."
                />
              </div>
              <div className="pt-4 border-t border-gray-100 flex justify-end gap-3">
                <button type="button" onClick={() => setShowPayHistoryModal(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-emerald-600 text-white font-bold text-sm rounded-xl hover:bg-emerald-700 shadow-sm">{saving ? "Saving..." : "Save Compensation Adjustment"}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Modal: Document Inline Preview Modal */}
      {/* Munis push confirmation and payload summary */}
      {showMunisPushModal && munisSetting && (
        <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-gradient-to-r from-sky-600 to-blue-700 text-white flex items-center justify-between">
              <div>
                <h2 className="font-bold text-lg flex items-center gap-2"><Landmark className="w-5 h-5" /> Push Employee to Tyler Munis</h2>
                <p className="text-xs text-sky-100 mt-0.5">{munisSetting.mode === "live" ? "Live Munis Open API transmission" : "Demo mode — no data leaves H.R. Vista"}</p>
              </div>
              <button onClick={() => setShowMunisPushModal(false)} className="p-2 text-sky-100 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <div className="p-6 space-y-4">
              <div className="p-4 bg-sky-50 border border-sky-100 rounded-2xl text-sm space-y-2">
                <p className="font-bold text-sky-950">Employee payload preview</p>
                <div className="grid grid-cols-2 gap-2 text-xs">
                  <span className="text-sky-800">Employee #: <strong>{folder.employeeNumber}</strong></span>
                  <span className="text-sky-800">Status: <strong className="capitalize">{folder.status}</strong></span>
                  <span className="text-sky-800">Position: <strong>{folder.jobTitle}</strong></span>
                  <span className="text-sky-800">Department: <strong>{folder.department?.name || "Unassigned"}</strong></span>
                </div>
              </div>
              <div className="space-y-2 text-sm">
                <p className="font-semibold text-gray-800">Included data fields</p>
                <div className="flex flex-wrap gap-2 text-xs">
                  <span className="px-2.5 py-1 bg-gray-100 rounded-lg">Identity & contact</span>
                  <span className="px-2.5 py-1 bg-gray-100 rounded-lg">Position & department</span>
                  {munisSetting.includeCompensation && <span className="px-2.5 py-1 bg-emerald-50 text-emerald-700 rounded-lg">Compensation</span>}
                  {munisSetting.includeEmergencyContact && <span className="px-2.5 py-1 bg-amber-50 text-amber-700 rounded-lg">Emergency contact</span>}
                  {munisSetting.includeOrganization && <span className="px-2.5 py-1 bg-indigo-50 text-indigo-700 rounded-lg">Supervisor hierarchy</span>}
                </div>
              </div>
              <p className="text-xs text-gray-500">A timestamped audit record and response reference will be retained in H.R. Vista after this push.</p>
            </div>
            <div className="px-6 py-4 bg-gray-50 border-t border-gray-100 flex justify-end gap-3">
              <button onClick={() => setShowMunisPushModal(false)} className="px-4 py-2.5 text-sm font-bold text-gray-700 hover:bg-gray-200 rounded-xl">Cancel</button>
              <button onClick={pushEmployeeToMunis} disabled={pushingMunis} className="px-5 py-2.5 bg-sky-600 hover:bg-sky-700 text-white font-bold text-sm rounded-xl shadow-sm disabled:opacity-50 flex items-center gap-1.5">
                <RefreshCw className={`w-4 h-4 ${pushingMunis ? "animate-spin" : ""}`} />
                {pushingMunis ? "Pushing..." : munisSetting.mode === "live" ? "Confirm & Push to Munis" : "Run Demo Munis Push"}
              </button>
            </div>
          </div>
        </div>
      )}

      {viewDoc && (
        <div className="fixed inset-0 bg-black/75 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-5xl max-h-[92vh] overflow-hidden flex flex-col border border-gray-100">
            <div className="px-6 py-4 bg-slate-900 text-white flex items-center justify-between shrink-0">
              <div className="flex items-center gap-3 min-w-0">
                <FileText className="w-5 h-5 text-indigo-400" />
                <div className="min-w-0">
                  <h2 className="font-bold text-lg truncate">{viewDoc.label}</h2>
                  <p className="text-xs text-slate-400 truncate">{viewDoc.fileName} • {viewDoc.category}</p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <a
                  href={`/api/hris/employees/${employeeId}/documents/${viewDoc.id}`}
                  className="px-3 py-1.5 bg-indigo-600 text-white font-bold text-xs rounded-lg flex items-center gap-1.5"
                >
                  <Download className="w-3.5 h-3.5" /> Download Original
                </a>
                <button onClick={() => setViewDoc(null)} className="p-2 text-slate-400 hover:text-white"><X className="w-5 h-5" /></button>
              </div>
            </div>

            <div className="flex-1 bg-slate-100 flex items-center justify-center overflow-auto p-4">
              <iframe
                src={`/api/hris/employees/${employeeId}/documents/${viewDoc.id}?inline=true`}
                className="w-full h-full min-h-[600px] border-0 rounded-2xl bg-white shadow-md"
                title={viewDoc.fileName}
              />
            </div>

            <div className="px-6 py-3 bg-white border-t border-gray-200 flex justify-end">
              <button onClick={() => setViewDoc(null)} className="px-6 py-2 bg-slate-900 text-white font-bold text-xs rounded-xl">Close Dossier Viewer</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
