'use client';

import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { useSession } from 'next-auth/react';
import { motion, useReducedMotion } from 'motion/react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { type User } from '@/lib/types';
import { api } from '@/lib/store/api';
import { apiCall, apiErrorMessage } from '@/lib/store/api-call';
import { store } from '@/lib/store/store';
import { 
  TrendingUp, 
  Calendar, 
  BarChart3, 
  Save,
  Edit,
  Check,
  X,
  FileText,
  Palette,
  Plus,
  Trash2,
} from 'lucide-react';
import { AppSpinner } from '@/components/ui/app-loader';
import { ChartPanelSkeleton } from '@/components/ui/loading-skeletons';

import { formatDate as formatDateUtil, enumerateMonthRange, monthWindowForDateRange, personalKpiCyclesFromRecords, personalKpiPeriodKey, yearMonthFromDateInput, formatPersonalKpiCycleLabel, spanForPersonalKpiPeriod, parsePersonalKpiEditKey, latestPersonalKpiRecordWithRemarks } from '@/lib/date-utils';
import { MonthYearPicker } from '@/components/ui/month-year-picker';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { PerformanceReport } from './performance-report';
import { DesignPerformance } from './design-performance';
import { isSqaUser, shouldUseSqaPerformance, isUnitLeadUser, getUserPerformanceType, isDesignTeamLead, isSeoUser, isPmoUser } from '@/lib/utils';
import { isDesignHead } from '@/lib/constants';
import { staggerContainer, staggerItem } from '@/lib/motion';
import { TablePagination } from '@/components/ui/table-pagination';
import { useGetManagerAccessQuery } from '@/lib/store/api';
import { isEnteredKpiMonth } from '@/lib/scoring-utils';

const MONTHLY_PAGE_SIZE = 10;

// Utility function to format numbers to 2 decimal places maximum
const formatNumber = (value: number | undefined | null): string => {
  if (value === null || value === undefined || isNaN(value)) return '0.00';
  return Number(value).toFixed(2);
};

// Utility function to validate input values and return error state
const validateKPIValue = (value: number, maxValue: number): boolean => {
  return value >= 0 && value <= maxValue;
};

// Utility function to get input className based on validation
const getInputClassName = (value: number, maxValue: number, baseClassName: string): string => {
  const isValid = validateKPIValue(value, maxValue);
  const errorClass = isValid ? '' : ' border-red-500 bg-red-50 focus:border-red-500 focus:ring-red-500';
  return baseClassName + errorClass;
};

interface UserPerformanceProps {
  user: User;
  dateFrom?: string;
  dateTo?: string;
}

// Developer KPI configuration
const DEVELOPER_KPI_CONFIG = {
  codeQuality: { label: 'Code Quality', weight: 20, max: 20 },
  developmentSpeed: { label: 'Development Speed', weight: 10, max: 10 },
  productivity: { label: 'Productivity', weight: 20, max: 20 },
  collaboration: { label: 'Collaboration', weight: 10, max: 10 },
  technicalDebt: { label: 'Technical Debt', weight: 15, max: 15 },
  resourceUtil: { label: 'Resource Utilization', weight: 10, max: 10 },
  projectVelocity: { label: 'Project Velocity', weight: 10, max: 10 },
  teamMorale: { label: 'Team Morale', weight: 5, max: 5 }
};

// SQA KPI configuration
const SQA_KPI_CONFIG = {
  defectDetectionEfficiency: { label: 'Defect Detection Efficiency', weight: 15, max: 15 },
  testCoverage: { label: 'Test Coverage', weight: 20, max: 20 },
  automatedTestingRatio: { label: 'Automated Testing Ratio', weight: 10, max: 10 },
  defectResolutionTime: { label: 'Defect Resolution Time', weight: 15, max: 15 },
  testExecutionEfficiency: { label: 'Test Execution Efficiency', weight: 10, max: 10 },
  documentationQuality: { label: 'Documentation Quality', weight: 10, max: 10 },
  regressionTestingEffectiveness: { label: 'Regression Testing Effectiveness', weight: 15, max: 15 },
  qualityGateAdherence: { label: 'Quality Gate Adherence', weight: 5, max: 5 }
};

// Unit Lead KPI configuration
const UNIT_LEAD_KPI_CONFIG = {
  sprintGoalAchievement: { label: 'Sprint Goal Achievement', weight: 20, max: 20 },
  teamProductivity: { label: 'Team Productivity', weight: 15, max: 15 },
  codeQualityManagement: { label: 'Code Quality Management', weight: 15, max: 15 },
  teamDevelopment: { label: 'Team Development', weight: 10, max: 10 },
  stakeholderSatisfaction: { label: 'Stakeholder Satisfaction', weight: 10, max: 10 },
  riskManagement: { label: 'Risk Management', weight: 10, max: 10 },
  teamRetentionSatisfaction: { label: 'Team Retention & Satisfaction', weight: 10, max: 10 },
  processImprovement: { label: 'Process Improvement', weight: 10, max: 10 }
};

const BIANNUAL_KPI_CONFIG = {
  professionalDev: { label: 'Professional Development', weight: 20, max: 20 },
  processImprovement: { label: 'Process Improvement', weight: 40, max: 40 },
  productInnovation: { label: 'Product Innovation', weight: 40, max: 40 }
};

// IT-specific biannual KPI config (different labels)
const IT_BIANNUAL_KPI_CONFIG = {
  professionalDev: { label: 'Education', weight: 20, max: 20 },
  processImprovement: { label: 'Process Improvement', weight: 40, max: 40 },
  productInnovation: { label: 'Infrastructure', weight: 40, max: 40 }
};

// Design KPI configurations
const DESIGN_GRAPHIC_KPI_CONFIG = {
  designQuality: { label: 'Design Quality', weight: 30, max: 30 },
  designSpeed: { label: 'Design Speed', weight: 25, max: 25 },
  deliverableVolume: { label: 'Deliverable Volume', weight: 20, max: 20 },
  collaboration: { label: 'Collaboration', weight: 10, max: 10 },
  technicalKnowledge: { label: 'Technical Knowledge', weight: 15, max: 15 }
};

const DESIGN_UX_KPI_CONFIG = {
  designQuality: { label: 'Design Quality', weight: 30, max: 30 },
  designSpeed: { label: 'Design Speed', weight: 25, max: 25 },
  userExperienceLogic: { label: 'User Experience Logic', weight: 20, max: 20 },
  sowRevisionAdaptation: { label: 'SOW Revision Adaptation', weight: 10, max: 10 },
  technicalKnowledge: { label: 'Technical Knowledge', weight: 15, max: 15 }
};

const DESIGN_ANIMATION_KPI_CONFIG = {
  deliverableQuality: { label: 'Deliverable Quality', weight: 30, max: 30 },
  deliverableSpeed: { label: 'Deliverable Speed', weight: 25, max: 25 },
  editingEfforts: { label: 'Editing Efforts', weight: 20, max: 20 },
  revisionAdaptation: { label: 'Revision Adaptation', weight: 10, max: 10 },
  technicalKnowledge: { label: 'Technical Knowledge', weight: 15, max: 15 }
};

const DESIGN_TEAM_LEAD_KPI_CONFIG = {
  deliverableDeadlines: { label: 'Deliverable Deadlines', weight: 20, max: 20 },
  teamProductivity: { label: 'Team Productivity', weight: 15, max: 15 },
  artDirection: { label: 'Art Direction', weight: 15, max: 15 },
  teamDevelopment: { label: 'Team Development', weight: 10, max: 10 },
  stakeholderCommunication: { label: 'Stakeholder Communication', weight: 10, max: 10 },
  priorityAdaptation: { label: 'Priority Adaptation', weight: 10, max: 10 },
  teamRetentionSatisfaction: { label: 'Team Retention & Satisfaction', weight: 10, max: 10 },
  uptoDateTaskRecords: { label: 'Up-to-Date Task Records', weight: 10, max: 10 }
};

const DESIGN_PERSONAL_BIANNUAL_KPI_CONFIG = {
  professionalDevelopment: { label: 'Professional Development', weight: 20, max: 20 },
  improvementOfDesignStyle: { label: 'Improvement of Design Style', weight: 40, max: 40 },
  designTrendsKnowledge: { label: 'Design Trends Knowledge', weight: 40, max: 40 }
};

// Marketing Monthly KPI configuration
const MARKETING_MONTHLY_KPI_CONFIG = {
  campaignPerformance: { label: 'Campaign Performance', weight: 15, max: 15 },
  leadGeneration: { label: 'Lead Generation & Conversion', weight: 15, max: 15 },
  budgetUtilization: { label: 'Budget Utilization & ROI', weight: 15, max: 15 },
  contentEffectiveness: { label: 'Content Effectiveness', weight: 10, max: 10 },
  optimizationTesting: { label: 'Optimization & A/B Testing', weight: 10, max: 10 },
  funnelConversion: { label: 'Funnel & Conversion Tracking', weight: 10, max: 10 },
  reportingInsights: { label: 'Reporting & Insights', weight: 15, max: 15 },
  complianceBrandSafety: { label: 'Compliance & Brand Safety', weight: 10, max: 10 },
};

// Marketing Biannual (Personnel) KPI configuration
const MARKETING_BIANNUAL_KPI_CONFIG = {
  skillDevelopment: { label: 'Skill Development & Certifications', weight: 15, max: 15 },
  processAdherence: { label: 'Process Adherence', weight: 20, max: 20 },
  ownershipAccountability: { label: 'Ownership & Accountability', weight: 20, max: 20 },
  communicationCoordination: { label: 'Communication & Coordination', weight: 15, max: 15 },
  problemSolvingInitiative: { label: 'Problem-Solving & Initiative', weight: 15, max: 15 },
  professionalConduct: { label: 'Professional Conduct', weight: 15, max: 15 },
};

// PMO (Project Management) Monthly KPI configuration
const PMO_MONTHLY_KPI_CONFIG = {
  onTimeCompletion: { label: 'On-Time Completion', fullLabel: 'On-Time Project and Task Completion', weight: 20, max: 20 },
  dataAccuracyReporting: { label: 'Data Accuracy & Reporting', fullLabel: 'Data Accuracy and Reporting', weight: 20, max: 20 },
  stakeholderSatisfaction: { label: 'Stakeholder Satisfaction', weight: 15, max: 15 },
  userStoryCompletion: { label: 'User Stories in Sprints', fullLabel: 'Completion of User Stories in Sprints', weight: 15, max: 15 },
  dataVisualizationInsights: { label: 'Data Visualization & Insights', fullLabel: 'Data Visualization and Insights Quality', weight: 10, max: 10 },
  riskIssueResolution: { label: 'Risk & Issue Resolution', fullLabel: 'Risk Management and Issue Resolution', weight: 10, max: 10 },
  collaborationEngagement: { label: 'Collaboration & Engagement', fullLabel: 'Collaboration and Team Engagement', weight: 10, max: 10 },
};

// SEO Monthly KPI configuration
const SEO_MONTHLY_KPI_CONFIG = {
  organicTrafficGrowth: { label: 'Organic Traffic Growth', weight: 25, max: 25 },
  keywordPerformance: { label: 'Keyword Performance', weight: 20, max: 20 },
  technicalSeoHealth: { label: 'Technical SEO Health', weight: 15, max: 15 },
  onPageOptimization: { label: 'On-Page Optimization', weight: 10, max: 10 },
  contentPerformance: { label: 'Content Performance', weight: 10, max: 10 },
  backlinksAuthority: { label: 'Backlinks & Authority', weight: 10, max: 10 },
  conversionContribution: { label: 'Conversion Contribution', weight: 5, max: 5 },
  reportingMonitoring: { label: 'Reporting & Monitoring', weight: 5, max: 5 },
};

// SEO Biannual (Personnel) KPI configuration
const SEO_BIANNUAL_KPI_CONFIG = {
  skillDevelopmentLearning: { label: 'Skill Development & Learning', weight: 30, max: 30 },
  processAdherenceDocumentation: { label: 'Process Adherence & Documentation', weight: 20, max: 20 },
  ownershipTaskExecution: { label: 'Ownership & Task Execution', weight: 20, max: 20 },
  analyticalThinking: { label: 'Analytical Thinking', weight: 15, max: 15 },
  communicationCollaboration: { label: 'Communication & Collaboration', weight: 10, max: 10 },
  professionalConductReliability: { label: 'Professional Conduct & Reliability', weight: 5, max: 5 },
};

// IT Monthly KPI configuration with short labels for table display
const IT_MONTHLY_KPI_CONFIG = {
  installConfigureMaintain: { 
    label: 'Install & Maintain Systems', 
    fullLabel: 'Install, configure, and maintain computer systems, servers, and network devices',
    weight: 10, 
    max: 10 
  },
  manageMonitorNetworks: { 
    label: 'Manage Networks', 
    fullLabel: 'Manage and monitor LAN/WAN, firewalls, switches, and Wi-Fi networks',
    weight: 10, 
    max: 10 
  },
  setupMaintainServers: { 
    label: 'Setup & Maintain Servers', 
    fullLabel: 'Set up and maintain file-sharing and data storage servers',
    weight: 10, 
    max: 10 
  },
  implementBackupRecovery: { 
    label: 'Backup & Recovery', 
    fullLabel: 'Implement data backup, indexing, and recovery procedures',
    weight: 10, 
    max: 10 
  },
  createManageEmailAccounts: { 
    label: 'Email Accounts', 
    fullLabel: 'Create and manage company email accounts (G-Suite / Microsoft 365 / C-Panel)',
    weight: 10, 
    max: 10 
  },
  maintainAssetInventory: { 
    label: 'Asset Inventory', 
    fullLabel: 'Maintain and update the IT asset inventory and equipment list',
    weight: 10, 
    max: 10 
  },
  troubleshootIssues: { 
    label: 'Troubleshooting', 
    fullLabel: 'Troubleshoot hardware, software, and network-related issues promptly',
    weight: 5, 
    max: 5 
  },
  optimizeInternetUsage: { 
    label: 'Internet Optimization', 
    fullLabel: 'Optimize internet usage and reduce cost without compromising performance',
    weight: 10, 
    max: 10 
  },
  ensureDataSecurity: { 
    label: 'Data Security', 
    fullLabel: 'Ensure data security, user access control, and IT policy compliance',
    weight: 10, 
    max: 10 
  },
  provideTechnicalSupport: { 
    label: 'Technical Support', 
    fullLabel: 'Provide technical support for online meetings, video conferences, and remote setups',
    weight: 5, 
    max: 5 
  },
  collaborateWithTeam: { 
    label: 'Team Collaboration', 
    fullLabel: 'Collaborate effectively with the team and promote a cooperative work environment',
    weight: 5, 
    max: 5 
  },
  assistEventPlanning: { 
    label: 'Event Planning', 
    fullLabel: 'Assist in planning and organizing company IT-related events (e.g., gaming or team-building sessions)',
    weight: 5, 
    max: 5 
  }
};


interface MonthlyPerformanceData {
  id?: string;
  userId: string;
  month: number;
  year: number;
  [key: string]: any; // Dynamic KPI fields
  weightedAverage: number;
  remarks?: string;
  reviewedBy?: string;
  reviewedAt?: Date;
  isPublished: boolean;
}

interface BiAnnualPerformanceData {
  id?: string;
  userId: string;
  period: string;
  year: number;
  professionalDev?: number;
  processImprovement?: number;
  productInnovation?: number;
  weightedAverage: number;
  remarks?: string;
  reviewedBy?: string;
  reviewedAt?: Date;
  isPublished: boolean;
  [key: string]: any;
}

// Design-specific interfaces
interface DesignMonthlyPerformanceData {
  id?: string;
  userId: string;
  month: number;
  year: number;
  [key: string]: any; // Dynamic KPI fields for different design sub-teams
  weightedAverage: number;
  remarks?: string;
  reviewedBy?: string;
  reviewedAt?: Date;
  isPublished: boolean;
}

interface DesignBiAnnualPerformanceData {
  id?: string;
  userId: string;
  period: string;
  year: number;
  professionalDevelopment: number;
  improvementOfDesignStyle: number;
  designTrendsKnowledge: number;
  weightedAverage: number;
  remarks?: string;
  reviewedBy?: string;
  reviewedAt?: Date;
  isPublished: boolean;
}

async function getJsonList(endpoint: string, userId: string, label: string): Promise<any[]> {
  try {
    const data = await apiCall(
      api.endpoints.getPerformance.initiate({ endpoint, userId }),
    );
    return Array.isArray(data) ? data : [];
  } catch (error) {
    console.error(`❌ ${label} API error:`, error);
    return [];
  }
}

export function UserPerformance({ user, dateFrom, dateTo }: UserPerformanceProps) {
  const [monthlyData, setMonthlyData] = useState<MonthlyPerformanceData[]>([]);
  const [biannualData, setBiannualData] = useState<BiAnnualPerformanceData[]>([]);
  
  // Design-specific state
  const [designMonthlyData, setDesignMonthlyData] = useState<DesignMonthlyPerformanceData[]>([]);
  const [designBiannualData, setDesignBiannualData] = useState<DesignBiAnnualPerformanceData[]>([]);
  
  // IT-specific state
  const [itMonthlyData, setItMonthlyData] = useState<any[]>([]);

  // Earliest month from attendance / work-history — KPI rows start here
  const [earliestDataMonth, setEarliestDataMonth] = useState<{ year: number; month: number } | null>(null);

  const [loading, setLoading] = useState(true);
  const [isEditingDepartmental, setIsEditingDepartmental] = useState(false);
  const [isEditingPersonal, setIsEditingPersonal] = useState(false);
  const [isEditingPersonalRemarks, setIsEditingPersonalRemarks] = useState(false);
  const [editingMonthlyData, setEditingMonthlyData] = useState<Record<string, Partial<MonthlyPerformanceData>>>({});
  const [editingBiannualData, setEditingBiannualData] = useState<Record<string, Partial<BiAnnualPerformanceData>>>({});
  const [newCycleFrom, setNewCycleFrom] = useState("");
  const [newCycleTo, setNewCycleTo] = useState("");
  const [departmentCycles, setDepartmentCycles] = useState<Array<{ period: string; year: number }>>([]);
  const [isAddingCycle, setIsAddingCycle] = useState(false);
  const [periodToDelete, setPeriodToDelete] = useState<{
    period: string;
    year: number;
    label: string;
  } | null>(null);
  const [isDeletingCycle, setIsDeletingCycle] = useState(false);
  
  // Design-specific editing state
  const [editingDesignMonthlyData, setEditingDesignMonthlyData] = useState<Record<string, Partial<DesignMonthlyPerformanceData>>>({});
  const [editingDesignBiannualData, setEditingDesignBiannualData] = useState<Record<string, Partial<DesignBiAnnualPerformanceData>>>({});
  const [personalRemarks, setPersonalRemarks] = useState<string>('');
  const [editingRemarks, setEditingRemarks] = useState<Record<string, string>>({});
  const [departmentalSaveStatus, setDepartmentalSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
  const [personalSaveStatus, setPersonalSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
  const [personalRemarksSaveStatus, setPersonalRemarksSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
  const [departmentalPage, setDepartmentalPage] = useState(1);
  const prefersReducedMotion = useReducedMotion();
  const departmentalTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const personalTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const personalRemarksTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const [dataLoaded, setDataLoaded] = useState(false); // Prevent unnecessary reloads
  const loadedUserRef = useRef<string | null>(null); // Track which user's data we've loaded
  const { toast } = useToast();

  // Departmental KPI rows follow the selected date range (inclusive months).
  const FISCAL_YEAR_MONTHS = useMemo(() => {
    const { start, end } = monthWindowForDateRange(dateFrom, dateTo);
    return enumerateMonthRange(start, end);
  }, [dateFrom, dateTo]);

  const IT_FISCAL_YEAR_MONTHS = FISCAL_YEAR_MONTHS;

  const BIANNUAL_PERIODS = useMemo(
    () => personalKpiCyclesFromRecords([...departmentCycles, ...biannualData], dateFrom, dateTo),
    [departmentCycles, biannualData, dateFrom, dateTo],
  );

  const IT_BIANNUAL_PERIODS = BIANNUAL_PERIODS;

  const displayedPersonalCycles = useMemo(() => {
    const base = BIANNUAL_PERIODS;
    if (!isEditingPersonal) return base;
    const extras = Object.values(editingBiannualData)
      .filter((row) => row.period && row.year != null)
      .filter(
        (row) =>
          !base.some((c) => c.period === row.period && c.year === row.year),
      )
      .map((row) => {
        const span = spanForPersonalKpiPeriod(
          row.period as string,
          row.year as number,
        );
        return {
          period: row.period as string,
          year: row.year as number,
          label: formatPersonalKpiCycleLabel(span.start, span.end),
          start: span.start,
          end: span.end,
        };
      });
    return [...base, ...extras].sort(
      (a, b) =>
        a.start.year * 100 +
        a.start.month -
        (b.start.year * 100 + b.start.month),
    );
  }, [BIANNUAL_PERIODS, isEditingPersonal, editingBiannualData]);

  const personalRemarkPeriods = useMemo(
    () =>
      displayedPersonalCycles.map((cycle) => {
        const record = biannualData.find(
          (row) => row.period === cycle.period && row.year === cycle.year,
        );
        return {
          ...cycle,
          remarks: record?.remarks || "",
          record,
        };
      }),
    [displayedPersonalCycles, biannualData],
  );
  const { data: session } = useSession();
  // Departments the viewer is assigned to head (Department head)
  const { data: managerAccess } = useGetManagerAccessQuery(undefined, {
    skip: !['MANAGER', 'UNIT_LEAD'].includes(session?.user?.role || ''),
  });
  const managedDepartments: string[] = useMemo(
    () => managerAccess?.managedDepartments || [],
    [managerAccess],
  );

  // Determine user type for performance tracking - memoized to prevent unnecessary recalculations
  const isUserSqa = useMemo(() => isSqaUser(user), [user.role, user.position]);
  const isUserUnitLead = useMemo(() => isUnitLeadUser(user), [user.role, user.position]);
  
  // IT user detection - must be checked before other types
  const isItUser = useMemo(() => user.department === 'Network IT', [user.department]);

  const departmentalMonths = useMemo(
    () => (isItUser ? IT_FISCAL_YEAR_MONTHS : FISCAL_YEAR_MONTHS),
    [isItUser, IT_FISCAL_YEAR_MONTHS, FISCAL_YEAR_MONTHS]
  );

  const paginatedDepartmentalMonths = useMemo(() => {
    const start = (departmentalPage - 1) * MONTHLY_PAGE_SIZE;
    return departmentalMonths.slice(start, start + MONTHLY_PAGE_SIZE);
  }, [departmentalMonths, departmentalPage]);
  
  // SEO user detection (within Marketing department, position contains "SEO")
  const isSeoUserMemo = useMemo(() => isSeoUser(user), [user.department, user.position]);
  
  // Marketing user detection (Marketing dept but NOT SEO)
  const isMarketingUser = useMemo(() => user.department === 'Marketing' && !isSeoUser(user), [user.department, user.position]);
  const isPmo = useMemo(() => isPmoUser(user), [user.department]);
  
  // Design user detection
  const isDesignUser = useMemo(() => user.department === 'Design', [user.department]);
  const designSubTeam = useMemo(() => user.designSubTeam, [user.designSubTeam]);
  const isDesignLead = useMemo(() => {
    return isDesignUser && (
      isDesignHead(user.position || '') ||
      isDesignTeamLead(user) ||
      (user.role === 'UNIT_LEAD' && user.department?.toLowerCase() === 'design')
    );
  }, [user.position, user.role, user.department, isDesignUser]);
  
  const userPerformanceType = useMemo(() => getUserPerformanceType(user), [user.role, user.position, user.department, isItUser]);

  // Determine which design performance table to use
  const getDesignPerformanceType = useCallback(() => {
    if (!isDesignUser) return null;
    
    if (isDesignLead) return 'design-team-lead';
    
    switch (designSubTeam) {
      case 'Graphics':
        return 'design-graphic';
      case 'UI/UX':
        return 'design-ux';
      case 'Animations':
        return 'design-animation';
      default:
        return null;
    }
  }, [isDesignUser, isDesignLead, designSubTeam]);

  const designPerformanceType = useMemo(() => getDesignPerformanceType(), [getDesignPerformanceType]);
  
  // Select appropriate KPI config based on user type - memoized
  const MONTHLY_KPI_CONFIG = useMemo(() => {
    if (isDesignUser && designPerformanceType) {
      switch (designPerformanceType) {
        case 'design-graphic':
          return DESIGN_GRAPHIC_KPI_CONFIG;
        case 'design-ux':
          return DESIGN_UX_KPI_CONFIG;
        case 'design-animation':
          return DESIGN_ANIMATION_KPI_CONFIG;
        case 'design-team-lead':
          return DESIGN_TEAM_LEAD_KPI_CONFIG;
        default:
          return DEVELOPER_KPI_CONFIG;
      }
    }
    if (isItUser) return IT_MONTHLY_KPI_CONFIG;
    if (isSeoUserMemo) return SEO_MONTHLY_KPI_CONFIG;
    if (isMarketingUser) return MARKETING_MONTHLY_KPI_CONFIG;
    if (isPmo) return PMO_MONTHLY_KPI_CONFIG;
    if (isUserUnitLead) return UNIT_LEAD_KPI_CONFIG;
    if (isUserSqa) return SQA_KPI_CONFIG;
    return DEVELOPER_KPI_CONFIG;
  }, [isUserUnitLead, isUserSqa, isDesignUser, isItUser, isSeoUserMemo, isMarketingUser, isPmo, designPerformanceType]);
  
  // Select appropriate biannual KPI config
  const BIANNUAL_CONFIG = useMemo(() => {
    if (isDesignUser) return DESIGN_PERSONAL_BIANNUAL_KPI_CONFIG;
    if (isSeoUserMemo) return SEO_BIANNUAL_KPI_CONFIG;
    if (isMarketingUser) return MARKETING_BIANNUAL_KPI_CONFIG;
    return BIANNUAL_KPI_CONFIG;
  }, [isDesignUser, isSeoUserMemo, isMarketingUser]);
  
  // Select appropriate API endpoint based on user type - memoized
  const monthlyApiEndpoint = useMemo(() => {
    if (isDesignUser && designPerformanceType) {
      return `/api/performance/${designPerformanceType}-monthly`;
    }
    if (isItUser) return '/api/performance/it-monthly';
    if (isSeoUserMemo) return '/api/performance/seo-monthly';
    if (isMarketingUser) return '/api/performance/marketing-monthly';
    if (isPmo) return '/api/performance/pmo-monthly';
    if (isUserUnitLead) return '/api/performance/unit-lead-monthly';
    if (isUserSqa) return '/api/performance/sqa-monthly';
    return '/api/performance/monthly';
  }, [isUserUnitLead, isUserSqa, isDesignUser, isItUser, isSeoUserMemo, isMarketingUser, isPmo, designPerformanceType]);

  const biannualApiEndpoint = useMemo(() => {
    if (isDesignUser) return '/api/performance/design-personal-biannual';
    if (isSeoUserMemo) return '/api/performance/seo-biannual';
    if (isMarketingUser) return '/api/performance/marketing-biannual';
    return '/api/performance/biannual';
  }, [isDesignUser, isSeoUserMemo, isMarketingUser]);

  // Debug logging for user detection (only when user actually changes)
  useEffect(() => {
    if (process.env.NODE_ENV === 'development') {
      console.log('🔍 User detection:', {
        userId: user.id,
        userRole: user.role,
        userDepartment: user.department,
        isUserSqa,
        isUserUnitLead,
        isItUser,
        isMarketingUser,
        userPerformanceType,
        isDesignUser,
        designSubTeam,
        isDesignLead,
        designPerformanceType
      });
    }
  }, [user.id, isItUser, userPerformanceType]); // Only log when user ID changes
  


  // Add helper function to get default value (70% of weight limit) - memoized
  const getDefaultKPIValue = useCallback((weight: number): number => {
    return Math.round(weight * 0.7);
  }, []);

  // Manual refresh function for when data needs to be reloaded
  const refreshData = useCallback(() => {
    if (process.env.NODE_ENV === 'development') {
      console.log('🔄 Manual data refresh requested');
    }
    store.dispatch(api.util.invalidateTags(["Performance", "Attendance", "ItWorkHistory"]));
    setDataLoaded(false);
    loadedUserRef.current = null; // Reset to force reload
  }, [user.id]);

  useEffect(() => {
    // Only run when user.id actually changes
    if (loadedUserRef.current === user.id && dataLoaded) {
      if (process.env.NODE_ENV === 'development') {
        console.log('📋 Data already loaded for user:', user.id, '- skipping reload');
      }
      return;
    }

    if (process.env.NODE_ENV === 'development') {
      console.log('🔧 UserPerformance: Loading data for user:', user.id);
    }
    
    // Mark this user as being loaded immediately to prevent duplicate calls
    loadedUserRef.current = user.id;
    
    // Clear previous user data
    setDataLoaded(false);
    setMonthlyData([]);
    setBiannualData([]);
    setDesignMonthlyData([]);
    setDesignBiannualData([]);
    setItMonthlyData([]);
    setDepartmentCycles([]);
    setPersonalRemarks(''); // Clear personal remarks for new user
    
    // Inline the loading logic to avoid dependency on loadPerformanceData function
    const loadData = async () => {
      try {
        setLoading(true);
        
        if (process.env.NODE_ENV === 'development') {
          console.log('🔄 Loading performance data for user:', user.id, 'Type:', userPerformanceType, 'Design Type:', designPerformanceType, 'Is IT User:', isItUser);
        }
        
        // Load appropriate performance data based on user type
        if (isDesignUser && designPerformanceType) {
          const designMonthlyArray = await getJsonList(
            monthlyApiEndpoint,
            user.id,
            'Design Monthly',
          );
          setDesignMonthlyData(designMonthlyArray);

          const designBiannualArray = await getJsonList(
            biannualApiEndpoint,
            user.id,
            'Design Biannual',
          );
          setDesignBiannualData(designBiannualArray);

          const latestDesignBiannual = latestPersonalKpiRecordWithRemarks(designBiannualArray);
          if (latestDesignBiannual && latestDesignBiannual.remarks) {
            setPersonalRemarks(latestDesignBiannual.remarks);
          }
        } else if (isItUser) {
          const itMonthlyPerformances = await getJsonList(
            monthlyApiEndpoint,
            user.id,
            'IT Monthly',
          );
          setItMonthlyData(itMonthlyPerformances);

          const biannualArray = await getJsonList(
            biannualApiEndpoint,
            user.id,
            'IT Biannual',
          );
          setBiannualData(biannualArray);

          const latestBiannual = latestPersonalKpiRecordWithRemarks(biannualArray);
          if (latestBiannual && latestBiannual.remarks) {
            setPersonalRemarks(latestBiannual.remarks);
          }
        } else {
          const monthlyPerformances = await getJsonList(
            monthlyApiEndpoint,
            user.id,
            'Monthly',
          );
          setMonthlyData(monthlyPerformances);

          const biannualArray = await getJsonList(
            biannualApiEndpoint,
            user.id,
            'Biannual',
          );
          setBiannualData(biannualArray);

          const latestBiannual = latestPersonalKpiRecordWithRemarks(biannualArray);
          if (latestBiannual && latestBiannual.remarks) {
            setPersonalRemarks(latestBiannual.remarks);
          }
        }

        const sharedCycles = await getJsonList(
          '/api/performance/personal-kpi-cycles',
          user.id,
          'Personal KPI cycles',
        );
        setDepartmentCycles(
          sharedCycles.filter((row) => row?.period && row?.year != null),
        );
        
        // Determine earliest data month from attendance and work history
        try {
          let earliest: { year: number; month: number } | null = null;

          try {
            const attData = await apiCall<{ monthlyAttendance?: Array<{ year: number; month: number }> }>(
              api.endpoints.getMonthlyAttendance.initiate({ userId: user.id }),
            );
            const records = attData.monthlyAttendance || [];
            for (const r of records) {
              const val = r.year * 100 + r.month;
              if (!earliest || val < earliest.year * 100 + earliest.month) {
                earliest = { year: r.year, month: r.month };
              }
            }
          } catch (attErr) {
            console.error('❌ Attendance monthly API error:', attErr);
          }

          if (isItUser) {
            try {
              const whData = await apiCall<any[]>(
                api.endpoints.getItWorkHistory.initiate({ userId: user.id }),
              );
              for (const r of (Array.isArray(whData) ? whData : [])) {
                const d = new Date(r.ticketDate);
                const val = d.getFullYear() * 100 + (d.getMonth() + 1);
                if (!earliest || val < earliest.year * 100 + earliest.month) {
                  earliest = { year: d.getFullYear(), month: d.getMonth() + 1 };
                }
              }
            } catch (whErr) {
              console.error('❌ IT work history API error:', whErr);
            }
          }

          setEarliestDataMonth(earliest);
        } catch (e) {
          console.error('Error fetching earliest data month:', e);
        }

      } catch (error) {
        console.error('Error loading performance data:', error);
        setMonthlyData([]);
        setBiannualData([]);
        setDesignMonthlyData([]);
        setDesignBiannualData([]);
        toast({
          title: "Error",
          description: "Failed to load performance data",
          variant: "destructive",
        });
      } finally {
        setLoading(false);
        setDataLoaded(true);
      }
    };

    loadData();
  }, [user.id]); // Only reload when user actually changes

  // Set personal remarks from the most recent biannual record when data loads
  useEffect(() => {
    if (!dataLoaded) return;
    const records = isDesignUser ? designBiannualData : biannualData;
    setPersonalRemarks(latestPersonalKpiRecordWithRemarks(records)?.remarks || '');
  }, [dataLoaded, biannualData, designBiannualData, isDesignUser]);

  // Cleanup timeouts on unmount
  useEffect(() => {
    return () => {
      if (departmentalTimeoutRef.current) {
        clearTimeout(departmentalTimeoutRef.current);
      }
      if (personalTimeoutRef.current) {
        clearTimeout(personalTimeoutRef.current);
      }
    };
  }, []);

  useEffect(() => {
    setDepartmentalPage(1);
  }, [user.id, departmentalMonths.length, isItUser, dateFrom, dateTo]);

  // Helper function to initialize monthly editing data
  const initializeDepartmentalEditingData = useCallback(() => {
    const monthlyEditData: Record<string, Partial<MonthlyPerformanceData>> = {};
    
    // Use appropriate data source based on user type
    const dataSource = isItUser ? itMonthlyData : monthlyData;
    
    // Use IT-specific months for IT users, otherwise use regular fiscal year months
    const monthsToUse = isItUser ? IT_FISCAL_YEAR_MONTHS : FISCAL_YEAR_MONTHS;
    
    // Initialize with existing data or default 70% values
    monthsToUse.forEach(({ month, year }) => {
      const key = `${month}_${year}`;
      const existingData = dataSource.find(d => d.month === month && d.year === year);
      
      const defaultData: any = {
        userId: user.id,
        month,
        year,
        weightedAverage: 0,
        isPublished: false,
        remarks: '' // Initialize with empty string for better control
      };

      // Add default values for each KPI
      Object.entries(MONTHLY_KPI_CONFIG).forEach(([kpiKey, config]) => {
        defaultData[kpiKey] = getDefaultKPIValue(config.weight);
      });

      monthlyEditData[key] = existingData ? { ...existingData } : defaultData;
    });

    return monthlyEditData;
  }, [monthlyData, itMonthlyData, isItUser, user.id, MONTHLY_KPI_CONFIG, IT_FISCAL_YEAR_MONTHS, FISCAL_YEAR_MONTHS]);

  // Helper function to initialize design monthly editing data
  const initializeDesignDepartmentalEditingData = useCallback(() => {
    const designMonthlyEditData: Record<string, Partial<DesignMonthlyPerformanceData>> = {};
    
    // Initialize with existing data or default 70% values
    FISCAL_YEAR_MONTHS.forEach(({ month, year }) => {
      const key = `${month}_${year}`;
      const existingData = designMonthlyData.find(d => d.month === month && d.year === year);
      
      const defaultData: any = {
        userId: user.id,
        month,
        year,
        weightedAverage: 0,
        isPublished: false,
        remarks: ''
      };

      // Initialize KPI fields with existing data or defaults
      Object.entries(MONTHLY_KPI_CONFIG).forEach(([field, config]) => {
        defaultData[field] = existingData?.[field] || getDefaultKPIValue(config.weight);
      });

      designMonthlyEditData[key] = existingData ? { ...existingData } : defaultData;
    });
    
    return designMonthlyEditData;
  }, [designMonthlyData, user.id, MONTHLY_KPI_CONFIG, getDefaultKPIValue, FISCAL_YEAR_MONTHS]);

  // Helper function to initialize personal editing data
  const initializePersonalEditingData = useCallback(() => {
    const biannualEditData: Record<string, Partial<BiAnnualPerformanceData>> = {};
    
    // Use IT-specific periods for IT users, otherwise use regular periods
    const periodsToUse = isItUser ? IT_BIANNUAL_PERIODS : BIANNUAL_PERIODS;
    const biannualConfigForInit = isSeoUserMemo ? SEO_BIANNUAL_KPI_CONFIG : isMarketingUser ? MARKETING_BIANNUAL_KPI_CONFIG : isItUser ? IT_BIANNUAL_KPI_CONFIG : BIANNUAL_KPI_CONFIG;
    
    periodsToUse.forEach(({ period, year }) => {
      const key = `${period}_${year}`;
      const existingData = biannualData.find(d => d.period === period && d.year === year);
      
      if (existingData) {
        biannualEditData[key] = { ...existingData };
      } else {
        const defaults: any = {
          userId: user.id,
          period,
          year,
          weightedAverage: 0,
          isPublished: false,
          remarks: ''
        };
        Object.entries(biannualConfigForInit).forEach(([field, config]) => {
          defaults[field] = getDefaultKPIValue(config.weight);
        });
        biannualEditData[key] = defaults;
      }
    });

    return biannualEditData;
  }, [biannualData, user.id, isItUser, isMarketingUser, IT_BIANNUAL_PERIODS, BIANNUAL_PERIODS]);

  // Helper function to initialize design biannual editing data
  const initializeDesignPersonalEditingData = useCallback(() => {
    const designBiannualEditData: Record<string, Partial<DesignBiAnnualPerformanceData>> = {};
    
    BIANNUAL_PERIODS.forEach(({ period, year }) => {
      const key = `${period}_${year}`;
      const existingData = designBiannualData.find(d => d.period === period && d.year === year);
      
      const defaultData: any = {
        userId: user.id,
        period,
        year,
        weightedAverage: 0,
        isPublished: false,
        remarks: personalRemarks || ''
      };

      // Initialize KPI fields with existing data or defaults
      Object.entries(BIANNUAL_CONFIG).forEach(([field, config]) => {
        defaultData[field] = (existingData as any)?.[field] || getDefaultKPIValue(config.weight);
      });

      designBiannualEditData[key] = existingData ? { ...existingData } : defaultData;
    });
    
    return designBiannualEditData;
  }, [designBiannualData, user.id, getDefaultKPIValue, personalRemarks, BIANNUAL_CONFIG, BIANNUAL_PERIODS]);

  // Functions to start editing with immediate data initialization
  const startDepartmentalEditing = useCallback(() => {
    if (departmentalTimeoutRef.current) {
      clearTimeout(departmentalTimeoutRef.current);
    }
    setDepartmentalSaveStatus('idle');
    
    if (isDesignUser && designPerformanceType) {
      const editingData = initializeDesignDepartmentalEditingData();
      setEditingDesignMonthlyData(editingData);
    } else {
      const editingData = initializeDepartmentalEditingData();
      setEditingMonthlyData(editingData);
    }
    
    setIsEditingDepartmental(true);
  }, [initializeDepartmentalEditingData, initializeDesignDepartmentalEditingData, isDesignUser, designPerformanceType]);

  const startPersonalEditing = useCallback(() => {
    if (personalTimeoutRef.current) {
      clearTimeout(personalTimeoutRef.current);
    }
    setPersonalSaveStatus('idle');
    
    if (isDesignUser) {
      const editingData = initializeDesignPersonalEditingData();
      setEditingDesignBiannualData(editingData);
    } else {
      const editingData = initializePersonalEditingData();
      setEditingBiannualData(editingData);
    }
    
    setIsEditingPersonal(true);
    setNewCycleFrom("");
    setNewCycleTo("");
  }, [initializePersonalEditingData, initializeDesignPersonalEditingData, isDesignUser]);

  const addPersonalCycle = useCallback(async () => {
    const start = yearMonthFromDateInput(newCycleFrom);
    const end = yearMonthFromDateInput(newCycleTo);
    if (!start || !end) {
      toast({
        title: "Choose a cycle range",
        description: "Set both start and end months for the new Personal KPI period.",
        variant: "destructive",
      });
      return;
    }
    if (start.year * 100 + start.month > end.year * 100 + end.month) {
      toast({
        title: "Invalid cycle range",
        description: "The cycle start must be on or before the cycle end.",
        variant: "destructive",
      });
      return;
    }

    const { period, year } = personalKpiPeriodKey(start, end);
    const key = `${period}_${year}`;
    if (
      displayedPersonalCycles.some((c) => c.period === period && c.year === year) ||
      editingBiannualData[key]
    ) {
      toast({
        title: "Period already exists",
        description: `${formatPersonalKpiCycleLabel(start, end)} is already in the table.`,
        variant: "destructive",
      });
      return;
    }

    const groupLabel = user.department || "this department";
    setIsAddingCycle(true);
    try {
      await apiCall(
        api.endpoints.savePerformance.initiate({
          endpoint: "/api/performance/personal-kpi-cycles",
          body: { userId: user.id, period, year },
        }),
      );
    } catch (error) {
      toast({
        title: "Could not add period",
        description: apiErrorMessage(error, "Failed to apply this period to the department."),
        variant: "destructive",
      });
      setIsAddingCycle(false);
      return;
    }

    const biannualConfigForInit = isSeoUserMemo
      ? SEO_BIANNUAL_KPI_CONFIG
      : isMarketingUser
        ? MARKETING_BIANNUAL_KPI_CONFIG
        : isItUser
          ? IT_BIANNUAL_KPI_CONFIG
          : BIANNUAL_KPI_CONFIG;
    const defaults: Record<string, unknown> = {
      userId: user.id,
      period,
      year,
      weightedAverage: 0,
      isPublished: false,
      remarks: "",
    };
    Object.entries(biannualConfigForInit).forEach(([field, config]) => {
      defaults[field] = getDefaultKPIValue(config.weight);
    });

    setDepartmentCycles((prev) =>
      prev.some((c) => c.period === period && c.year === year)
        ? prev
        : [...prev, { period, year }],
    );
    setEditingBiannualData((prev) => ({ ...prev, [key]: defaults }));
    setNewCycleFrom("");
    setNewCycleTo("");
    setIsAddingCycle(false);
    toast({
      title: "Period added",
      description: `${formatPersonalKpiCycleLabel(start, end)} now appears for every ${groupLabel} employee.`,
    });
  }, [
    newCycleFrom,
    newCycleTo,
    displayedPersonalCycles,
    editingBiannualData,
    isSeoUserMemo,
    isMarketingUser,
    isItUser,
    user.id,
    user.department,
    getDefaultKPIValue,
    toast,
  ]);

  const deletePersonalCycle = useCallback(async () => {
    if (!periodToDelete) return;
    const { period, year, label } = periodToDelete;
    const key = `${period}_${year}`;
    setIsDeletingCycle(true);
    try {
      await apiCall(
        api.endpoints.deletePerformance.initiate({
          endpoint: "/api/performance/personal-kpi-cycles",
          params: { userId: user.id, period, year },
        }),
      );
      setDepartmentCycles((prev) =>
        prev.filter((c) => !(c.period === period && c.year === year)),
      );
      setBiannualData((prev) =>
        prev.filter((c) => !(c.period === period && c.year === year)),
      );
      setEditingBiannualData((prev) => {
        const next = { ...prev };
        delete next[key];
        return next;
      });
      setPeriodToDelete(null);
      toast({
        title: "Period deleted",
        description: `${label} was removed for every ${user.department || "department"} employee.`,
      });
    } catch (error) {
      toast({
        title: "Could not delete period",
        description: apiErrorMessage(error, "Failed to delete this Personal KPI period."),
        variant: "destructive",
      });
    } finally {
      setIsDeletingCycle(false);
    }
  }, [periodToDelete, user.id, user.department, toast]);

  // Calculate weighted average - memoized
  const calculateMonthlyWeightedAverage = useCallback((data: Partial<MonthlyPerformanceData>) => {
    const total = Object.entries(MONTHLY_KPI_CONFIG).reduce((sum, [key, config]) => {
      const value = data[key] || 0;
      return sum + (value as number * config.weight / 100);
    }, 0);
    return Number(formatNumber(total));
  }, [MONTHLY_KPI_CONFIG]);

  const calculateBiannualWeightedAverage = useCallback((data: Partial<BiAnnualPerformanceData>) => {
    const configToUse = isSeoUserMemo ? SEO_BIANNUAL_KPI_CONFIG : isMarketingUser ? MARKETING_BIANNUAL_KPI_CONFIG : isItUser ? IT_BIANNUAL_KPI_CONFIG : BIANNUAL_KPI_CONFIG;
    const total = Object.entries(configToUse).reduce((sum, [key, config]) => {
      const value = (data as any)[key] || 0;
      return sum + (value as number * config.weight / 100);
    }, 0);
    return Number(formatNumber(total));
  }, [isMarketingUser, isItUser]);

  // Get performance color based on score - memoized
  const getPerformanceColor = useCallback((score: number) => {
    if (score >= 90) return 'bg-emerald-100 text-emerald-800 border-emerald-200 dark:bg-emerald-950/50 dark:text-emerald-300 dark:border-emerald-800';
    if (score >= 80) return 'bg-green-100 text-green-800 border-green-200 dark:bg-green-950/50 dark:text-green-300 dark:border-green-800';
    if (score >= 70) return 'bg-primary/15 text-primary border-primary/20 dark:bg-primary/20 dark:text-primary dark:border-primary/30';
    if (score >= 60) return 'bg-yellow-100 text-yellow-800 border-yellow-200 dark:bg-yellow-950/50 dark:text-yellow-300 dark:border-yellow-800';
    if (score >= 40) return 'bg-orange-100 text-orange-800 border-orange-200 dark:bg-orange-950/50 dark:text-orange-300 dark:border-orange-800';
    return 'bg-red-100 text-red-800 border-red-200 dark:bg-red-950/50 dark:text-red-300 dark:border-red-800';
  }, []);

  // Get performance grade based on score - memoized
  const getPerformanceGrade = useCallback((score: number): string => {
    if (score >= 90) return 'A+';
    if (score >= 85) return 'A';
    if (score >= 80) return 'B+';
    if (score >= 75) return 'B';
    if (score >= 70) return 'C+';
    if (score >= 65) return 'C';
    if (score >= 60) return 'D+';
    if (score >= 55) return 'D';
    return 'F';
  }, []);

  // Handle KPI value changes
  const handleMonthlyKPIChange = useCallback((month: number, year: number, field: string, value: string) => {
    const key = `${month}_${year}`;
    const numValue = parseFloat(value) || 0;
    const fieldConfig = (MONTHLY_KPI_CONFIG as any)[field];
    const maxValue = fieldConfig?.max || 100;
    const fieldLabel = fieldConfig?.label || field;
    
    if (numValue < 0 || numValue > maxValue) {
      toast({
        title: "Invalid Value",
        description: `${fieldLabel} must be between 0 and ${maxValue}`,
        variant: "destructive",
        duration: 3000,
      });
      return;
    }

    setEditingMonthlyData(prev => ({
      ...prev,
      [key]: {
        ...prev[key],
        [field]: numValue,
        weightedAverage: calculateMonthlyWeightedAverage({
          ...prev[key],
          [field]: numValue
        } as MonthlyPerformanceData)
      }
    }));
  }, [toast, MONTHLY_KPI_CONFIG]);

  // Handle monthly KPI blur to auto-correct out-of-range values
  const handleMonthlyKPIBlur = useCallback((month: number, year: number, field: string, value: string) => {
    const numValue = parseFloat(value) || 0;
    const fieldConfig = (MONTHLY_KPI_CONFIG as any)[field];
    const maxValue = fieldConfig?.max || 100;
    
    if (numValue < 0) {
      handleMonthlyKPIChange(month, year, field, '0');
    } else if (numValue > maxValue) {
      handleMonthlyKPIChange(month, year, field, maxValue.toString());
    }
  }, [handleMonthlyKPIChange, MONTHLY_KPI_CONFIG]);

  // Design-specific KPI change handlers
  const handleDesignMonthlyKPIChange = useCallback((key: string, field: string, value: number) => {
    setEditingDesignMonthlyData(prev => ({
      ...prev,
      [key]: {
        ...prev[key],
        userId: user.id,
        month: parseInt(key.split('_')[0]),
        year: parseInt(key.split('_')[1]),
        [field]: value,
        weightedAverage: 0 // Will be calculated on save
      }
    }));
  }, [user.id]);

  const handleDesignBiannualKPIChange = useCallback((key: string, field: string, value: number) => {
    const parsed = parsePersonalKpiEditKey(key);
    setEditingDesignBiannualData(prev => ({
      ...prev,
      [key]: {
        ...prev[key],
        userId: user.id,
        period: prev[key]?.period || parsed.period,
        year: prev[key]?.year ?? parsed.year,
        [field]: value,
        weightedAverage: 0 // Will be calculated on save
      }
    }));
  }, [user.id]);

  const handleBiannualKPIChange = (period: string, year: number, field: string, value: string) => {
    const key = `${period}_${year}`;
    const activeBiannualConfig = isSeoUserMemo ? SEO_BIANNUAL_KPI_CONFIG : isMarketingUser ? MARKETING_BIANNUAL_KPI_CONFIG : isItUser ? IT_BIANNUAL_KPI_CONFIG : BIANNUAL_KPI_CONFIG;
    
    // Allow empty string for user convenience while typing
    if (value === '') {
      setEditingBiannualData(prev => ({
        ...prev,
        [key]: {
          ...prev[key],
          [field]: 0,
          weightedAverage: calculateBiannualWeightedAverage({
            ...prev[key],
            [field]: 0
          } as BiAnnualPerformanceData)
        }
      }));
      return;
    }
    
    const numValue = parseFloat(value);
    
    // Check if it's a valid number
    if (isNaN(numValue)) {
      toast({
        title: "Invalid Input",
        description: "Please enter a valid number",
        variant: "destructive",
        duration: 2000,
      });
      return;
    }
    
    const fieldConfig = (activeBiannualConfig as any)[field];
    const maxValue = fieldConfig?.max || 100;
    const fieldLabel = fieldConfig?.label || field;
    
    if (numValue < 0 || numValue > maxValue) {
      toast({
        title: "Invalid Value",
        description: `${fieldLabel} must be between 0 and ${maxValue}`,
        variant: "destructive",
        duration: 3000,
      });
      return;
    }

    setEditingBiannualData(prev => ({
      ...prev,
      [key]: {
        ...prev[key],
        [field]: numValue,
        weightedAverage: calculateBiannualWeightedAverage({
          ...prev[key],
          [field]: numValue
        } as BiAnnualPerformanceData)
      }
    }));
  };

  // Handle biannual KPI blur to auto-correct out-of-range values
  const handleBiannualKPIBlur = (period: string, year: number, field: string, value: string) => {
    if (value === '') return;
    
    const numValue = parseFloat(value);
    if (isNaN(numValue)) return;
    
    const biannualConfigToUse = isSeoUserMemo ? SEO_BIANNUAL_KPI_CONFIG : isMarketingUser ? MARKETING_BIANNUAL_KPI_CONFIG : isItUser ? IT_BIANNUAL_KPI_CONFIG : BIANNUAL_KPI_CONFIG;
    const fieldConfig = (biannualConfigToUse as any)[field];
    const maxValue = fieldConfig?.max || 100;
    
    if (numValue < 0) {
      handleBiannualKPIChange(period, year, field, '0');
      toast({
        title: "Value Corrected",
        description: `Negative values are not allowed. Set to 0.`,
        duration: 2000,
      });
    } else if (numValue > maxValue) {
      handleBiannualKPIChange(period, year, field, maxValue.toString());
      toast({
        title: "Value Corrected",
        description: `Maximum value is ${maxValue}. Value has been corrected.`,
        duration: 2000,
      });
    }
  };

  // Handle remarks changes
  const handleMonthlyRemarksChange = (month: number, year: number, value: string) => {
    const key = `${month}_${year}`;
    setEditingMonthlyData(prev => ({
      ...prev,
      [key]: {
        ...prev[key],
        remarks: value
      }
    }));
  };

  const handleBiannualRemarksChange = (period: string, year: number, value: string) => {
    const key = `${period}_${year}`;
    setEditingBiannualData(prev => ({
      ...prev,
      [key]: {
        ...prev[key],
        remarks: value
      }
    }));
  };

  // Helper functions to check if data has changed
  const hasMonthlyDataChanged = (data: Partial<MonthlyPerformanceData>, month: number, year: number) => {
    const existingData = monthlyData.find(d => d.month === month && d.year === year);
    
    if (existingData) {
      return Object.entries(MONTHLY_KPI_CONFIG).some(([key]) => {
        return data[key] !== existingData[key];
      }) || data.remarks !== existingData.remarks;
    }
    return true; // No existing data, always save
  };

  const hasBiannualDataChanged = (data: Partial<BiAnnualPerformanceData>, period: string, year: number) => {
    const existingData = biannualData.find(d => d.period === period && d.year === year);
    
    if (existingData) {
      const biannualConfigToCheck = isSeoUserMemo ? SEO_BIANNUAL_KPI_CONFIG : isMarketingUser ? MARKETING_BIANNUAL_KPI_CONFIG : isItUser ? IT_BIANNUAL_KPI_CONFIG : BIANNUAL_KPI_CONFIG;
      const changed = Object.keys(biannualConfigToCheck).some(key =>
        (data as any)[key] !== (existingData as any)[key]
      ) || data.remarks !== existingData.remarks;
      return changed;
    }
    
    return true;
  };

  // Save departmental (monthly) changes
  const saveDepartmentalChanges = async () => {
    setDepartmentalSaveStatus('saving');
    
    try {
      const monthlyEntries = Object.entries(editingMonthlyData);
      if (monthlyEntries.length > 0) {
        for (const [key, data] of monthlyEntries) {
          const [month, year] = key.split('_').map(Number);
          
          if (hasMonthlyDataChanged(data, month, year)) {
            // Filter data to only include relevant KPIs for the user type
            const filteredData: any = {
              userId: data.userId,
              month: data.month,
              year: data.year,
              remarks: data.remarks,
              isPublished: data.isPublished
            };
            
            // Add only the KPIs that are relevant to this user type
            Object.keys(MONTHLY_KPI_CONFIG).forEach(kpiKey => {
              if (data[kpiKey] !== undefined) {
                filteredData[kpiKey] = data[kpiKey];
              }
            });
            
            const dataWithWeightedAvg = {
              ...filteredData,
              weightedAverage: calculateMonthlyWeightedAverage(filteredData)
            };
            
            console.log('🔍 Saving departmental performance data:', {
              month,
              year,
              isUserSqa,
              endpoint: monthlyApiEndpoint,
              userPosition: user.position,
              userName: user.name,
              kpiConfig: Object.keys(MONTHLY_KPI_CONFIG),
              dataKeys: Object.keys(dataWithWeightedAvg),
              dataToSend: dataWithWeightedAvg
            });
            
            try {
              await apiCall(
                api.endpoints.savePerformance.initiate({
                  endpoint: monthlyApiEndpoint,
                  body: dataWithWeightedAvg,
                }),
              );
            } catch (err) {
              const errorData = apiErrorMessage(err);
              console.error('❌ Departmental save failed:', {
                endpoint: monthlyApiEndpoint,
                error: errorData,
                sentData: dataWithWeightedAvg
              });
              throw new Error(`Failed to save ${isItUser ? 'IT' : isSeoUserMemo ? 'SEO' : isMarketingUser ? 'Marketing' : isPmo ? 'PMO' : isUserUnitLead ? 'Unit Lead' : isUserSqa ? 'SQA' : 'development'} performance data for ${month}/${year}: ${errorData}`);
            }
          }
        }
        
        // Update local state instead of reloading to avoid screen refresh
        if (isItUser) {
          const updatedItMonthlyData = itMonthlyData.map(existing => {
            const key = `${existing.month}_${existing.year}`;
            return editingMonthlyData[key] ? { ...existing, ...editingMonthlyData[key] } : existing;
          });
          
          // Add new entries that don't exist yet
          Object.entries(editingMonthlyData).forEach(([key, data]) => {
            const [month, year] = key.split('_').map(Number);
            const exists = updatedItMonthlyData.some(item => item.month === month && item.year === year);
            if (!exists && data.userId) {
              updatedItMonthlyData.push(data as any);
            }
          });
          
          setItMonthlyData(updatedItMonthlyData);
        } else {
        const updatedMonthlyData = monthlyData.map(existing => {
          const key = `${existing.month}_${existing.year}`;
          return editingMonthlyData[key] ? { ...existing, ...editingMonthlyData[key] } : existing;
        });
        
        // Add new entries that don't exist yet
        Object.entries(editingMonthlyData).forEach(([key, data]) => {
          const [month, year] = key.split('_').map(Number);
          const exists = updatedMonthlyData.some(item => item.month === month && item.year === year);
          if (!exists && data.userId) {
            updatedMonthlyData.push(data as MonthlyPerformanceData);
          }
        });
        
        setMonthlyData(updatedMonthlyData);
        }
        setDepartmentalSaveStatus('saved');
        setIsEditingDepartmental(false);
        setEditingMonthlyData({});
        
        toast({
          title: "✅ Departmental KPIs Saved",
          description: `${isItUser ? 'IT' : isSeoUserMemo ? 'SEO' : isMarketingUser ? 'Marketing' : isPmo ? 'PMO' : isUserUnitLead ? 'Unit Lead' : isUserSqa ? 'SQA' : 'Development'} performance data saved successfully!`,
          duration: 4000,
        });
        
        if (departmentalTimeoutRef.current) {
          clearTimeout(departmentalTimeoutRef.current);
        }
        departmentalTimeoutRef.current = setTimeout(() => setDepartmentalSaveStatus('idle'), 3000);
        console.log('✅ Departmental performance data saved successfully');
      }
      
    } catch (error) {
      console.error('Error saving departmental data:', error);
      setDepartmentalSaveStatus('error');
      toast({
        title: "❌ Departmental Save Failed",
        description: (error as Error).message || "Failed to save departmental changes. Please try again.",
        variant: "destructive",
        duration: 6000,
      });
      if (departmentalTimeoutRef.current) {
        clearTimeout(departmentalTimeoutRef.current);
      }
      departmentalTimeoutRef.current = setTimeout(() => setDepartmentalSaveStatus('idle'), 3000);
    }
  };

  // Save personal (biannual) changes  
  const savePersonalChanges = async () => {
    setPersonalSaveStatus('saving');
    
    try {
      const biannualEntries = Object.entries(editingBiannualData);
      if (biannualEntries.length > 0) {
        for (const [key, data] of biannualEntries) {
          const parsed = parsePersonalKpiEditKey(key);
          const period = (data.period as string) || parsed.period;
          const year = Number(data.year ?? parsed.year);
          
          if (hasBiannualDataChanged(data, period, year)) {
            const dataWithWeightedAvg = {
              ...data,
              weightedAverage: calculateBiannualWeightedAverage(data)
            };
            
            console.log('🔍 Saving personal performance data:', {
              period,
              year,
              userPosition: user.position,
              userName: user.name,
              dataToSend: dataWithWeightedAvg
            });
            
            try {
              await apiCall(
                api.endpoints.savePerformance.initiate({
                  endpoint: biannualApiEndpoint,
                  body: dataWithWeightedAvg,
                }),
              );
            } catch (err) {
              const errorData = apiErrorMessage(err);
              console.error('❌ Personal save failed:', {
                endpoint: biannualApiEndpoint,
                error: errorData,
                sentData: dataWithWeightedAvg
              });
              throw new Error(`Failed to save personal performance data for ${period} ${year}: ${errorData}`);
            }
          }
        }
        
        // Update local state instead of reloading to avoid screen refresh
        const updatedBiannualData = biannualData.map(existing => {
          const key = `${existing.period}_${existing.year}`;
          return editingBiannualData[key] ? { ...existing, ...editingBiannualData[key] } : existing;
        });
        
        // Add new entries that don't exist yet
        Object.entries(editingBiannualData).forEach(([key, data]) => {
          const parsed = parsePersonalKpiEditKey(key);
          const period = (data.period as string) || parsed.period;
          const year = Number(data.year ?? parsed.year);
          const exists = updatedBiannualData.some(item => item.period === period && item.year === year);
          if (!exists && data.userId) {
            updatedBiannualData.push(data as BiAnnualPerformanceData);
          }
        });
        
        setBiannualData(updatedBiannualData);
        setPersonalSaveStatus('saved');
        setIsEditingPersonal(false);
        setEditingBiannualData({});
        setNewCycleFrom("");
        setNewCycleTo("");
        
        toast({
          title: "✅ Personal KPIs Saved",
          description: "Personal performance data saved successfully!",
          duration: 4000,
        });
        
        if (personalTimeoutRef.current) {
          clearTimeout(personalTimeoutRef.current);
        }
        personalTimeoutRef.current = setTimeout(() => setPersonalSaveStatus('idle'), 3000);
        console.log('✅ Personal performance data saved successfully');
      }
      
    } catch (error) {
      console.error('Error saving personal data:', error);
      setPersonalSaveStatus('error');
      toast({
        title: "❌ Personal Save Failed",
        description: (error as Error).message || "Failed to save personal changes. Please try again.",
        variant: "destructive",
        duration: 6000,
      });
      if (personalTimeoutRef.current) {
        clearTimeout(personalTimeoutRef.current);
      }
      personalTimeoutRef.current = setTimeout(() => setPersonalSaveStatus('idle'), 3000);
    }
  };

  const cancelDepartmentalEditing = () => {
    if (departmentalTimeoutRef.current) {
      clearTimeout(departmentalTimeoutRef.current);
    }
    setIsEditingDepartmental(false);
    setEditingMonthlyData({});
    setDepartmentalSaveStatus('idle');
  };

  const cancelPersonalEditing = () => {
    if (personalTimeoutRef.current) {
      clearTimeout(personalTimeoutRef.current);
    }
    setIsEditingPersonal(false);
    setEditingBiannualData({});
    setPersonalSaveStatus('idle');
    setNewCycleFrom("");
    setNewCycleTo("");
  };

  // Personal Remarks functions
  const startPersonalRemarksEditing = () => {
    const next: Record<string, string> = {};
    for (const cycle of personalRemarkPeriods) {
      next[`${cycle.period}_${cycle.year}`] = cycle.remarks || "";
    }
    setEditingRemarks(next);
    setIsEditingPersonalRemarks(true);
  };

  const cancelPersonalRemarksEditing = () => {
    if (personalRemarksTimeoutRef.current) {
      clearTimeout(personalRemarksTimeoutRef.current);
    }
    setIsEditingPersonalRemarks(false);
    setEditingRemarks({});
    setPersonalRemarksSaveStatus('idle');
    setPersonalRemarks(latestPersonalKpiRecordWithRemarks(biannualData)?.remarks || '');
  };

  const savePersonalRemarks = async () => {
    setPersonalRemarksSaveStatus('saving');
    
    try {
      let updatedBiannualData = [...biannualData];

      for (const cycle of personalRemarkPeriods) {
        const key = `${cycle.period}_${cycle.year}`;
        const nextRemarks = editingRemarks[key] ?? "";
        const previousRemarks = cycle.remarks || "";
        if (nextRemarks === previousRemarks) continue;
        if (!nextRemarks.trim() && !cycle.record) continue;

        const existing = cycle.record as (BiAnnualPerformanceData & Record<string, unknown>) | undefined;
        const {
          id: _id,
          user: _user,
          createdAt: _createdAt,
          updatedAt: _updatedAt,
          reviewedAt: _reviewedAt,
          ...existingFields
        } = (existing || {}) as Record<string, unknown>;

        const dataToSave = {
          ...existingFields,
          userId: user.id,
          period: cycle.period,
          year: cycle.year,
          remarks: nextRemarks,
          isPublished: existing?.isPublished ?? false,
        };

        const saved = await apiCall(
          api.endpoints.savePerformance.initiate({
            endpoint: biannualApiEndpoint,
            body: dataToSave,
          }),
        );

        const idx = updatedBiannualData.findIndex(
          (row) => row.period === cycle.period && row.year === cycle.year,
        );
        if (idx >= 0) {
          updatedBiannualData[idx] = {
            ...updatedBiannualData[idx],
            remarks: nextRemarks,
          };
        } else {
          updatedBiannualData.push(
            (saved as BiAnnualPerformanceData) ||
              ({
                ...dataToSave,
                weightedAverage: 0,
              } as BiAnnualPerformanceData),
          );
        }
      }
      
      setBiannualData(updatedBiannualData);
      setPersonalRemarks(
        latestPersonalKpiRecordWithRemarks(updatedBiannualData)?.remarks || '',
      );
      setPersonalRemarksSaveStatus('saved');
      setIsEditingPersonalRemarks(false);
      setEditingRemarks({});
      
      toast({
        title: "✅ Personal Remarks Saved",
        description: "Personal KPI remarks saved successfully!",
        duration: 4000,
      });
      
      if (personalRemarksTimeoutRef.current) {
        clearTimeout(personalRemarksTimeoutRef.current);
      }
      personalRemarksTimeoutRef.current = setTimeout(() => setPersonalRemarksSaveStatus('idle'), 3000);
      
    } catch (error) {
      console.error('Error saving personal remarks:', error);
      setPersonalRemarksSaveStatus('error');
      toast({
        title: "❌ Personal Remarks Save Failed",
        description: (error as Error).message || "Failed to save personal remarks. Please try again.",
        variant: "destructive",
        duration: 6000,
      });
      if (personalRemarksTimeoutRef.current) {
        clearTimeout(personalRemarksTimeoutRef.current);
      }
      personalRemarksTimeoutRef.current = setTimeout(() => setPersonalRemarksSaveStatus('idle'), 3000);
    }
  };

  // Get monthly data for specific month/year
  const getMonthlyData = (month: number, year: number) => {
    const dataSource = isItUser ? itMonthlyData : monthlyData;
    const existingData = dataSource.find(d => d.month === month && d.year === year);
    if (existingData) return existingData;

    // Return default structure
    const defaultData: any = {
      userId: user.id,
      month,
      year,
      weightedAverage: 0,
      isPublished: false
    };

    // Add default values for each KPI
    Object.keys(MONTHLY_KPI_CONFIG).forEach(key => {
      defaultData[key] = 0;
    });

    return defaultData as MonthlyPerformanceData;
  };

  // Get biannual data for specific period/year
  const getBiannualData = (period: string, year: number) => {
    const existing = biannualData.find(d => d.period === period && d.year === year);
    if (existing) return existing;
    const defaults: any = {
      userId: user.id,
      period,
      year,
      weightedAverage: 0,
      isPublished: false
    };
    const biannualConfigForDefault = isSeoUserMemo ? SEO_BIANNUAL_KPI_CONFIG : isMarketingUser ? MARKETING_BIANNUAL_KPI_CONFIG : isItUser ? IT_BIANNUAL_KPI_CONFIG : BIANNUAL_KPI_CONFIG;
    Object.keys(biannualConfigForDefault).forEach(key => { defaults[key] = 0; });
    return defaults as BiAnnualPerformanceData;
  };

  // Check if the current user has permission to edit this user's performance
  // MOVED BEFORE EARLY RETURNS TO FOLLOW RULES OF HOOKS
  const canEdit = useMemo(() => {
    if (!session?.user) return false;
    
    const currentUserPosition = session.user.position;
    const currentUserRole = session.user.role;
    const currentUserId = session.user.id;
    
    // SUPER_ADMIN has full editing access
    const isSuperAdmin = currentUserRole === 'SUPER_ADMIN';
    
    // Executive access (CEO, COO)
    const hasExecutiveAccess = currentUserPosition && ['CEO', 'COO'].includes(currentUserPosition);
    
    // HR access
    const hasHRAccess = currentUserPosition && (
      currentUserPosition.includes('HR') || 
      currentUserPosition.includes('Human Resources') ||
      currentUserPosition === 'VP Human Resources' ||
      currentUserPosition === 'HR Manager' ||
      currentUserPosition === 'HR Business Partner' ||
      currentUserPosition === 'Talent Acquisition Manager'
    );
    
    // Manager role check (excluding UPPER_MANAGEMENT from edit permissions)
    const hasManagerialRole = ['MANAGER', 'UNIT_LEAD'].includes(currentUserRole);
    
    // Direct report check (is this user's manager)
    const isDirectManager = user.managerId === currentUserId;
    
    // Same department manager check (home department or a department they head)
    const isSameDepartmentManager =
      hasManagerialRole &&
      (user.department === session.user.department ||
        (!!user.department && managedDepartments.includes(user.department)));
    
    // SUPER_ADMIN can edit all performance data
    if (isSuperAdmin) {
      return true;
    }
    
    // Block editing for CEO, COO positions (but allow SUPER_ADMIN and HR)
    if (hasExecutiveAccess) {
      return false;
    }
    
    // HR users can edit all users' performance data
    if (hasHRAccess) {
      return true;
    }
    
    // UPPER_MANAGEMENT has view-only access, no edit permissions
    const canEditPerformance = isDirectManager || isSameDepartmentManager;

    return canEditPerformance;
  }, [session?.user, user.managerId, user.department, managedDepartments]);

  if (loading) {
    return (
      <div className="space-y-6">
        <ChartPanelSkeleton />
        <ChartPanelSkeleton />
      </div>
    );
  }

  // Render Design Performance for Design users
  if (isDesignUser && designPerformanceType) {
    return (
      <motion.div
        className="space-y-5"
        variants={staggerContainer}
        initial={prefersReducedMotion ? false : 'initial'}
        animate={prefersReducedMotion ? false : 'animate'}
      >
        <motion.div variants={staggerItem} className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-primary/10 dark:bg-primary/15">
              <TrendingUp className="h-5 w-5 text-primary" />
            </div>
            <div>
              <h2 className="text-xl font-semibold text-foreground">
                Design {isDesignLead ? 'Team Lead' : designSubTeam || 'Department'} Performance Metrics
              </h2>
              <p className="text-sm text-muted-foreground">
                Track and manage {user.name}'s design {isDesignLead ? 'team leadership' : (designSubTeam?.toLowerCase() || 'department')} performance KPIs
              </p>
            </div>
          </div>
        </motion.div>

        <motion.div variants={staggerItem}>
          <DesignPerformance 
            user={user}
            designPerformanceType={designPerformanceType}
            designSubTeam={designSubTeam}
            isDesignTeamLead={isDesignLead}
            canEdit={canEdit}
            dateFrom={dateFrom}
            dateTo={dateTo}
          />
        </motion.div>
      </motion.div>
    );
  }

  return (
    <motion.div
      className="space-y-5"
      initial={prefersReducedMotion ? false : { opacity: 0 }}
      animate={prefersReducedMotion ? false : { opacity: 1 }}
      transition={{ duration: 0.2 }}
    >
      <motion.div variants={staggerItem} className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-primary/10 dark:bg-primary/15">
            <TrendingUp className="h-5 w-5 text-primary" />
          </div>
          <div>
            <h2 className="text-xl font-semibold text-foreground">
              {isDesignUser ? 
                `Design ${isDesignLead ? 'Team Lead' : designSubTeam || 'Department'} Performance Metrics` :
                isPmo ? 'PMO Performance Metrics' :
                isUserUnitLead ? 'Unit Lead Performance Metrics' : 
                isUserSqa ? 'SQA Performance Metrics' : 'Development Performance Metrics'}
            </h2>
            <p className="text-sm text-muted-foreground">
              Track and manage {user.name}'s {
                isDesignUser ? 
                  `design ${isDesignLead ? 'team leadership' : (designSubTeam?.toLowerCase() || 'department')}` :
                  isPmo ? 'project management' :
                  isUserUnitLead ? 'leadership and team management' : 
                  isUserSqa ? 'SQA testing' : 'development'
              } performance KPIs
            </p>
          </div>
        </div>
        
        <div className="flex items-center gap-2">
          {(departmentalSaveStatus === 'saved' || personalSaveStatus === 'saved') && (
            <div className="flex items-center gap-1.5 text-emerald-600 dark:text-emerald-400">
              <Check className="h-4 w-4" />
              <span className="text-sm font-medium">Saved!</span>
            </div>
          )}
          
          {(departmentalSaveStatus === 'error' || personalSaveStatus === 'error') && (
            <div className="flex items-center gap-1.5 text-destructive">
              <X className="h-4 w-4" />
              <span className="text-sm font-medium">Save Failed</span>
            </div>
          )}
        </div>
      </motion.div>

      <motion.div
        className="w-full space-y-5"
        variants={staggerContainer}
        initial={prefersReducedMotion ? false : 'initial'}
        animate={prefersReducedMotion ? false : 'animate'}
      >
        {/* Performance Summary Section */}
        {(() => {
          // Only records inside the selected date range (same rows as the tables below).
          const monthlyYearData = (isItUser ? itMonthlyData : monthlyData).filter(
            (d) =>
              departmentalMonths.some((m) => m.month === d.month && m.year === d.year) &&
              isEnteredKpiMonth(d), // all-zero months count as not entered
          );
          const biannualYearData = biannualData.filter((d) =>
            BIANNUAL_PERIODS.some((c) => c.period === d.period && c.year === d.year),
          );
          
          if (monthlyYearData.length === 0 && biannualYearData.length === 0) {
            return null;
          }
          
          return (
            <motion.section variants={staggerItem} className="rounded-xl border border-border bg-card overflow-hidden">
              <div className="flex items-center gap-2 px-5 py-3.5 border-b border-border">
                <TrendingUp className="h-4 w-4 text-primary" />
                <h3 className="text-sm font-semibold text-foreground">
                  {isPmo ? 'PMO Performance Summary' :
                   isUserUnitLead ? 'Unit Lead Performance Summary' :
                   isUserSqa ? 'SQA Performance Summary' : 'Development Performance Summary'}
                </h3>
              </div>
              
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 divide-x divide-y lg:divide-y-0 divide-border">
                {monthlyYearData.length > 0 && (
                  <>
                    <div className="px-5 py-4">
                      <div className="text-xs font-medium text-muted-foreground mb-1">Monthly Sum</div>
                      <div className="flex items-center gap-2">
                        {(() => {
                          const monthlySum = Object.keys(MONTHLY_KPI_CONFIG).reduce((sum, field) => {
                            const avg = monthlyYearData.reduce((sum, d) => sum + (d[field] || 0), 0) / monthlyYearData.length;
                            return sum + avg;
                          }, 0);
                          return (
                            <>
                              <span className="text-2xl font-semibold tracking-tight tabular-nums text-foreground">{formatNumber(monthlySum)}</span>
                              <Badge className={`${getPerformanceColor(monthlySum)} text-xs font-semibold`}>
                                {getPerformanceGrade(monthlySum)}
                              </Badge>
                            </>
                          );
                        })()}
                      </div>
                      <div className="text-xs text-muted-foreground mt-1">
                        Sum of KPI Averages
                      </div>
                    </div>

                    <div className="px-5 py-4">
                      <div className="text-xs font-medium text-muted-foreground mb-1">Best Month</div>
                      {(() => {
                        const bestMonth = monthlyYearData.reduce((best, current) => 
                          current.weightedAverage > best.weightedAverage ? current : best
                        );
                        const monthName = new Date(bestMonth.year, bestMonth.month - 1).toLocaleString('default', { month: 'long', year: 'numeric' });
                        return (
                          <>
                            <div className="text-lg font-semibold tracking-tight tabular-nums text-foreground">{formatNumber(bestMonth.weightedAverage)}%</div>
                            <div className="text-xs text-muted-foreground">{monthName}</div>
                          </>
                        );
                      })()}
                    </div>
                  </>
                )}

                {biannualYearData.length > 0 && (
                  <>
                    <div className="px-5 py-4">
                      <div className="text-xs font-medium text-muted-foreground mb-1">Biannual Sum</div>
                      <div className="flex items-center gap-2">
                        {(() => {
                          const biannualSum = Object.keys(BIANNUAL_KPI_CONFIG).reduce((sum, field) => {
                            const avg = biannualYearData.reduce((sum, d) => sum + (d[field as keyof BiAnnualPerformanceData] as number), 0) / biannualYearData.length;
                            return sum + avg;
                          }, 0);
                          return (
                            <>
                              <span className="text-2xl font-semibold tracking-tight tabular-nums text-foreground">{formatNumber(biannualSum)}</span>
                              <Badge className={`${getPerformanceColor(biannualSum)} text-xs font-semibold`}>
                                {getPerformanceGrade(biannualSum)}
                              </Badge>
                            </>
                          );
                        })()}
                      </div>
                      <div className="text-xs text-muted-foreground mt-1">
                        Sum of KPI Averages
                      </div>
                    </div>

                    <div className="px-5 py-4">
                      <div className="text-xs font-medium text-muted-foreground mb-1">Data Points</div>
                      <div className="text-lg font-semibold tracking-tight tabular-nums text-foreground">
                        {monthlyYearData.length + biannualYearData.length}
                      </div>
                      <div className="text-xs text-muted-foreground">
                        {monthlyYearData.length} Monthly, {biannualYearData.length} Biannual
                      </div>
                    </div>
                  </>
                )}
              </div>
            </motion.section>
          );
        })()}

        {/* Performance Scoring Legend - same for both */}
        <motion.section variants={staggerItem} className="rounded-xl border border-border bg-card overflow-hidden">
          <div className="flex items-center gap-2 px-5 py-3.5 border-b border-border">
            <div className="p-1.5 rounded-md bg-primary/10 dark:bg-primary/15">
              <TrendingUp className="h-4 w-4 text-primary" />
            </div>
            <h3 className="text-sm font-semibold text-foreground">Performance Scoring Legend</h3>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 divide-x divide-y md:divide-y-0 divide-border">
            <div className="flex flex-col items-center px-4 py-3">
              <Badge className="bg-emerald-100 text-emerald-800 border-emerald-200 dark:bg-emerald-950/50 dark:text-emerald-300 dark:border-emerald-800 text-xs font-bold mb-1.5">A+</Badge>
              <span className="text-xs font-medium text-foreground">90-100%</span>
              <span className="text-[11px] text-muted-foreground text-center mt-0.5">Excellent</span>
            </div>
            <div className="flex flex-col items-center px-4 py-3">
              <Badge className="bg-green-100 text-green-800 border-green-200 dark:bg-green-950/50 dark:text-green-300 dark:border-green-800 text-xs font-bold mb-1.5">A/B+</Badge>
              <span className="text-xs font-medium text-foreground">80-89%</span>
              <span className="text-[11px] text-muted-foreground text-center mt-0.5">Good</span>
            </div>
            <div className="flex flex-col items-center px-4 py-3">
              <Badge className="bg-primary/15 text-primary border-primary/20 dark:bg-primary/20 dark:text-primary dark:border-primary/30 text-xs font-bold mb-1.5">B/C+</Badge>
              <span className="text-xs font-medium text-foreground">70-79%</span>
              <span className="text-[11px] text-muted-foreground text-center mt-0.5">Satisfactory</span>
            </div>
            <div className="flex flex-col items-center px-4 py-3">
              <Badge className="bg-yellow-100 text-yellow-800 border-yellow-200 dark:bg-yellow-950/50 dark:text-yellow-300 dark:border-yellow-800 text-xs font-bold mb-1.5">C/D+</Badge>
              <span className="text-xs font-medium text-foreground">60-69%</span>
              <span className="text-[11px] text-muted-foreground text-center mt-0.5">Needs Improvement</span>
            </div>
            <div className="flex flex-col items-center px-4 py-3">
              <Badge className="bg-orange-100 text-orange-800 border-orange-200 dark:bg-orange-950/50 dark:text-orange-300 dark:border-orange-800 text-xs font-bold mb-1.5">D</Badge>
              <span className="text-xs font-medium text-foreground">40-59%</span>
              <span className="text-[11px] text-muted-foreground text-center mt-0.5">Below Average</span>
            </div>
            <div className="flex flex-col items-center px-4 py-3">
              <Badge className="bg-red-100 text-red-800 border-red-200 dark:bg-red-950/50 dark:text-red-300 dark:border-red-800 text-xs font-bold mb-1.5">F</Badge>
              <span className="text-xs font-medium text-foreground">0-39%</span>
              <span className="text-[11px] text-muted-foreground text-center mt-0.5">Poor</span>
            </div>
          </div>
        </motion.section>

        {/* Personal KPI Remarks Section */}
        <motion.section variants={staggerItem} className="rounded-xl border border-border bg-card overflow-hidden">
          <div className="flex items-center justify-between px-5 py-3.5 border-b border-border">
            <div className="flex items-center gap-2">
              <FileText className="h-4 w-4 text-primary" />
              <h3 className="text-sm font-semibold text-foreground">
                Personal KPI Remarks
              </h3>
            </div>
            
            <div className="flex items-center gap-2">
              {personalRemarksSaveStatus === 'saved' && (
                <div className="flex items-center gap-1.5 text-emerald-600 dark:text-emerald-400">
                  <Check className="h-4 w-4" />
                  <span className="text-sm font-medium">Saved!</span>
                </div>
              )}
              
              {personalRemarksSaveStatus === 'error' && (
                <div className="flex items-center gap-1.5 text-destructive">
                  <X className="h-4 w-4" />
                  <span className="text-sm font-medium">Save Failed</span>
                </div>
              )}
              
              {isEditingPersonalRemarks ? (
                <div className="flex gap-2">
                  <Button 
                    variant="outline" 
                    onClick={cancelPersonalRemarksEditing}
                    disabled={personalRemarksSaveStatus === 'saving'}
                    size="sm"
                  >
                    <X className="h-4 w-4 mr-2" />
                    Cancel
                  </Button>
                  <Button 
                    onClick={savePersonalRemarks}
                    disabled={personalRemarksSaveStatus === 'saving'}
                    size="sm"
                  >
                    {personalRemarksSaveStatus === 'saving' ? (
                      <>
                        <AppSpinner className="mr-2" />
                        Saving...
                      </>
                    ) : (
                      <>
                        <Save className="h-4 w-4 mr-2" />
                        Save Remarks
                      </>
                    )}
                  </Button>
                </div>
              ) : (
                canEdit && (
                  <Button 
                    onClick={startPersonalRemarksEditing}
                    size="sm"
                  >
                    <Edit className="h-4 w-4 mr-2" />
                    Edit Remarks
                  </Button>
                )
              )}
            </div>
          </div>

          <div className="p-4 space-y-3">
            {personalRemarkPeriods.length === 0 ? (
              <div className="bg-muted/40 p-3 rounded-lg border border-border min-h-[96px]">
                <p className="text-sm text-foreground/80">
                  No Personal KPI periods in this date range.
                </p>
              </div>
            ) : (
              personalRemarkPeriods.map((cycle) => {
                const key = `${cycle.period}_${cycle.year}`;
                const text = isEditingPersonalRemarks
                  ? (editingRemarks[key] ?? cycle.remarks)
                  : cycle.remarks;
                return (
                  <div key={key} className="space-y-1.5">
                    <p className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">
                      {cycle.label}
                    </p>
                    {isEditingPersonalRemarks ? (
                      <Textarea
                        value={text}
                        onChange={(e) =>
                          setEditingRemarks((prev) => ({
                            ...prev,
                            [key]: e.target.value,
                          }))
                        }
                        placeholder={`Remarks for ${cycle.label}...`}
                        className="w-full min-h-[88px] resize-none"
                        rows={3}
                      />
                    ) : (
                      <div className="bg-muted/40 p-3 rounded-lg border border-border min-h-[72px]">
                        <p className="text-sm text-foreground/80 whitespace-pre-wrap">
                          {text || "No remarks for this period yet."}
                        </p>
                      </div>
                    )}
                  </div>
                );
              })
            )}
          </div>
        </motion.section>

        {/* KPIs — stacked full-width to avoid unbalanced empty columns */}
        <div className="space-y-5">
          {/* Departmental KPIs Section */}
          <motion.section variants={staggerItem} className="rounded-xl border border-border bg-card overflow-hidden">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 px-5 py-3 border-b border-border">
              <div className="flex items-center gap-2 min-w-0">
                <Calendar className="h-4 w-4 text-primary shrink-0" />
                <div className="min-w-0">
                  <h3 className="text-sm font-semibold text-foreground truncate">
                    {isItUser ? 'IT Departmental KPIs (Monthly)' : isSeoUserMemo ? 'SEO Departmental KPIs (Monthly)' : isMarketingUser ? 'Marketing Departmental KPIs (Monthly)' : isPmo ? 'PMO Departmental KPIs (Monthly)' : isUserSqa ? 'SQA Quality Departmental KPIs (Monthly)' : 'Departmental KPIs Projects (Monthly)'}
                  </h3>
                  <span className="text-xs text-muted-foreground">
                    {departmentalMonths.length} month{departmentalMonths.length === 1 ? '' : 's'} · paginated
                  </span>
                </div>
              </div>
            
            <div className="flex items-center gap-2 shrink-0">
              {departmentalSaveStatus === 'saved' && (
                <div className="flex items-center gap-1.5 text-emerald-600 dark:text-emerald-400">
                  <Check className="h-4 w-4" />
                  <span className="text-sm font-medium">Saved!</span>
                </div>
              )}
              
              {departmentalSaveStatus === 'error' && (
                <div className="flex items-center gap-1.5 text-destructive">
                  <X className="h-4 w-4" />
                  <span className="text-sm font-medium">Save Failed</span>
                </div>
              )}
              
              {isEditingDepartmental ? (
                <div className="flex gap-2">
                  <Button 
                    variant="outline" 
                    onClick={cancelDepartmentalEditing}
                    disabled={departmentalSaveStatus === 'saving'}
                    size="sm"
                  >
                    <X className="h-4 w-4 mr-2" />
                    Cancel
                  </Button>
                  <Button 
                    onClick={saveDepartmentalChanges}
                    disabled={departmentalSaveStatus === 'saving'}
                    size="sm"
                  >
                    {departmentalSaveStatus === 'saving' ? (
                      <>
                        <AppSpinner className="mr-2" />
                        Saving...
                      </>
                    ) : (
                      <>
                        <Save className="h-4 w-4 mr-2" />
                        Save Changes
                      </>
                    )}
                  </Button>
                </div>
              ) : (
                canEdit && (
                  <Button 
                    onClick={startDepartmentalEditing}
                    size="sm"
                  >
                    <Edit className="h-4 w-4 mr-2" />
                    Edit Departmental
                  </Button>
                )
              )}
            </div>
          </div>

          <div className="overflow-x-auto">
            <table className={`w-full border-collapse ${isItUser ? 'table-fixed' : ''}`}>
              <thead>
                <tr className="bg-muted/50 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                  <th className={`border-b border-border px-3 py-2 text-left ${isItUser ? 'w-24' : 'min-w-[120px]'}`}>
                    Month
                  </th>
                  {Object.entries(MONTHLY_KPI_CONFIG).map(([key, config]) => {
                    const fullLabel = (config as any).fullLabel || config.label;
                    const displayLabel = isItUser ? config.label : fullLabel;
                    return (
                      <th 
                        key={key} 
                        className={`border-b border-border px-2 py-2 text-center normal-case ${isItUser ? 'w-28' : 'min-w-[90px]'}`}
                        title={isItUser ? fullLabel : undefined}
                      >
                        <div className="flex flex-col items-center justify-center">
                          <span className={`${isItUser ? 'text-[10px] leading-tight' : 'text-[11px]'} font-semibold text-foreground`}>
                            {displayLabel}
                          </span>
                          <span className={`${isItUser ? 'text-[9px]' : 'text-[10px]'} text-primary font-normal mt-0.5 normal-case`}>
                          {config.weight}%
                        </span>
                      </div>
                    </th>
                    );
                  })}
                  <th className={`border-b border-border ${isItUser ? 'px-2 py-2 w-20' : 'px-3 py-2 min-w-[80px]'} text-center`}>
                    <div className="flex flex-col normal-case">
                      <span className={isItUser ? 'text-[10px]' : 'text-[11px] text-foreground'}>Total</span>
                      <span className={`${isItUser ? 'text-[9px]' : 'text-[10px]'} text-emerald-600 dark:text-emerald-400 font-normal`}>Sum</span>
                    </div>
                  </th>
                </tr>
              </thead>
              <tbody>
                {paginatedDepartmentalMonths.map(({ month, monthName, year }) => {
                  const data = getMonthlyData(month, year);
                  
                  return (
                    <tr key={`${month}-${year}`} className="hover:bg-muted/40 border-b border-border/60">
                      <td className={`px-3 py-2 font-medium text-foreground ${isItUser ? 'text-xs' : 'text-sm'}`}>
                        {monthName} {year}
                      </td>
                      
                      {Object.entries(MONTHLY_KPI_CONFIG).map(([field, config]) => {
                        const key = `${month}_${year}`;
                        const editingData = editingMonthlyData[key];
                        const displayValue = isEditingDepartmental && editingData 
                          ? editingData[field] as number
                          : data[field] as number;
                        
                        return (
                          <td key={field} className={`px-2 py-1.5 text-center`}>
                            {isEditingDepartmental ? (
                              <Input
                                type="number"
                                min="0"
                                max={config.max}
                                step="1"
                                value={displayValue || ''}
                                onChange={(e) => {
                                  const inputValue = e.target.value;
                                  // Allow empty input or valid numbers while typing
                                  if (inputValue === '' || /^\d*\.?\d*$/.test(inputValue)) {
                                    const num = parseFloat(inputValue);
                                    if (inputValue === '' || (num >= 0 && num <= config.max)) {
                                      handleMonthlyKPIChange(month, year, field, inputValue);
                                    } else {
                                      // Allow temporarily invalid values while typing, will be corrected on blur
                                      handleMonthlyKPIChange(month, year, field, inputValue);
                                    }
                                  }
                                }}
                                onBlur={(e) => handleMonthlyKPIBlur(month, year, field, e.target.value)}
                                className={getInputClassName(displayValue || 0, config.max, isItUser ? "w-12 h-8 text-center text-xs" : "w-16 h-8 text-center text-sm")}
                                title={`Enter value between 0 and ${config.max} for ${(config as any).fullLabel || config.label}`}
                              />
                            ) : (
                              <Badge
                                className={`${getPerformanceColor(displayValue || 0)} ${isItUser ? 'text-[10px] px-1.5 py-0.5' : 'text-xs px-2 py-1'}`}
                              >
                                {displayValue || 0}
                              </Badge>
                            )}
                          </td>
                        );
                      })}
                      
                      <td className={`px-2 py-1.5 text-center`}>
                        <span className="text-xs text-muted-foreground">-</span>
                      </td>
                    </tr>
                  );
                })}
                
                {/* Average Row */}
                {(() => {
                  // Show overall average across all recorded data
                  const monthlyDataFiltered = (isItUser ? itMonthlyData : monthlyData).filter(
                    (d) =>
                      departmentalMonths.some(
                        (m) => m.month === d.month && m.year === d.year,
                      ) && isEnteredKpiMonth(d), // all-zero months count as not entered
                  );
                  
                  if (monthlyDataFiltered.length === 0) return null;
                  return (
                    <tr className="bg-muted/30 font-semibold border-t border-border">
                      <td className={`px-3 py-2 text-foreground ${isItUser ? 'text-xs' : 'text-sm'}`}>Overall Average</td>
                      {Object.keys(MONTHLY_KPI_CONFIG).map((field) => {
                        const avg = monthlyDataFiltered.length > 0 
                          ? monthlyDataFiltered.reduce((sum, d) => sum + (d[field] || 0), 0) / monthlyDataFiltered.length
                          : 0;
                        
                        return (
                          <td key={field} className="px-2 py-1.5 text-center">
                            <Badge className={`${getPerformanceColor(avg)} font-bold ${isItUser ? 'text-[10px] px-1.5 py-0.5' : 'text-xs'}`}>
                              {formatNumber(avg)}
                            </Badge>
                          </td>
                        );
                      })}
                      <td className="px-2 py-1.5 text-center">
                        {(() => {
                          const kpiSum = monthlyDataFiltered.length > 0 
                            ? Object.keys(MONTHLY_KPI_CONFIG).reduce((sum, field) => {
                                const avg = monthlyDataFiltered.reduce((sum, d) => sum + (d[field] || 0), 0) / monthlyDataFiltered.length;
                                return sum + avg;
                              }, 0)
                            : 0;
                          
                          return (
                            <Badge className={`${getPerformanceColor(kpiSum)} font-bold ${isItUser ? 'text-[10px] px-1.5 py-0.5' : 'text-xs'}`}>
                              {formatNumber(kpiSum)}
                            </Badge>
                          );
                        })()}
                      </td>
                    </tr>
                  );
                })()}
              </tbody>
            </table>
          </div>

          {departmentalMonths.length > 0 && (
            <TablePagination
              currentPage={departmentalPage}
              totalItems={departmentalMonths.length}
              pageSize={MONTHLY_PAGE_SIZE}
              onPageChange={setDepartmentalPage}
              itemLabel="months"
            />
          )}

          {(isItUser ? itMonthlyData : monthlyData).length === 0 && (
            <div className="text-center py-6 text-muted-foreground">
              <Calendar className="h-10 w-10 mx-auto mb-3 opacity-30" />
              <p className="text-sm">No {isItUser ? 'IT' : isSeoUserMemo ? 'SEO' : isMarketingUser ? 'Marketing' : isPmo ? 'PMO' : isUserUnitLead ? 'Unit Lead' : isUserSqa ? 'SQA' : 'development'} performance data available yet.</p>
              <p className="text-xs mt-1">Click on any cell above to start entering KPI data.</p>
            </div>
          )}
        </motion.section>

        {/* Bi-Annual KPIs — full width, content-height (no stretch beside monthly table) */}
        <motion.section variants={staggerItem} className="rounded-xl border border-border bg-card overflow-hidden">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 px-5 py-3 border-b border-border">
            <div className="flex items-center gap-2 min-w-0">
              <BarChart3 className="h-4 w-4 text-emerald-600 dark:text-emerald-400 shrink-0" />
              <div className="min-w-0">
                <h3 className="text-sm font-semibold text-foreground truncate">
                  Personnel KPIs Projects/Products
                </h3>
                <span className="text-xs text-muted-foreground">
                  One row per review cycle
                  {' · '}
                  {displayedPersonalCycles.length} period
                  {displayedPersonalCycles.length === 1 ? '' : 's'}
                </span>
              </div>
            </div>
            
            <div className="flex items-center gap-2 shrink-0">
              {personalSaveStatus === 'saved' && (
                <div className="flex items-center gap-1.5 text-emerald-600 dark:text-emerald-400">
                  <Check className="h-4 w-4" />
                  <span className="text-sm font-medium">Saved!</span>
                </div>
              )}
              
              {personalSaveStatus === 'error' && (
                <div className="flex items-center gap-1.5 text-destructive">
                  <X className="h-4 w-4" />
                  <span className="text-sm font-medium">Save Failed</span>
                </div>
              )}
              
              {isEditingPersonal ? (
                <div className="flex gap-2">
                  <Button 
                    variant="outline" 
                    onClick={cancelPersonalEditing}
                    disabled={personalSaveStatus === 'saving'}
                    size="sm"
                  >
                    <X className="h-4 w-4 mr-2" />
                    Cancel
                  </Button>
                  <Button 
                    onClick={savePersonalChanges}
                    disabled={personalSaveStatus === 'saving'}
                    size="sm"
                  >
                    {personalSaveStatus === 'saving' ? (
                      <>
                        <AppSpinner className="mr-2" />
                        Saving...
                      </>
                    ) : (
                      <>
                        <Save className="h-4 w-4 mr-2" />
                        Save Changes
                      </>
                    )}
                  </Button>
                </div>
              ) : (
                canEdit && (
                  <Button 
                    onClick={startPersonalEditing}
                    size="sm"
                  >
                    <Edit className="h-4 w-4 mr-2" />
                    Edit Personal
                  </Button>
                )
              )}
            </div>
          </div>

          {isEditingPersonal && (
            <div className="flex flex-wrap items-end gap-2 border-b border-border bg-muted/30 px-5 py-3">
              <div className="space-y-1">
                <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
                  New cycle from
                </p>
                <MonthYearPicker
                  value={newCycleFrom}
                  onChange={setNewCycleFrom}
                  max={newCycleTo || undefined}
                  buttonClassName="h-8 w-[148px]"
                  title="Cycle start month"
                  placeholder="Select month"
                />
              </div>
              <div className="space-y-1">
                <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
                  to
                </p>
                <MonthYearPicker
                  value={newCycleTo}
                  onChange={setNewCycleTo}
                  min={newCycleFrom || undefined}
                  buttonClassName="h-8 w-[148px]"
                  title="Cycle end month"
                  placeholder="Select month"
                />
              </div>
              <Button
                type="button"
                size="sm"
                variant="outline"
                onClick={addPersonalCycle}
                disabled={isAddingCycle}
                className="h-8"
              >
                <Plus className="mr-1.5 h-4 w-4" />
                {isAddingCycle ? "Adding..." : "Add period"}
              </Button>
              <p className="w-full text-[11px] text-muted-foreground">
                Month and year only. Adding or deleting a period applies to every {user.department || "department"} employee.
              </p>
            </div>
          )}

          <div className="overflow-x-auto">
            <table className="w-full table-fixed border-collapse">
              <thead>
                <tr className="bg-muted/50 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                  <th className="border-b border-border px-3 py-2 text-left w-[22%]">
                    Period
                  </th>
                  {Object.entries(isSeoUserMemo ? SEO_BIANNUAL_KPI_CONFIG : isMarketingUser ? MARKETING_BIANNUAL_KPI_CONFIG : isItUser ? IT_BIANNUAL_KPI_CONFIG : BIANNUAL_KPI_CONFIG).map(([key, config]) => (
                    <th key={key} className="border-b border-border px-3 py-2 text-center normal-case">
                      <div className="flex flex-col">
                        <span className="text-[11px] font-semibold text-foreground">{config.label}</span>
                        <span className="text-[10px] text-emerald-600 dark:text-emerald-400 font-normal">
                          {config.weight}%
                        </span>
                      </div>
                    </th>
                  ))}
                  <th className="border-b border-border px-3 py-2 text-center w-[12%]">
                    <div className="flex flex-col normal-case">
                      <span className="text-[11px] text-foreground">Total</span>
                      <span className="text-[10px] text-emerald-600 dark:text-emerald-400 font-normal">Sum</span>
                    </div>
                  </th>
                  {isEditingPersonal && (
                    <th className="border-b border-border px-2 py-2 text-center w-[8%]">
                      <span className="sr-only">Actions</span>
                    </th>
                  )}
                </tr>
              </thead>
              <tbody>
                {displayedPersonalCycles.map(({ period, label, year }) => {
                  const data = getBiannualData(period, year);
                  
                  return (
                    <tr key={`${period}-${year}`} className="hover:bg-muted/40 border-b border-border/60 last:border-b-0">
                      <td className="px-3 py-2.5 font-medium text-foreground text-sm">
                        {label}
                      </td>
                      
                      {Object.entries(isSeoUserMemo ? SEO_BIANNUAL_KPI_CONFIG : isMarketingUser ? MARKETING_BIANNUAL_KPI_CONFIG : isItUser ? IT_BIANNUAL_KPI_CONFIG : BIANNUAL_KPI_CONFIG).map(([field, config]) => {
                        const key = `${period}_${year}`;
                        const editingData = editingBiannualData[key];
                        const displayValue = isEditingPersonal && editingData 
                          ? editingData[field as keyof BiAnnualPerformanceData] as number
                          : data[field as keyof BiAnnualPerformanceData] as number;
                        
                        return (
                          <td key={field} className="px-2 py-1.5 text-center">
                            {isEditingPersonal ? (
                              <Input
                                type="number"
                                min="0"
                                max={config.max}
                                step="1"
                                value={displayValue || ''}
                                onChange={(e) => {
                                  const inputValue = e.target.value;
                                  // Allow empty input or valid numbers while typing
                                  if (inputValue === '' || /^\d*\.?\d*$/.test(inputValue)) {
                                    const num = parseFloat(inputValue);
                                    if (inputValue === '' || (num >= 0 && num <= config.max)) {
                                      handleBiannualKPIChange(period, year, field, inputValue);
                                    } else {
                                      // Allow temporarily invalid values while typing, will be corrected on blur
                                      handleBiannualKPIChange(period, year, field, inputValue);
                                    }
                                  }
                                }}
                                onBlur={(e) => handleBiannualKPIBlur(period, year, field, e.target.value)}
                                className={getInputClassName(displayValue || 0, config.max, "w-16 h-8 text-center text-sm")}
                                title={`Enter value between 0 and ${config.max} for ${config.label}`}
                              />
                            ) : (
                              <Badge
                                className={`${getPerformanceColor(displayValue || 0)} text-xs px-2 py-1`}
                              >
                                {displayValue || 0}
                              </Badge>
                            )}
                          </td>
                        );
                      })}
                      
                      <td className="px-2 py-1.5 text-center">
                        {(() => {
                          const biannualConfigForSum = isSeoUserMemo ? SEO_BIANNUAL_KPI_CONFIG : isMarketingUser ? MARKETING_BIANNUAL_KPI_CONFIG : isItUser ? IT_BIANNUAL_KPI_CONFIG : BIANNUAL_KPI_CONFIG;
                          const sum = Object.keys(biannualConfigForSum).reduce((sum, field) => {
                            const value = isEditingPersonal && editingBiannualData[`${period}_${year}`] 
                              ? editingBiannualData[`${period}_${year}`][field as keyof BiAnnualPerformanceData] as number
                              : data[field as keyof BiAnnualPerformanceData] as number;
                            return sum + (value || 0);
                          }, 0);
                          return (
                            <Badge className={`${getPerformanceColor(sum)} font-bold text-xs`}>
                              {sum}
                            </Badge>
                          );
                        })()}
                      </td>
                      {isEditingPersonal && (
                        <td className="px-2 py-1.5 text-center">
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 text-muted-foreground hover:text-destructive"
                            title={`Delete ${label}`}
                            disabled={isDeletingCycle || personalSaveStatus === "saving"}
                            onClick={() => setPeriodToDelete({ period, year, label })}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </td>
                      )}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {displayedPersonalCycles.length === 0 && (
            <div className="text-center py-5 text-muted-foreground">
              <BarChart3 className="h-8 w-8 mx-auto mb-2 opacity-30" />
              <p className="text-sm">No Personal KPI cycles in this date range.</p>
              <p className="text-xs mt-1">
                {canEdit
                  ? "Click Edit Personal, then Add period (for example July 2025 – September 2026)."
                  : "Widen the date range to see earlier review cycles."}
              </p>
            </div>
          )}
        </motion.section>
        </div>
      </motion.div>

      <AlertDialog
        open={!!periodToDelete}
        onOpenChange={(open) => {
          if (!open && !isDeletingCycle) setPeriodToDelete(null);
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete this Personal KPI period?</AlertDialogTitle>
            <AlertDialogDescription>
              {periodToDelete
                ? `${periodToDelete.label} will be removed for every ${user.department || "department"} employee. Saved scores and remarks for this period will also be deleted. This cannot be undone.`
                : ""}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeletingCycle}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              disabled={isDeletingCycle}
              onClick={(event) => {
                event.preventDefault();
                void deletePersonalCycle();
              }}
            >
              {isDeletingCycle ? "Deleting..." : "Delete period"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </motion.div>
  );
}