'use client';
import { useState } from 'react';
import { usePerformanceStore } from '../../../lib/performanceStore';
import { motion } from 'framer-motion';

const BRAND = '#b828a0';

const RATING_BG: Record<number, string> = {
  1: 'bg-red-100 text-red-700',
  2: 'bg-orange-100 text-orange-700',
  3: 'bg-amber-100 text-amber-700',
  4: 'bg-blue-100 text-blue-700',
  5: 'bg-green-100 text-green-700',
};

const RATING_LABELS: Record<number, string> = {
  1: 'Poor',
  2: 'Needs Improvement',
  3: 'Meets Expectations',
  4: 'Exceeds Expectations',
  5: 'Outstanding',
};

// Helper to get unique departments from all performance data
const getUniqueDepartments = (employees: any[]) => {
  const depts = new Set(employees.map(e => e.dept).filter(Boolean));
  return ['All', ...Array.from(depts)];
};

// Staff Performance Modal Component
function StaffPerformanceModal({ 
  employee, 
  onClose,
  workPlans,
  kpis,
  quarterlyTargets,
  ipis,
  pips,
  appraisal,
  companyGoals,
  onAddComment
}: { 
  employee: { id: string; name: string; role: string; dept: string; employeeType: string; hod: string };
  onClose: () => void;
  workPlans: any[];
  kpis: any[];
  quarterlyTargets: any[];
  ipis: any[];
  pips: any[];
  appraisal: any;
  companyGoals: any[];
  onAddComment: (comment: string, itemType: string, itemId: string, itemTitle: string) => void;
}) {
  const [activeTab, setActiveTab] = useState<'workplans' | 'kpis' | 'quarterly' | 'ipis' | 'pips' | 'appraisal'>('workplans');
  const [hrComment, setHrComment] = useState('');

  const TYPE_COLORS: Record<string, string> = {
    workplans: '#2563eb',
    kpis: '#7c3aed',
    quarterly: '#d97706',
    ipis: '#059669',
    pips: '#dc2626',
    appraisal: '#b828a0',
  };

  const TYPE_ICONS: Record<string, string> = {
    workplans: 'ri-file-list-3-line',
    kpis: 'ri-bar-chart-line',
    quarterly: 'ri-calendar-check-line',
    ipis: 'ri-line-chart-line',
    pips: 'ri-file-copy-line',
    appraisal: 'ri-star-line',
  };

  const TYPE_LABELS: Record<string, string> = {
    workplans: 'Work Plans',
    kpis: 'KPIs',
    quarterly: 'Quarterly Targets',
    ipis: 'Individual Performance Indicators',
    pips: 'Performance Improvement Plans',
    appraisal: 'Appraisal',
  };

  const calculateProgress = (current: number, target: number): number => {
    if (target === 0) return 0;
    return Math.min(100, Math.round((current / target) * 100));
  };

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-5xl max-h-[90vh] overflow-y-auto">
        <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between sticky top-0 bg-white z-10" style={{ background: BRAND }}>
          <div>
            <h3 className="font-bold text-white text-lg">{employee.name}</h3>
            <p className="text-pink-200 text-xs">{employee.role} · {employee.dept} · {employee.employeeType} · HOD: {employee.hod}</p>
          </div>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center cursor-pointer">
            <i className="ri-close-line text-white text-xl"></i>
          </button>
        </div>

        <div className="p-6">
          {/* Quick Stats */}
          <div className="grid grid-cols-6 gap-3 mb-6">
            <div className="bg-blue-50 rounded-xl p-3 text-center">
              <p className="text-2xl font-bold text-blue-700">{workPlans.length}</p>
              <p className="text-xs text-gray-600">Work Plans</p>
            </div>
            <div className="bg-purple-50 rounded-xl p-3 text-center">
              <p className="text-2xl font-bold text-purple-700">{kpis.length}</p>
              <p className="text-xs text-gray-600">KPIs</p>
            </div>
            <div className="bg-amber-50 rounded-xl p-3 text-center">
              <p className="text-2xl font-bold text-amber-700">{quarterlyTargets.length}</p>
              <p className="text-xs text-gray-600">Quarterly Targets</p>
            </div>
            <div className="bg-green-50 rounded-xl p-3 text-center">
              <p className="text-2xl font-bold text-green-700">{ipis.length}</p>
              <p className="text-xs text-gray-600">IPIs</p>
            </div>
            <div className="bg-red-50 rounded-xl p-3 text-center">
              <p className="text-2xl font-bold text-red-700">{pips.length}</p>
              <p className="text-xs text-gray-600">PIPs</p>
            </div>
            <div className="bg-pink-50 rounded-xl p-3 text-center">
              <p className="text-2xl font-bold text-pink-700">{appraisal ? 1 : 0}</p>
              <p className="text-xs text-gray-600">Appraisal</p>
            </div>
          </div>

          {/* Tabs */}
          <div className="flex gap-1 border-b border-gray-200 mb-4 overflow-x-auto">
            {(['workplans', 'kpis', 'quarterly', 'ipis', 'pips', 'appraisal'] as const).map(tab => (
              <button
                key={tab}
                onClick={() => setActiveTab(tab)}
                className={`flex items-center gap-2 px-4 py-2 text-sm font-medium transition-all cursor-pointer whitespace-nowrap ${
                  activeTab === tab ? 'border-b-2 text-gray-800' : 'text-gray-500 hover:text-gray-700'
                }`}
                style={activeTab === tab ? { borderBottomColor: BRAND, color: BRAND } : {}}
              >
                <i className={TYPE_ICONS[tab]}></i>
                {TYPE_LABELS[tab]}
              </button>
            ))}
          </div>

          {/* Work Plans Content */}
          {activeTab === 'workplans' && (
            <div>
              {workPlans.length === 0 ? (
                <div className="text-center py-12 text-gray-400">
                  <i className="ri-file-list-3-line text-5xl block mb-3"></i>
                  <p>No work plans submitted yet</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {workPlans.map(wp => (
                    <div key={wp.id} className="bg-gray-50 rounded-xl p-4 border border-gray-100">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <h4 className="font-semibold text-gray-800">{wp.objective}</h4>
                          <p className="text-xs text-gray-500 mt-1">Target: {wp.target}</p>
                          <p className="text-xs text-gray-500">Due: {wp.dueDate}</p>
                          {wp.linkedTarget && (
                            <p className="text-xs text-gray-400 mt-1">Linked to: {wp.linkedTarget}</p>
                          )}
                        </div>
                        <div className="text-right">
                          <span className={`text-xs px-2.5 py-1 rounded-full font-semibold ${
                            wp.status === 'Completed' ? 'bg-green-100 text-green-700' : 
                            wp.status === 'In Progress' ? 'bg-blue-100 text-blue-700' : 
                            'bg-gray-100 text-gray-600'
                          }`}>
                            {wp.status}
                          </span>
                        </div>
                      </div>
                      <div className="mt-3">
                        <div className="flex items-center gap-2">
                          <div className="flex-1 bg-gray-200 rounded-full h-2">
                            <div className="h-2 rounded-full" style={{ width: `${wp.progress}%`, background: BRAND }}></div>
                          </div>
                          <span className="text-xs font-semibold text-gray-700">{wp.progress}%</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* KPIs Content */}
          {activeTab === 'kpis' && (
            <div>
              {kpis.length === 0 ? (
                <div className="text-center py-12 text-gray-400">
                  <i className="ri-bar-chart-line text-5xl block mb-3"></i>
                  <p>No KPIs submitted yet</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {kpis.map(kpi => (
                    <div key={kpi.id} className="bg-gray-50 rounded-xl p-4 border border-gray-100">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <h4 className="font-semibold text-gray-800">{kpi.kpiName}</h4>
                          <p className="text-xs text-gray-500 mt-1">{kpi.description}</p>
                          <div className="flex gap-3 mt-2 flex-wrap">
                            <p className="text-xs text-gray-500">Target: {kpi.target} {kpi.unit}</p>
                            <p className="text-xs text-gray-500">Current: {kpi.current} {kpi.unit}</p>
                            <p className="text-xs text-gray-500">Period: {kpi.period}</p>
                          </div>
                        </div>
                        <div className="text-right">
                          <span className={`text-xs px-2.5 py-1 rounded-full font-semibold ${
                            kpi.status === 'Completed' ? 'bg-green-100 text-green-700' : 
                            kpi.status === 'Active' ? 'bg-blue-100 text-blue-700' : 
                            'bg-red-100 text-red-700'
                          }`}>
                            {kpi.status}
                          </span>
                        </div>
                      </div>
                      <div className="mt-3">
                        <div className="flex items-center gap-2">
                          <div className="flex-1 bg-gray-200 rounded-full h-2">
                            <div className="h-2 rounded-full" style={{ width: `${kpi.progress}%`, background: BRAND }}></div>
                          </div>
                          <span className="text-xs font-semibold text-gray-700">{kpi.progress}%</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Quarterly Targets Content */}
          {activeTab === 'quarterly' && (
            <div>
              {quarterlyTargets.length === 0 ? (
                <div className="text-center py-12 text-gray-400">
                  <i className="ri-calendar-check-line text-5xl block mb-3"></i>
                  <p>No quarterly targets submitted yet</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {quarterlyTargets.map(qt => (
                    <div key={qt.id} className="bg-gray-50 rounded-xl p-4 border border-gray-100">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <span className="text-xs font-semibold px-2 py-0.5 rounded-full bg-purple-100 text-purple-700">{qt.quarter}</span>
                          </div>
                          <h4 className="font-semibold text-gray-800">{qt.title}</h4>
                          <p className="text-xs text-gray-500 mt-1">{qt.description}</p>
                          <p className="text-xs text-gray-500 mt-1">Target: {qt.target} {qt.unit || ''}</p>
                          <p className="text-xs text-gray-500">Due: {qt.dueDate}</p>
                        </div>
                        <div className="text-right">
                          <span className={`text-xs px-2.5 py-1 rounded-full font-semibold ${
                            qt.status === 'Completed' ? 'bg-green-100 text-green-700' : 
                            qt.status === 'In Progress' ? 'bg-blue-100 text-blue-700' : 
                            qt.status === 'Delayed' ? 'bg-red-100 text-red-700' : 
                            'bg-gray-100 text-gray-600'
                          }`}>
                            {qt.status}
                          </span>
                        </div>
                      </div>
                      <div className="mt-3">
                        <div className="flex items-center gap-2">
                          <div className="flex-1 bg-gray-200 rounded-full h-2">
                            <div className="h-2 rounded-full" style={{ width: `${qt.progress}%`, background: BRAND }}></div>
                          </div>
                          <span className="text-xs font-semibold text-gray-700">{qt.progress}%</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* IPIs Content */}
          {activeTab === 'ipis' && (
            <div>
              {ipis.length === 0 ? (
                <div className="text-center py-12 text-gray-400">
                  <i className="ri-line-chart-line text-5xl block mb-3"></i>
                  <p>No IPIs submitted yet</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {ipis.map(ipi => (
                    <div key={ipi.id} className="bg-gray-50 rounded-xl p-4 border border-gray-100">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <h4 className="font-semibold text-gray-800">{ipi.indicator}</h4>
                          <div className="flex gap-3 mt-2 flex-wrap">
                            <p className="text-xs text-gray-500">Baseline: {ipi.baseline} {ipi.unit}</p>
                            <p className="text-xs text-gray-500">Target: {ipi.target} {ipi.unit}</p>
                            <p className="text-xs text-gray-500">Current: {ipi.current} {ipi.unit}</p>
                          </div>
                          {ipi.workPlan && (
                            <p className="text-xs text-gray-400 mt-1">Linked to: {ipi.workPlan.objective}</p>
                          )}
                        </div>
                      </div>
                      <div className="mt-3">
                        <div className="flex items-center gap-2">
                          <div className="flex-1 bg-gray-200 rounded-full h-2">
                            <div className="h-2 rounded-full" style={{ width: `${ipi.progress}%`, background: BRAND }}></div>
                          </div>
                          <span className="text-xs font-semibold text-gray-700">{ipi.progress}%</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* PIPs Content */}
          {activeTab === 'pips' && (
            <div>
              {pips.length === 0 ? (
                <div className="text-center py-12 text-gray-400">
                  <i className="ri-file-copy-line text-5xl block mb-3"></i>
                  <p>No Performance Improvement Plans submitted yet</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {pips.map(pip => (
                    <div key={pip.id} className="bg-gray-50 rounded-xl p-4 border border-gray-100">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <h4 className="font-semibold text-gray-800">{pip.title}</h4>
                          <p className="text-xs text-gray-500 mt-1">{pip.description}</p>
                          <div className="flex gap-3 mt-2">
                            <p className="text-xs text-gray-500">Start: {pip.startDate}</p>
                            <p className="text-xs text-gray-500">End: {pip.endDate}</p>
                          </div>
                          {pip.improvementAreas && (
                            <p className="text-xs text-gray-500 mt-1">Areas: {pip.improvementAreas}</p>
                          )}
                        </div>
                        <div className="text-right">
                          <span className={`text-xs px-2.5 py-1 rounded-full font-semibold ${
                            pip.status === 'Completed' ? 'bg-green-100 text-green-700' : 
                            pip.status === 'In Progress' ? 'bg-blue-100 text-blue-700' : 
                            'bg-red-100 text-red-700'
                          }`}>
                            {pip.status}
                          </span>
                        </div>
                      </div>
                      <div className="mt-3">
                        <div className="flex items-center gap-2">
                          <div className="flex-1 bg-gray-200 rounded-full h-2">
                            <div className="h-2 rounded-full" style={{ width: `${pip.progress}%`, background: BRAND }}></div>
                          </div>
                          <span className="text-xs font-semibold text-gray-700">{pip.progress}%</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Appraisal Content */}
          {activeTab === 'appraisal' && (
            <div>
              {!appraisal ? (
                <div className="text-center py-12 text-gray-400">
                  <i className="ri-star-line text-5xl block mb-3"></i>
                  <p>No appraisal submitted yet</p>
                </div>
              ) : (
                <div className="space-y-4">
                  <div className="bg-gray-50 rounded-xl p-4">
                    <p className="text-sm font-semibold text-gray-700 mb-2">Appraisal Details — {appraisal.period}</p>
                    <div className="grid grid-cols-2 gap-3 mb-3">
                      <div>
                        <p className="text-xs text-gray-500">Status</p>
                        <p className="text-sm font-medium">{appraisal.status}</p>
                      </div>
                      <div>
                        <p className="text-xs text-gray-500">Overall Rating</p>
                        <p className="text-sm font-bold" style={{ color: BRAND }}>{appraisal.overallRating?.toFixed(1)}/5</p>
                      </div>
                    </div>
                    <div className="mt-2">
                      <p className="text-xs text-gray-500">Self Assessment Comments</p>
                      <p className="text-sm text-gray-700">{appraisal.selfAssessmentComments || '—'}</p>
                    </div>
                    {appraisal.hodComments && (
                      <div className="mt-2">
                        <p className="text-xs text-gray-500">HOD Comments</p>
                        <p className="text-sm text-gray-700">{appraisal.hodComments}</p>
                      </div>
                    )}
                  </div>

                  {appraisal.companyGoalRatings && appraisal.companyGoalRatings.length > 0 && (
                    <div className="bg-gray-50 rounded-xl p-4">
                      <p className="text-sm font-semibold text-gray-700 mb-2">Goal Ratings</p>
                      <div className="space-y-2">
                        {appraisal.companyGoalRatings.map((rating: any) => {
                          const goal = companyGoals.find((g: any) => g.id === rating.goalId);
                          return (
                            <div key={rating.goalId} className="border-b border-gray-200 pb-2 last:border-0">
                              <p className="text-xs font-medium text-gray-700">{goal?.title || rating.goalId}</p>
                              <div className="flex gap-3 mt-1">
                                <span className="text-xs text-gray-500">Self: {rating.selfRating}/5</span>
                                {rating.hodRating && <span className="text-xs text-gray-500">HOD: {rating.hodRating}/5</span>}
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          )}
        </div>

        <div className="px-6 py-4 border-t border-gray-100 bg-gray-50 flex items-center justify-between">
          <div className="flex-1 flex gap-2">
            <input value={hrComment} onChange={e => setHrComment(e.target.value)}
              placeholder="Add HR comment on any performance item above..."
              className="flex-1 border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
            <button onClick={() => {
              if (!hrComment.trim() || !activeTab) return;
              const items = activeTab === 'workplans' ? workPlans : activeTab === 'kpis' ? kpis : activeTab === 'quarterly' ? quarterlyTargets : activeTab === 'ipis' ? ipis : pips;
              const firstItem = items[0];
              if (!firstItem) return;
              onAddComment(hrComment.trim(), activeTab as any, firstItem.id || '', activeTab);
              setHrComment('');
            }} disabled={!hrComment.trim()}
              className="px-3 py-2 rounded-lg text-sm font-medium text-white cursor-pointer disabled:opacity-40 whitespace-nowrap"
              style={{ background: '#b828a0' }}>
              <i className="ri-send-plane-line"></i>
            </button>
          </div>
          <button onClick={onClose} className="ml-3 px-5 py-2.5 bg-gray-200 rounded-xl text-sm text-gray-700 cursor-pointer whitespace-nowrap hover:bg-gray-300">
            Close
          </button>
        </div>
      </div>
    </div>
  );
}

export default function StaffPerformanceTab() {
  const [search, setSearch] = useState('');
  const [deptFilter, setDeptFilter] = useState('All');
  const [selectedEmp, setSelectedEmp] = useState<any>(null);
  
  const { 
    workPlans, 
    kpis, 
    quarterlyTargets, 
    ipis, 
    pips,
    appraisals,
    companyGoals,
    employees,
    addComment
  } = usePerformanceStore();

  // Get all unique employees from performance data
  const allEmployees = employees.length > 0 ? employees : [
    ...workPlans.map(w => ({ id: w.employeeId, name: w.employee, dept: w.department, role: w.role || 'Staff', employeeType: w.employeeType || 'Employee', hod: w.hod || 'N/A' })),
    ...kpis.map(k => ({ id: k.employeeId, name: k.employee, dept: k.department, role: k.role || 'Staff', employeeType: k.employeeType || 'Employee', hod: k.hod || 'N/A' })),
    ...quarterlyTargets.map(q => ({ id: q.employeeId, name: q.employee, dept: q.department, role: q.role || 'Staff', employeeType: q.employeeType || 'Employee', hod: q.hod || 'N/A' })),
    ...ipis.map(i => ({ id: i.employeeId, name: i.employee, dept: i.department, role: i.role || 'Staff', employeeType: i.employeeType || 'Employee', hod: i.hod || 'N/A' })),
    ...pips.map(p => ({ id: p.employeeId, name: p.employee, dept: p.department, role: p.role || 'Staff', employeeType: p.employeeType || 'Employee', hod: p.hod || 'N/A' })),
  ];

  // Deduplicate employees by ID
  const uniqueEmployees = Array.from(new Map(allEmployees.map(emp => [emp.id, emp])).values());

  const DEPTS = getUniqueDepartments(uniqueEmployees);

  const filtered = uniqueEmployees.filter(emp => {
    const ms = deptFilter === 'All' || emp.dept === deptFilter;
    const mq = !search || emp.name.toLowerCase().includes(search.toLowerCase()) || emp.id.toLowerCase().includes(search.toLowerCase());
    return ms && mq;
  });

  // Get performance data for a specific employee
  const getStaffPerformanceData = (employeeId: string, employeeName: string) => {
    return {
      workPlans: workPlans.filter(w => w.employeeId === employeeId || w.employee === employeeName),
      kpis: kpis.filter(k => k.employeeId === employeeId || k.employee === employeeName),
      quarterlyTargets: quarterlyTargets.filter(q => q.employeeId === employeeId || q.employee === employeeName),
      ipis: ipis.filter(i => i.employeeId === employeeId || i.employee === employeeName),
      pips: pips.filter(p => p.employeeId === employeeId || p.employee === employeeName),
      appraisal: appraisals.find(a => a.employeeId === employeeId),
    };
  };

  // Get stats counts for an employee
  const getStaffStats = (employeeId: string, employeeName: string) => {
    const staffWorkPlans = workPlans.filter(w => w.employeeId === employeeId || w.employee === employeeName);
    const staffKPIs = kpis.filter(k => k.employeeId === employeeId || k.employee === employeeName);
    const staffQuarterly = quarterlyTargets.filter(q => q.employeeId === employeeId || q.employee === employeeName);
    const staffIPIs = ipis.filter(i => i.employeeId === employeeId || i.employee === employeeName);
    const staffPIPs = pips.filter(p => p.employeeId === employeeId || p.employee === employeeName);
    
    return {
      workPlansCount: staffWorkPlans.length,
      kpisCount: staffKPIs.length,
      quarterlyCount: staffQuarterly.length,
      ipisCount: staffIPIs.length,
      pipsCount: staffPIPs.length,
    };
  };

  // Get avatar initials
  const getAvatar = (name: string) => {
    return name.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase();
  };

  return (
    <div>
      <div className="flex items-center gap-3 flex-wrap mb-5">
        <div className="relative">
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search staff..."
            className="bg-white border border-gray-200 rounded-lg px-4 py-2 text-sm w-52 outline-none pr-8" />
          <div className="w-4 h-4 flex items-center justify-center absolute right-3 top-1/2 -translate-y-1/2">
            <i className="ri-search-line text-gray-400 text-sm"></i>
          </div>
        </div>
        <div className="flex gap-1">
          {DEPTS.map(d => (
            <button key={d} onClick={() => setDeptFilter(d)}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${deptFilter === d ? 'text-white' : 'bg-gray-100 text-gray-600'}`}
              style={deptFilter === d ? { background: BRAND } : {}}>
              {d === 'All' ? 'All Depts' : d}
            </button>
          ))}
        </div>
        <span className="text-xs text-gray-400 ml-auto">{filtered.length} staff</span>
      </div>

      <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-gray-50 border-b border-gray-100">
                {['Staff', 'Dept', 'Role', 'Type', 'Work Plan', 'KPIs', 'Targets', 'IPIs', 'PIPs', 'Actions'].map(h => (
                  <th key={h} className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 && (
                <tr><td colSpan={10} className="text-center py-12 text-gray-400">No staff found</td></tr>
              )}
              {filtered.map((emp, i) => {
                const stats = getStaffStats(emp.id, emp.name);
                const appraisal = appraisals.find(a => a.employeeId === emp.id);
                const pip = pips.find(p => p.employeeId === emp.id || p.employee === emp.name);
                return (
                  <motion.tr key={emp.id}
                    initial={{ opacity: 0, y: 8 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: i * 0.03 }}
                    className="border-b border-gray-50 hover:bg-pink-50/20 transition-colors"
                  >
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold" style={{ background: BRAND }}>
                          {getAvatar(emp.name)}
                        </div>
                        <div>
                          <p className="text-sm font-medium text-gray-800">{emp.name}</p>
                          <p className="text-xs text-gray-400">{emp.id}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-xs text-gray-600">{emp.dept}</td>
                    <td className="px-4 py-3 text-xs text-gray-600">{emp.role}</td>
                    <td className="px-4 py-3">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${emp.employeeType === 'Intern' ? 'bg-orange-100 text-orange-700' : 'bg-blue-100 text-blue-700'}`}>
                        {emp.employeeType}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-xs text-gray-600">{stats.workPlansCount} plans</td>
                    <td className="px-4 py-3 text-xs text-gray-600">{stats.kpisCount} KPIs</td>
                    <td className="px-4 py-3 text-xs text-gray-600">{stats.quarterlyCount} targets</td>
                    <td className="px-4 py-3 text-xs text-gray-600">{stats.ipisCount} IPIs</td>
                    <td className="px-4 py-3 text-xs text-gray-600">{stats.pipsCount} PIPs</td>
                    <td className="px-4 py-3">
                      <button onClick={() => {
                        const performanceData = getStaffPerformanceData(emp.id, emp.name);
                        setSelectedEmp({
                          ...emp,
                          ...performanceData,
                          appraisal: appraisal,
                          companyGoals: companyGoals
                        });
                      }}
                        className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium text-white cursor-pointer whitespace-nowrap"
                        style={{ background: BRAND }}>
                        <i className="ri-eye-line"></i> View
                      </button>
                    </td>
                  </motion.tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {/* Staff Performance Modal */}
      {selectedEmp && (
        <StaffPerformanceModal
          employee={{
            id: selectedEmp.id,
            name: selectedEmp.name,
            role: selectedEmp.role,
            dept: selectedEmp.dept,
            employeeType: selectedEmp.employeeType,
            hod: selectedEmp.hod || 'N/A'
          }}
          onClose={() => setSelectedEmp(null)}
          workPlans={selectedEmp.workPlans || []}
          kpis={selectedEmp.kpis || []}
          quarterlyTargets={selectedEmp.quarterlyTargets || []}
          ipis={selectedEmp.ipis || []}
          pips={selectedEmp.pips || []}
          appraisal={selectedEmp.appraisal}
          companyGoals={companyGoals}
          onAddComment={(comment, itemType, itemId, itemTitle) => {
            addComment({
              employeeId: selectedEmp.id,
              itemType: itemType as any,
              itemId,
              itemTitle,
              commentBy: 'HR Manager',
              commentByRole: 'HR',
              comment,
            });
          }}
        />
      )}
    </div>
  );
}