'use client';
import { useEffect, useState } from 'react';
import { useAuth } from '../../../lib/authContext';
import EmployeeLayout from '../../../components/EmployeeLayout';
import { Appraisal, PIP, initialAppraisals, COMPANY_GOALS, DEPARTMENT_GOALS, RATING_LABELS, RATING_BG, ALL_EMPLOYEES, getDeptGoals } from '../../hr/performance/performanceData';
import SelfAssessmentForm from './SelfAssessmentForm';
import WorkPlanCard, { WorkPlan, WorkPlanTask } from './WorkPlanCard';
import KPIGauge, { KPIType } from './KPIGauge';
import QuarterlyTargetCard, { QuarterlyTargetType } from './QuarterlyTargetCard';
import IPICard, { IPIType } from './IPICard';
import { motion } from 'framer-motion';
import { usePerformanceStore } from '../../../lib/performanceStore';
import {
  fetchPerformanceData,
  createWorkPlan,
  updateWorkPlan,
  createKpi,
  updateKpi,
  createQuarterlyTarget,
  updateQuarterlyTarget,
  createIpi,
  updateIpi,
} from '../../../lib/performanceApi';

type Tab = 'workplan' | 'kpis' | 'quarterly' | 'ipis' | 'appraisals' | 'pip';

const BRAND = '#b828a0';

export default function EmployeePerformancePage() {
  const { user } = useAuth();
  const { getDeptTargets } = usePerformanceStore();
  const empId = user?.employeeId || 'UF001';

  const DEPT_TARGETS = getDeptTargets(user?.dept || '');

  const [appraisals, setAppraisals] = useState<Appraisal[]>(initialAppraisals);
  const [assessingAppraisal, setAssessingAppraisal] = useState<Appraisal | null>(null);
  const [viewAppraisal, setViewAppraisal] = useState<Appraisal | null>(null);
  const [activeTab, setActiveTab] = useState<Tab>('workplan');
  const [showAIPIP, setShowAIPIP] = useState(false);
  const [aiPipForm, setAiPipForm] = useState({ improvementAreas: '', actionPlan: '', successMetrics: '', duration: '90 days' as '30 days' | '60 days' | '90 days', startDate: '' });

  const [workPlans, setWorkPlans] = useState<WorkPlan[]>([]);
  const [showAddWorkPlan, setShowAddWorkPlan] = useState(false);
  const [showAddTask, setShowAddTask] = useState<string | null>(null);
  const [newWorkPlan, setNewWorkPlan] = useState({ objective: '', target: '', dueDate: '', linkedTargetId: '' });
  const [newTask, setNewTask] = useState({ title: '', objective: '', expectedOutput: '', startDate: '', endDate: '', remarks: '' });

  const [kpis, setKpis] = useState<KPIType[]>([]);
  const [showAddKPI, setShowAddKPI] = useState(false);
  const [newKPI, setNewKPI] = useState<{ title: string; description: string; targetValue: string; measurementMethod: string; frequency: 'Monthly' | 'Quarterly' | 'Annual'; targetDeadline: string; weight: string; linkedGoalId: string }>({ title: '', description: '', targetValue: '', measurementMethod: '', frequency: 'Monthly', targetDeadline: '', weight: '', linkedGoalId: '' });

  const [ipis, setIpis] = useState<IPIType[]>([]);
  const [showAddIPI, setShowAddIPI] = useState(false);
  const [newIPI, setNewIPI] = useState({ workPlanTaskId: '', indicatorName: '', target: '', measurementCriteria: '', expectedPerformance: '', ratingScale: '' });
  const [pips, setPips] = useState<PIP[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [toast, setToast] = useState('');

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

  useEffect(() => {
    const employeeIdentifier = user?.employeeId || user?.id;
    if (!employeeIdentifier) return;

    const load = async () => {
      setIsLoading(true);
      try {
        const data = await fetchPerformanceData(employeeIdentifier);
        setWorkPlans(data.workPlans);
        setKpis(data.kpis);
        setQuarterlyTargets(data.quarterlyTargets);
        setIpis(data.ipis);
        // Ensure PIP has all required fields
const mappedPips = data.pips.map((pip: any) => ({
  ...pip,
  improvementAreas: Array.isArray(pip.improvementAreas) ? pip.improvementAreas : [],
  checkIns: pip.checkIns || [],
}));
setPips(mappedPips as PIP[]);
      } catch (error) {
        console.error('Error loading performance data:', error);
      } finally {
        setIsLoading(false);
      }
    };

    load();
  }, [user?.employeeId, user?.id]);

  const [quarterlyTargets, setQuarterlyTargets] = useState<QuarterlyTargetType[]>([]);
  const [showAddQuarterly, setShowAddQuarterly] = useState(false);
  const [newQuarterly, setNewQuarterly] = useState({ quarter: 'Q1', year: '2026', title: '', kpiMeasurement: '', expectedOutcome: '', completionTimeline: '', weight: '10', linkedWorkPlanId: '' });

  const myAppraisals = appraisals.filter(a => a.employeeId === empId);
  const myPIPs = pips.filter(p => p.employeeId === empId);
  const emp = ALL_EMPLOYEES.find(e => e.id === empId);
  const { getCommentsFor, markRead } = usePerformanceStore();
  const myComments = getCommentsFor(empId);
  const unreadComments = myComments.filter(c => !c.read);

  const handleSave = (updated: Appraisal) => {
    setAppraisals(prev => prev.map(a => a.id === updated.id ? updated : a));
    setAssessingAppraisal(null);
  };

  const handleGenerateAIPIP = () => {
    if (!emp) return;
    const rating = myAppraisals[0]?.overallRating || 0;
    const dept = emp.dept;
    const role = emp.position;

    const aiImprovementAreas = [
      `Improve ${role.toLowerCase()} core competencies and technical skills relevant to ${dept} operations`,
      `Enhance productivity and timeliness in delivering assigned tasks and departmental targets`,
      `Strengthen communication and collaboration within the ${dept} team and cross-functional units`,
      `Demonstrate measurable improvement in quality of work outputs and adherence to SOPs`,
    ];

    const aiActionPlan = [
      `Week 1-2: Conduct skills gap assessment with HOD (${emp.hod}) and enroll in targeted training programs`,
      `Week 3-4: Implement daily task planning and weekly progress reporting to direct supervisor`,
      `Week 5-8: Participate in peer mentoring sessions and complete at least 2 knowledge-sharing workshops`,
      `Week 9-10: Undertake a mini-project with clear deliverables to demonstrate applied learning`,
      `Week 11-12: Final evaluation meeting with HOD and HR to review progress against PIP objectives`,
    ].join('\n');

    const aiSuccessMetrics = [
      `Achieve minimum performance rating of 3.0/5.0 in the next quarterly appraisal (up from ${rating.toFixed(1)})`,
      `Submit 100% of assigned tasks on time with zero quality complaints for 60 consecutive days`,
      `Complete at least one relevant professional development course with certificate submission`,
      `Receive positive feedback from at least 2 peers and direct supervisor on teamwork and collaboration`,
    ].join('\n');

    setAiPipForm(f => ({
      ...f,
      improvementAreas: aiImprovementAreas.join('\n'),
      actionPlan: aiActionPlan,
      successMetrics: aiSuccessMetrics,
      startDate: f.startDate || new Date().toISOString().split('T')[0],
    }));
  };

  const handleCreateEmployeePIP = () => {
    if (!emp || !aiPipForm.startDate) return;
    const daysMap = { '30 days': 30, '60 days': 60, '90 days': 90 };
    const start = new Date(aiPipForm.startDate);
    const end = new Date(start);
    end.setDate(end.getDate() + daysMap[aiPipForm.duration]);
    // Note: In a real app this would save to the store; here we just show the form
    setShowAIPIP(false);
    setAiPipForm({ improvementAreas: '', actionPlan: '', successMetrics: '', duration: '90 days', startDate: '' });
  };

  const handleUpdateWorkPlan = async (planId: string, updates: Partial<WorkPlan>) => {
    const updated = await updateWorkPlan(planId, updates);
    if (updated) {
      setWorkPlans(prev => prev.map(wp => (wp.id === planId ? updated : wp)));
      return true;
    }
    return false;
  };

  const handleAddWorkPlan = async () => {
    if (!newWorkPlan.objective || !newWorkPlan.target) {
      showToast('Please fill in objective and target');
      return;
    }
    const employeeIdentifier = user?.employeeId || user?.id;
    if (!employeeIdentifier) return;
    setIsLoading(true);
    try {
      const saved = await createWorkPlan({
        employeeId: employeeIdentifier,
        objective: newWorkPlan.objective,
        target: newWorkPlan.target,
        dueDate: newWorkPlan.dueDate,
        linkedTargetId: newWorkPlan.linkedTargetId,
      });
      if (saved) {
        setWorkPlans(prev => [...prev, saved]);
        setNewWorkPlan({ objective: '', target: '', dueDate: '', linkedTargetId: '' });
        setShowAddWorkPlan(false);
        showToast('Work plan saved successfully');
      } else {
        showToast('Error saving work plan');
      }
    } finally {
      setIsLoading(false);
    }
  };

  const handleAddTask = async (planId: string) => {
    if (!newTask.title || !newTask.objective) return;
    const plan = workPlans.find(wp => wp.id === planId);
    if (!plan) return;
    const newTaskObj: WorkPlanTask = {
      id: `T-${planId}-${Date.now()}`,
      title: newTask.title,
      objective: newTask.objective,
      expectedOutput: newTask.expectedOutput,
      startDate: newTask.startDate,
      endDate: newTask.endDate,
      status: 'Not Started',
      remarks: newTask.remarks,
      weeklyProgress: [],
    };
    const updatedTasks = [...(Array.isArray(plan.tasks) ? plan.tasks : []), newTaskObj];
    const success = await handleUpdateWorkPlan(planId, { tasks: updatedTasks });
    if (success) {
      setNewTask({ title: '', objective: '', expectedOutput: '', startDate: '', endDate: '', remarks: '' });
      setShowAddTask(null);
      showToast('Task added successfully');
    }
  };

  const handleUpdateProgress = async (planId: string, week: number, progress: number, notes: string) => {
    const plan = workPlans.find(wp => wp.id === planId);
    if (!plan) return;
    const newProgress = Math.min(100, (plan.progress || 0) + progress);
    const newStatus = newProgress >= 100 ? 'Completed' : newProgress > 0 ? 'In Progress' : 'Not Started';
    const existingTasks = Array.isArray(plan.tasks) ? plan.tasks : [];
    const weeklyEntry = { week, progress, notes, date: new Date().toISOString() };
    const updatedTasks = existingTasks.map((task, index) =>
      index === 0
        ? {
            ...task,
            weeklyProgress: [...(Array.isArray(task.weeklyProgress) ? task.weeklyProgress : []), weeklyEntry],
            status: newProgress >= 100 ? 'Completed' as const : newProgress > 0 ? 'In Progress' as const : 'Not Started' as const,
          }
        : task
    );
    setWorkPlans(prev =>
      prev.map(wp =>
        wp.id === planId ? { ...wp, progress: newProgress, status: newStatus, tasks: updatedTasks } : wp
      )
    );
    const success = await handleUpdateWorkPlan(planId, {
      progress: newProgress,
      status: newStatus,
      tasks: updatedTasks,
    });
    if (success) showToast(`Progress updated to ${newProgress}%`);
    else showToast('Error saving progress');
  };

  const handleAddKPI = async () => {
    if (!newKPI.title || !newKPI.targetValue) return;
    const employeeIdentifier = user?.employeeId || user?.id;
    if (!employeeIdentifier) return;
    setIsLoading(true);
    try {
      const saved = await createKpi({
        employeeId: employeeIdentifier,
        title: newKPI.title,
        description: newKPI.description,
        targetValue: newKPI.targetValue,
        measurementMethod: newKPI.measurementMethod,
        frequency: newKPI.frequency,
        targetDeadline: newKPI.targetDeadline,
        linkedGoalId: newKPI.linkedGoalId,
      });
      if (saved) {
        setKpis(prev => [...prev, saved]);
        setNewKPI({ title: '', description: '', targetValue: '', measurementMethod: '', frequency: 'Monthly', targetDeadline: '', weight: '', linkedGoalId: '' });
        setShowAddKPI(false);
        showToast('KPI saved successfully');
      } else {
        showToast('Error saving KPI');
      }
    } finally {
      setIsLoading(false);
    }
  };

  const handleAddIPI = async () => {
    if (!newIPI.indicatorName?.trim()) return;
    const employeeIdentifier = user?.employeeId || user?.id;
    if (!employeeIdentifier) return;
    let taskTitle = '';
    let workPlanId = '';
    const allTasks = workPlans.flatMap(wp => (Array.isArray(wp.tasks) ? wp.tasks : []));
    const task = allTasks.find(t => t.id === newIPI.workPlanTaskId);
    taskTitle = task?.title || '';
    const parentPlan = workPlans.find(
      wp => Array.isArray(wp.tasks) && wp.tasks.some(t => t.id === newIPI.workPlanTaskId)
    );
    workPlanId = parentPlan?.id || workPlans[0]?.id || '';
    if (!workPlanId) {
      showToast('Create a work plan first');
      return;
    }
    setIsLoading(true);
    try {
      const saved = await createIpi({
        employeeId: employeeIdentifier,
        workPlanId,
        workPlanTaskId: newIPI.workPlanTaskId,
        indicatorName: newIPI.indicatorName,
        target: newIPI.target,
        measurementCriteria: newIPI.measurementCriteria,
        expectedPerformance: newIPI.expectedPerformance,
        ratingScale: newIPI.ratingScale,
        taskTitle,
      });
      if (saved) {
        setIpis(prev => [...prev, saved]);
        setNewIPI({ workPlanTaskId: '', indicatorName: '', target: '', measurementCriteria: '', expectedPerformance: '', ratingScale: '' });
        setShowAddIPI(false);
        showToast('IPI saved successfully');
      } else {
        showToast('Error saving IPI');
      }
    } finally {
      setIsLoading(false);
    }
  };

  const handleAddQuarterly = async () => {
    if (!newQuarterly.title || !newQuarterly.kpiMeasurement) return;
    const employeeIdentifier = user?.employeeId || user?.id;
    if (!employeeIdentifier) return;
    setIsLoading(true);
    try {
      const saved = await createQuarterlyTarget({
        employeeId: employeeIdentifier,
        title: newQuarterly.title,
        quarter: newQuarterly.quarter,
        year: Number(newQuarterly.year),
        target: newQuarterly.kpiMeasurement,
        kpiMeasurement: newQuarterly.kpiMeasurement,
        expectedOutcome: newQuarterly.expectedOutcome,
        completionTimeline: newQuarterly.completionTimeline,
        weight: Number(newQuarterly.weight),
        linkedWorkPlanId: newQuarterly.linkedWorkPlanId,
      });
      if (saved) {
        setQuarterlyTargets(prev => [...prev, saved]);
        setNewQuarterly({ quarter: 'Q1', year: '2026', title: '', kpiMeasurement: '', expectedOutcome: '', completionTimeline: '', weight: '10', linkedWorkPlanId: '' });
        setShowAddQuarterly(false);
        showToast('Quarterly target saved successfully');
      } else {
        showToast('Error saving quarterly target');
      }
    } finally {
      setIsLoading(false);
    }
  };

  const TABS: { id: Tab; label: string; icon: string }[] = [
    { id: 'workplan', label: 'Work Plan', icon: 'ri-file-list-3-line' },
    { id: 'kpis', label: 'My KPIs', icon: 'ri-bar-chart-line' },
    { id: 'quarterly', label: 'Quarterly Targets', icon: 'ri-calendar-check-line' },
    { id: 'ipis', label: 'My IPIs', icon: 'ri-line-chart-line' },
    { id: 'appraisals', label: 'Appraisals', icon: 'ri-star-line' },
    { id: 'pip', label: 'PIP', icon: 'ri-alarm-warning-line' },
  ];

  const statusColors: Record<string, string> = {
    'Pending Self-Assessment': 'bg-yellow-100 text-yellow-700',
    'Submitted': 'bg-blue-100 text-blue-700',
    'Pending HOD Approval': 'bg-amber-100 text-amber-700',
    'Approved by HOD': 'bg-purple-100 text-purple-700',
    'Completed': 'bg-green-100 text-green-700',
  };

  return (
    <EmployeeLayout title="My Performance">
      {toast && (
        <div className="fixed top-20 right-6 z-[100] bg-green-600 text-white px-5 py-3 rounded-xl shadow-lg text-sm font-medium">
          {toast}
        </div>
      )}
      {isLoading && (
        <div className="fixed inset-0 bg-black/30 z-[200] flex items-center justify-center">
          <div className="bg-white rounded-xl p-6 flex items-center gap-3">
            <div className="w-6 h-6 border-2 border-purple-600 border-t-transparent rounded-full animate-spin" />
            <span className="text-sm text-gray-700">Saving...</span>
          </div>
        </div>
      )}
      {!user && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-10 text-center text-gray-500">
          Loading…
        </div>
      )}
      <div className="mb-5">
        <h2 className="text-lg font-bold text-gray-800">Performance Management</h2>
        <p className="text-sm text-gray-500 mt-0.5">Work plan, KPIs, targets, tasks, and appraisals</p>
      </div>

      {unreadComments.length > 0 && (
        <div className="mb-4 bg-purple-50 border border-purple-300 rounded-xl px-4 py-3">
          <div className="flex items-center gap-2 mb-2">
            <i className="ri-chat-3-line text-purple-600"></i>
            <p className="text-sm font-semibold text-purple-800">{unreadComments.length} new comment{unreadComments.length > 1 ? 's' : ''} from your supervisor</p>
          </div>
          <div className="space-y-2">
            {unreadComments.map(c => (
              <div key={c.id} className="bg-white rounded-lg px-3 py-2.5 border border-purple-200 flex items-start justify-between gap-3">
                <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">{c.itemType.toUpperCase()}</span>
                    <span className="text-xs font-medium text-gray-700">{c.itemTitle}</span>
                    <span className="text-xs text-gray-400">{c.createdAt}</span>
                  </div>
                  <p className="text-xs text-gray-700">{c.comment}</p>
                  <p className="text-xs text-purple-500 mt-1">From: <strong>{c.commentBy}</strong></p>
                </div>
                <button onClick={() => markRead(c.id)} className="text-xs text-purple-600 hover:text-purple-800 cursor-pointer whitespace-nowrap flex items-center gap-1">
                  <i className="ri-check-line"></i> Mark read
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="mb-4 bg-amber-50 border border-amber-200 rounded-xl px-4 py-3 flex items-start gap-2">
        <i className="ri-information-line text-amber-600 mt-0.5"></i>
        <p className="text-xs text-amber-800">Your HOD can review and comment on your performance items. Check the purple notification above for any new feedback.</p>
      </div>

      <div className="mb-5 overflow-x-auto">
        <div className="flex gap-1 bg-white rounded-xl shadow-sm border border-gray-100 p-1 min-w-max">
          {TABS.map(t => (
            <button key={t.id} onClick={() => setActiveTab(t.id)}
              className={`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${activeTab === t.id ? 'text-white shadow-sm' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'}`}
              style={activeTab === t.id ? { background: BRAND } : {}}>
              <div className="w-4 h-4 flex items-center justify-center">
                <i className={`${t.icon} text-xs`}></i>
              </div>
              {t.label}
              {t.id === 'pip' && myPIPs.filter(p => p.status === 'Active').length > 0 && (
                <span className="ml-1 bg-red-500 text-white text-xs rounded-full w-4 h-4 flex items-center justify-center font-bold">!</span>
              )}
            </button>
          ))}
        </div>
      </div>

      {activeTab === 'workplan' && (
        <div className="space-y-4">
          <motion.div
            initial={{ opacity: 0, y: 12 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.4 }}
            className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5"
          >
            <div className="flex items-center justify-between mb-4">
              <div>
                <h3 className="font-bold text-gray-800">My Work Plan 2026</h3>
                <p className="text-xs text-gray-500 mt-0.5">Based on departmental targets set by your HOD</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>

            <div className="mb-4 bg-blue-50 border border-blue-200 rounded-xl p-4">
              <p className="text-xs font-semibold mb-2 text-blue-700">Organization Strategic Goals (Uwezo Fund 2025/2026)</p>
              <div className="space-y-1.5">
                {COMPANY_GOALS.map((g, idx) => (
                  <div key={g.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 bg-blue-600">{idx + 1}</div>
                    <div>
                      <p className="text-xs font-medium text-blue-800">{g.kra}</p>
                      <p className="text-xs text-blue-700">{g.title}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {DEPT_TARGETS.length > 0 && (
              <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 }}>Departmental Targets (Set by HOD)</p>
                <div className="space-y-2">
                  {DEPT_TARGETS.map(dt => (
                    <div key={dt.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 }}>
                        {dt.id.replace('DT', '').replace('SDT-', '').slice(0, 2)}
                      </div>
                      <p className="text-xs text-gray-700">{dt.title}</p>
                    </div>
                  ))}
                </div>
              </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">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 cursor-pointer">
                      <option value="">Select target...</option>
                      {DEPT_TARGETS.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="Your work plan objective" />
                  </div>
                  <div>
                    <label className="text-xs font-medium text-gray-600 block mb-1">Target / Success Metric</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>
            )}

            {showAddTask && (
              <div className="bg-blue-50 border border-blue-200 rounded-xl p-4 mb-4">
                <h4 className="font-semibold text-blue-800 text-sm mb-3">Add Task to Work Plan</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">Task Title *</label>
                    <input value={newTask.title} onChange={e => setNewTask(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. Design data collection forms" />
                  </div>
                  <div className="col-span-2">
                    <label className="text-xs font-medium text-gray-600 block mb-1">Objective *</label>
                    <input value={newTask.objective} onChange={e => setNewTask(p => ({ ...p, objective: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="What this task aims to achieve" />
                  </div>
                  <div className="col-span-2">
                    <label className="text-xs font-medium text-gray-600 block mb-1">Expected Output</label>
                    <input value={newTask.expectedOutput} onChange={e => setNewTask(p => ({ ...p, expectedOutput: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="Deliverable from this task" />
                  </div>
                  <div>
                    <label className="text-xs font-medium text-gray-600 block mb-1">Start Date</label>
                    <input type="date" value={newTask.startDate} onChange={e => setNewTask(p => ({ ...p, startDate: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                  </div>
                  <div>
                    <label className="text-xs font-medium text-gray-600 block mb-1">End Date</label>
                    <input type="date" value={newTask.endDate} onChange={e => setNewTask(p => ({ ...p, endDate: 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">Remarks</label>
                    <textarea value={newTask.remarks} onChange={e => setNewTask(p => ({ ...p, remarks: e.target.value }))} rows={2} maxLength={200} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" />
                  </div>
                </div>
                <div className="flex gap-2 mt-3">
                  <button onClick={() => setShowAddTask(null)} className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
                  <button onClick={() => handleAddTask(showAddTask)} className="px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: BRAND }}>Save Task</button>
                </div>
              </div>
            )}

            <div className="space-y-4">
              {workPlans.map(plan => {
                const wpComments = myComments.filter(c => c.itemId === plan.id && c.itemType === 'workplan');
                return (
                  <div key={plan.id}>
                    <WorkPlanCard
                      plan={plan}
                      deptTargetTitle={DEPT_TARGETS.find(t => t.id === plan.linkedTargetId)?.title}
                      onAddTask={(id) => setShowAddTask(id)}
                      onUpdateProgress={handleUpdateProgress}
                      onUpdate={async updatedPlan => {
                        setWorkPlans(prev => prev.map(wp => (wp.id === updatedPlan.id ? updatedPlan : wp)));
                        await handleUpdateWorkPlan(updatedPlan.id, updatedPlan);
                      }}
                    />
                    {wpComments.map(c => (
                      <div key={c.id} className="mt-2 bg-purple-50 border border-purple-200 rounded-xl px-3 py-2.5">
                        <div className="flex items-center gap-2 mb-1">
                          <i className="ri-chat-3-line text-purple-600 text-sm"></i>
                          <span className="text-xs font-semibold text-purple-700">HOD Comment — {c.createdAt}</span>
                          {!c.read && <span className="text-xs bg-purple-600 text-white px-1.5 py-0.5 rounded-full">New</span>}
                        </div>
                        <p className="text-xs text-gray-700">{c.comment}</p>
                      </div>
                    ))}
                  </div>
                );
              })}
            </div>
          </motion.div>
        </div>
      )}

      {activeTab === 'kpis' && (
        <div className="space-y-4">
          <div className="flex items-center justify-between mb-2">
            <h3 className="font-bold text-gray-800">My Key Performance Indicators</h3>
            <button onClick={() => setShowAddKPI(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 KPI
            </button>
          </div>

          {showAddKPI && (
            <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 mb-4">
              <h4 className="font-semibold text-gray-700 text-sm mb-3">New KPI</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">Linked Organization / Strategic Goal</label>
                  <select value={newKPI.linkedGoalId} onChange={e => setNewKPI(p => ({ ...p, linkedGoalId: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8 cursor-pointer">
                    <option value="">Select strategic goal (optional)...</option>
                    {COMPANY_GOALS.map(g => (
                      <option key={g.id} value={g.id}>{g.kra}: {g.title.slice(0, 60)}...</option>
                    ))}
                  </select>
                </div>
                <div className="col-span-2">
                  <label className="text-xs font-medium text-gray-600 block mb-1">KPI Title *</label>
                  <input value={newKPI.title} onChange={e => setNewKPI(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. Customer Satisfaction Score" />
                </div>
                <div className="col-span-2">
                  <label className="text-xs font-medium text-gray-600 block mb-1">Description</label>
                  <textarea value={newKPI.description} onChange={e => setNewKPI(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="What this KPI measures" />
                </div>
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Target Value *</label>
                  <input value={newKPI.targetValue} onChange={e => setNewKPI(p => ({ ...p, targetValue: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. 90% or 4.5/5" />
                </div>
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Measurement Method</label>
                  <input value={newKPI.measurementMethod} onChange={e => setNewKPI(p => ({ ...p, measurementMethod: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="How this is measured" />
                </div>
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Frequency</label>
                  <div className="flex gap-1 bg-gray-100 rounded-lg p-1">
                    {(['Monthly','Quarterly','Annual'] as const).map(f => (
                      <button key={f} onClick={() => setNewKPI(p => ({ ...p, frequency: f }))}
                        className={`flex-1 py-1.5 rounded-md text-xs font-medium cursor-pointer whitespace-nowrap ${newKPI.frequency === f ? 'bg-white text-gray-800 shadow-sm' : 'text-gray-500'}`}>
                        {f}
                      </button>
                    ))}
                  </div>
                </div>
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Target Deadline</label>
                  <input type="date" value={newKPI.targetDeadline} onChange={e => setNewKPI(p => ({ ...p, targetDeadline: 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={() => setShowAddKPI(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={handleAddKPI} className="px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: BRAND }}>Save KPI</button>
              </div>
            </motion.div>
          )}

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {kpis.map((k, i) => {
              const kpiComments = myComments.filter(c => c.itemId === k.id && c.itemType === 'kpi');
              return (
                <div key={k.id}>
                  <KPIGauge
                    kpi={k}
                    index={i}
                    onUpdate={async updated => {
                      const saved = await updateKpi(updated.id, updated);
                      if (saved) {
                        setKpis(prev => prev.map(x => (x.id === saved.id ? saved : x)));
                        showToast('KPI updated successfully');
                      } else {
                        showToast('Error updating KPI');
                      }
                    }}
                  />
                  {kpiComments.map(c => (
                    <div key={c.id} className="mt-2 bg-purple-50 border border-purple-200 rounded-xl px-3 py-2.5">
                      <div className="flex items-center gap-2 mb-1">
                        <i className="ri-chat-3-line text-purple-600 text-sm"></i>
                        <span className="text-xs font-semibold text-purple-700">HOD Comment — {c.createdAt}</span>
                        {!c.read && <span className="text-xs bg-purple-600 text-white px-1.5 py-0.5 rounded-full">New</span>}
                      </div>
                      <p className="text-xs text-gray-700">{c.comment}</p>
                    </div>
                  ))}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {activeTab === 'quarterly' && (
        <div className="space-y-4">
          <div className="flex items-center justify-between mb-2">
            <h3 className="font-bold text-gray-800">Quarterly Targets</h3>
            <button onClick={() => setShowAddQuarterly(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>

          {showAddQuarterly && (
            <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 mb-4">
              <h4 className="font-semibold text-gray-700 text-sm mb-3">New Quarterly Target</h4>
              <div className="grid grid-cols-2 gap-3">
                <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={() => setNewQuarterly(p => ({ ...p, quarter: q }))}
                        className={`flex-1 py-1.5 rounded-md text-xs font-medium cursor-pointer whitespace-nowrap ${newQuarterly.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">Year</label>
                  <input value={newQuarterly.year} onChange={e => setNewQuarterly(p => ({ ...p, year: 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">Target Title *</label>
                  <input value={newQuarterly.title} onChange={e => setNewQuarterly(p => ({ ...p, title: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="What you aim to achieve this quarter" />
                </div>
                <div className="col-span-2">
                  <label className="text-xs font-medium text-gray-600 block mb-1">KPI Measurement *</label>
                  <input value={newQuarterly.kpiMeasurement} onChange={e => setNewQuarterly(p => ({ ...p, kpiMeasurement: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="How progress is measured" />
                </div>
                <div className="col-span-2">
                  <label className="text-xs font-medium text-gray-600 block mb-1">Expected Outcome</label>
                  <input value={newQuarterly.expectedOutcome} onChange={e => setNewQuarterly(p => ({ ...p, expectedOutcome: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="Final deliverable or result" />
                </div>
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Completion Timeline</label>
                  <input type="date" value={newQuarterly.completionTimeline} onChange={e => setNewQuarterly(p => ({ ...p, completionTimeline: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                </div>
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Weight (%)</label>
                  <input type="number" value={newQuarterly.weight} onChange={e => setNewQuarterly(p => ({ ...p, weight: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="10" />
                </div>
                <div className="col-span-2">
                  <label className="text-xs font-medium text-gray-600 block mb-1">Linked Work Plan</label>
                  <select value={newQuarterly.linkedWorkPlanId} onChange={e => setNewQuarterly(p => ({ ...p, linkedWorkPlanId: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8 cursor-pointer">
                    <option value="">Select work plan...</option>
                    {workPlans.map(w => <option key={w.id} value={w.id}>{w.objective.slice(0, 50)}...</option>)}
                  </select>
                </div>
              </div>
              <div className="flex gap-2 mt-3">
                <button onClick={() => setShowAddQuarterly(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={handleAddQuarterly} className="px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: BRAND }}>Save Target</button>
              </div>
            </motion.div>
          )}

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {quarterlyTargets.map((q, i) => {
              const qtComments = myComments.filter(c => c.itemId === q.id && c.itemType === 'quarterly');
              return (
                <div key={q.id}>
                  <QuarterlyTargetCard
                    target={q}
                    index={i}
                    workPlanTitle={workPlans.find(w => w.id === q.linkedWorkPlanId)?.objective}
                    onUpdate={async updated => {
                      const saved = await updateQuarterlyTarget(updated.id, updated);
                      if (saved) {
                        setQuarterlyTargets(prev => prev.map(x => (x.id === saved.id ? saved : x)));
                        showToast('Quarterly target updated successfully');
                      } else {
                        showToast('Error updating quarterly target');
                      }
                    }}
                  />
                  {qtComments.map(c => (
                    <div key={c.id} className="mt-2 bg-purple-50 border border-purple-200 rounded-xl px-3 py-2.5">
                      <div className="flex items-center gap-2 mb-1">
                        <i className="ri-chat-3-line text-purple-600 text-sm"></i>
                        <span className="text-xs font-semibold text-purple-700">HOD Comment — {c.createdAt}</span>
                        {!c.read && <span className="text-xs bg-purple-600 text-white px-1.5 py-0.5 rounded-full">New</span>}
                      </div>
                      <p className="text-xs text-gray-700">{c.comment}</p>
                    </div>
                  ))}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {activeTab === 'ipis' && (
        <div className="space-y-4">
          <div className="flex items-center justify-between mb-2">
            <div>
              <h3 className="font-bold text-gray-800">My Individual Performance Indicators (IPIs)</h3>
              <p className="text-xs text-gray-500 mt-0.5">Linked to work plan activities 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 && (
            <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 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 Activity *</label>
                  <select value={newIPI.workPlanTaskId} onChange={e => setNewIPI(p => ({ ...p, workPlanTaskId: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8 cursor-pointer">
                    <option value="">Select activity...</option>
                    {workPlans.flatMap(wp => (Array.isArray(wp.tasks) ? wp.tasks : [])).map(t => (
                      <option key={t.id} value={t.id}>{t.title} ({workPlans.find(wp => Array.isArray(wp.tasks) && wp.tasks.some(tt => tt.id === t.id))?.objective})</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Indicator Name *</label>
                  <input value={newIPI.indicatorName} onChange={e => setNewIPI(p => ({ ...p, indicatorName: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. Reports submitted before Friday deadline" />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <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. 100%" />
                  </div>
                  <div>
                    <label className="text-xs font-medium text-gray-600 block mb-1">Rating Scale</label>
                    <input value={newIPI.ratingScale} onChange={e => setNewIPI(p => ({ ...p, ratingScale: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. 1-5 (5=Excellent)" />
                  </div>
                </div>
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Measurement Criteria</label>
                  <input value={newIPI.measurementCriteria} onChange={e => setNewIPI(p => ({ ...p, measurementCriteria: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="How this indicator is measured" />
                </div>
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Expected Performance</label>
                  <input value={newIPI.expectedPerformance} onChange={e => setNewIPI(p => ({ ...p, expectedPerformance: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="Expected level of performance" />
                </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>
            </motion.div>
          )}

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {ipis.map((ipi, i) => {
              const ipiComments = myComments.filter(c => c.itemId === ipi.id && c.itemType === 'ipi');
              return (
                <div key={ipi.id}>
                  <IPICard
                    ipi={ipi}
                    index={i}
                    onUpdate={async updated => {
                      const saved = await updateIpi(updated.id, updated);
                      if (saved) {
                        setIpis(prev => prev.map(x => (x.id === saved.id ? saved : x)));
                        showToast('IPI updated successfully');
                      } else {
                        showToast('Error updating IPI');
                      }
                    }}
                  />
                  {ipiComments.map(c => (
                    <div key={c.id} className="mt-2 bg-purple-50 border border-purple-200 rounded-xl px-3 py-2.5">
                      <div className="flex items-center gap-2 mb-1">
                        <i className="ri-chat-3-line text-purple-600 text-sm"></i>
                        <span className="text-xs font-semibold text-purple-700">HOD Comment — {c.createdAt}</span>
                        {!c.read && <span className="text-xs bg-purple-600 text-white px-1.5 py-0.5 rounded-full">New</span>}
                      </div>
                      <p className="text-xs text-gray-700">{c.comment}</p>
                    </div>
                  ))}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {activeTab === 'appraisals' && (
        <div className="space-y-4">
          {myAppraisals.length === 0 ? (
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-12 text-center">
              <div className="w-16 h-16 flex items-center justify-center mx-auto mb-4 rounded-2xl" style={{ background: '#fdf2fb' }}>
                <i className="ri-bar-chart-line text-3xl" style={{ color: '#b828a0' }}></i>
              </div>
              <p className="text-gray-500 font-medium">No appraisals yet</p>
              <p className="text-gray-400 text-sm mt-1">Your HR team will create an appraisal for you when the cycle begins.</p>
            </div>
          ) : (
            myAppraisals.map(a => {
              const canAssess = a.status === 'Pending Self-Assessment';
              const isSubmitted = a.status !== 'Pending Self-Assessment';
              const allRatings = [...a.companyGoalRatings, ...a.deptGoalRatings];
              const avgSelf = allRatings.length > 0
                ? (allRatings.reduce((s, r) => s + r.selfRating, 0) / allRatings.length).toFixed(1)
                : null;

              return (
                <div key={a.id} className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
                  <div className="flex items-start justify-between mb-4">
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <h3 className="font-bold text-gray-800">{a.period}</h3>
                        <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${statusColors[a.status]}`}>
                          {a.status}
                        </span>
                      </div>
                      <p className="text-sm text-gray-500">HOD: {a.hodName}</p>
                    </div>
                    <div className="text-right">
                      {a.overallRating > 0 ? (
                        <>
                          <p className="text-3xl font-bold" style={{ color: '#b828a0' }}>{a.overallRating.toFixed(1)}</p>
                          <p className="text-xs text-gray-400">out of 5</p>
                        </>
                      ) : avgSelf ? (
                        <>
                          <p className="text-2xl font-bold text-blue-600">{avgSelf}</p>
                          <p className="text-xs text-gray-400">self avg</p>
                        </>
                      ) : (
                        <p className="text-2xl font-bold text-gray-300">—</p>
                      )}
                    </div>
                  </div>

                  {canAssess && (
                    <div className="bg-yellow-50 border border-yellow-200 rounded-xl p-3 mb-4 flex items-center gap-2">
                      <i className="ri-alarm-warning-line text-yellow-600 text-sm"></i>
                      <p className="text-xs text-yellow-800 font-medium">Your self-assessment is pending. Please complete it before the deadline.</p>
                    </div>
                  )}

                  {a.hodComments && (
                    <div className="rounded-xl p-3 mb-4" style={{ background: '#fdf2fb', border: '1px solid #f0c0ec' }}>
                      <p className="text-xs font-semibold mb-1" style={{ color: '#b828a0' }}>HOD Feedback</p>
                      <p className="text-xs text-gray-700">{a.hodComments}</p>
                    </div>
                  )}

                  <div className="flex gap-3 flex-wrap">
                    {canAssess && (
                      <button onClick={() => setAssessingAppraisal(a)}
                        className="flex items-center gap-2 px-4 py-2 text-white rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap"
                        style={{ background: '#b828a0' }}>
                        <i className="ri-edit-2-line"></i> Start Self-Assessment
                      </button>
                    )}
                    {isSubmitted && (
                      <button onClick={() => setViewAppraisal(a)}
                        className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-xl text-sm text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
                        <i className="ri-eye-line"></i> View Details
                      </button>
                    )}
                  </div>
                </div>
              );
            })
          )}
        </div>
      )}

      {activeTab === 'pip' && (
        <div className="space-y-4">
          <div className="bg-blue-50 border border-blue-200 rounded-xl px-4 py-3 flex items-start gap-2">
            <i className="ri-information-line text-blue-600 mt-0.5"></i>
            <p className="text-xs text-blue-800">PIPs can be initiated by HR or your HOD based on your appraisal performance. You can also create your own AI-generated PIP below.</p>
          </div>

          <div className="flex gap-2 mb-2">
            <button onClick={() => setShowAIPIP(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: '#6366f1' }}>
              <i className="ri-magic-line"></i> AI Generate My PIP
            </button>
          </div>

          {showAIPIP && (
            <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 mb-4">
              <div className="flex items-center justify-between mb-3">
                <h4 className="font-semibold text-gray-700 text-sm">AI-Generated PIP</h4>
                <button onClick={() => setShowAIPIP(false)} className="w-7 h-7 flex items-center justify-center rounded-lg hover:bg-gray-100 cursor-pointer"><i className="ri-close-line text-gray-500"></i></button>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">PIP Duration</label>
                  <select value={aiPipForm.duration} onChange={e => setAiPipForm(f => ({ ...f, duration: e.target.value as any }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8 cursor-pointer">
                    <option>30 days</option><option>60 days</option><option>90 days</option>
                  </select>
                </div>
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Start Date</label>
                  <input type="date" value={aiPipForm.startDate} onChange={e => setAiPipForm(f => ({ ...f, startDate: 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">Improvement Areas</label>
                  <textarea value={aiPipForm.improvementAreas} onChange={e => setAiPipForm(f => ({ ...f, improvementAreas: e.target.value }))} rows={3} maxLength={500} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" placeholder="List improvement areas..." />
                </div>
                <div className="col-span-2">
                  <label className="text-xs font-medium text-gray-600 block mb-1">Action Plan</label>
                  <textarea value={aiPipForm.actionPlan} onChange={e => setAiPipForm(f => ({ ...f, actionPlan: e.target.value }))} rows={3} maxLength={500} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" placeholder="Specific steps..." />
                </div>
                <div className="col-span-2">
                  <label className="text-xs font-medium text-gray-600 block mb-1">Success Metrics</label>
                  <textarea value={aiPipForm.successMetrics} onChange={e => setAiPipForm(f => ({ ...f, successMetrics: e.target.value }))} rows={2} maxLength={500} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" placeholder="Measurable criteria..." />
                </div>
              </div>
              <div className="flex gap-2 mt-3 flex-wrap">
                <button onClick={() => setShowAIPIP(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={handleGenerateAIPIP}
                  className="px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap flex items-center gap-1.5"
                  style={{ background: '#6366f1' }}>
                  <i className="ri-magic-line"></i> AI Suggest PIP
                </button>
                <button onClick={handleCreateEmployeePIP} className="px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Create My PIP</button>
              </div>
            </motion.div>
          )}

          {myPIPs.length === 0 ? (
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-12 text-center">
              <div className="w-16 h-16 flex items-center justify-center mx-auto mb-4 rounded-2xl bg-green-50">
                <i className="ri-checkbox-circle-line text-3xl text-green-500"></i>
              </div>
              <p className="text-gray-500 font-medium">No Performance Improvement Plans</p>
              <p className="text-gray-400 text-sm mt-1">You currently have no active PIPs. Keep up the great work!</p>
            </div>
          ) : (
            myPIPs.map(pip => (
              <div key={pip.id} className="bg-white rounded-2xl shadow-sm border border-red-200 p-5">
                <div className="flex items-start justify-between mb-4">
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <h3 className="font-bold text-gray-800">PIP — {pip.id}</h3>
                      <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${pip.status === 'Extended' ? 'bg-red-100 text-red-700' : pip.status === 'Successful' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-600'}`}>
                        {pip.status}
                      </span>
                    </div>
                    <p className="text-sm text-gray-500">Duration: {pip.duration} · Started: {pip.startDate}</p>
                    <p className="text-sm text-gray-500">Supervisor: {pip.hod}</p>
                  </div>
                  <div className="text-right">
                    <p className="text-2xl font-bold text-red-600">{pip.checkIns[pip.checkIns.length - 1]?.progress || 0}%</p>
                    <p className="text-xs text-gray-400">Progress</p>
                  </div>
                </div>
                <div className="w-full bg-gray-100 rounded-full h-3 mb-4">
                  <div className="h-3 rounded-full" style={{ width: `${pip.checkIns[pip.checkIns.length - 1]?.progress || 0}%`, background: '#dc2626' }}></div>
                </div>
                <div className="space-y-2">
                  <p className="text-xs font-semibold text-gray-600">Improvement Areas:</p>
                  {pip.improvementAreas.map((area, i) => (
                    <div key={i} className="flex items-center gap-2 text-xs text-gray-600">
                      <i className="ri-arrow-right-s-line text-red-400"></i>
                      <span>{area}</span>
                    </div>
                  ))}
                </div>
                {pip.checkIns.length > 0 && (
                  <div className="mt-4 border-t border-gray-100 pt-3">
                    <p className="text-xs font-semibold text-gray-600 mb-2">Latest Check-in</p>
                    <div className="bg-gray-50 rounded-lg p-3">
                      <p className="text-xs text-gray-600">{pip.checkIns[pip.checkIns.length - 1]?.notes}</p>
                      <p className="text-xs text-gray-400 mt-1">{pip.checkIns[pip.checkIns.length - 1]?.date}</p>
                    </div>
                  </div>
                )}
                <div className="mt-3 text-xs text-gray-400 bg-gray-50 rounded-lg px-3 py-2">
                  <i className="ri-information-line mr-1"></i>
                  Contact your HOD or HR Manager to update PIP progress or improvement areas.
                </div>
              </div>
            ))
          )}
        </div>
      )}

      {assessingAppraisal && (
        <SelfAssessmentForm
          appraisal={assessingAppraisal}
          onSave={handleSave}
          onClose={() => setAssessingAppraisal(null)}
        />
      )}

      {viewAppraisal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl w-full max-w-2xl max-h-[90vh] flex flex-col shadow-2xl">
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: '#b828a0' }}>
              <div>
                <h2 className="text-white font-bold">Appraisal Details — {viewAppraisal.period}</h2>
                <p className="text-pink-200 text-xs">{viewAppraisal.status}</p>
              </div>
              <button onClick={() => setViewAppraisal(null)} 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="flex-1 overflow-y-auto p-6 space-y-4">
              {viewAppraisal.companyGoalRatings.length > 0 && (
                <div>
                  <h4 className="font-semibold text-gray-800 text-sm mb-3">Company Goal Ratings</h4>
                  <div className="space-y-2">
                    {viewAppraisal.companyGoalRatings.map(r => {
                      const goal = COMPANY_GOALS.find(g => g.id === r.goalId);
                      return (
                        <div key={r.goalId} className="border border-gray-100 rounded-xl p-3">
                          <p className="text-sm font-medium text-gray-800 mb-2">{goal?.title}</p>
                          <div className="flex items-center gap-3">
                            <div>
                              <p className="text-xs text-gray-400">Self</p>
                              <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${RATING_BG[r.selfRating]}`}>{r.selfRating}/5</span>
                            </div>
                            {r.hodRating && (
                              <div>
                                <p className="text-xs text-gray-400">HOD</p>
                                <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${RATING_BG[r.hodRating]}`}>{r.hodRating}/5</span>
                              </div>
                            )}
                          </div>
                          {r.selfComment && <p className="text-xs text-gray-500 mt-1 italic">"{r.selfComment}"</p>}
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}
              {viewAppraisal.hodComments && (
                <div className="rounded-xl p-4" style={{ background: '#fdf2fb', border: '1px solid #f0c0ec' }}>
                  <p className="text-xs font-semibold mb-1" style={{ color: '#b828a0' }}>HOD Feedback</p>
                  <p className="text-sm text-gray-700">{viewAppraisal.hodComments}</p>
                </div>
              )}
            </div>
            <div className="px-6 pb-6">
              <button onClick={() => setViewAppraisal(null)} className="w-full py-3 rounded-xl border border-gray-200 text-sm font-medium text-gray-600 cursor-pointer whitespace-nowrap">Close</button>
            </div>
          </div>
        </div>
      )}
    </EmployeeLayout>
  );
}