'use client';
import { useState } from 'react';
import HODLayout from '../../../components/HODLayout';
import { useAuth } from '../../../lib/authContext';
import DeptTargetCard from './DeptTargetCard';
import StaffReviewModal from './StaffReviewModal';
import { usePerformanceStore } from '../../../lib/performanceStore';
import { motion } from 'framer-motion';

const BRAND = '#B22698';

export interface DeptTarget {
  id: string;
  title: string;
  description: string;
  quarter: string;
  expectedOutcomes: string;
  deadline: string;
  priority: 'High' | 'Medium' | 'Low';
  measurableObjectives: string;
  progress: number;
  status: 'Pending' | 'Ongoing' | 'Completed' | 'Delayed';
}

export interface WorkPlan {
  id: string;
  employee: string;
  employeeId: string;
  objective: string;
  target: string;
  progress: number;
  dueDate: string;
  status: 'Not Started' | 'In Progress' | 'Completed';
  linkedTargetId: string;
}

export interface IPIType {
  id: string;
  workPlanId: string;
  employeeId: string;
  indicator: string;
  baseline: string;
  target: string;
  current: string;
  unit: string;
  progress: number;
}

const UWEZO_OBJECTIVES = [
  { id: 'OBJ1', title: 'To promote sustainable enterprises for generation of gainful self employment for the Youth, Women and Persons With Disability' },
  { id: 'OBJ2', title: 'To Automate the Fund\'s processes (digitalization of the Fund\'s processes)' },
];

export default function HODPerformancePage() {
  const { user } = useAuth();
  const { addDeptTarget: saveToStore, updateDeptTarget: updateInStore, kpis: storeKPIsAll, quarterlyTargets: storeQTAll, pips: storePIPsAll, addComment: storeAddComment } = usePerformanceStore();

  const [activeTab, setActiveTab] = useState<'targets' | 'workplans' | 'ipis' | 'kpis' | 'quarterly' | 'pip' | 'staff' | 'review'>('targets');
  const [quarterFilter, setQuarterFilter] = useState('All');
  const [showAddTarget, setShowAddTarget] = useState(false);
  const [showAddWorkPlan, setShowAddWorkPlan] = useState(false);
  const [showAddIPI, setShowAddIPI] = useState(false);
  const [toast, setToast] = useState('');

  const [deptTargets, setDeptTargets] = useState<DeptTarget[]>([
    { id: 'DT1', title: 'Digitize 80% of internal processes', description: 'Migrate manual workflows to digital platforms across all 5 departments.', quarter: 'Q2', expectedOutcomes: 'All departments using digital tools for reporting and communication.', deadline: '2026-06-30', priority: 'High', measurableObjectives: '80% of processes digitized; 100% staff trained on digital tools.', progress: 45, status: 'Ongoing' },
    { id: 'DT2', title: 'Support 500 youth enterprises', description: 'Provide business development support to 500 youth enterprises in Q3.', quarter: 'Q3', expectedOutcomes: '500 beneficiaries trained and linked to banking partners.', deadline: '2026-09-30', priority: 'High', measurableObjectives: '500 enterprises registered; 80% accessing loans.', progress: 62, status: 'Ongoing' },
    { id: 'DT3', title: 'Quarterly donor visit coordination', description: 'Facilitate Q1 donor visit with full M&E documentation.', quarter: 'Q1', expectedOutcomes: 'Donor visit completed with positive feedback.', deadline: '2026-03-31', priority: 'Medium', measurableObjectives: 'Visit conducted; report submitted within 7 days.', progress: 100, status: 'Completed' },
    { id: 'DT4', title: 'Reduce system downtime to below 0.5%', description: 'Improve IT infrastructure reliability across all systems.', quarter: 'Q2', expectedOutcomes: 'System uptime at 99.5% or better.', deadline: '2026-06-30', priority: 'Medium', measurableObjectives: 'Monthly uptime reports showing 99.5%+ availability.', progress: 30, status: 'Delayed' },
  ]);

  const [workPlans, setWorkPlans] = useState<WorkPlan[]>([
    { id: 'WP1', employee: 'Peter Otieno', employeeId: 'UF002', objective: 'Deploy new training portal', target: 'Portal live by Q2', progress: 30, dueDate: '2026-06-30', status: 'In Progress', linkedTargetId: 'DT1' },
    { id: 'WP2', employee: 'Alice Odhiambo', employeeId: 'UF009', objective: 'Migrate database to cloud', target: 'Cloud migration 100%', progress: 70, dueDate: '2026-05-31', status: 'In Progress', linkedTargetId: 'DT1' },
    { id: 'WP3', employee: 'Brian Omondi', employeeId: 'UF012', objective: 'Network security audit', target: 'All vulnerabilities patched', progress: 90, dueDate: '2026-04-30', status: 'Completed', linkedTargetId: 'DT4' },
  ]);

  const [ipis, setIpis] = useState<IPIType[]>([
    { id: 'IPI1', workPlanId: 'WP1', employeeId: 'UF002', indicator: 'Portal uptime', baseline: '95%', target: '99.5%', current: '98%', unit: '%', progress: 40 },
    { id: 'IPI2', workPlanId: 'WP2', employeeId: 'UF009', indicator: 'Database migration speed', baseline: '50%', target: '100%', current: '70%', unit: '%', progress: 40 },
    { id: 'IPI3', workPlanId: 'WP3', employeeId: 'UF012', indicator: 'Security patches applied', baseline: '60%', target: '100%', current: '95%', unit: '%', progress: 88 },
  ]);

  const [newTarget, setNewTarget] = useState<Partial<DeptTarget>>({
    title: '', description: '', quarter: 'Q1', expectedOutcomes: '', deadline: '', priority: 'Medium', measurableObjectives: '',
  });
  const [newWorkPlan, setNewWorkPlan] = useState({ employee: '', objective: '', target: '', dueDate: '', linkedTargetId: '' });
  const [newIPI, setNewIPI] = useState({ workPlanId: '', indicator: '', baseline: '', target: '', current: '', unit: '' });

  const [reviewModal, setReviewModal] = useState<{ employee: string; item: string; type: string } | null>(null);
  const [reviewNote, setReviewNote] = useState('');
  const [reviewToast, setReviewToast] = useState('');
  const [staffReviewModal, setStaffReviewModal] = useState<{ id: string; name: string; role: string; dept: string } | null>(null);

  const [commentModal, setCommentModal] = useState<{ itemId: string; itemType: string; itemTitle: string; employeeId: string; employeeName: string } | null>(null);
  const [commentText, setCommentText] = useState('');

  if (!user) return null;

  const showToast = (msg: string) => { setToast(msg); setTimeout(() => setToast(''), 3500); };

  const handleAddTarget = () => {
    if (!newTarget.title || !newTarget.description || !newTarget.deadline) return;
    const t: DeptTarget = {
      id: `DT${deptTargets.length + 1}`,
      title: newTarget.title || '',
      description: newTarget.description || '',
      quarter: (newTarget.quarter as any) || 'Q1',
      expectedOutcomes: newTarget.expectedOutcomes || '',
      deadline: newTarget.deadline || '',
      priority: (newTarget.priority as any) || 'Medium',
      measurableObjectives: newTarget.measurableObjectives || '',
      progress: 0,
      status: 'Pending',
    };
    setDeptTargets(prev => [...prev, t]);
    saveToStore({
      dept: user.dept || 'General',
      title: t.title,
      description: t.description,
      quarter: t.quarter,
      expectedOutcomes: t.expectedOutcomes,
      deadline: t.deadline,
      priority: t.priority,
      measurableObjectives: t.measurableObjectives,
      progress: 0,
      status: 'Pending',
    });
    setNewTarget({ title: '', description: '', quarter: 'Q1', expectedOutcomes: '', deadline: '', priority: 'Medium', measurableObjectives: '' });
    setShowAddTarget(false);
    showToast('Departmental target added and shared with your staff.');
  };

  const handleAddWorkPlan = () => {
    if (!newWorkPlan.objective || !newWorkPlan.employee) return;
    setWorkPlans(prev => [...prev, {
      id: `WP${prev.length + 1}`,
      employee: newWorkPlan.employee,
      employeeId: '',
      objective: newWorkPlan.objective,
      target: newWorkPlan.target,
      progress: 0,
      dueDate: newWorkPlan.dueDate,
      status: 'Not Started',
      linkedTargetId: newWorkPlan.linkedTargetId,
    }]);
    setNewWorkPlan({ employee: '', objective: '', target: '', dueDate: '', linkedTargetId: '' });
    setShowAddWorkPlan(false);
    showToast('Work plan added successfully.');
  };

  const handleAddIPI = () => {
    if (!newIPI.indicator || !newIPI.workPlanId) return;
    setIpis(prev => [...prev, {
      id: `IPI${prev.length + 1}`,
      workPlanId: newIPI.workPlanId,
      employeeId: '',
      indicator: newIPI.indicator,
      baseline: newIPI.baseline,
      target: newIPI.target,
      current: newIPI.current,
      unit: newIPI.unit,
      progress: 0,
    }]);
    setNewIPI({ workPlanId: '', indicator: '', baseline: '', target: '', current: '', unit: '' });
    setShowAddIPI(false);
    showToast('IPI added successfully.');
  };

  const deptKPIs = storeKPIsAll.filter(k => k.department === (user.dept || ''));
  const deptQT = storeQTAll.filter(q => q.department === (user.dept || ''));
  const deptPIPs = storePIPsAll.filter(p => p.department === (user.dept || ''));

  const handleSubmitComment = () => {
    if (!commentModal || !commentText.trim()) return;
    storeAddComment({
      employeeId: commentModal.employeeId,
      itemType: commentModal.itemType as any,
      itemId: commentModal.itemId,
      itemTitle: commentModal.itemTitle,
      commentBy: user.name || 'HOD',
      commentByRole: 'HOD',
      comment: commentText,
    });
    setCommentModal(null);
    setCommentText('');
    showToast('Comment sent to ' + commentModal.employeeName);
  };

  const TABS = [
    { id: 'targets' as const, label: 'Departmental Targets', icon: 'ri-flag-line' },
    { id: 'workplans' as const, label: 'Staff Work Plans', icon: 'ri-file-list-3-line' },
    { id: 'ipis' as const, label: 'IPIs', icon: 'ri-line-chart-line' },
    { id: 'kpis' as const, label: 'Staff KPIs', icon: 'ri-bar-chart-line' },
    { id: 'quarterly' as const, label: 'Quarterly Targets', icon: 'ri-calendar-check-line' },
    { id: 'pip' as const, label: 'PIPs', icon: 'ri-alarm-warning-line' },
    { id: 'staff' as const, label: 'Staff Overview', icon: 'ri-team-line' },
    { id: 'review' as const, label: 'Review Requests', icon: 'ri-feedback-line' },
  ];

  const deptStaff = ['Peter Otieno', 'Alice Odhiambo', 'Brian Omondi'];
  const quarters = ['All', 'Q1', 'Q2', 'Q3', 'Q4'];

  const filteredTargets = quarterFilter === 'All' ? deptTargets : deptTargets.filter(t => t.quarter === quarterFilter);

  return (
    <HODLayout title="Performance Management">
      {toast && (
        <div className="fixed top-20 right-6 z-[100] text-white px-5 py-3 rounded-xl shadow-lg flex items-center gap-2" style={{ background: BRAND }}>
          <i className="ri-checkbox-circle-line"></i>
          <span className="text-sm font-medium">{toast}</span>
        </div>
      )}

      <div className="space-y-5">
        <div>
          <h2 className="text-lg font-bold text-gray-800">{user.dept} Department — Performance</h2>
          <p className="text-sm text-gray-500">Set targets, review work plans, and track individual performance indicators</p>
        </div>

        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4 }}
          className="grid grid-cols-2 lg:grid-cols-4 gap-4"
        >
          {[
            { label: 'Department Targets', value: deptTargets.length, icon: 'ri-flag-line', color: '#B22698' },
            { label: 'Work Plans', value: workPlans.length, icon: 'ri-file-list-3-line', color: '#2563eb' },
            { label: 'Active IPIs', value: ipis.length, icon: 'ri-line-chart-line', color: '#059669' },
            { label: 'Avg Progress', value: `${Math.round(deptTargets.reduce((s, t) => s + t.progress, 0) / (deptTargets.length || 1))}%`, icon: 'ri-bar-chart-line', color: '#d97706' },
          ].map((s, i) => (
            <motion.div
              key={s.label}
              initial={{ opacity: 0, y: 12, scale: 0.98 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              transition={{ duration: 0.4, delay: i * 0.1 }}
              whileHover={{ scale: 1.02, y: -4, boxShadow: '0 12px 40px rgba(178, 38, 152, 0.08)' }}
              whileTap={{ scale: 0.98 }}
              className="bg-white rounded-2xl p-5 border border-gray-100 shadow-sm cursor-pointer"
            >
              <div className="w-10 h-10 rounded-xl flex items-center justify-center mb-3" style={{ background: s.color + '15' }}>
                <i className={`${s.icon} text-lg`} style={{ color: s.color }}></i>
              </div>
              <p className="text-2xl font-bold text-gray-800">{s.value}</p>
              <p className="text-xs text-gray-500 mt-0.5">{s.label}</p>
            </motion.div>
          ))}
        </motion.div>

        <div className="bg-white rounded-xl border border-gray-100 shadow-sm mb-5">
          <div className="flex border-b border-gray-100 overflow-x-auto">
            {TABS.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className="flex items-center gap-2 px-5 py-3 text-sm font-medium border-b-2 transition-all cursor-pointer whitespace-nowrap"
                style={activeTab === tab.id ? { borderColor: BRAND, color: BRAND } : { borderColor: 'transparent', color: '#6b7280' }}
              >
                <i className={`${tab.icon} text-sm`}></i>
                {tab.label}
              </button>
            ))}
          </div>

          <div className="p-5">
            {activeTab === 'targets' && (
              <div>
                <div className="flex items-center justify-between mb-4 flex-wrap gap-3">
                  <div>
                    <h3 className="font-semibold text-gray-800">Departmental Targets</h3>
                    <p className="text-xs text-gray-500 mt-0.5">Aligned to Uwezo Fund Objectives (set by HR)</p>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="flex bg-gray-50 rounded-lg p-1 gap-1">
                      {quarters.map(q => (
                        <button
                          key={q}
                          onClick={() => setQuarterFilter(q)}
                          className={`px-3 py-1.5 rounded-md text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${
                            quarterFilter === q ? 'bg-white text-gray-800 shadow-sm' : 'text-gray-500 hover:text-gray-700'
                          }`}
                        >
                          {q}
                        </button>
                      ))}
                    </div>
                    <button onClick={() => setShowAddTarget(true)}
                      className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap"
                      style={{ background: BRAND }}>
                      <i className="ri-add-line"></i> Add Target
                    </button>
                  </div>
                </div>

                <div className="mb-4 bg-pink-50 border border-pink-200 rounded-xl p-4">
                  <p className="text-xs font-semibold mb-2" style={{ color: BRAND }}>Uwezo Fund Objectives (Set by HR)</p>
                  <div className="space-y-2">
                    {UWEZO_OBJECTIVES.map(obj => (
                      <div key={obj.id} className="flex items-start gap-2">
                        <div className="w-5 h-5 flex items-center justify-center rounded-full flex-shrink-0 text-xs font-bold text-white mt-0.5" style={{ background: BRAND }}>
                          {obj.id.replace('OBJ', '')}
                        </div>
                        <p className="text-xs text-gray-700">{obj.title}</p>
                      </div>
                    ))}
                  </div>
                </div>

                {showAddTarget && (
                  <div className="bg-gray-50 border border-gray-200 rounded-xl p-4 mb-4">
                    <h4 className="font-semibold text-gray-700 text-sm mb-3">New Departmental Target</h4>
                    <div className="grid grid-cols-2 gap-3">
                      <div className="col-span-2">
                        <label className="text-xs font-medium text-gray-600 block mb-1">Target Title *</label>
                        <input value={newTarget.title} onChange={e => setNewTarget(p => ({ ...p, title: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. Digitize 80% of internal processes" />
                      </div>
                      <div className="col-span-2">
                        <label className="text-xs font-medium text-gray-600 block mb-1">Description *</label>
                        <textarea value={newTarget.description} onChange={e => setNewTarget(p => ({ ...p, description: e.target.value }))} rows={2} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" placeholder="Brief description of the target" />
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-600 block mb-1">Quarter</label>
                        <div className="flex gap-1 bg-gray-100 rounded-lg p-1">
                          {['Q1','Q2','Q3','Q4'].map(q => (
                            <button key={q} onClick={() => setNewTarget(p => ({ ...p, quarter: q as any }))}
                              className={`flex-1 py-1.5 rounded-md text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${newTarget.quarter === q ? 'bg-white text-gray-800 shadow-sm' : 'text-gray-500'}`}>
                              {q}
                            </button>
                          ))}
                        </div>
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-600 block mb-1">Priority</label>
                        <div className="flex gap-1 bg-gray-100 rounded-lg p-1">
                          {(['High','Medium','Low'] as const).map(p => (
                            <button key={p} onClick={() => setNewTarget(prev => ({ ...prev, priority: p }))}
                              className={`flex-1 py-1.5 rounded-md text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${newTarget.priority === p ? 'bg-white text-gray-800 shadow-sm' : 'text-gray-500'}`}>
                              {p}
                            </button>
                          ))}
                        </div>
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-600 block mb-1">Deadline</label>
                        <input type="date" value={newTarget.deadline} onChange={e => setNewTarget(p => ({ ...p, deadline: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                      </div>
                      <div className="col-span-2">
                        <label className="text-xs font-medium text-gray-600 block mb-1">Expected Outcomes</label>
                        <input value={newTarget.expectedOutcomes} onChange={e => setNewTarget(p => ({ ...p, expectedOutcomes: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="What will be achieved" />
                      </div>
                      <div className="col-span-2">
                        <label className="text-xs font-medium text-gray-600 block mb-1">Measurable Objectives</label>
                        <textarea value={newTarget.measurableObjectives} onChange={e => setNewTarget(p => ({ ...p, measurableObjectives: e.target.value }))} rows={2} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" placeholder="Specific, measurable objectives" />
                      </div>
                    </div>
                    <div className="flex gap-2 mt-3">
                      <button onClick={() => setShowAddTarget(false)} className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
                      <button onClick={handleAddTarget} className="px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: BRAND }}>Save Target</button>
                    </div>
                  </div>
                )}

                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                  {filteredTargets.map((t, i) => (
                    <DeptTargetCard key={t.id} target={t} index={i} onUpdate={updated => setDeptTargets(prev => prev.map(x => x.id === updated.id ? updated : x))} />
                  ))}
                </div>
              </div>
            )}

            {activeTab === 'workplans' && (
              <div>
                <div className="flex items-center justify-between mb-4">
                  <div>
                    <h3 className="font-semibold text-gray-800">Staff Work Plans</h3>
                    <p className="text-xs text-gray-500 mt-0.5">Work plans created by staff based on departmental targets</p>
                  </div>
                  <button onClick={() => setShowAddWorkPlan(true)}
                    className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap"
                    style={{ background: BRAND }}>
                    <i className="ri-add-line"></i> Add Work Plan
                  </button>
                </div>

                {showAddWorkPlan && (
                  <div className="bg-gray-50 border border-gray-200 rounded-xl p-4 mb-4">
                    <h4 className="font-semibold text-gray-700 text-sm mb-3">New Work Plan</h4>
                    <div className="space-y-3">
                      <div>
                        <label className="text-xs font-medium text-gray-600 block mb-1">Employee</label>
                        <select value={newWorkPlan.employee} onChange={e => setNewWorkPlan(p => ({ ...p, employee: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8">
                          <option value="">Select employee...</option>
                          {deptStaff.map(s => <option key={s}>{s}</option>)}
                        </select>
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-600 block mb-1">Linked Departmental Target</label>
                        <select value={newWorkPlan.linkedTargetId} onChange={e => setNewWorkPlan(p => ({ ...p, linkedTargetId: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8">
                          <option value="">Select target...</option>
                          {deptTargets.map(t => <option key={t.id} value={t.id}>{t.title.slice(0, 50)}...</option>)}
                        </select>
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-600 block mb-1">Objective</label>
                        <input value={newWorkPlan.objective} onChange={e => setNewWorkPlan(p => ({ ...p, objective: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="Work plan objective" />
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-600 block mb-1">Target</label>
                        <input value={newWorkPlan.target} onChange={e => setNewWorkPlan(p => ({ ...p, target: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="Measurable target" />
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-600 block mb-1">Due Date</label>
                        <input type="date" value={newWorkPlan.dueDate} onChange={e => setNewWorkPlan(p => ({ ...p, dueDate: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                      </div>
                    </div>
                    <div className="flex gap-2 mt-3">
                      <button onClick={() => setShowAddWorkPlan(false)} className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
                      <button onClick={handleAddWorkPlan} className="px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: BRAND }}>Save Work Plan</button>
                    </div>
                  </div>
                )}

                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="bg-gray-50 border-b border-gray-100">
                        <th className="text-left px-5 py-3 text-xs font-semibold text-gray-500 uppercase">Employee</th>
                        <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Objective</th>
                        <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Target</th>
                        <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Due Date</th>
                        <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Progress</th>
                        <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Status</th>
                      </tr>
                    </thead>
                    <tbody>
                      {workPlans.map(wp => (
                        <motion.tr key={wp.id} initial={{ opacity: 0, x: -8 }} whileInView={{ opacity: 1, x: 0 }} viewport={{ once: true }} className="border-b border-gray-50 hover:bg-gray-50/50">
                          <td className="px-5 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 flex-shrink-0" style={{ background: BRAND }}>
                                {wp.employee.split(' ').map(n => n[0]).join('').slice(0, 2)}
                              </div>
                              <span className="font-medium text-gray-800">{wp.employee}</span>
                            </div>
                          </td>
                          <td className="px-4 py-3 text-gray-700">{wp.objective}</td>
                          <td className="px-4 py-3 text-gray-600">{wp.target}</td>
                          <td className="px-4 py-3 text-xs text-gray-500">{wp.dueDate}</td>
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-2">
                              <div className="flex-1 bg-gray-100 rounded-full h-2 w-24">
                                <div className="h-2 rounded-full" style={{ width: `${wp.progress}%`, background: BRAND }}></div>
                              </div>
                              <span className="text-xs font-bold text-gray-700">{wp.progress}%</span>
                            </div>
                          </td>
                          <td className="px-4 py-3">
                            <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>
                          </td>
                        </motion.tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {activeTab === 'ipis' && (
              <div>
                <div className="flex items-center justify-between mb-4">
                  <div>
                    <h3 className="font-semibold text-gray-800">Individual Performance Indicators</h3>
                    <p className="text-xs text-gray-500 mt-0.5">IPIs linked to work plans for effectiveness measurement</p>
                  </div>
                  <button onClick={() => setShowAddIPI(true)}
                    className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap"
                    style={{ background: BRAND }}>
                    <i className="ri-add-line"></i> Add IPI
                  </button>
                </div>

                {showAddIPI && (
                  <div className="bg-gray-50 border border-gray-200 rounded-xl p-4 mb-4">
                    <h4 className="font-semibold text-gray-700 text-sm mb-3">New IPI</h4>
                    <div className="space-y-3">
                      <div>
                        <label className="text-xs font-medium text-gray-600 block mb-1">Linked Work Plan</label>
                        <select value={newIPI.workPlanId} onChange={e => setNewIPI(p => ({ ...p, workPlanId: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8">
                          <option value="">Select work plan...</option>
                          {workPlans.map(w => <option key={w.id} value={w.id}>{w.employee}: {w.objective.slice(0, 40)}...</option>)}
                        </select>
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-600 block mb-1">Indicator</label>
                        <input value={newIPI.indicator} onChange={e => setNewIPI(p => ({ ...p, indicator: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. Response time, accuracy rate" />
                      </div>
                      <div className="grid grid-cols-3 gap-3">
                        <div>
                          <label className="text-xs font-medium text-gray-600 block mb-1">Baseline</label>
                          <input value={newIPI.baseline} onChange={e => setNewIPI(p => ({ ...p, baseline: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. 50%" />
                        </div>
                        <div>
                          <label className="text-xs font-medium text-gray-600 block mb-1">Target</label>
                          <input value={newIPI.target} onChange={e => setNewIPI(p => ({ ...p, target: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. 90%" />
                        </div>
                        <div>
                          <label className="text-xs font-medium text-gray-600 block mb-1">Current</label>
                          <input value={newIPI.current} onChange={e => setNewIPI(p => ({ ...p, current: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. 75%" />
                        </div>
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-600 block mb-1">Unit</label>
                        <input value={newIPI.unit} onChange={e => setNewIPI(p => ({ ...p, unit: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. %, hours, count" />
                      </div>
                    </div>
                    <div className="flex gap-2 mt-3">
                      <button onClick={() => setShowAddIPI(false)} className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
                      <button onClick={handleAddIPI} className="px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: BRAND }}>Save IPI</button>
                    </div>
                  </div>
                )}

                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="bg-gray-50 border-b border-gray-100">
                        <th className="text-left px-5 py-3 text-xs font-semibold text-gray-500 uppercase">Work Plan</th>
                        <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Indicator</th>
                        <th className="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Baseline</th>
                        <th className="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Target</th>
                        <th className="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Current</th>
                        <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Progress</th>
                      </tr>
                    </thead>
                    <tbody>
                      {ipis.map(ipi => {
                        const wp = workPlans.find(w => w.id === ipi.workPlanId);
                        return (
                          <motion.tr key={ipi.id} initial={{ opacity: 0, x: -8 }} whileInView={{ opacity: 1, x: 0 }} viewport={{ once: true }} className="border-b border-gray-50 hover:bg-gray-50/50">
                            <td className="px-5 py-3">
                              <p className="text-xs font-medium text-gray-700">{wp?.objective || ipi.workPlanId}</p>
                              <p className="text-xs text-gray-400">{wp?.employee}</p>
                            </td>
                            <td className="px-4 py-3 font-medium text-gray-800">{ipi.indicator}</td>
                            <td className="px-4 py-3 text-center text-gray-500">{ipi.baseline}</td>
                            <td className="px-4 py-3 text-center font-semibold text-gray-700">{ipi.target}</td>
                            <td className="px-4 py-3 text-center font-bold" style={{ color: BRAND }}>{ipi.current}</td>
                            <td className="px-4 py-3">
                              <div className="flex items-center gap-2">
                                <div className="flex-1 bg-gray-100 rounded-full h-2 w-24">
                                  <div className="h-2 rounded-full" style={{ width: `${ipi.progress}%`, background: BRAND }}></div>
                                </div>
                                <span className="text-xs font-bold text-gray-700">{ipi.progress}%</span>
                              </div>
                            </td>
                          </motion.tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {activeTab === 'review' && (
              <div>
                <div className="flex items-center justify-between mb-4">
                  <div>
                    <h3 className="font-semibold text-gray-800">Recommend for Review</h3>
                    <p className="text-xs text-gray-500 mt-0.5">Send review requests to employees for their work plans, KPIs, IPIs, or PIPs</p>
                  </div>
                </div>
                <div className="space-y-3">
                  {deptStaff.map(s => (
                    <div key={s} className="bg-white border border-gray-100 rounded-xl p-4 shadow-sm">
                      <div className="flex items-center gap-3 mb-3">
                        <div className="w-9 h-9 rounded-full flex items-center justify-center text-white font-bold text-sm" style={{ background: BRAND }}>
                          {s.split(' ').map(n => n[0]).join('').slice(0, 2)}
                        </div>
                        <p className="font-semibold text-gray-800">{s}</p>
                      </div>
                      <div className="flex flex-wrap gap-2">
                        {['Work Plan', 'KPIs', 'Quarterly Targets', 'IPIs', 'PIP'].map(item => (
                          <button key={item}
                            onClick={() => { setReviewModal({ employee: s, item, type: item }); setReviewNote(''); }}
                            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-xs font-medium cursor-pointer whitespace-nowrap hover:bg-pink-50 transition-colors"
                            style={{ borderColor: BRAND, color: BRAND }}>
                            <i className="ri-feedback-line text-xs"></i>
                            Review {item}
                          </button>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
                {reviewToast && (
                  <div className="fixed top-20 right-6 z-[100] text-white px-5 py-3 rounded-xl shadow-lg flex items-center gap-2" style={{ background: BRAND }}>
                    <i className="ri-checkbox-circle-line"></i><span className="text-sm font-medium">{reviewToast}</span>
                  </div>
                )}
              </div>
            )}

            {activeTab === 'kpis' && (
              <div>
                <div className="flex items-center justify-between mb-4">
                  <div>
                    <h3 className="font-semibold text-gray-800">Staff KPIs — {user.dept}</h3>
                    <p className="text-xs text-gray-500 mt-0.5">Key Performance Indicators for all staff in your department</p>
                  </div>
                </div>
                {deptKPIs.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 found for your department</p></div>
                ) : (
                  <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                      <thead>
                        <tr className="bg-gray-50 border-b border-gray-100">
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Staff</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">KPI</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Target</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Current</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Progress</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Status</th>
                          <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Comment</th>
                        </tr>
                      </thead>
                      <tbody>
                        {deptKPIs.map(k => (
                          <tr key={k.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                            <td className="px-4 py-3">
                              <div className="flex items-center gap-2">
                                <div className="w-7 h-7 rounded-full flex items-center justify-center text-white text-xs font-bold" style={{ background: BRAND }}>{k.employee?.split(' ').map((n: string) => n[0]).join('').slice(0, 2)}</div>
                                <div><p className="font-medium text-gray-800 text-sm">{k.employee}</p><p className="text-xs text-gray-400">{k.employeeType}</p></div>
                              </div>
                            </td>
                            <td className="px-4 py-3"><p className="font-medium text-gray-800">{k.kpiName}</p><p className="text-xs text-gray-400">{k.description}</p></td>
                            <td className="px-4 py-3 text-sm text-gray-600">{k.target} {k.unit}</td>
                            <td className="px-4 py-3 text-sm font-semibold" style={{ color: BRAND }}>{k.current} {k.unit}</td>
                            <td className="px-4 py-3">
                              <div className="flex items-center gap-2">
                                <div className="flex-1 bg-gray-100 rounded-full h-2 w-20"><div className="h-2 rounded-full" style={{ width: `${k.progress}%`, background: BRAND }}></div></div>
                                <span className="text-xs font-bold text-gray-700">{k.progress}%</span>
                              </div>
                            </td>
                            <td className="px-4 py-3"><span className={`text-xs px-2 py-0.5 rounded-full font-medium ${k.status === 'Completed' ? 'bg-green-100 text-green-700' : k.status === 'Active' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'}`}>{k.status}</span></td>
                            <td className="px-4 py-3 text-right">
                              <button onClick={() => setCommentModal({ itemId: k.id, itemType: 'kpi', itemTitle: k.kpiName, employeeId: k.employeeId, employeeName: k.employee })}
                                className="flex items-center gap-1 px-2 py-1.5 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap ml-auto"
                                style={{ background: BRAND + '15', color: BRAND }}>
                                <i className="ri-chat-3-line"></i> Comment
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            )}

            {activeTab === 'quarterly' && (
              <div>
                <div className="flex items-center justify-between mb-4">
                  <div>
                    <h3 className="font-semibold text-gray-800">Staff Quarterly Targets — {user.dept}</h3>
                    <p className="text-xs text-gray-500 mt-0.5">Quarterly targets for all staff in your department</p>
                  </div>
                </div>
                {deptQT.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 found</p></div>
                ) : (
                  <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                      <thead>
                        <tr className="bg-gray-50 border-b border-gray-100">
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Staff</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Quarter</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Target</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Progress</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Status</th>
                          <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Comment</th>
                        </tr>
                      </thead>
                      <tbody>
                        {deptQT.map(q => (
                          <tr key={q.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                            <td className="px-4 py-3">
                              <div className="flex items-center gap-2">
                                <div className="w-7 h-7 rounded-full flex items-center justify-center text-white text-xs font-bold" style={{ background: BRAND }}>{q.employee?.split(' ').map((n: string) => n[0]).join('').slice(0, 2)}</div>
                                <p className="font-medium text-gray-800 text-sm">{q.employee}</p>
                              </div>
                            </td>
                            <td className="px-4 py-3"><span className="text-xs font-bold px-2 py-1 rounded-full bg-purple-100 text-purple-700">{q.quarter}</span></td>
                            <td className="px-4 py-3"><p className="font-medium text-gray-800">{q.title}</p><p className="text-xs text-gray-400">{q.description}</p></td>
                            <td className="px-4 py-3">
                              <div className="flex items-center gap-2">
                                <div className="flex-1 bg-gray-100 rounded-full h-2 w-20"><div className="h-2 rounded-full" style={{ width: `${q.progress}%`, background: BRAND }}></div></div>
                                <span className="text-xs font-bold text-gray-700">{q.progress}%</span>
                              </div>
                            </td>
                            <td className="px-4 py-3"><span className={`text-xs px-2 py-0.5 rounded-full font-medium ${q.status === 'Completed' ? 'bg-green-100 text-green-700' : q.status === 'In Progress' ? 'bg-blue-100 text-blue-700' : q.status === 'Delayed' ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-600'}`}>{q.status}</span></td>
                            <td className="px-4 py-3 text-right">
                              <button onClick={() => setCommentModal({ itemId: q.id, itemType: 'quarterly', itemTitle: q.title, employeeId: q.employeeId, employeeName: q.employee })}
                                className="flex items-center gap-1 px-2 py-1.5 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap ml-auto"
                                style={{ background: BRAND + '15', color: BRAND }}>
                                <i className="ri-chat-3-line"></i> Comment
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            )}

            {activeTab === 'pip' && (
              <div>
                <div className="flex items-center justify-between mb-4">
                  <div>
                    <h3 className="font-semibold text-gray-800">Performance Improvement Plans — {user.dept}</h3>
                    <p className="text-xs text-gray-500 mt-0.5">PIPs for staff in your department</p>
                  </div>
                </div>
                {deptPIPs.length === 0 ? (
                  <div className="text-center py-12 text-gray-400">
                    <div className="w-16 h-16 flex items-center justify-center mx-auto mb-3 rounded-2xl bg-green-50"><i className="ri-checkbox-circle-line text-3xl text-green-500"></i></div>
                    <p className="font-medium text-gray-500">No Active PIPs</p>
                    <p className="text-sm mt-1">No staff in your department currently have an active PIP.</p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {deptPIPs.map(pip => (
                      <div key={pip.id} className="bg-white border border-red-200 rounded-xl p-4 shadow-sm">
                        <div className="flex items-start justify-between mb-3">
                          <div>
                            <div className="flex items-center gap-2 mb-1">
                              <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold" style={{ background: BRAND }}>{pip.employee?.split(' ').map((n: string) => n[0]).join('').slice(0, 2)}</div>
                              <div>
                                <p className="font-semibold text-gray-800">{pip.employee}</p>
                                <p className="text-xs text-gray-500">{pip.role} · {pip.employeeType}</p>
                              </div>
                            </div>
                            <p className="text-sm font-medium text-gray-700 mt-2">{pip.title}</p>
                            <p className="text-xs text-gray-500">{pip.description}</p>
                            <div className="flex gap-3 mt-2 text-xs text-gray-500">
                              <span>Start: {pip.startDate}</span>
                              <span>End: {pip.endDate}</span>
                            </div>
                          </div>
                          <span className={`text-xs px-2.5 py-1 rounded-full font-semibold ${pip.status === 'Completed' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>{pip.status}</span>
                        </div>
                        <div className="flex items-center gap-2 mb-3">
                          <div className="flex-1 bg-gray-100 rounded-full h-2"><div className="h-2 rounded-full" style={{ width: `${pip.progress}%`, background: '#dc2626' }}></div></div>
                          <span className="text-xs font-bold text-gray-700">{pip.progress}%</span>
                        </div>
                        <div className="text-xs text-gray-600 mb-2"><strong>Improvement Areas:</strong> {pip.improvementAreas}</div>
                        <button onClick={() => setCommentModal({ itemId: pip.id, itemType: 'pip' as any, itemTitle: pip.title, employeeId: pip.employeeId, employeeName: pip.employee })}
                          className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap"
                          style={{ background: BRAND + '15', color: BRAND }}>
                          <i className="ri-chat-3-line"></i> Add Comment
                        </button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}

            {activeTab === 'staff' && (
              <div>
                <div className="flex items-center justify-between mb-4">
                  <h3 className="font-semibold text-gray-800">Staff Performance Overview</h3>
                  <p className="text-xs text-gray-500">Click &quot;Review &amp; Comment&quot; to view and comment on each staff member&apos;s performance items</p>
                </div>
                <div className="grid grid-cols-1 gap-4">
                  {deptStaff.map(s => {
                    const staffWP = workPlans.filter(w => w.employee === s);
                    const avgProgress = staffWP.length > 0 ? Math.round(staffWP.reduce((sum, w) => sum + w.progress, 0) / staffWP.length) : 0;
                    const staffId = s === 'Peter Otieno' ? 'UF002' : s === 'Alice Odhiambo' ? 'UF009' : 'UF012';
                    return (
                      <motion.div key={s} initial={{ opacity: 0, y: 12 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} className="bg-white border border-gray-100 rounded-xl p-4 shadow-sm">
                        <div className="flex items-center gap-3 mb-3">
                          <div className="w-10 h-10 rounded-full flex items-center justify-center text-white font-bold text-sm" style={{ background: BRAND }}>
                            {s.split(' ').map(n => n[0]).join('').slice(0, 2)}
                          </div>
                          <div className="flex-1">
                            <p className="font-semibold text-gray-800">{s}</p>
                            <p className="text-xs text-gray-500">{staffWP.length} work plans &bull; {user?.dept || 'Department'}</p>
                          </div>
                          <div className="text-right mr-3">
                            <p className="text-2xl font-bold text-gray-800">{avgProgress}%</p>
                            <p className="text-xs text-gray-400">Avg Progress</p>
                          </div>
                          <button
                            onClick={() => setStaffReviewModal({ id: staffId, name: s, role: staffWP[0]?.employee || s, dept: user?.dept || 'Department' })}
                            className="flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold text-white cursor-pointer whitespace-nowrap"
                            style={{ background: BRAND }}>
                            <i className="ri-chat-3-line"></i> Review &amp; Comment
                          </button>
                        </div>
                        <div className="flex items-center gap-2">
                          <div className="flex-1 bg-gray-100 rounded-full h-2">
                            <div className="h-2 rounded-full" style={{ width: `${avgProgress}%`, background: BRAND }}></div>
                          </div>
                        </div>
                        <div className="mt-3 flex gap-2 flex-wrap">
                          {staffWP.map(w => (
                            <span key={w.id} className={`text-xs px-2.5 py-1 rounded-full font-medium ${w.status === 'Completed' ? 'bg-green-100 text-green-700' : w.status === 'In Progress' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600'}`}>
                              {w.objective.slice(0, 30)}...
                            </span>
                          ))}
                        </div>
                      </motion.div>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
      {reviewModal && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
            <h3 className="font-bold text-gray-800 mb-1">Recommend for Review</h3>
            <p className="text-sm text-gray-500 mb-4">
              Sending review request to <strong>{reviewModal.employee}</strong> for their <strong>{reviewModal.item}</strong>.
            </p>
            <div className="mb-4">
              <label className="block text-xs font-semibold text-gray-600 mb-1">Review Notes *</label>
              <textarea value={reviewNote} onChange={e => setReviewNote(e.target.value)} rows={3}
                placeholder="Specify what needs to be reviewed or updated..."
                className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none resize-none" />
            </div>
            <div className="flex gap-3">
              <button onClick={() => setReviewModal(null)}
                className="flex-1 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
              <button onClick={() => {
                setReviewToast(`Review request sent to ${reviewModal.employee} for ${reviewModal.item}`);
                setTimeout(() => setReviewToast(''), 3500);
                setReviewModal(null);
                setReviewNote('');
              }} disabled={!reviewNote.trim()}
                className="flex-1 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer disabled:opacity-50 whitespace-nowrap"
                style={{ background: BRAND }}>
                Send Review Request
              </button>
            </div>
          </div>
        </div>
      )}

      {staffReviewModal && (
        <StaffReviewModal
          employee={staffReviewModal}
          onClose={() => setStaffReviewModal(null)}
        />
      )}

      {commentModal && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
            <h3 className="font-bold text-gray-800 mb-1">Add Comment</h3>
            <p className="text-sm text-gray-500 mb-4">Your comment on <strong>{commentModal.itemTitle}</strong> will be visible to <strong>{commentModal.employeeName}</strong>.</p>
            <textarea value={commentText} onChange={e => setCommentText(e.target.value)} rows={4} maxLength={500}
              placeholder="Type your feedback or review note..."
              className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none resize-none" />
            <p className="text-xs text-gray-400 mt-1">{commentText.length}/500</p>
            <div className="flex gap-3 mt-4">
              <button onClick={() => { setCommentModal(null); setCommentText(''); }}
                className="flex-1 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
              <button onClick={handleSubmitComment} disabled={!commentText.trim()}
                className="flex-1 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer disabled:opacity-50 whitespace-nowrap"
                style={{ background: BRAND }}>Send Comment</button>
            </div>
          </div>
        </div>
      )}
    </HODLayout>
  );
}