import React, { useState, useEffect } from 'react';
import { User } from '../types';
import { 
  Users, 
  Search, 
  Phone, 
  Folder, 
  Eye, 
  RefreshCw, 
  Plus, 
  Trash2, 
  X, 
  ShieldCheck, 
  CheckCircle2, 
  Building2,
  TrendingUp,
  UserCheck,
  PauseCircle,
  PlayCircle,
  Clock,
  Layers,
  FileText,
  DollarSign,
  Briefcase,
  GitCommit,
  MapPin,
  ChevronRight,
  Save,
  Edit3
} from 'lucide-react';

interface AdminEmployeesProps {
  user: User | null;
}

// 18-Level Corporate Hierarchy
const STANDARD_DESIGNATIONS = [
  'Chairman',
  'Managing Director (MD)',
  'Chief Executive Officer (CEO)',
  'Sub Admin',
  'General Manager (GM)',
  'Deputy General Manager (DGM)',
  'Assistant General Manager (AGM)',
  'Senior Manager',
  'Manager',
  'Deputy Manager',
  'Assistant Manager',
  'Senior Executive',
  'Executive',
  'Junior Executive',
  'Senior Officer',
  'Officer',
  'Junior Officer',
  'Intern'
];

// Roles/Designations allowed to display CONFIRM ORDER and AMOUNT metric cards
const ALLOWED_METRIC_ROLES = [
  'Senior Executive',
  'Executive',
  'Junior Executive',
  'Senior Officer',
  'Officer',
  'Junior Officer'
];

const isMetricVisible = (designation?: string) => {
  if (!designation) return false;
  const dClean = designation.toLowerCase().trim();
  return ALLOWED_METRIC_ROLES.some(role => dClean === role.toLowerCase().trim());
};

// Standard Departments
const STANDARD_DEPARTMENTS = [
  'Management',
  'Human Resources (HR)',
  'Administration (Admin)',
  'Admin',
  'Finance & Accounts',
  'Commercial & Import/Export',
  'Planning',
  'Merchandising',
  'Industrial Engineering (IE)',
  'Quality Assurance (QA)',
  'Quality Control (QC)',
  'Supply Chain Management (SCM)',
  'Inventory / Store',
  'Information Technology (IT)',
  'Audit',
  'Driver'
];

export default function AdminEmployees({ user }: AdminEmployeesProps) {
  const [employees, setEmployees] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [departmentFilter, setDepartmentFilter] = useState('All');
  const [statusFilter, setStatusFilter] = useState<'All' | 'Active' | 'Hold' | 'Delete'>('All');
  const [selectedEmployee, setSelectedEmployee] = useState<any | null>(null);
  
  // Provisioning Modal State
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [customDept, setCustomDept] = useState('');
  const [showCustomDept, setShowCustomDept] = useState(false);
  const [customDesig, setCustomDesig] = useState('');
  const [showCustomDesig, setShowCustomDesig] = useState(false);

  // Form State
  const [newStaff, setNewStaff] = useState({
    name: '',
    email: '',
    phone: '01811489253',
    department: 'Management',
    designation: 'Chairman',
    managerId: '',
    address: 'Dhaka, Bangladesh',
    password: ''
  });

  // Edit Form State (Inside View Modal)
  const [editDept, setEditDept] = useState('');
  const [editDesig, setEditDesig] = useState('');
  const [editManagerId, setEditManagerId] = useState('');
  const [isUpdating, setIsUpdating] = useState(false);
  const [updateMessage, setUpdateMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  useEffect(() => {
    if (selectedEmployee) {
      setEditDept(selectedEmployee.department || 'Management');
      setEditDesig(selectedEmployee.designation || 'Executive');
      setEditManagerId(
        selectedEmployee.managerId || 
        selectedEmployee.reportingBoss?.staffId || 
        selectedEmployee.reportingBoss?.id || 
        ''
      );
      setUpdateMessage(null);
    }
  }, [selectedEmployee]);

  const handleSaveEmployeeEdits = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedEmployee) return;

    setIsUpdating(true);
    setUpdateMessage(null);

    try {
      const isChairman = editDesig.toLowerCase().includes('chairman');
      if (!isChairman && !editManagerId) {
        throw new Error('Hierarchy Rule Violation: Non-Chairman employees must be assigned to a reporting superior.');
      }

      const targetId = selectedEmployee.id || selectedEmployee.staffId;
      const res = await fetch(`/api/admin/employees/${targetId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          department: editDept,
          designation: editDesig,
          managerId: isChairman ? null : editManagerId
        })
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || 'Failed to update employee details');
      }

      setUpdateMessage({ type: 'success', text: 'Employee details updated successfully!' });

      await fetchEmployees();

      const freshList = await fetch('/api/admin/employees').then(r => r.json());
      const updatedEmp = freshList.find((emp: any) => emp.id === targetId || emp.staffId === targetId);
      if (updatedEmp) {
        setSelectedEmployee(updatedEmp);
      }
    } catch (err: any) {
      setUpdateMessage({ type: 'error', text: err.message || 'Error updating employee' });
    } finally {
      setIsUpdating(false);
    }
  };

  const fetchEmployees = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/admin/employees');
      if (res.ok) {
        const data = await res.json();
        setEmployees(data);
      } else {
        setEmployees([]);
      }
    } catch (err) {
      console.error('Error fetching admin employees:', err);
    } finally {
      setLoading(false);
    }
  };

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

  // Compute Distinct Departments list
  const allDepartments = Array.from(
    new Set([
      'All',
      ...STANDARD_DEPARTMENTS,
      ...employees.map((e) => e.department).filter(Boolean)
    ])
  );

  // Compute KPI Cards Data
  const totalStaffCount = employees.filter(e => e.staffStatus !== 'Delete').length;
  const activeStaffCount = employees.filter(e => (e.staffStatus || 'Active') === 'Active').length;
  const activePercentage = totalStaffCount > 0 ? Math.round((activeStaffCount / totalStaffCount) * 100) : 100;
  const uniqueDeptCount = new Set(employees.map(e => e.department).filter(Boolean)).size;
  const verifiedHierarchyCount = employees.filter(e => 
    e.designation?.toLowerCase().includes('chairman') || e.managerId || e.reportingBoss
  ).length;
  const hierarchyIntegrityPercent = totalStaffCount > 0 ? Math.round((verifiedHierarchyCount / totalStaffCount) * 100) : 100;

  // Filter Employees
  const filteredEmployees = employees.filter(e => {
    const matchesSearch = 
      e.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      e.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (e.staffId && e.staffId.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (e.designation && e.designation.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (e.department && e.department.toLowerCase().includes(searchTerm.toLowerCase()));

    const matchesDept = departmentFilter === 'All' || e.department === departmentFilter;
    const currentStatus = e.staffStatus || 'Active';
    const matchesStatus = statusFilter === 'All' || currentStatus === statusFilter;

    return matchesSearch && matchesDept && matchesStatus;
  });

  // Handle Form Submit for New Staff
  const handleCreateStaff = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newStaff.name || !newStaff.email) {
      alert('Please provide full name and email address.');
      return;
    }

    const selectedDept = showCustomDept ? customDept : newStaff.department;
    const selectedDesig = showCustomDesig ? customDesig : newStaff.designation;

    const isChairmanSelection = selectedDesig.toLowerCase().includes('chairman');

    // Hierarchy Rule: Non-Chairman roles MUST select a manager
    if (!isChairmanSelection && !newStaff.managerId) {
      alert('Hierarchy Rule Violation: Every employee role except the Chairman must be assigned to an upper-level reporting boss profile.');
      return;
    }

    setIsSubmitting(true);
    try {
      const payload = {
        ...newStaff,
        department: selectedDept,
        designation: selectedDesig,
        reportingHierarchy: isChairmanSelection ? 'Apex Chairman / N/A' : undefined
      };

      const res = await fetch('/api/admin/employees', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      const data = await res.json();

      if (res.ok && data.success) {
        alert('New staff account provisioned successfully!');
        setIsAddModalOpen(false);
        setNewStaff({
          name: '',
          email: '',
          phone: '01811489253',
          department: 'Management',
          designation: 'Chairman',
          managerId: '',
          address: 'Dhaka, Bangladesh',
          password: ''
        });
        setShowCustomDept(false);
        setShowCustomDesig(false);
        fetchEmployees();
      } else {
        alert(data.error || 'Failed to create staff account');
      }
    } catch (err) {
      console.error('Error creating staff:', err);
      alert('An error occurred while provisioning staff account.');
    } finally {
      setIsSubmitting(false);
    }
  };

  // Toggle Employee Status (Active <-> Hold)
  const handleToggleStatus = async (emp: any) => {
    const currentStatus = emp.staffStatus || 'Active';
    const nextStatus = currentStatus === 'Active' ? 'Hold' : 'Active';

    try {
      const targetId = emp.id || emp.staffId;
      const res = await fetch(`/api/admin/employees/${targetId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ staffStatus: nextStatus })
      });
      if (res.ok) {
        await fetchEmployees();
        if (selectedEmployee && (selectedEmployee.id === emp.id || selectedEmployee.staffId === emp.staffId)) {
          setSelectedEmployee(prev => prev ? ({ ...prev, staffStatus: nextStatus }) : null);
        }
      } else {
        alert('Failed to update status');
      }
    } catch (err) {
      console.error('Status toggle error:', err);
    }
  };

  // Delete / Deactivate Staff Account
  const handleDeleteStaff = async (emp: any) => {
    if (!confirm(`Are you sure you want to delete or deactivate staff account for "${emp.name}"?`)) {
      return;
    }

    try {
      const targetId = emp.id || emp.staffId;
      const res = await fetch(`/api/admin/employees/${targetId}`, {
        method: 'DELETE'
      });
      if (res.ok) {
        await fetchEmployees();
        if (selectedEmployee && (selectedEmployee.id === emp.id || selectedEmployee.staffId === emp.staffId)) {
          setSelectedEmployee(null);
        }
      } else {
        const data = await res.json();
        alert(data.error || 'Failed to delete staff account');
      }
    } catch (err) {
      console.error('Error deleting staff:', err);
      alert('Error deleting staff account');
    }
  };

  return (
    <div className="space-y-6 font-sans pb-12">
      {/* Component 1: Header Banner & Quick Action CTA */}
      <div className="bg-white rounded-2xl border border-slate-200/90 p-5 md:p-6 shadow-xs flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <div className="flex items-center gap-2">
            <span className="p-2 bg-indigo-50 text-indigo-600 rounded-xl">
              <Users className="w-5 h-5" />
            </span>
            <h1 className="text-base md:text-lg font-black text-slate-900 tracking-wider uppercase font-mono">
              INTERNAL STAFF DIRECTORY
            </h1>
          </div>
          <p className="text-xs text-slate-500 mt-1.5 font-medium leading-relaxed max-w-2xl">
            Real-time repository containing organization records, reporting dependencies, and credentials mapping.
          </p>
        </div>

        <button
          onClick={() => setIsAddModalOpen(true)}
          className="bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white font-bold text-xs px-4 py-2.5 rounded-xl shadow-xs transition flex items-center gap-2 shrink-0 cursor-pointer"
        >
          <span className="text-base font-extrabold">+</span>
          <span>+ New Staff Account</span>
        </button>
      </div>

      {/* Component 2: KPI Metrics Overview Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4">
        <div className="bg-white p-4 rounded-2xl border border-slate-200/80 shadow-2xs space-y-1">
          <div className="flex items-center justify-between text-slate-400">
            <span className="text-[11px] font-bold uppercase tracking-wider text-slate-500">Total Directory</span>
            <Users className="w-4 h-4 text-indigo-500" />
          </div>
          <p className="text-xl md:text-2xl font-black text-slate-900 font-mono">{totalStaffCount}</p>
          <p className="text-[10px] text-slate-400 font-medium">Registered Employee Records</p>
        </div>

        <div className="bg-white p-4 rounded-2xl border border-slate-200/80 shadow-2xs space-y-1">
          <div className="flex items-center justify-between text-slate-400">
            <span className="text-[11px] font-bold uppercase tracking-wider text-slate-500">Active Rate</span>
            <TrendingUp className="w-4 h-4 text-emerald-500" />
          </div>
          <p className="text-xl md:text-2xl font-black text-emerald-600 font-mono">{activePercentage}%</p>
          <p className="text-[10px] text-slate-400 font-medium">{activeStaffCount} Active / {totalStaffCount} Total</p>
        </div>

        <div className="bg-white p-4 rounded-2xl border border-slate-200/80 shadow-2xs space-y-1">
          <div className="flex items-center justify-between text-slate-400">
            <span className="text-[11px] font-bold uppercase tracking-wider text-slate-500">Department Spread</span>
            <Layers className="w-4 h-4 text-blue-500" />
          </div>
          <p className="text-xl md:text-2xl font-black text-slate-900 font-mono">{uniqueDeptCount}</p>
          <p className="text-[10px] text-slate-400 font-medium">Active Corporate Wings</p>
        </div>

        <div className="bg-white p-4 rounded-2xl border border-slate-200/80 shadow-2xs space-y-1">
          <div className="flex items-center justify-between text-slate-400">
            <span className="text-[11px] font-bold uppercase tracking-wider text-slate-500">Hierarchy Integrity</span>
            <ShieldCheck className="w-4 h-4 text-amber-500" />
          </div>
          <p className="text-xl md:text-2xl font-black text-amber-600 font-mono">{hierarchyIntegrityPercent}%</p>
          <p className="text-[10px] text-slate-400 font-medium">Boss Dependency Verified</p>
        </div>
      </div>

      {/* Component 3: Search & Multi-Filter Control Bar */}
      <div className="bg-white p-3.5 rounded-2xl border border-slate-200/90 shadow-2xs flex flex-col sm:flex-row items-center justify-between gap-3">
        <div className="relative w-full sm:w-80">
          <Search className="w-4 h-4 text-slate-400 absolute left-3.5 top-2.5" />
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="Search staff name, ID, email, department..."
            className="w-full pl-10 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 font-medium"
          />
        </div>

        <div className="flex flex-wrap sm:flex-nowrap items-center gap-2.5 w-full sm:w-auto justify-between sm:justify-end">
          {/* Department Dropdown Filter */}
          <select
            value={departmentFilter}
            onChange={(e) => setDepartmentFilter(e.target.value)}
            className="px-3 py-1.5 bg-slate-50 border border-slate-200 rounded-xl text-xs font-semibold text-slate-700 focus:outline-none focus:ring-2 focus:ring-indigo-500"
          >
            {allDepartments.map((dept) => (
              <option key={dept} value={dept}>
                {dept === 'All' ? 'All Departments' : dept}
              </option>
            ))}
          </select>

          {/* Status Pills Filter */}
          <div className="flex bg-slate-100 p-1 rounded-xl text-xs font-semibold text-slate-600">
            {(['All', 'Active', 'Hold', 'Delete'] as const).map((st) => (
              <button
                key={st}
                onClick={() => setStatusFilter(st)}
                className={`px-3 py-1 rounded-lg transition shrink-0 cursor-pointer text-[11px] ${
                  statusFilter === st ? 'bg-white text-slate-900 shadow-2xs font-bold' : 'hover:text-slate-900'
                }`}
              >
                {st}
              </button>
            ))}
          </div>

          <button
            onClick={fetchEmployees}
            title="Refresh Directory"
            className="p-2 text-slate-500 hover:text-slate-800 bg-slate-100 hover:bg-slate-200 rounded-xl transition cursor-pointer shrink-0"
          >
            <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
          </button>
        </div>
      </div>

      {/* Component 4: Primary Directory Data Table */}
      <div className="bg-white rounded-2xl border border-slate-200/90 shadow-2xs overflow-hidden p-3 md:p-5">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs border-collapse">
            <thead>
              <tr className="border-b border-slate-100 bg-slate-50/60">
                <th className="px-4 py-3.5 font-bold text-slate-400 text-[10px] uppercase tracking-wider">STAFF</th>
                <th className="px-4 py-3.5 font-bold text-slate-400 text-[10px] uppercase tracking-wider">PRIMARY CONTACT</th>
                <th className="px-4 py-3.5 font-bold text-slate-400 text-[10px] uppercase tracking-wider">DEPARTMENT</th>
                <th className="px-4 py-3.5 font-bold text-slate-400 text-[10px] uppercase tracking-wider">DESIGNATION</th>
                <th className="px-4 py-3.5 font-bold text-slate-400 text-[10px] uppercase tracking-wider">REPORTING HIERARCHY</th>
                <th className="px-4 py-3.5 font-bold text-slate-400 text-[10px] uppercase tracking-wider text-center">CONFIRM ORDER</th>
                <th className="px-4 py-3.5 font-bold text-slate-400 text-[10px] uppercase tracking-wider text-center">AMOUNT</th>
                <th className="px-4 py-3.5 font-bold text-slate-400 text-[10px] uppercase tracking-wider text-right">ACTION LOGS</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {loading ? (
                <tr>
                  <td colSpan={8} className="px-4 py-12 text-center text-slate-400 font-mono text-xs">
                    Loading staff directory database...
                  </td>
                </tr>
              ) : filteredEmployees.length === 0 ? (
                <tr>
                  <td colSpan={8} className="px-4 py-12 text-center text-slate-400 font-sans text-xs">
                    No staff records found matching criteria.
                  </td>
                </tr>
              ) : (
                filteredEmployees.map((e) => {
                  const staffCode = e.staffId || e.id;
                  const dept = e.department || 'Management';
                  const desig = (e.designation || 'CHAIRMAN').toUpperCase();
                  const hierarchy = e.reportingHierarchy || 'Apex Chairman / N/A';
                  const isHold = e.staffStatus === 'Hold';
                  const isDelete = e.staffStatus === 'Delete';

                  return (
                    <tr key={e.id} className="hover:bg-slate-50/80 transition group">
                      {/* Column 1: STAFF (Status Dot + Staff ID Badge + Staff Name) */}
                      <td className="px-4 py-4 whitespace-nowrap">
                        <div className="flex items-center space-x-2">
                          <span 
                            className={`w-2.5 h-2.5 rounded-full shrink-0 inline-block ${
                              isDelete ? 'bg-rose-500' : isHold ? 'bg-amber-500' : 'bg-emerald-500'
                            }`} 
                            title={`Status: ${e.staffStatus || 'Active'}`} 
                          />
                          <span className="bg-slate-100 border border-slate-200 text-slate-800 font-mono text-[11px] px-2 py-0.5 rounded font-bold">
                            {staffCode}
                          </span>
                        </div>
                        <p className="font-bold text-slate-900 text-xs mt-1.5">{e.name}</p>
                      </td>

                      {/* Column 2: PRIMARY CONTACT */}
                      <td className="px-4 py-4 whitespace-nowrap">
                        <p className="font-bold text-slate-900 text-xs">{e.email}</p>
                        <div className="flex items-center text-slate-500 font-mono text-[11px] space-x-1 mt-0.5">
                          <Phone className="w-3 h-3 text-slate-400 shrink-0" />
                          <span>{e.phone || '01811489253'}</span>
                        </div>
                      </td>

                      {/* Column 3: DEPARTMENT */}
                      <td className="px-4 py-4 whitespace-nowrap">
                        <span className="bg-blue-50/80 border border-blue-100 text-slate-700 font-semibold text-[11px] px-3 py-1 rounded-full inline-flex items-center gap-1.5 shadow-2xs">
                          <Folder className="w-3.5 h-3.5 text-blue-500 shrink-0" />
                          <span>{dept}</span>
                        </span>
                      </td>

                      {/* Column 4: DESIGNATION */}
                      <td className="px-4 py-4 whitespace-nowrap">
                        <span className="bg-slate-100/90 border border-slate-200 text-slate-600 text-[10px] font-bold px-2.5 py-1 rounded uppercase tracking-wider inline-block">
                          {desig}
                        </span>
                      </td>

                      {/* Column 5: REPORTING HIERARCHY */}
                      <td className="px-4 py-4 whitespace-nowrap">
                        {(() => {
                          const parts = hierarchy.split('/').map(p => p.trim());
                          const bossName = parts[0] || hierarchy;
                          const bossDesig = parts.slice(1).join(' / ');
                          return (
                            <div className="bg-amber-50/80 border border-amber-300 text-amber-900 text-[11px] font-bold px-3 py-1.5 rounded-md inline-block">
                              <div>{bossName}</div>
                              {bossDesig && (
                                <div className="text-[10px] text-amber-800/90 font-medium leading-tight mt-0.5">
                                  {bossDesig}
                                </div>
                              )}
                            </div>
                          );
                        })()}
                      </td>

                      {/* Column 6: CONFIRM ORDER */}
                      <td className="px-3 py-3 whitespace-nowrap text-center">
                        {isMetricVisible(e.designation) && (e.orderQty || e.shipQty) ? (() => {
                          const ordQty = e.orderQty || 0;
                          const shipQty = e.shipQty || 0;
                          const balQty = Math.max(0, ordQty - shipQty);
                          return (
                            <div className="bg-slate-50/80 border border-slate-200/70 rounded-xl p-2 px-2.5 text-left font-sans text-xs inline-block shadow-2xs">
                              <div className="flex items-center gap-1.5 mb-0.5">
                                <span className="text-[10px] text-slate-400 font-bold min-w-[20px]">OQ:</span>
                                <span className="font-bold text-slate-800 text-xs">{ordQty.toLocaleString()}</span>
                              </div>
                              <div className="flex items-center gap-1.5 mb-1">
                                <span className="text-[10px] text-slate-400 font-bold min-w-[20px]">SQ:</span>
                                <span className="font-bold text-emerald-600 text-xs">{shipQty.toLocaleString()}</span>
                              </div>
                              <div className="pt-1 border-t border-slate-200/60 flex items-center gap-1.5">
                                <span className="text-[10px] text-slate-400 font-bold min-w-[20px]">BQ:</span>
                                <span className="font-bold text-indigo-600 text-xs">{balQty.toLocaleString()}</span>
                              </div>
                            </div>
                          );
                        })() : (
                          <span className="text-slate-400 font-medium text-sm">-</span>
                        )}
                      </td>

                      {/* Column 7: AMOUNT */}
                      <td className="px-3 py-3 whitespace-nowrap text-center">
                        {isMetricVisible(e.designation) && (e.totalAmount || e.receivedAmount) ? (() => {
                          const totalAmt = e.totalAmount || 0;
                          const recvAmt = e.receivedAmount || 0;
                          const balAmt = Math.max(0, totalAmt - recvAmt);
                          return (
                            <div className="bg-slate-50/80 border border-slate-200/70 rounded-xl p-2 px-2.5 text-left font-sans text-xs inline-block shadow-2xs">
                              <div className="flex items-center gap-1.5 mb-0.5">
                                <span className="text-[10px] text-slate-400 font-bold min-w-[18px]">TA:</span>
                                <span className="font-bold text-slate-800 text-xs">৳{totalAmt.toLocaleString()}</span>
                              </div>
                              <div className="flex items-center gap-1.5 mb-1">
                                <span className="text-[10px] text-slate-400 font-bold min-w-[18px]">RA:</span>
                                <span className="font-bold text-teal-600 text-xs">৳{recvAmt.toLocaleString()}</span>
                              </div>
                              <div className="pt-1 border-t border-slate-200/60 flex items-center gap-1.5">
                                <span className="text-[10px] text-slate-400 font-bold min-w-[18px]">BA:</span>
                                <span className="font-bold text-amber-700 text-xs">৳{balAmt.toLocaleString()}</span>
                              </div>
                            </div>
                          );
                        })() : (
                          <span className="text-slate-400 font-medium text-sm">-</span>
                        )}
                      </td>

                      {/* Column 8: ACTION LOGS */}
                      <td className="px-4 py-4 whitespace-nowrap text-right">
                        <button
                          onClick={() => setSelectedEmployee(e)}
                          className="bg-indigo-50 hover:bg-indigo-100 text-indigo-600 font-bold text-[11px] px-3.5 py-1.5 rounded-lg border border-indigo-100 inline-flex items-center gap-1.5 transition cursor-pointer shadow-2xs"
                        >
                          <Eye className="w-3.5 h-3.5" />
                          <span>View</span>
                        </button>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Modal A: "+ New Staff Account" Provisioning Form Modal */}
      {isAddModalOpen && (
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-xs z-50 flex items-center justify-center p-4 overflow-y-auto">
          <div className="bg-white rounded-2xl border border-slate-200 max-w-lg w-full p-6 shadow-2xl space-y-4 my-8">
            <div className="flex items-center justify-between border-b border-slate-100 pb-3">
              <div className="flex items-center space-x-2">
                <div className="p-2 bg-indigo-50 text-indigo-600 rounded-xl">
                  <UserCheck className="w-5 h-5" />
                </div>
                <div>
                  <h3 className="font-extrabold text-slate-900 text-base">New Staff Account</h3>
                  <p className="text-xs text-slate-400">Provision an internal staff user with corporate hierarchy mapping</p>
                </div>
              </div>
              <button
                onClick={() => setIsAddModalOpen(false)}
                className="text-slate-400 hover:text-slate-600 p-1.5 rounded-lg hover:bg-slate-100 transition cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleCreateStaff} className="space-y-3.5 text-xs">
              <div>
                <label className="block font-bold text-slate-700 mb-1">Full Name *</label>
                <input
                  type="text"
                  required
                  value={newStaff.name}
                  onChange={(e) => setNewStaff({ ...newStaff, name: e.target.value })}
                  placeholder="e.g. Abu Turab"
                  className="w-full px-3.5 py-2 border border-slate-200 rounded-xl bg-slate-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500"
                />
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block font-bold text-slate-700 mb-1">Email Address *</label>
                  <input
                    type="email"
                    required
                    value={newStaff.email}
                    onChange={(e) => setNewStaff({ ...newStaff, email: e.target.value })}
                    placeholder="abaplanning2018@gmail.com"
                    className="w-full px-3.5 py-2 border border-slate-200 rounded-xl bg-slate-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500"
                  />
                </div>

                <div>
                  <label className="block font-bold text-slate-700 mb-1">Phone Contact</label>
                  <input
                    type="text"
                    value={newStaff.phone}
                    onChange={(e) => setNewStaff({ ...newStaff, phone: e.target.value })}
                    placeholder="01811489253"
                    className="w-full px-3.5 py-2 border border-slate-200 rounded-xl bg-slate-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 font-mono"
                  />
                </div>
              </div>

              {/* Department Selector */}
              <div>
                <div className="flex items-center justify-between mb-1">
                  <label className="block font-bold text-slate-700">Department</label>
                  <button
                    type="button"
                    onClick={() => setShowCustomDept(!showCustomDept)}
                    className="text-[11px] font-semibold text-indigo-600 hover:underline cursor-pointer"
                  >
                    {showCustomDept ? 'Select Standard Dept' : '+ Custom Dept'}
                  </button>
                </div>
                {showCustomDept ? (
                  <input
                    type="text"
                    required
                    value={customDept}
                    onChange={(e) => setCustomDept(e.target.value)}
                    placeholder="e.g. Special Operations"
                    className="w-full px-3.5 py-2 border border-slate-200 rounded-xl bg-slate-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 font-medium"
                  />
                ) : (
                  <select
                    value={newStaff.department}
                    onChange={(e) => setNewStaff({ ...newStaff, department: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-xl bg-slate-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 font-medium"
                  >
                    {STANDARD_DEPARTMENTS.map((d) => (
                      <option key={d} value={d}>
                        {d}
                      </option>
                    ))}
                  </select>
                )}
              </div>

              {/* Designation Selector (17 Levels) */}
              <div>
                <div className="flex items-center justify-between mb-1">
                  <label className="block font-bold text-slate-700">Designation (Corporate Level)</label>
                  <button
                    type="button"
                    onClick={() => setShowCustomDesig(!showCustomDesig)}
                    className="text-[11px] font-semibold text-indigo-600 hover:underline cursor-pointer"
                  >
                    {showCustomDesig ? 'Select Standard Level' : '+ Custom Designation'}
                  </button>
                </div>
                {showCustomDesig ? (
                  <input
                    type="text"
                    required
                    value={customDesig}
                    onChange={(e) => setCustomDesig(e.target.value)}
                    placeholder="e.g. Chief Risk Officer"
                    className="w-full px-3.5 py-2 border border-slate-200 rounded-xl bg-slate-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 font-medium uppercase"
                  />
                ) : (
                  <select
                    value={newStaff.designation}
                    onChange={(e) => {
                      const des = e.target.value;
                      setNewStaff({ ...newStaff, designation: des, managerId: des.toLowerCase().includes('chairman') ? '' : newStaff.managerId });
                    }}
                    className="w-full px-3 py-2 border border-slate-200 rounded-xl bg-slate-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 font-medium"
                  >
                    {STANDARD_DESIGNATIONS.map((lvl) => (
                      <option key={lvl} value={lvl}>
                        {lvl}
                      </option>
                    ))}
                  </select>
                )}
              </div>

              {/* Reporting Superior / Manager Selector */}
              <div>
                <label className="block font-bold text-slate-700 mb-1">
                  Reporting Superior / Manager *
                  {newStaff.designation.toLowerCase().includes('chairman') && (
                    <span className="text-emerald-600 font-semibold ml-1.5">(Apex Position - Optional)</span>
                  )}
                </label>
                {newStaff.designation.toLowerCase().includes('chairman') ? (
                  <div className="p-2.5 bg-amber-50 border border-amber-200 rounded-xl text-amber-900 font-bold text-[11px]">
                    Apex Chairman / N/A (No reporting manager required)
                  </div>
                ) : (
                  <select
                    required
                    value={newStaff.managerId}
                    onChange={(e) => setNewStaff({ ...newStaff, managerId: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-xl bg-slate-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 font-medium"
                  >
                    <option value="">-- Select Reporting Boss --</option>
                    {employees
                      .filter((emp) => emp.staffId && emp.staffId.startsWith('ASA'))
                      .map((emp) => (
                        <option key={emp.staffId || emp.id} value={emp.staffId || emp.id}>
                          {emp.name} ({emp.staffId}) - {emp.designation || 'Officer'}
                        </option>
                      ))}
                  </select>
                )}
              </div>

              <div>
                <label className="block font-bold text-slate-700 mb-1">Office Address</label>
                <input
                  type="text"
                  value={newStaff.address}
                  onChange={(e) => setNewStaff({ ...newStaff, address: e.target.value })}
                  placeholder="Dhaka, Bangladesh"
                  className="w-full px-3.5 py-2 border border-slate-200 rounded-xl bg-slate-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500"
                />
              </div>

              <div>
                <label className="block font-bold text-slate-700 mb-1">Account Password</label>
                <input
                  type="password"
                  value={newStaff.password}
                  onChange={(e) => setNewStaff({ ...newStaff, password: e.target.value })}
                  placeholder="Default password (123456)"
                  className="w-full px-3.5 py-2 border border-slate-200 rounded-xl bg-slate-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500"
                />
              </div>

              <div className="pt-3 flex items-center justify-end space-x-2 border-t border-slate-100">
                <button
                  type="button"
                  onClick={() => setIsAddModalOpen(false)}
                  className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold rounded-xl text-xs transition cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="px-5 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl text-xs transition shadow-2xs cursor-pointer"
                >
                  {isSubmitting ? 'Provisioning...' : 'Provision Staff Record'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Modal B: "Staff Profile & Action Audit Log" View Modal */}
      {selectedEmployee && (
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-xs z-50 flex items-center justify-center p-4 overflow-y-auto">
          <div className="bg-white rounded-2xl border border-slate-200 max-w-2xl w-full p-6 shadow-2xl space-y-6 my-8 max-h-[90vh] overflow-y-auto">
            {/* Header */}
            <div className="flex items-start justify-between border-b border-slate-100 pb-4">
              <div className="flex items-center space-x-4">
                <div className="w-14 h-14 rounded-2xl bg-indigo-600 text-white flex items-center justify-center font-bold text-lg uppercase shadow-xs">
                  {selectedEmployee.name.slice(0, 2)}
                </div>
                <div>
                  <div className="flex items-center space-x-2">
                    <h3 className="font-extrabold text-slate-900 text-lg">{selectedEmployee.name}</h3>
                    <span className="bg-indigo-50 text-indigo-700 border border-indigo-200 font-mono text-xs px-2.5 py-0.5 rounded-md font-bold">
                      {selectedEmployee.staffId || selectedEmployee.id}
                    </span>
                  </div>
                  <p className="text-xs text-slate-500 font-medium mt-0.5">
                    {selectedEmployee.department || 'Management'} • <span className="uppercase font-bold text-indigo-600">{selectedEmployee.designation}</span>
                  </p>
                </div>
              </div>
              <button
                onClick={() => setSelectedEmployee(null)}
                className="text-slate-400 hover:text-slate-600 p-1.5 rounded-lg hover:bg-slate-100 transition cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Quick Management Actions Toolbar */}
            <div className="flex flex-wrap items-center justify-between gap-3 bg-slate-50 p-3.5 rounded-xl border border-slate-200/80 shadow-2xs">
              <div className="flex items-center gap-2">
                <span className="text-xs font-bold text-slate-500 uppercase tracking-wider font-mono">Account Status:</span>
                <span className={`font-bold px-2.5 py-1 rounded-md border text-xs flex items-center gap-1.5 ${
                  selectedEmployee.staffStatus === 'Hold'
                    ? 'text-amber-800 bg-amber-50 border-amber-300'
                    : 'text-emerald-800 bg-emerald-50 border-emerald-300'
                }`}>
                  <CheckCircle2 className={`w-3.5 h-3.5 ${selectedEmployee.staffStatus === 'Hold' ? 'text-amber-600' : 'text-emerald-600'}`} />
                  <span>{selectedEmployee.staffStatus || 'Active'}</span>
                </span>
              </div>

              <div className="flex items-center gap-2">
                {selectedEmployee.staffStatus === 'Hold' ? (
                  <button
                    type="button"
                    onClick={() => handleToggleStatus(selectedEmployee)}
                    className="bg-emerald-50 hover:bg-emerald-100 text-emerald-700 font-bold text-xs px-3 py-1.5 rounded-lg border border-emerald-200 inline-flex items-center gap-1.5 transition cursor-pointer shadow-2xs"
                  >
                    <PlayCircle className="w-3.5 h-3.5 text-emerald-600" />
                    <span>Activate Account</span>
                  </button>
                ) : (
                  <button
                    type="button"
                    onClick={() => handleToggleStatus(selectedEmployee)}
                    className="bg-amber-50 hover:bg-amber-100 text-amber-700 font-bold text-xs px-3 py-1.5 rounded-lg border border-amber-200 inline-flex items-center gap-1.5 transition cursor-pointer shadow-2xs"
                  >
                    <PauseCircle className="w-3.5 h-3.5 text-amber-600" />
                    <span>Put on Hold</span>
                  </button>
                )}

                <button
                  type="button"
                  onClick={() => handleDeleteStaff(selectedEmployee)}
                  className="bg-rose-50 hover:bg-rose-100 text-rose-600 font-bold text-xs px-3 py-1.5 rounded-lg border border-rose-200 inline-flex items-center gap-1.5 transition cursor-pointer shadow-2xs"
                >
                  <Trash2 className="w-3.5 h-3.5 text-rose-600" />
                  <span>Delete Account</span>
                </button>
              </div>
            </div>

            {/* Profile Info Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-xs bg-slate-50/70 p-4 rounded-xl border border-slate-200/80">
              <div className="space-y-2">
                <div className="flex items-center space-x-2 text-slate-600">
                  <Phone className="w-3.5 h-3.5 text-slate-400" />
                  <span className="font-semibold">{selectedEmployee.phone || '01811489253'}</span>
                </div>
                <div className="flex items-center space-x-2 text-slate-600">
                  <FileText className="w-3.5 h-3.5 text-slate-400" />
                  <span className="font-semibold">{selectedEmployee.email}</span>
                </div>
              </div>
              <div className="space-y-2">
                <div className="flex items-center space-x-2 text-slate-600">
                  <MapPin className="w-3.5 h-3.5 text-slate-400" />
                  <span className="font-semibold">{selectedEmployee.address || 'Dhaka, Bangladesh'}</span>
                </div>
                <div className="flex items-center space-x-2">
                  <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />
                  <span className="font-bold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200 text-[10px]">
                    Status: {selectedEmployee.staffStatus || 'Active'}
                  </span>
                </div>
              </div>
            </div>

            {/* Edit Department, Designation & Reporting Superior Section */}
            <div className="bg-indigo-50/60 border border-indigo-200/80 rounded-2xl p-4 space-y-3 shadow-2xs">
              <div className="flex items-center justify-between border-b border-indigo-100 pb-2">
                <h4 className="font-bold text-slate-900 text-xs uppercase tracking-wider font-mono flex items-center gap-1.5">
                  <Edit3 className="w-4 h-4 text-indigo-600" />
                  <span>Update Staff Credentials & Superior</span>
                </h4>
                <span className="text-[10px] bg-indigo-100/80 text-indigo-700 px-2.5 py-0.5 rounded-md font-bold border border-indigo-200">
                  Admin Editable
                </span>
              </div>

              {updateMessage && (
                <div className={`p-2.5 rounded-xl text-xs font-medium flex items-center justify-between ${
                  updateMessage.type === 'success' 
                    ? 'bg-emerald-50 text-emerald-800 border border-emerald-200' 
                    : 'bg-rose-50 text-rose-800 border border-rose-200'
                }`}>
                  <span>{updateMessage.text}</span>
                  <button onClick={() => setUpdateMessage(null)} className="text-slate-400 hover:text-slate-600">
                    <X className="w-3.5 h-3.5" />
                  </button>
                </div>
              )}

              <form onSubmit={handleSaveEmployeeEdits} className="space-y-3 text-xs">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                  {/* 1. Department */}
                  <div>
                    <label className="block text-[11px] font-bold text-slate-700 mb-1">
                      Department <span className="text-rose-500">*</span>
                    </label>
                    <select
                      value={editDept}
                      onChange={(e) => setEditDept(e.target.value)}
                      className="w-full px-2.5 py-1.5 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 text-xs font-medium shadow-2xs"
                    >
                      {STANDARD_DEPARTMENTS.map((dept) => (
                        <option key={dept} value={dept}>{dept}</option>
                      ))}
                      {!STANDARD_DEPARTMENTS.includes(editDept) && editDept && (
                        <option value={editDept}>{editDept}</option>
                      )}
                    </select>
                  </div>

                  {/* 2. Designation */}
                  <div>
                    <label className="block text-[11px] font-bold text-slate-700 mb-1">
                      Designation <span className="text-rose-500">*</span>
                    </label>
                    <select
                      value={editDesig}
                      onChange={(e) => {
                        const val = e.target.value;
                        setEditDesig(val);
                        if (val.toLowerCase().includes('chairman')) {
                          setEditManagerId('');
                        }
                      }}
                      className="w-full px-2.5 py-1.5 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 text-xs font-medium shadow-2xs"
                    >
                      {STANDARD_DESIGNATIONS.map((desig) => (
                        <option key={desig} value={desig}>{desig}</option>
                      ))}
                      {!STANDARD_DESIGNATIONS.includes(editDesig) && editDesig && (
                        <option value={editDesig}>{editDesig}</option>
                      )}
                    </select>
                  </div>

                  {/* 3. Reporting Superior / Manager */}
                  <div>
                    <label className="block text-[11px] font-bold text-slate-700 mb-1">
                      Reporting Superior / Manager {!editDesig.toLowerCase().includes('chairman') && <span className="text-rose-500">*</span>}
                    </label>
                    {editDesig.toLowerCase().includes('chairman') ? (
                      <input
                        type="text"
                        disabled
                        value="None (Chairman - Top Level)"
                        className="w-full px-2.5 py-1.5 border border-slate-200 rounded-lg bg-slate-100 text-slate-500 text-xs font-medium"
                      />
                    ) : (
                      <select
                        value={editManagerId}
                        onChange={(e) => setEditManagerId(e.target.value)}
                        className="w-full px-2.5 py-1.5 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 text-xs font-medium shadow-2xs"
                      >
                        <option value="">-- Select Reporting Boss --</option>
                        {employees
                          .filter((emp) => 
                            emp.staffId && 
                            emp.staffId.startsWith('ASA') && 
                            emp.id !== selectedEmployee.id && 
                            emp.staffId !== selectedEmployee.staffId
                          )
                          .map((emp) => (
                            <option key={emp.staffId || emp.id} value={emp.staffId || emp.id}>
                              {emp.name} ({emp.staffId}) - {emp.designation || 'Officer'}
                            </option>
                          ))}
                      </select>
                    )}
                  </div>
                </div>

                <div className="flex justify-end pt-1">
                  <button
                    type="submit"
                    disabled={isUpdating}
                    className="bg-indigo-600 hover:bg-indigo-700 text-white font-bold px-4 py-1.5 rounded-lg text-xs transition shadow-xs flex items-center space-x-1.5 cursor-pointer disabled:opacity-50"
                  >
                    <Save className="w-3.5 h-3.5" />
                    <span>{isUpdating ? 'Saving...' : 'Save Changes'}</span>
                  </button>
                </div>
              </form>
            </div>

            {/* Reporting Hierarchy Section */}
            <div className="space-y-3">
              <h4 className="font-bold text-slate-900 text-xs uppercase tracking-wider font-mono flex items-center gap-1.5">
                <GitCommit className="w-4 h-4 text-indigo-500" />
                <span>Reporting Hierarchy Mapping</span>
              </h4>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                {/* My Boss */}
                <div className="p-3.5 bg-amber-50/80 border border-amber-200 rounded-xl space-y-1">
                  <span className="text-[10px] font-bold text-amber-800 uppercase tracking-wider block">Assigned Superior (Boss)</span>
                  <p className="font-extrabold text-slate-900 text-xs">{selectedEmployee.reportingHierarchy || 'Apex Chairman / N/A'}</p>
                </div>

                {/* Subordinates Count */}
                <div className="p-3.5 bg-blue-50/80 border border-blue-200 rounded-xl space-y-1">
                  <span className="text-[10px] font-bold text-blue-800 uppercase tracking-wider block">Direct Subordinates</span>
                  <p className="font-extrabold text-slate-900 text-xs">
                    {selectedEmployee.subordinatesCount || 0} Direct Reporting Staff
                  </p>
                </div>
              </div>

              {/* Subordinates List */}
              {selectedEmployee.subordinates && selectedEmployee.subordinates.length > 0 && (
                <div className="mt-2 bg-white border border-slate-200 rounded-xl p-3 space-y-2">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Subordinate Team Members:</span>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                    {selectedEmployee.subordinates.map((sub: any) => (
                      <div key={sub.id} className="flex items-center justify-between p-2 bg-slate-50 rounded-lg text-xs border border-slate-100">
                        <div>
                          <p className="font-bold text-slate-800">{sub.name}</p>
                          <p className="text-[10px] text-slate-500">{sub.department} • {sub.designation}</p>
                        </div>
                        <span className="font-mono text-[10px] font-bold text-slate-400">{sub.staffId}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Performance Metrics */}
            <div className="space-y-3">
              <h4 className="font-bold text-slate-900 text-xs uppercase tracking-wider font-mono flex items-center gap-1.5">
                <Briefcase className="w-4 h-4 text-emerald-500" />
                <span>Operational & Order Performance</span>
              </h4>

              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-center">
                <div className="bg-slate-50 p-3 rounded-xl border border-slate-200/80">
                  <span className="text-[10px] font-bold text-slate-400 uppercase block">Confirm Order</span>
                  <p className="font-mono font-bold text-slate-900 text-xs mt-1">
                    {isMetricVisible(selectedEmployee.designation) && selectedEmployee.orderQty ? `${selectedEmployee.orderQty.toLocaleString()} pcs` : '-'}
                  </p>
                </div>
                <div className="bg-slate-50 p-3 rounded-xl border border-slate-200/80">
                  <span className="text-[10px] font-bold text-slate-400 uppercase block">Ship Qty</span>
                  <p className="font-mono font-bold text-slate-900 text-xs mt-1">
                    {isMetricVisible(selectedEmployee.designation) && selectedEmployee.shipQty ? `${selectedEmployee.shipQty.toLocaleString()} pcs` : '-'}
                  </p>
                </div>
                <div className="bg-slate-50 p-3 rounded-xl border border-slate-200/80">
                  <span className="text-[10px] font-bold text-slate-400 uppercase block">Total Amount</span>
                  <p className="font-mono font-bold text-slate-900 text-xs mt-1">
                    {isMetricVisible(selectedEmployee.designation) && selectedEmployee.totalAmount ? `৳${selectedEmployee.totalAmount.toLocaleString()}` : '-'}
                  </p>
                </div>
                <div className="bg-slate-50 p-3 rounded-xl border border-slate-200/80">
                  <span className="text-[10px] font-bold text-slate-400 uppercase block">Received Amount</span>
                  <p className="font-mono font-bold text-slate-900 text-xs mt-1">
                    {isMetricVisible(selectedEmployee.designation) && selectedEmployee.receivedAmount ? `৳${selectedEmployee.receivedAmount.toLocaleString()}` : '-'}
                  </p>
                </div>
              </div>
            </div>

            {/* System Action Audit Log Timeline */}
            <div className="space-y-3">
              <h4 className="font-bold text-slate-900 text-xs uppercase tracking-wider font-mono flex items-center gap-1.5">
                <Clock className="w-4 h-4 text-blue-500" />
                <span>System Action Audit Log</span>
              </h4>

              <div className="border border-slate-200 rounded-xl p-3 bg-slate-50/50 space-y-3 max-h-40 overflow-y-auto">
                {selectedEmployee.auditLogs && selectedEmployee.auditLogs.length > 0 ? (
                  selectedEmployee.auditLogs.map((log: any) => (
                    <div key={log.id} className="flex items-start space-x-3 text-xs border-b border-slate-100 pb-2 last:border-none last:pb-0">
                      <div className="w-2 h-2 rounded-full bg-indigo-500 mt-1 shrink-0" />
                      <div className="flex-1">
                        <div className="flex items-center justify-between">
                          <span className="font-bold text-slate-800">{log.action}</span>
                          <span className="text-[10px] font-mono text-slate-400">
                            {new Date(log.timestamp).toLocaleDateString()}
                          </span>
                        </div>
                        <p className="text-[11px] text-slate-500 mt-0.5">{log.details}</p>
                      </div>
                    </div>
                  ))
                ) : (
                  <p className="text-xs text-slate-400 text-center py-2">No activity logs recorded yet.</p>
                )}
              </div>
            </div>

            {/* Footer */}
            <div className="pt-2">
              <button
                onClick={() => setSelectedEmployee(null)}
                className="w-full bg-slate-900 hover:bg-slate-800 text-white font-bold py-2.5 rounded-xl text-xs transition cursor-pointer shadow-xs"
              >
                Close Audit Record
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
