'use client';

import { motion } from 'motion/react';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { staggerContainer, staggerItem } from '@/lib/motion';
import {
  Award,
  BarChart3,
  Calendar,
  Clock,
  Users,
  Target,
  FileText,
  Star,
  AlertCircle,
  CheckCircle
} from 'lucide-react';
import {
  getPerformanceGrade,
  getPerformanceDescription,
  getPerformanceColorClasses
} from '@/lib/scoring-utils';
import { calculateEmploymentStatus, getEmploymentStatusBadgeColor } from '@/lib/date-utils';
import { isSqaUser, isUnitLeadUser, getUserPerformanceType, isDesignUser, getDesignPerformanceType, isDesignTeamLead, isSeoUser, isPmoUser } from '@/lib/utils';
import { isDesignHead } from '@/lib/constants';

interface UserReportCardProps {
  user: any;
  monthlyPerformance: any[];
  sqaMonthlyPerformance?: any[]; // SQA performance prop
  unitLeadMonthlyPerformance?: any[]; // Unit Lead performance prop
  designMonthlyPerformance?: any[]; // Design performance prop
  itMonthlyPerformance?: any[];
  marketingMonthlyPerformance?: any[];
  seoMonthlyPerformance?: any[];
  pmoMonthlyPerformance?: any[];
  biannualPerformance: any[];
  designBiannualPerformance?: any[];
  marketingBiannualPerformance?: any[];
  seoBiannualPerformance?: any[];
  monthlyAttendance: any[];
  loggedHours: any[];
  /** Server-side aggregates — same metrics as scanning loggedHours rows */
  loggedHoursSummary?: {
    totalHours: number;
    totalEntries: number;
    uniqueProjects: number;
    totalTasks: number;
  } | null;
  itWorkHistory?: any[];
  isUserSqa?: boolean;
  isUserUnitLead?: boolean;
  isUserDesign?: boolean;
  isMarketingUser?: boolean;
  isSeoUser?: boolean;
  userPerformanceType?: 'sqa' | 'unitLead' | 'developer' | 'design' | 'it' | 'marketing' | 'seo' | 'pmo';
  designPerformanceType?: 'graphics' | 'ux' | 'animation' | 'teamLead' | 'personal';
}

// Report Card Weights
const REPORT_CARD_WEIGHTS = {
  departmentalKPIs: 30,    // Monthly KPIs - 30%
  personnelKPIs: 10,       // Biannual KPIs - 10%
  attendance: 10,          // Monthly Attendance - 10%
  loggedHours: 50          // Logged Hours - 50%
};

// 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);
};

const panelClass = 'rounded-xl border border-border bg-card p-5';

// Display names for Personnel (bi-annual) KPI fields of every review type
const PERSONNEL_KPI_LABELS: Record<string, string> = {
  professionalDev: 'Professional Development',
  processImprovement: 'Process Improvement',
  productInnovation: 'Product Innovation',
  professionalDevelopment: 'Professional Development',
  improvementOfDesignStyle: 'Improvement of Design Style',
  designTrendsKnowledge: 'Design Trends Knowledge',
  skillDevelopment: 'Skill Development & Certifications',
  processAdherence: 'Process Adherence',
  ownershipAccountability: 'Ownership & Accountability',
  communicationCoordination: 'Communication & Coordination',
  problemSolvingInitiative: 'Problem-Solving & Initiative',
  professionalConduct: 'Professional Conduct',
  skillDevelopmentLearning: 'Skill Development & Learning',
  processAdherenceDocumentation: 'Process Adherence & Documentation',
  ownershipTaskExecution: 'Ownership & Task Execution',
  analyticalThinking: 'Analytical Thinking',
  communicationCollaboration: 'Communication & Collaboration',
  professionalConductReliability: 'Professional Conduct & Reliability',
};

export function UserReportCard({
  user,
  monthlyPerformance,
  sqaMonthlyPerformance = [],
  unitLeadMonthlyPerformance = [],
  designMonthlyPerformance = [],
  itMonthlyPerformance = [],
  marketingMonthlyPerformance = [],
  seoMonthlyPerformance = [],
  pmoMonthlyPerformance = [],
  biannualPerformance,
  designBiannualPerformance = [],
  marketingBiannualPerformance = [],
  seoBiannualPerformance = [],
  monthlyAttendance,
  loggedHours,
  loggedHoursSummary = null,
  itWorkHistory = [],
  isUserSqa,
  isUserUnitLead,
  isUserDesign,
  isMarketingUser,
  isSeoUser: isSeoUserProp,
  userPerformanceType,
  designPerformanceType
}: UserReportCardProps) {

  // Determine user type (fallback to detection if not provided)
  const isSqa = isUserSqa !== undefined ? isUserSqa : isSqaUser(user);
  const isUnitLead = isUserUnitLead !== undefined ? isUserUnitLead : isUnitLeadUser(user);
  const isDesign = isUserDesign !== undefined ? isUserDesign : isDesignUser(user);
  const isIt = user.department === 'Network IT';
  const isPmo = isPmoUser(user);
  const performanceType = userPerformanceType || getUserPerformanceType(user);
  const designType = designPerformanceType || (isDesign ? getDesignPerformanceType(user) : null);
  
  // Additional fallback detection for Design users
  const forceDesignDetection = user.department?.toLowerCase() === 'design' || 
                              user.position?.toLowerCase().includes('designer') ||
                              user.position?.toLowerCase().includes('ui/ux') ||
                              user.position?.toLowerCase().includes('graphic') ||
                              user.position?.toLowerCase().includes('animation');
  
  const finalIsDesign = isDesign || forceDesignDetection;
  const finalDesignType = designType || (forceDesignDetection ? getDesignPerformanceType(user) : null);
  
  // AGGRESSIVE DESIGN DETECTION - Force Design KPIs for any user with "Designer" in position
  const isDefinitelyDesigner = user.position?.toLowerCase().includes('designer') || 
                               user.position?.toLowerCase().includes('design') ||
                               user.department?.toLowerCase() === 'design';
  
  // Override all previous detection if user is obviously a designer
  const forceDesignKPIs = isDefinitelyDesigner;
  
  console.log('🚨 AGGRESSIVE DESIGN DETECTION:', {
    userId: user.id,
    userName: user.name,
    userPosition: user.position,
    userDepartment: user.department,
    isDefinitelyDesigner,
    forceDesignKPIs,
    willForceDesignKPIs: forceDesignKPIs
  });
  
  // Debug: User type detection
  console.log('🔍 DEBUGGING USER TYPE DETECTION:', {
    userId: user.id,
    userName: user.name,
    userRole: user.role,
    userDepartment: user.department,
    userPosition: user.position,
    userDesignSubTeam: user.designSubTeam,
    isUserSqaProp: isUserSqa,
    isUserUnitLeadProp: isUserUnitLead,
    isUserDesignProp: isUserDesign,
    calculatedIsSqa: isSqaUser(user),
    calculatedIsUnitLead: isUnitLeadUser(user),
    calculatedIsDesign: isDesignUser(user),
    finalIsSqa: isSqa,
    finalIsUnitLead: isUnitLead,
    finalIsDesign,
    originalIsDesign: isDesign,
    forceDesignDetection: forceDesignDetection,
    forceDesignKPIs: forceDesignKPIs,
    userPerformanceTypeProp: userPerformanceType,
    designPerformanceTypeProp: designPerformanceType,
    calculatedPerformanceType: getUserPerformanceType(user),
    calculatedDesignType: isDesign ? getDesignPerformanceType(user) : null,
    finalPerformanceType: performanceType,
    finalDesignType: finalDesignType,
    originalDesignType: designType,
    userObjectKeys: Object.keys(user),
    userObjectValues: user
  });
  
  // Force Design detection for debugging
  console.log('🔧 FORCE DESIGN DETECTION CHECK:', {
    departmentCheck: user.department?.toLowerCase() === 'design',
    departmentValue: user.department,
    departmentType: typeof user.department,
    positionCheck: user.position?.toLowerCase().includes('designer'),
    positionValue: user.position,
    positionType: typeof user.position
  });
  
  // Use appropriate performance data based on user type
  const getPerformanceData = () => {
    // FORCE DESIGN DETECTION - If user has "Designer" in position, they get Design KPIs
    if (forceDesignKPIs) {
      console.log('🚨 FORCING Design performance data for:', user.name);
      return designMonthlyPerformance || [];
    }
    
    // Check role directly as well as the flags - DESIGN TEAM LEADS HAVE PRIORITY
    const isActuallyDesign = finalIsDesign || user.department?.toLowerCase() === 'design';
    const isActuallyDesignTeamLead = isActuallyDesign && (
      isDesignTeamLead(user) || 
      isDesignHead(user.position || '') ||
      (user.role === 'UNIT_LEAD' && user.department?.toLowerCase() === 'design')
    );
    const isActuallyUnitLead = (isUnitLead || user.role === 'UNIT_LEAD') && !isActuallyDesignTeamLead;
    const isActuallySqa = isSqa || (user.position && user.position.toLowerCase().includes('qa'));
    const isActuallyIt = isIt || user.department === 'Network IT';
    
    if (isActuallyDesign) {
      console.log('📊 Using Design performance data:', designMonthlyPerformance?.length || 0, 'records');
      return designMonthlyPerformance || [];
    }
    if (isPmo) {
      return pmoMonthlyPerformance || [];
    }
    if (isActuallyUnitLead) {
      console.log('📊 Using Unit Lead performance data:', unitLeadMonthlyPerformance?.length || 0, 'records');
      return unitLeadMonthlyPerformance || [];
    }
    if (isActuallySqa) {
      console.log('📊 Using SQA performance data:', sqaMonthlyPerformance?.length || 0, 'records');
      return sqaMonthlyPerformance || [];
    }
    if (isActuallyIt) {
      console.log('📊 Using IT performance data:', itMonthlyPerformance?.length || 0, 'records');
      return itMonthlyPerformance || [];
    }
    if (isSeoUserProp || isSeoUser(user)) {
      console.log('📊 Using SEO performance data:', seoMonthlyPerformance?.length || 0, 'records');
      return seoMonthlyPerformance || [];
    }
    if (isMarketingUser || (user.department === 'Marketing' && !isSeoUser(user))) {
      console.log('📊 Using Marketing performance data:', marketingMonthlyPerformance?.length || 0, 'records');
      return marketingMonthlyPerformance || [];
    }
    console.log('📊 Using Member performance data:', monthlyPerformance?.length || 0, 'records');
    return monthlyPerformance || [];
  };
  const performanceData = getPerformanceData();

  // Use appropriate biannual performance data based on user type
  const getBiannualPerformanceData = () => {
    // FORCE DESIGN DETECTION
    if (forceDesignKPIs) {
      console.log('🚨 FORCING Design Bi-Annual performance data for:', user.name);
      return designBiannualPerformance || [];
    }
    
    if (finalIsDesign) {
      console.log('📊 Using Design Bi-Annual performance data:', designBiannualPerformance?.length || 0, 'records');
      return designBiannualPerformance || [];
    }
    if (isSeoUserProp || isSeoUser(user)) {
      console.log('📊 Using SEO Bi-Annual performance data:', seoBiannualPerformance?.length || 0, 'records');
      return seoBiannualPerformance || [];
    }
    if (isMarketingUser || (user.department === 'Marketing' && !isSeoUser(user))) {
      console.log('📊 Using Marketing Bi-Annual performance data:', marketingBiannualPerformance?.length || 0, 'records');
      return marketingBiannualPerformance || [];
    }
    console.log('📊 Using Regular Bi-Annual performance data:', biannualPerformance?.length || 0, 'records');
    return biannualPerformance || [];
  };
  const biannualData = getBiannualPerformanceData();

  console.log('🔍 Report Card - User type detection:', {
    userId: user.id,
    userName: user.name,
    userPosition: user.position,
    userRole: user.role,
    isSqa,
    isUnitLead,
    performanceType,
    performanceDataLength: performanceData.length,
    unitLeadDataLength: unitLeadMonthlyPerformance?.length || 0,
    sqaDataLength: sqaMonthlyPerformance?.length || 0,
    memberDataLength: monthlyPerformance?.length || 0
  });

  // Calculate Departmental KPIs Score (Monthly Performance - 30%)
  const calculateDepartmentalScore = () => {
    // Define KPI fields based on user type
    const getKPIFields = () => {
      // FORCE DESIGN KPI FIELDS - If user has "Designer" in position
      if (forceDesignKPIs) {
        console.log('🚨 FORCING Design KPI fields for:', user.name);
        
        // CRITICAL FIX: Check if user is a Design Team Lead FIRST (before checking designSubTeam)
        // Team leads should get team lead KPIs regardless of their designSubTeam
        if (isDesignTeamLead(user) || isDesignHead(user.position || '')) {
          console.log('🚨 FORCED Design type: teamLead (detected from position)');
          return ['deliverableDeadlines', 'teamProductivity', 'artDirection', 'teamDevelopment', 
                  'stakeholderCommunication', 'priorityAdaptation', 'teamRetentionSatisfaction', 'uptoDateTaskRecords'];
        }
        
        // Determine design type based on designSubTeam or position
        const designTypeForced = user.designSubTeam?.toLowerCase() === 'graphics' ? 'graphics' :
                                user.designSubTeam?.toLowerCase() === 'ui/ux' ? 'ux' :
                                user.designSubTeam?.toLowerCase() === 'animations' ? 'animation' :
                                user.position?.toLowerCase().includes('graphic') ? 'graphics' :
                                user.position?.toLowerCase().includes('ui') || user.position?.toLowerCase().includes('ux') ? 'ux' :
                                user.position?.toLowerCase().includes('animation') ? 'animation' :
                                'graphics'; // Default to graphics for designers
        
        console.log('🚨 FORCED Design type:', designTypeForced);
        
        switch (designTypeForced) {
          case 'graphics':
            return ['designQuality', 'designSpeed', 'deliverableVolume', 'collaboration', 'technicalKnowledge'];
          case 'ux':
            return ['designQuality', 'designSpeed', 'userExperienceLogic', 'sowRevisionAdaptation', 'technicalKnowledge'];
          case 'animation':
            return ['deliverableQuality', 'deliverableSpeed', 'editingEfforts', 'revisionAdaptation', 'technicalKnowledge'];
          default:
            return ['designQuality', 'designSpeed', 'deliverableVolume', 'collaboration', 'technicalKnowledge'];
        }
      }
      
      // Check role directly as well as the flags - DESIGN TEAM LEADS HAVE PRIORITY
      const isActuallyDesign = finalIsDesign || user.department?.toLowerCase() === 'design';
      const isActuallyDesignTeamLead = isActuallyDesign && (
        isDesignTeamLead(user) || 
        isDesignHead(user.position || '') ||
        (user.role === 'UNIT_LEAD' && user.department?.toLowerCase() === 'design')
      );
      const isActuallyUnitLead = (isUnitLead || user.role === 'UNIT_LEAD') && !isActuallyDesignTeamLead;
      const isActuallySqa = isSqa || (user.position && user.position.toLowerCase().includes('qa'));
      const isActuallyIt = isIt || user.department === 'Network IT';
      
      console.log('🔍 KPI Field Selection Debug:', {
        userId: user.id,
        userRole: user.role,
        userPosition: user.position,
        userDepartment: user.department,
        userDesignSubTeam: user.designSubTeam,
        isUnitLead,
        isSqa,
        isDesign,
        finalIsDesign,
        forceDesignKPIs,
        isActuallyUnitLead,
        isActuallySqa,
        isActuallyDesign,
        isActuallyDesignTeamLead,
        willSelectDesignTeamLeadKPIs: isActuallyDesignTeamLead,
        willSelectDesignKPIs: isActuallyDesign && !isActuallyDesignTeamLead,
        willSelectUnitLeadKPIs: isActuallyUnitLead,
        willSelectSqaKPIs: isActuallySqa
      });
      
      // PRIORITY ORDER: Design Team Lead > Design Member > Production Unit Lead > SQA > Developer
      if (isActuallyDesignTeamLead) {
        console.log('✅ Selecting Design Team Lead KPIs');
        return ['deliverableDeadlines', 'teamProductivity', 'artDirection', 'teamDevelopment', 
                'stakeholderCommunication', 'priorityAdaptation', 'teamRetentionSatisfaction', 'uptoDateTaskRecords'];
      } else if (isActuallyDesign) {
        console.log('✅ Selecting Design KPIs for type:', finalDesignType);
        switch (finalDesignType) {
          case 'graphics':
            return ['designQuality', 'designSpeed', 'deliverableVolume', 'collaboration', 'technicalKnowledge'];
          case 'ux':
            return ['designQuality', 'designSpeed', 'userExperienceLogic', 'sowRevisionAdaptation', 'technicalKnowledge'];
          case 'animation':
            return ['deliverableQuality', 'deliverableSpeed', 'editingEfforts', 'revisionAdaptation', 'technicalKnowledge'];
          case 'personal':
          default:
            return ['professionalDevelopment', 'improvementOfDesignStyle', 'designTrendsKnowledge'];
        }
      } else if (isPmo) {
        return ['onTimeCompletion', 'dataAccuracyReporting', 'stakeholderSatisfaction', 'userStoryCompletion',
                'dataVisualizationInsights', 'riskIssueResolution', 'collaborationEngagement'];
      } else if (isActuallyUnitLead) {
        console.log('✅ Selecting Unit Lead KPIs');
        return ['sprintGoalAchievement', 'teamProductivity', 'codeQualityManagement', 'teamDevelopment', 
                'stakeholderSatisfaction', 'riskManagement', 'teamRetentionSatisfaction', 'processImprovement'];
      } else if (isActuallySqa) {
        console.log('✅ Selecting SQA KPIs');
        return ['defectDetectionEfficiency', 'testCoverage', 'automatedTestingRatio', 'defectResolutionTime',
                'testExecutionEfficiency', 'documentationQuality', 'regressionTestingEffectiveness', 'qualityGateAdherence'];
      } else if (isIt) {
        console.log('✅ Selecting IT KPIs');
        return ['installConfigureMaintain', 'manageMonitorNetworks', 'setupMaintainServers', 'implementBackupRecovery',
                'createManageEmailAccounts', 'maintainAssetInventory', 'troubleshootIssues', 'optimizeInternetUsage',
                'ensureDataSecurity', 'provideTechnicalSupport', 'collaborateWithTeam', 'assistEventPlanning'];
      } else if (isSeoUserProp || isSeoUser(user)) {
        console.log('✅ Selecting SEO KPIs');
        return ['organicTrafficGrowth', 'keywordPerformance', 'technicalSeoHealth', 'onPageOptimization',
                'contentPerformance', 'backlinksAuthority', 'conversionContribution', 'reportingMonitoring'];
      } else if (isMarketingUser || (user.department === 'Marketing' && !isSeoUser(user))) {
        console.log('✅ Selecting Marketing KPIs');
        return ['campaignPerformance', 'leadGeneration', 'budgetUtilization', 'contentEffectiveness',
                'optimizationTesting', 'funnelConversion', 'reportingInsights', 'complianceBrandSafety'];
      } else {
        console.log('✅ Selecting Member KPIs');
        return ['codeQuality', 'developmentSpeed', 'productivity', 'collaboration',
                'technicalDebt', 'resourceUtil', 'projectVelocity', 'teamMorale'];
      }
    };

    const kpiFields = getKPIFields();
    
    console.log('🔍 KPI Fields Debug:', {
      userId: user.id,
      isUnitLead,
      isSqa,
      kpiFields,
      fieldCount: kpiFields.length,
      userRole: user.role
    });

    // A month saved with every KPI at 0 counts as not entered
    const scoredMonths = performanceData.filter((perf) =>
      kpiFields.some((field) => (Number(perf[field]) || 0) !== 0),
    );

    if (scoredMonths.length === 0) {
      const emptyBreakdown: any = { totalRecords: 0 };
      kpiFields.forEach(field => {
        emptyBreakdown[field] = 0;
      });

      return {
        score: 0,
        grade: 'F',
        count: 0,
        details: 'No data available',
        breakdown: emptyBreakdown
      };
    };

    // Initialize sums for each KPI field
    const kpiSums: any = {};
    kpiFields.forEach(field => {
      kpiSums[field] = 0;
    });

    // Sum each KPI across all months (dynamic approach)
    scoredMonths.forEach(perf => {
      kpiFields.forEach(field => {
        kpiSums[field] += perf[field] || 0;
      });
    });

    // Calculate averages
    const count = scoredMonths.length;
    const kpiAverages: any = {};
    kpiFields.forEach(field => {
      kpiAverages[field] = kpiSums[field] / count;
    });

    // Sum the averages
    const sumOfAverages = Object.values(kpiAverages).reduce((sum: number, avg: unknown) => sum + (avg as number), 0);
    const roundedScore = Math.round(sumOfAverages * 100) / 100;

    // Debug logging
    const getUserTypeDisplay = () => {
      if (isUnitLead) return 'UNIT_LEAD';
      if (isSqa) return 'SQA';
      return 'DEVELOPER';
    };

    console.log(`🔍 ${getUserTypeDisplay()} KPIs DEBUG:`, {
      userType: performanceType,
      kpiAverages,
      sumOfAverages,
      roundedScore,
      recordCount: scoredMonths.length,
      kpiFields
    });

    const getDetailsText = () => {
      if (isPmo) return 'PMO';
      if (isUnitLead) return 'Unit Lead';
      if (isSqa) return 'SQA';
      return 'development';
    };

    return {
      score: roundedScore,
      grade: getPerformanceGrade(roundedScore),
      count: scoredMonths.length,
      details: `${scoredMonths.length} ${getDetailsText()} performance records`,
      breakdown: {
        ...kpiAverages,
        totalRecords: scoredMonths.length
      }
    };
  };

  // Calculate Personnel KPIs Score (Biannual Performance - 20%)
  const calculatePersonnelScore = () => {
    // FORCE DESIGN PERSONNEL KPIs
    if (forceDesignKPIs) {
      console.log('🚨 FORCING Design Personnel KPIs for:', user.name);
      
      if (biannualData.length === 0) return {
        score: 0,
        grade: 'F',
        count: 0,
        details: 'No data available',
        breakdown: {
          professionalDevelopment: 0,
          improvementOfDesignStyle: 0,
          designTrendsKnowledge: 0,
          totalPeriods: 0
        }
      };

      // Design users have different biannual KPIs
      const kpiSums = {
        professionalDevelopment: 0,
        improvementOfDesignStyle: 0,
        designTrendsKnowledge: 0
      };

      // Sum each KPI across all periods
      biannualData.forEach(perf => {
        kpiSums.professionalDevelopment += perf.professionalDevelopment || 0;
        kpiSums.improvementOfDesignStyle += perf.improvementOfDesignStyle || 0;
        kpiSums.designTrendsKnowledge += perf.designTrendsKnowledge || 0;
      });

      // Calculate averages first, then sum them (same as performance table)
      const count = biannualData.length;
      const kpiAverages = {
        professionalDevelopment: kpiSums.professionalDevelopment / count,
        improvementOfDesignStyle: kpiSums.improvementOfDesignStyle / count,
        designTrendsKnowledge: kpiSums.designTrendsKnowledge / count
      };

      // Sum the averages (same as performance table logic)
      const sumOfAverages = Object.values(kpiAverages).reduce((sum, avg) => sum + avg, 0);
      const roundedScore = Math.round(sumOfAverages * 100) / 100;

      console.log('🚨 FORCED DESIGN PERSONNEL KPIs DEBUG:');
      console.log('KPI Averages:', kpiAverages);
      console.log('Sum of Averages:', sumOfAverages);
      console.log('Rounded Score:', roundedScore);

      return {
        score: roundedScore,
        grade: getPerformanceGrade(roundedScore),
        count: biannualData.length,
        details: `${biannualData.length} periods evaluated`,
        breakdown: {
          professionalDevelopment: Math.round(kpiAverages.professionalDevelopment * 100) / 100,
          improvementOfDesignStyle: Math.round(kpiAverages.improvementOfDesignStyle * 100) / 100,
          designTrendsKnowledge: Math.round(kpiAverages.designTrendsKnowledge * 100) / 100,
          totalPeriods: count
        }
      };
    }
    
    if (biannualData.length === 0) {
      const emptyBreakdown: any = { totalPeriods: 0 };
      if (finalIsDesign) {
        emptyBreakdown.professionalDevelopment = 0;
        emptyBreakdown.improvementOfDesignStyle = 0;
        emptyBreakdown.designTrendsKnowledge = 0;
      } else if (isSeoUserProp || isSeoUser(user)) {
        ['skillDevelopmentLearning', 'processAdherenceDocumentation', 'ownershipTaskExecution',
         'analyticalThinking', 'communicationCollaboration', 'professionalConductReliability'].forEach(f => { emptyBreakdown[f] = 0; });
      } else if (isMarketingUser || (user.department === 'Marketing' && !isSeoUser(user))) {
        ['skillDevelopment', 'processAdherence', 'ownershipAccountability',
         'communicationCoordination', 'problemSolvingInitiative', 'professionalConduct'].forEach(f => { emptyBreakdown[f] = 0; });
      } else {
        emptyBreakdown.professionalDev = 0;
        emptyBreakdown.processImprovement = 0;
        emptyBreakdown.productInnovation = 0;
      }
      return { score: 0, grade: 'F', count: 0, details: 'No data available', breakdown: emptyBreakdown };
    }

    if (finalIsDesign) {
      // Design users have different biannual KPIs
      const kpiSums = {
        professionalDevelopment: 0,
        improvementOfDesignStyle: 0,
        designTrendsKnowledge: 0
      };

      // Sum each KPI across all periods
      biannualData.forEach(perf => {
        kpiSums.professionalDevelopment += perf.professionalDevelopment || 0;
        kpiSums.improvementOfDesignStyle += perf.improvementOfDesignStyle || 0;
        kpiSums.designTrendsKnowledge += perf.designTrendsKnowledge || 0;
      });

      // Calculate averages first, then sum them (same as performance table)
      const count = biannualData.length;
      const kpiAverages = {
        professionalDevelopment: kpiSums.professionalDevelopment / count,
        improvementOfDesignStyle: kpiSums.improvementOfDesignStyle / count,
        designTrendsKnowledge: kpiSums.designTrendsKnowledge / count
      };

      // Sum the averages (same as performance table logic)
      const sumOfAverages = Object.values(kpiAverages).reduce((sum, avg) => sum + avg, 0);
      const roundedScore = Math.round(sumOfAverages * 100) / 100;

      console.log('🔍 DESIGN PERSONNEL KPIs DEBUG:');
      console.log('KPI Averages:', kpiAverages);
      console.log('Sum of Averages:', sumOfAverages);
      console.log('Rounded Score:', roundedScore);

      return {
        score: roundedScore,
        grade: getPerformanceGrade(roundedScore),
        count: biannualData.length,
        details: `${biannualData.length} periods evaluated`,
        breakdown: {
          professionalDevelopment: Math.round(kpiAverages.professionalDevelopment * 100) / 100,
          improvementOfDesignStyle: Math.round(kpiAverages.improvementOfDesignStyle * 100) / 100,
          designTrendsKnowledge: Math.round(kpiAverages.designTrendsKnowledge * 100) / 100,
          totalPeriods: count
        }
      };
    } else if (isSeoUserProp || isSeoUser(user)) {
      const seoKpiFields = ['skillDevelopmentLearning', 'processAdherenceDocumentation', 'ownershipTaskExecution',
                             'analyticalThinking', 'communicationCollaboration', 'professionalConductReliability'];
      const kpiSums: Record<string, number> = {};
      seoKpiFields.forEach(f => { kpiSums[f] = 0; });

      biannualData.forEach((perf: any) => {
        seoKpiFields.forEach(f => { kpiSums[f] += perf[f] || 0; });
      });

      const count = biannualData.length;
      const kpiAverages: Record<string, number> = {};
      seoKpiFields.forEach(f => { kpiAverages[f] = kpiSums[f] / count; });

      const sumOfAverages = Object.values(kpiAverages).reduce((sum, avg) => sum + avg, 0);
      const roundedScore = Math.round(sumOfAverages * 100) / 100;

      return {
        score: roundedScore,
        grade: getPerformanceGrade(roundedScore),
        count: biannualData.length,
        details: `${biannualData.length} periods evaluated`,
        breakdown: {
          ...Object.fromEntries(seoKpiFields.map(f => [f, Math.round(kpiAverages[f] * 100) / 100])),
          totalPeriods: count
        }
      };
    } else if (isMarketingUser || (user.department === 'Marketing' && !isSeoUser(user))) {
      const marketingKpiFields = ['skillDevelopment', 'processAdherence', 'ownershipAccountability',
                                   'communicationCoordination', 'problemSolvingInitiative', 'professionalConduct'];
      const kpiSums: Record<string, number> = {};
      marketingKpiFields.forEach(f => { kpiSums[f] = 0; });

      biannualData.forEach((perf: any) => {
        marketingKpiFields.forEach(f => { kpiSums[f] += perf[f] || 0; });
      });

      const count = biannualData.length;
      const kpiAverages: Record<string, number> = {};
      marketingKpiFields.forEach(f => { kpiAverages[f] = kpiSums[f] / count; });

      const sumOfAverages = Object.values(kpiAverages).reduce((sum, avg) => sum + avg, 0);
      const roundedScore = Math.round(sumOfAverages * 100) / 100;

      return {
        score: roundedScore,
        grade: getPerformanceGrade(roundedScore),
        count: biannualData.length,
        details: `${biannualData.length} periods evaluated`,
        breakdown: {
          ...Object.fromEntries(marketingKpiFields.map(f => [f, Math.round(kpiAverages[f] * 100) / 100])),
          totalPeriods: count
        }
      };
    } else {
      const kpiSums = {
        professionalDev: 0,
        processImprovement: 0,
        productInnovation: 0
      };

      biannualData.forEach(perf => {
        kpiSums.professionalDev += perf.professionalDev || 0;
        kpiSums.processImprovement += perf.processImprovement || 0;
        kpiSums.productInnovation += perf.productInnovation || 0;
      });

      // Calculate averages first, then sum them (same as performance table)
      const count = biannualData.length;
      const kpiAverages = {
        professionalDev: kpiSums.professionalDev / count,
        processImprovement: kpiSums.processImprovement / count,
        productInnovation: kpiSums.productInnovation / count
      };

      // Sum the averages (same as performance table logic)
      const sumOfAverages = Object.values(kpiAverages).reduce((sum, avg) => sum + avg, 0);
      const roundedScore = Math.round(sumOfAverages * 100) / 100;

      // Debug logging
      console.log('🔍 PERSONNEL KPIs DEBUG:');
      console.log('KPI Averages:', kpiAverages);
      console.log('Sum of Averages:', sumOfAverages);
      console.log('Rounded Score:', roundedScore);

      return {
        score: roundedScore,
        grade: getPerformanceGrade(roundedScore),
        count: biannualData.length,
        details: `${biannualData.length} periods evaluated`,
        breakdown: {
          professionalDev: Math.round(kpiAverages.professionalDev * 100) / 100,
          processImprovement: Math.round(kpiAverages.processImprovement * 100) / 100,
          productInnovation: Math.round(kpiAverages.productInnovation * 100) / 100,
          totalPeriods: count
        }
      };
    }
  };

  // Calculate Attendance Score (15%)
  const calculateAttendanceScore = () => {
    if (monthlyAttendance.length === 0) return {
      score: 0,
      grade: 'F',
      count: 0,
      details: 'No data available',
      breakdown: {
        attendanceRate: 0,
        punctualityScore: 0,
        totalExpected: 0,
        totalPresent: 0,
        totalLateMinutes: 0,
        avgLateMinutesPerDay: 0,
        punctualityPenalty: 0,
        totalMonths: 0
      }
    };

    const totalExpected = monthlyAttendance.reduce((sum, record) => sum + record.expectedDays, 0);
    const totalPresent = monthlyAttendance.reduce((sum, record) => sum + record.presentDays, 0);
    const totalLateMinutes = monthlyAttendance.reduce((sum, record) => sum + record.totalLateMinutes, 0);

    // Calculate attendance percentage
    const attendanceRate = totalExpected > 0 ? (totalPresent / totalExpected) * 100 : 0;

    // Calculate punctuality score (deduct points for being late)
    const avgLateMinutesPerDay = totalPresent > 0 ? totalLateMinutes / totalPresent : 0;
    const punctualityPenalty = Math.min(avgLateMinutesPerDay / 10, 20); // Max 20% penalty for lateness
    const punctualityScore = Math.max(0, 100 - punctualityPenalty);

    // Final attendance score
    const attendanceScore = Math.max(0, attendanceRate - punctualityPenalty);

    return {
      score: Math.round(attendanceScore * 100) / 100,
      grade: getPerformanceGrade(attendanceScore),
      count: monthlyAttendance.length,
      details: `${attendanceRate.toFixed(1)}% attendance, ${Math.round(avgLateMinutesPerDay)}min avg late`,
      breakdown: {
        attendanceRate: Math.round(attendanceRate * 100) / 100,
        punctualityScore: Math.round(punctualityScore * 100) / 100,
        totalExpected,
        totalPresent,
        totalLateMinutes,
        avgLateMinutesPerDay: Math.round(avgLateMinutesPerDay * 100) / 100,
        punctualityPenalty: Math.round(punctualityPenalty * 100) / 100,
        totalMonths: monthlyAttendance.length
      }
    };
  };

  // --- New Work Summary Calculation ---
  const AVERAGE_TASKS = 150;
  
  // IT Work History benchmarks (annual targets)
  const IT_TICKET_BENCHMARK = 480; // Expected tickets per year (40 per month × 12)
  const IT_COMPLETION_TARGET = 95; // Target completion rate %

  // Tech stack-specific project benchmarks
  const getProjectBenchmark = (techStack: string | null | undefined): number => {
    switch (techStack) {
      case 'Backend':
        return 12;
      case 'Frontend':
        return 6;
      case 'Full Stack Developer':
        return 9;
      default:
        return 9; // Default for non-Production or unspecified
    }
  };

  // Calculate IT Work History Score (for IT users only)
  const calculateItWorkHistoryScore = () => {
    if (itWorkHistory.length === 0) return {
      score: 0,
      grade: 'F',
      count: 0,
      details: 'No work history data available',
      breakdown: {
        totalTickets: 0,
        completedTickets: 0,
        inProgressTickets: 0,
        pendingTickets: 0,
        completionRate: 0,
        ticketVolumeScore: 0,
        completionScore: 0,
        ticketTypes: {},
        recentActivity: 0
      }
    };

    // Calculate ticket metrics
    const totalTickets = itWorkHistory.length;
    const completedTickets = itWorkHistory.filter(t => t.status === 'Completed').length;
    const inProgressTickets = itWorkHistory.filter(t => t.status === 'In Progress').length;
    const pendingTickets = itWorkHistory.filter(t => t.status === 'Pending').length;
    
    // Completion rate
    const completionRate = totalTickets > 0 ? (completedTickets / totalTickets) * 100 : 0;
    
    // Ticket types breakdown
    const ticketTypes: { [key: string]: number } = {};
    itWorkHistory.forEach(t => {
      const type = t.ticketType || 'Other';
      ticketTypes[type] = (ticketTypes[type] || 0) + 1;
    });
    
    // Recent activity (last 30 days)
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    const recentActivity = itWorkHistory.filter(t => new Date(t.ticketDate) >= thirtyDaysAgo).length;
    
    // Calculate scores
    // Ticket Volume Score (50% weight) - How many tickets handled vs benchmark
    const ticketVolumeScore = Math.min((totalTickets / IT_TICKET_BENCHMARK) * 100, 100);
    
    // Completion Score (50% weight) - Based on completion rate vs target
    const completionScore = Math.min((completionRate / IT_COMPLETION_TARGET) * 100, 100);
    
    // Final weighted score
    const score = (ticketVolumeScore * 0.5) + (completionScore * 0.5);

    return {
      score: Math.round(score * 100) / 100,
      grade: getPerformanceGrade(score),
      count: totalTickets,
      details: `${totalTickets} tickets, ${completionRate.toFixed(1)}% completion rate`,
      breakdown: {
        totalTickets,
        completedTickets,
        inProgressTickets,
        pendingTickets,
        completionRate: Math.round(completionRate * 100) / 100,
        ticketVolumeScore: Math.round(ticketVolumeScore * 100) / 100,
        completionScore: Math.round(completionScore * 100) / 100,
        ticketTypes,
        recentActivity,
        benchmark: IT_TICKET_BENCHMARK
      }
    };
  };

  const calculateWorkSummaryScore = () => {
    // For IT users, use Work History instead of Logged Hours
    if (isIt) {
      return calculateItWorkHistoryScore();
    }
    
    // Prefer server aggregates (same formulas) to avoid shipping full log rows
    const totalHours =
      loggedHoursSummary?.totalHours ??
      loggedHours.reduce((sum, record) => sum + record.hours, 0);
    const totalEntries =
      loggedHoursSummary?.totalEntries ?? loggedHours.length;
    const uniqueProjects =
      loggedHoursSummary?.uniqueProjects ??
      new Set(
        loggedHours
          .map((record) => record.projectId || record.projectName)
          .filter(Boolean),
      ).size;
    const totalTasks =
      loggedHoursSummary?.totalTasks ??
      loggedHours.filter((record) => record.task && record.task.trim() !== '')
        .length;

    if (totalEntries === 0) return {
      score: 0,
      grade: 'F',
      count: 0,
      details: 'No data available',
      breakdown: {
        loggedHoursPercent: 0,
        projectsPercent: 0,
        tasksPercent: 0,
        userProjects: 0,
        userTasks: 0,
        totalHours: 0,
        expectedHours: 0,
        totalEntries: 0,
        uniqueProjects: 0,
        totalTasks: 0
      }
    };

    // Expected hours based on actual available days from monthly attendance
    const totalExpectedDays = monthlyAttendance.reduce((sum, record) => sum + record.expectedDays, 0);
    const expectedTotalHours = totalExpectedDays * 8;

    // Calculate completion rate (hours logged vs expected) - CAPPED AT 100%
    const loggedHoursPercent = expectedTotalHours > 0 ? Math.min((totalHours / expectedTotalHours) * 100, 100) : 0;
    const projectBenchmark = getProjectBenchmark(user.techStack);
    const projectsPercent = Math.min((uniqueProjects / projectBenchmark) * 100, 100);
    const tasksPercent = Math.min((totalTasks / AVERAGE_TASKS) * 100, 100);

    // Weighted score using capped values
    const score = (
      (loggedHoursPercent * 0.5) +
      (projectsPercent * 0.25) +
      (tasksPercent * 0.25)
    );

    return {
      score: Math.round(score * 100) / 100,
      grade: getPerformanceGrade(score),
      count: totalEntries,
      details: `${totalHours.toFixed(2)}h logged / ${expectedTotalHours}h expected (${loggedHoursPercent.toFixed(1)}%)`,
      breakdown: {
        loggedHoursPercent: Math.round(loggedHoursPercent * 100) / 100,
        projectsPercent: Math.round(projectsPercent * 100) / 100,
        tasksPercent: Math.round(tasksPercent * 100) / 100,
        userProjects: uniqueProjects,
        userTasks: totalTasks,
        totalHours: totalHours.toFixed(2),
        expectedHours: expectedTotalHours,
        totalEntries,
        uniqueProjects,
        totalTasks,
        projectBenchmark
      }
    };
  };

  // Calculate component scores
  const departmentalScore = calculateDepartmentalScore();
  const personnelScore = calculatePersonnelScore();
  const attendanceScore = calculateAttendanceScore();
  const workSummaryScore = calculateWorkSummaryScore();

  // Calculate Overall Report Card Score
  const calculateOverallScore = () => {
    const weightedScore =
      (departmentalScore.score * REPORT_CARD_WEIGHTS.departmentalKPIs / 100) +
      (personnelScore.score * REPORT_CARD_WEIGHTS.personnelKPIs / 100) +
      (attendanceScore.score * REPORT_CARD_WEIGHTS.attendance / 100) +
      (workSummaryScore.score * REPORT_CARD_WEIGHTS.loggedHours / 100);

    return {
      score: Math.round(weightedScore * 100) / 100,
      grade: getPerformanceGrade(weightedScore),
      description: getPerformanceDescription(weightedScore)
    };
  };

  const overallScore = calculateOverallScore();



  // Get strengths and improvement areas
  const getStrengthsAndImprovements = () => {
    const components = [
      { name: 'Departmental KPIs', score: departmentalScore.score, weight: REPORT_CARD_WEIGHTS.departmentalKPIs },
      { name: 'Personnel KPIs', score: personnelScore.score, weight: REPORT_CARD_WEIGHTS.personnelKPIs },
      { name: 'Attendance', score: attendanceScore.score, weight: REPORT_CARD_WEIGHTS.attendance },
      { name: 'Work Summary', score: workSummaryScore.score, weight: REPORT_CARD_WEIGHTS.loggedHours }
    ];

    const strengths = components.filter(c => c.score >= 80).sort((a, b) => b.score - a.score);
    const improvements = components.filter(c => c.score < 70).sort((a, b) => a.score - b.score);

    return { strengths, improvements };
  };

  const { strengths, improvements } = getStrengthsAndImprovements();

  return (
    <motion.div
      className="space-y-6"
      variants={staggerContainer}
      initial="initial"
      animate="animate"
    >
      {/* Overall score hero */}
      <motion.section variants={staggerItem} className={panelClass}>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
          <div className="text-center md:text-left">
            <div className="text-xl font-semibold tracking-tight text-foreground">{user.name}</div>
            <div className="text-sm text-muted-foreground">{user.position}</div>
            <div className="text-xs text-muted-foreground">{user.department}</div>
            {user.joinDate && (
              <div className="mt-2">
                <Badge
                  variant="outline"
                  className={`${getEmploymentStatusBadgeColor(calculateEmploymentStatus(user.joinDate).status)} font-medium text-xs border`}
                >
                  {calculateEmploymentStatus(user.joinDate).label}
                </Badge>
              </div>
            )}
          </div>

          <div className="text-center">
            <div className="flex items-center justify-center mb-1">
              <Badge className={`${getPerformanceColorClasses(overallScore.score)} text-lg px-3 py-1 font-bold`}>
                {overallScore.grade}
              </Badge>
            </div>
            <div className="text-2xl font-semibold tracking-tight tabular-nums text-foreground">
              {formatNumber(overallScore.score)}%
            </div>
            <div className="text-xs text-muted-foreground">Overall Score</div>
          </div>

          <div className="text-center">
            <div className="flex items-center justify-center mb-1">
              <Award className="h-5 w-5 text-primary" />
            </div>
            <div className="text-sm font-medium text-foreground">Performance Summary</div>
            <div className="text-xs text-muted-foreground">Comprehensive Evaluation</div>
          </div>

          <div className="text-center md:text-right">
            <div className="text-base font-semibold text-foreground">{overallScore.description}</div>
            <div className="text-xs text-muted-foreground">Performance Level</div>
          </div>
        </div>

        <div className="space-y-2">
          <div className="flex justify-between text-sm font-medium text-foreground">
            <span>Overall Performance</span>
            <span className="tabular-nums">{formatNumber(overallScore.score)}%</span>
          </div>
          <Progress value={overallScore.score} className="h-2" />
        </div>
      </motion.section>

      {biannualPerformance.length > 0 && (
        <motion.section variants={staggerItem} className={panelClass}>
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
                <FileText className="h-5 w-5 text-primary" />
              </div>
              <div>
                <h3 className="text-base font-semibold tracking-tight text-foreground">Performance Evaluation</h3>
                <p className="text-sm text-muted-foreground">Professional Development Assessment</p>
              </div>
            </div>
            <Badge variant="outline" className="bg-muted/50 text-primary border-border px-3 py-1">
              {biannualPerformance.length} Review{biannualPerformance.length > 1 ? 's' : ''}
            </Badge>
          </div>

          <div className="space-y-4">
            {biannualPerformance.map((perf, index) => (
              <div key={index} className="rounded-xl border border-border bg-muted/30 p-5">
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-3">
                    <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary text-primary-foreground text-sm font-bold">
                      {perf.period}
                    </div>
                    <div>
                      <div className="text-base font-semibold text-foreground">{perf.year} Review</div>
                      <div className="text-sm text-muted-foreground">
                        {perf.reviewedAt ? new Date(perf.reviewedAt).toLocaleDateString('en-US', {
                          year: 'numeric',
                          month: 'long',
                          day: 'numeric'
                        }) : 'Pending Review'}
                      </div>
                    </div>
                  </div>
                  {perf.isPublished && (
                    <div className="flex items-center gap-1">
                      <CheckCircle className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
                      <span className="text-sm font-medium text-emerald-700 dark:text-emerald-300">Published</span>
                    </div>
                  )}
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-3 mb-4">
                  <div className="rounded-lg border border-border bg-primary/10 p-4">
                    <div className="flex items-center justify-between">
                      <div>
                        <div className="text-xs text-primary font-semibold uppercase tracking-wider">{isIt ? 'Education' : 'Professional Development'}</div>
                        <div className="text-2xl font-bold text-primary mt-1 tabular-nums">{formatNumber(perf.professionalDev)}%</div>
                      </div>
                      <div className="w-8 h-8 bg-primary/20 rounded-full flex items-center justify-center">
                        <Users className="h-4 w-4 text-primary" />
                      </div>
                    </div>
                  </div>
                  <div className="rounded-lg border border-border bg-emerald-500/10 p-4">
                    <div className="flex items-center justify-between">
                      <div>
                        <div className="text-xs text-emerald-600 dark:text-emerald-400 font-semibold uppercase tracking-wider">Process Improvement</div>
                        <div className="text-2xl font-bold text-emerald-700 dark:text-emerald-300 mt-1 tabular-nums">{formatNumber(perf.processImprovement)}%</div>
                      </div>
                      <div className="w-8 h-8 bg-emerald-500/20 rounded-full flex items-center justify-center">
                        <Target className="h-4 w-4 text-emerald-700 dark:text-emerald-300" />
                      </div>
                    </div>
                  </div>
                  <div className="rounded-lg border border-border bg-primary/10 p-4">
                    <div className="flex items-center justify-between">
                      <div>
                        <div className="text-xs text-primary font-semibold uppercase tracking-wider">{isIt ? 'Infrastructure' : 'Product Innovation'}</div>
                        <div className="text-2xl font-bold text-primary mt-1 tabular-nums">{formatNumber(perf.productInnovation)}%</div>
                      </div>
                      <div className="w-8 h-8 bg-primary/20 rounded-full flex items-center justify-center">
                        <Star className="h-4 w-4 text-primary" />
                      </div>
                    </div>
                  </div>
                </div>

                {perf.remarks && (
                  <div className="rounded-lg border border-border bg-muted/50 p-4">
                    <div className="flex items-start gap-3">
                      <div className="flex-shrink-0">
                        <div className="w-9 h-9 bg-primary/10 rounded-full flex items-center justify-center">
                          <Star className="h-4 w-4 text-primary" />
                        </div>
                      </div>
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <h4 className="text-sm font-semibold text-foreground">Performance Summary</h4>
                          <Badge variant="secondary" className="bg-primary/10 text-primary">
                            {perf.year} - Period {perf.period}
                          </Badge>
                        </div>
                        <blockquote className="text-foreground/80 text-sm leading-relaxed italic border-l-2 border-primary/30 pl-4">
                          &ldquo;{perf.remarks}&rdquo;
                        </blockquote>
                      </div>
                    </div>
                  </div>
                )}

                {!perf.remarks && (
                  <div className="rounded-lg border border-border bg-amber-500/10 p-3">
                    <div className="flex items-center gap-2">
                      <AlertCircle className="h-4 w-4 text-amber-600 dark:text-amber-400" />
                      <span className="text-sm text-amber-700 dark:text-amber-300">No feedback provided for this review period</span>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>

          <div className="mt-6 pt-4 border-t border-border">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="rounded-lg border border-border bg-primary/10 p-4">
                <div className="flex items-center gap-3">
                  <div className="w-9 h-9 bg-primary/15 rounded-full flex items-center justify-center">
                    <BarChart3 className="h-4 w-4 text-primary" />
                  </div>
                  <div>
                    <div className="text-primary text-sm font-semibold">Total Reviews Completed</div>
                    <div className="text-2xl font-bold text-primary tabular-nums">{biannualPerformance.length}</div>
                  </div>
                </div>
              </div>
              <div className="rounded-lg border border-border bg-primary/10 p-4">
                <div className="flex items-center gap-3">
                  <div className="w-9 h-9 bg-primary/20 rounded-full flex items-center justify-center">
                    <Award className="h-4 w-4 text-muted-foreground" />
                  </div>
                  <div>
                    <div className="text-muted-foreground text-sm font-semibold">Overall Personal KPIs</div>
                    <div className="text-2xl font-bold text-primary tabular-nums">{formatNumber(personnelScore.score)}%</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </motion.section>
      )}

      <motion.div variants={staggerItem} className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* Departmental KPIs */}
        <motion.section variants={staggerItem} className={panelClass}>
          <div className="flex items-center gap-2 mb-3">
            <Target className="h-4 w-4 text-primary" />
            <h3 className="text-sm font-semibold tracking-tight">Departmental KPIs</h3>
          </div>
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <span className="text-2xl font-bold text-foreground">{formatNumber(departmentalScore.score)}%</span>
              <Badge className={`${getPerformanceColorClasses(departmentalScore.score)} font-semibold`}>
                {departmentalScore.grade}
              </Badge>
            </div>
            <Progress value={departmentalScore.score} className="h-2" />

            {/* KPI Breakdown */}
            {departmentalScore.breakdown && departmentalScore.breakdown.totalRecords > 0 ? (
              <div className="space-y-2 text-xs">
                <div className="font-medium text-foreground/80">Weight: 30% | KPI Details:</div>
                <div className="grid grid-cols-1 gap-1">
                  {forceDesignKPIs ? (
                    // FORCE DESIGN KPI DISPLAY - Show Design labels when forcing Design KPIs
                    (() => {
                      // CRITICAL FIX: Check if user is a Design Team Lead FIRST (before checking designSubTeam)
                      if (isDesignTeamLead(user) || isDesignHead(user.position || '')) {
                        console.log('🎨 DISPLAYING Design Team Lead KPI labels');
                        return (
                          <>
                            <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded">
                              <span className="font-medium text-primary">Deliverable Deadlines</span>
                              <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.deliverableDeadlines)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-emerald-500/10 rounded-md">
                              <span className="font-medium text-emerald-700 dark:text-emerald-300">Team Productivity</span>
                              <span className="font-bold text-emerald-700 dark:text-emerald-300">{formatNumber(departmentalScore.breakdown.teamProductivity)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                              <span className="font-medium text-primary">Art Direction</span>
                              <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.artDirection)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-amber-500/10 rounded-md">
                              <span className="font-medium text-amber-700 dark:text-amber-300">Team Development</span>
                              <span className="font-bold text-amber-700 dark:text-amber-300">{formatNumber(departmentalScore.breakdown.teamDevelopment)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                              <span className="font-medium text-primary">Stakeholder Communication</span>
                              <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.stakeholderCommunication)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-pink-500/10 rounded-md">
                              <span className="font-medium text-pink-700 dark:text-pink-300">Priority Adaptation</span>
                              <span className="font-bold text-pink-700 dark:text-pink-300">{formatNumber(departmentalScore.breakdown.priorityAdaptation)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-orange-500/10 rounded-md">
                              <span className="font-medium text-orange-700 dark:text-orange-300">Team Retention & Satisfaction</span>
                              <span className="font-bold text-orange-700 dark:text-orange-300">{formatNumber(departmentalScore.breakdown.teamRetentionSatisfaction)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-red-500/10 rounded-md">
                              <span className="font-medium text-red-700 dark:text-red-300">Up-to-Date Task Records</span>
                              <span className="font-bold text-red-700 dark:text-red-300">{formatNumber(departmentalScore.breakdown.uptoDateTaskRecords)}%</span>
                            </div>
                          </>
                        );
                      }
                      
                      const designTypeForced = user.designSubTeam?.toLowerCase() === 'graphics' ? 'graphics' :
                                              user.designSubTeam?.toLowerCase() === 'ui/ux' ? 'ux' :
                                              user.designSubTeam?.toLowerCase() === 'animations' ? 'animation' :
                                              user.position?.toLowerCase().includes('graphic') ? 'graphics' :
                                              user.position?.toLowerCase().includes('ui') || user.position?.toLowerCase().includes('ux') ? 'ux' :
                                              user.position?.toLowerCase().includes('animation') ? 'animation' :
                                              'graphics'; // Default to graphics for designers
                      
                      console.log('🎨 DISPLAYING Design KPI labels for type:', designTypeForced);
                      
                      if (designTypeForced === 'graphics') {
                        return (
                          <>
                            <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded">
                              <span className="font-medium text-primary">Design Quality</span>
                              <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.designQuality)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-emerald-500/10 rounded-md">
                              <span className="font-medium text-emerald-700 dark:text-emerald-300">Design Speed</span>
                              <span className="font-bold text-emerald-700 dark:text-emerald-300">{formatNumber(departmentalScore.breakdown.designSpeed)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                              <span className="font-medium text-primary">Deliverable Volume</span>
                              <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.deliverableVolume)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-orange-500/10 rounded-md">
                              <span className="font-medium text-orange-700 dark:text-orange-300">Collaboration</span>
                              <span className="font-bold text-orange-700 dark:text-orange-300">{formatNumber(departmentalScore.breakdown.collaboration)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-red-500/10 rounded-md">
                              <span className="font-medium text-red-700 dark:text-red-300">Technical Knowledge</span>
                              <span className="font-bold text-red-700 dark:text-red-300">{formatNumber(departmentalScore.breakdown.technicalKnowledge)}%</span>
                            </div>
                          </>
                        );
                      } else if (designTypeForced === 'ux') {
                        return (
                          <>
                            <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded">
                              <span className="font-medium text-primary">Design Quality</span>
                              <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.designQuality)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-emerald-500/10 rounded-md">
                              <span className="font-medium text-emerald-700 dark:text-emerald-300">Design Speed</span>
                              <span className="font-bold text-emerald-700 dark:text-emerald-300">{formatNumber(departmentalScore.breakdown.designSpeed)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                              <span className="font-medium text-primary">User Experience Logic</span>
                              <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.userExperienceLogic)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-orange-500/10 rounded-md">
                              <span className="font-medium text-orange-700 dark:text-orange-300">SOW Revision Adaptation</span>
                              <span className="font-bold text-orange-700 dark:text-orange-300">{formatNumber(departmentalScore.breakdown.sowRevisionAdaptation)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-red-500/10 rounded-md">
                              <span className="font-medium text-red-700 dark:text-red-300">Technical Knowledge</span>
                              <span className="font-bold text-red-700 dark:text-red-300">{formatNumber(departmentalScore.breakdown.technicalKnowledge)}%</span>
                            </div>
                          </>
                        );
                      } else if (designTypeForced === 'animation') {
                        return (
                          <>
                            <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded">
                              <span className="font-medium text-primary">Deliverable Quality</span>
                              <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.deliverableQuality)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-emerald-500/10 rounded-md">
                              <span className="font-medium text-emerald-700 dark:text-emerald-300">Deliverable Speed</span>
                              <span className="font-bold text-emerald-700 dark:text-emerald-300">{formatNumber(departmentalScore.breakdown.deliverableSpeed)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                              <span className="font-medium text-primary">Editing Efforts</span>
                              <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.editingEfforts)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-orange-500/10 rounded-md">
                              <span className="font-medium text-orange-700 dark:text-orange-300">Revision Adaptation</span>
                              <span className="font-bold text-orange-700 dark:text-orange-300">{formatNumber(departmentalScore.breakdown.revisionAdaptation)}%</span>
                            </div>
                            <div className="flex justify-between items-center p-1.5 bg-red-500/10 rounded-md">
                              <span className="font-medium text-red-700 dark:text-red-300">Technical Knowledge</span>
                              <span className="font-bold text-red-700 dark:text-red-300">{formatNumber(departmentalScore.breakdown.technicalKnowledge)}%</span>
                            </div>
                          </>
                        );
                      }
                    })()
                  ) : forceDesignKPIs && (isDesignTeamLead(user) || isDesignHead(user.position || '')) ? (
                    // DESIGN TEAM LEAD KPI DISPLAY
                    <>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded">
                        <span className="font-medium text-primary">Deliverable Deadlines</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.deliverableDeadlines)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-emerald-500/10 rounded-md">
                        <span className="font-medium text-emerald-700 dark:text-emerald-300">Team Productivity</span>
                        <span className="font-bold text-emerald-700 dark:text-emerald-300">{formatNumber(departmentalScore.breakdown.teamProductivity)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                        <span className="font-medium text-primary">Art Direction</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.artDirection)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-orange-500/10 rounded-md">
                        <span className="font-medium text-orange-700 dark:text-orange-300">Team Development</span>
                        <span className="font-bold text-orange-700 dark:text-orange-300">{formatNumber(departmentalScore.breakdown.teamDevelopment)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-red-500/10 rounded-md">
                        <span className="font-medium text-red-700 dark:text-red-300">Stakeholder Communication</span>
                        <span className="font-bold text-red-700 dark:text-red-300">{formatNumber(departmentalScore.breakdown.stakeholderCommunication)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                        <span className="font-medium text-primary">Priority Adaptation</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.priorityAdaptation)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-pink-500/10 rounded-md">
                        <span className="font-medium text-pink-700 dark:text-pink-300">Team Retention Satisfaction</span>
                        <span className="font-bold text-pink-700 dark:text-pink-300">{formatNumber(departmentalScore.breakdown.teamRetentionSatisfaction)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-amber-500/10 rounded-md">
                        <span className="font-medium text-amber-700 dark:text-amber-300">Up-to-Date Task Records</span>
                        <span className="font-bold text-amber-700 dark:text-amber-300">{formatNumber(departmentalScore.breakdown.uptoDateTaskRecords)}%</span>
                      </div>
                    </>
                  ) : isPmo ? (
                    <>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded">
                        <span className="font-medium text-primary">On-Time Completion</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.onTimeCompletion)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-emerald-500/10 rounded-md">
                        <span className="font-medium text-emerald-700 dark:text-emerald-300">Data Accuracy & Reporting</span>
                        <span className="font-bold text-emerald-700 dark:text-emerald-300">{formatNumber(departmentalScore.breakdown.dataAccuracyReporting)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                        <span className="font-medium text-primary">Stakeholder Satisfaction</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.stakeholderSatisfaction)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-orange-500/10 rounded-md">
                        <span className="font-medium text-orange-700 dark:text-orange-300">User Stories in Sprints</span>
                        <span className="font-bold text-orange-700 dark:text-orange-300">{formatNumber(departmentalScore.breakdown.userStoryCompletion)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-red-500/10 rounded-md">
                        <span className="font-medium text-red-700 dark:text-red-300">Data Visualization & Insights</span>
                        <span className="font-bold text-red-700 dark:text-red-300">{formatNumber(departmentalScore.breakdown.dataVisualizationInsights)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                        <span className="font-medium text-primary">Risk & Issue Resolution</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.riskIssueResolution)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-pink-500/10 rounded-md">
                        <span className="font-medium text-pink-700 dark:text-pink-300">Collaboration & Engagement</span>
                        <span className="font-bold text-pink-700 dark:text-pink-300">{formatNumber(departmentalScore.breakdown.collaborationEngagement)}%</span>
                      </div>
                    </>
                  ) : (isUnitLead || user.role === 'UNIT_LEAD') ? (
                    <>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded">
                        <span className="font-medium text-primary">Sprint Goal Achievement</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.sprintGoalAchievement)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-emerald-500/10 rounded-md">
                        <span className="font-medium text-emerald-700 dark:text-emerald-300">Team Productivity</span>
                        <span className="font-bold text-emerald-700 dark:text-emerald-300">{formatNumber(departmentalScore.breakdown.teamProductivity)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                        <span className="font-medium text-primary">Code Quality Management</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.codeQualityManagement)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-orange-500/10 rounded-md">
                        <span className="font-medium text-orange-700 dark:text-orange-300">Team Development</span>
                        <span className="font-bold text-orange-700 dark:text-orange-300">{formatNumber(departmentalScore.breakdown.teamDevelopment)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-red-500/10 rounded-md">
                        <span className="font-medium text-red-700 dark:text-red-300">Stakeholder Satisfaction</span>
                        <span className="font-bold text-red-700 dark:text-red-300">{formatNumber(departmentalScore.breakdown.stakeholderSatisfaction)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                        <span className="font-medium text-primary">Risk Management</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.riskManagement)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-pink-500/10 rounded-md">
                        <span className="font-medium text-pink-700 dark:text-pink-300">Team Retention Satisfaction</span>
                        <span className="font-bold text-pink-700 dark:text-pink-300">{formatNumber(departmentalScore.breakdown.teamRetentionSatisfaction)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-amber-500/10 rounded-md">
                        <span className="font-medium text-amber-700 dark:text-amber-300">Process Improvement</span>
                        <span className="font-bold text-amber-700 dark:text-amber-300">{formatNumber(departmentalScore.breakdown.processImprovement)}%</span>
                      </div>
                    </>
                  ) : isSqa ? (
                    <>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded">
                        <span className="font-medium text-primary">Defect Detection Efficiency</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.defectDetectionEfficiency)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-emerald-500/10 rounded-md">
                        <span className="font-medium text-emerald-700 dark:text-emerald-300">Test Coverage</span>
                        <span className="font-bold text-emerald-700 dark:text-emerald-300">{formatNumber(departmentalScore.breakdown.testCoverage)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                        <span className="font-medium text-primary">Automated Testing Ratio</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.automatedTestingRatio)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-orange-500/10 rounded-md">
                        <span className="font-medium text-orange-700 dark:text-orange-300">Defect Resolution Time</span>
                        <span className="font-bold text-orange-700 dark:text-orange-300">{formatNumber(departmentalScore.breakdown.defectResolutionTime)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-red-500/10 rounded-md">
                        <span className="font-medium text-red-700 dark:text-red-300">Test Execution Efficiency</span>
                        <span className="font-bold text-red-700 dark:text-red-300">{formatNumber(departmentalScore.breakdown.testExecutionEfficiency)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                        <span className="font-medium text-primary">Documentation Quality</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.documentationQuality)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-pink-500/10 rounded-md">
                        <span className="font-medium text-pink-700 dark:text-pink-300">Regression Testing Effectiveness</span>
                        <span className="font-bold text-pink-700 dark:text-pink-300">{formatNumber(departmentalScore.breakdown.regressionTestingEffectiveness)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-amber-500/10 rounded-md">
                        <span className="font-medium text-amber-700 dark:text-amber-300">Quality Gate Adherence</span>
                        <span className="font-bold text-amber-700 dark:text-amber-300">{formatNumber(departmentalScore.breakdown.qualityGateAdherence)}%</span>
                      </div>
                    </>
                  ) : isIt ? (
                    <>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded">
                        <span className="font-medium text-primary">Install/Configure/Maintain</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.installConfigureMaintain)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-emerald-500/10 rounded-md">
                        <span className="font-medium text-emerald-700 dark:text-emerald-300">Manage/Monitor Networks</span>
                        <span className="font-bold text-emerald-700 dark:text-emerald-300">{formatNumber(departmentalScore.breakdown.manageMonitorNetworks)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                        <span className="font-medium text-primary">Setup/Maintain Servers</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.setupMaintainServers)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-orange-500/10 rounded-md">
                        <span className="font-medium text-orange-700 dark:text-orange-300">Backup & Recovery</span>
                        <span className="font-bold text-orange-700 dark:text-orange-300">{formatNumber(departmentalScore.breakdown.implementBackupRecovery)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-red-500/10 rounded-md">
                        <span className="font-medium text-red-700 dark:text-red-300">Email Accounts</span>
                        <span className="font-bold text-red-700 dark:text-red-300">{formatNumber(departmentalScore.breakdown.createManageEmailAccounts)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                        <span className="font-medium text-primary">Asset Inventory</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.maintainAssetInventory)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-pink-500/10 rounded-md">
                        <span className="font-medium text-pink-700 dark:text-pink-300">Troubleshoot Issues</span>
                        <span className="font-bold text-pink-700 dark:text-pink-300">{formatNumber(departmentalScore.breakdown.troubleshootIssues)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-amber-500/10 rounded-md">
                        <span className="font-medium text-amber-700 dark:text-amber-300">Internet Optimization</span>
                        <span className="font-bold text-amber-700 dark:text-amber-300">{formatNumber(departmentalScore.breakdown.optimizeInternetUsage)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-teal-500/10 rounded-md">
                        <span className="font-medium text-teal-700 dark:text-teal-300">Data Security</span>
                        <span className="font-bold text-teal-700 dark:text-teal-300">{formatNumber(departmentalScore.breakdown.ensureDataSecurity)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-cyan-500/10 rounded-md">
                        <span className="font-medium text-cyan-700 dark:text-cyan-300">Technical Support</span>
                        <span className="font-bold text-cyan-700 dark:text-cyan-300">{formatNumber(departmentalScore.breakdown.provideTechnicalSupport)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-lime-500/10 rounded-md">
                        <span className="font-medium text-lime-700 dark:text-lime-300">Team Collaboration</span>
                        <span className="font-bold text-lime-700 dark:text-lime-300">{formatNumber(departmentalScore.breakdown.collaborateWithTeam)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-amber-500/10 rounded-md">
                        <span className="font-medium text-amber-700 dark:text-amber-300">Event Planning</span>
                        <span className="font-bold text-amber-700 dark:text-amber-300">{formatNumber(departmentalScore.breakdown.assistEventPlanning)}%</span>
                      </div>
                    </>
                  ) : (
                    <>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded">
                        <span className="font-medium text-primary">Code Quality</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.codeQuality)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-emerald-500/10 rounded-md">
                        <span className="font-medium text-emerald-700 dark:text-emerald-300">Development Speed</span>
                        <span className="font-bold text-emerald-700 dark:text-emerald-300">{formatNumber(departmentalScore.breakdown.developmentSpeed)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                        <span className="font-medium text-primary">Productivity</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.productivity)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-orange-500/10 rounded-md">
                        <span className="font-medium text-orange-700 dark:text-orange-300">Collaboration</span>
                        <span className="font-bold text-orange-700 dark:text-orange-300">{formatNumber(departmentalScore.breakdown.collaboration)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-red-500/10 rounded-md">
                        <span className="font-medium text-red-700 dark:text-red-300">Technical Debt</span>
                        <span className="font-bold text-red-700 dark:text-red-300">{formatNumber(departmentalScore.breakdown.technicalDebt)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded-md">
                        <span className="font-medium text-primary">Resource Utilization</span>
                        <span className="font-bold text-primary">{formatNumber(departmentalScore.breakdown.resourceUtil)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-pink-500/10 rounded-md">
                        <span className="font-medium text-pink-700 dark:text-pink-300">Project Velocity</span>
                        <span className="font-bold text-pink-700 dark:text-pink-300">{formatNumber(departmentalScore.breakdown.projectVelocity)}%</span>
                      </div>
                      <div className="flex justify-between items-center p-1.5 bg-amber-500/10 rounded-md">
                        <span className="font-medium text-amber-700 dark:text-amber-300">Team Morale</span>
                        <span className="font-bold text-amber-700 dark:text-amber-300">{formatNumber(departmentalScore.breakdown.teamMorale)}%</span>
                      </div>
                    </>
                  )}
                </div>
                <div className="text-xs text-muted-foreground mt-2">
                  <div>Average scores from {departmentalScore.breakdown.totalRecords} monthly evaluations</div>
                </div>
                {/* Calculation breakdown */}
                <div className="mt-2 p-2 rounded bg-muted/50 border text-xs text-foreground/80">
                  <span className="font-semibold">Calculation: </span>
                  <span className="text-muted-foreground">Sum of all KPI averages = </span>
                  <span className="font-bold text-foreground">{formatNumber(departmentalScore.score)}%</span>
                </div>
              </div>
            ) : (
              <div className="text-xs text-muted-foreground">
                <div className="font-medium">Weight: 30%</div>
                <div>{departmentalScore.details}</div>
              </div>
            )}
          </div>
        </motion.section>

        {/* Personnel KPIs */}
        <motion.section variants={staggerItem} className={panelClass}>
          <div className="flex items-center gap-2 mb-3">
            <Users className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
            <h3 className="text-sm font-semibold tracking-tight">Personnel KPIs</h3>
          </div>
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <span className="text-2xl font-bold text-foreground">{formatNumber(personnelScore.score)}%</span>
              <Badge className={`${getPerformanceColorClasses(personnelScore.score)} font-semibold`}>
                {personnelScore.grade}
              </Badge>
            </div>
            <Progress value={personnelScore.score} className="h-2" />

            {/* KPI Breakdown */}
            {personnelScore.breakdown && personnelScore.breakdown.totalPeriods > 0 ? (
              <div className="space-y-2 text-xs">
                <div className="font-medium text-foreground/80">Weight: 10% | KPI Details:</div>
                <div className="grid grid-cols-1 gap-1">
                  {/* One row per KPI in this person's review (Design / Marketing / SEO use their own KPIs) */}
                  {Object.keys(personnelScore.breakdown)
                    .filter((field) => field !== 'totalPeriods')
                    .map((field, index) => {
                      const rowClass = [
                        'bg-primary/10 rounded',
                        'bg-emerald-500/10 rounded-md',
                        'bg-primary/10 rounded-md',
                      ][index % 3];
                      const textClass = index % 3 === 1 ? 'text-emerald-700 dark:text-emerald-300' : 'text-primary';
                      const label =
                        isIt && field === 'professionalDev' ? 'Education' :
                        isIt && field === 'productInnovation' ? 'Infrastructure' :
                        PERSONNEL_KPI_LABELS[field] || field;
                      return (
                        <div key={field} className={`flex justify-between items-center p-1.5 ${rowClass}`}>
                          <span className={`font-medium ${textClass}`}>{label}</span>
                          <span className={`font-bold ${textClass}`}>{formatNumber((personnelScore.breakdown as any)[field])}%</span>
                        </div>
                      );
                    })}
                </div>
                <div className="text-xs text-muted-foreground mt-2">
                  <div>Average scores from {personnelScore.breakdown.totalPeriods} biannual evaluations</div>
                </div>
                {/* Calculation breakdown */}
                <div className="mt-2 p-2 rounded bg-muted/50 border text-xs text-foreground/80">
                  <span className="font-semibold">Calculation: </span>
                  <span className="text-muted-foreground">Sum of all KPI averages = </span>
                  <span className="font-bold text-foreground">{formatNumber(personnelScore.score)}%</span>
                </div>
              </div>
            ) : (
              <div className="text-xs text-muted-foreground">
                <div className="font-medium">Weight: 10%</div>
                <div>{personnelScore.details}</div>
              </div>
            )}
          </div>
        </motion.section>

        {/* Attendance */}
        <motion.section variants={staggerItem} className={panelClass}>
          <div className="flex items-center gap-2 mb-3">
            <Calendar className="h-4 w-4 text-primary" />
            <h3 className="text-sm font-semibold tracking-tight">Attendance</h3>
          </div>
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <span className="text-2xl font-bold text-foreground">{formatNumber(attendanceScore.score)}%</span>
              <Badge className={`${getPerformanceColorClasses(attendanceScore.score)} font-semibold`}>
                {attendanceScore.grade}
              </Badge>
            </div>
            <Progress value={attendanceScore.score} className="h-2" />

            {/* Attendance Breakdown */}
            {attendanceScore.breakdown && attendanceScore.breakdown.totalMonths > 0 ? (
              <div className="space-y-2 text-xs">
                <div className="font-medium text-foreground/80">Weight: 10% | Details:</div>
                <div className="grid grid-cols-1 gap-1">
                  <div className="flex justify-between items-center p-1.5 bg-primary/10 rounded">
                    <span className="font-medium text-primary">Attendance Rate</span>
                    <span className="text-right">
                      <span className="font-bold text-primary">{formatNumber(attendanceScore.breakdown.attendanceRate)}%</span>
                      <span className="text-primary text-xs ml-2">{attendanceScore.breakdown.totalPresent} / {attendanceScore.breakdown.totalExpected} days</span>
                    </span>
                  </div>
                  <div className="flex justify-between items-center p-1.5 bg-emerald-500/10 rounded-md">
                    <span className="font-medium text-emerald-700 dark:text-emerald-300">Punctuality Score</span>
                    <span className="text-right">
                      <span className="font-bold text-emerald-700 dark:text-emerald-300">{formatNumber(attendanceScore.breakdown.punctualityScore)}%</span>
                      <span className="text-emerald-600 dark:text-emerald-400 text-xs ml-2">{formatNumber(attendanceScore.breakdown.avgLateMinutesPerDay)}min avg late</span>
                    </span>
                  </div>
                  <div className="flex justify-between items-center p-1.5 bg-red-500/10 rounded-md">
                    <span className="font-medium text-red-700 dark:text-red-300">Punctuality Penalty</span>
                    <span className="text-right">
                      <span className="font-bold text-red-700 dark:text-red-300">-{formatNumber(attendanceScore.breakdown.punctualityPenalty)}%</span>
                      <span className="text-red-600 dark:text-red-400 text-xs ml-2">{attendanceScore.breakdown.totalLateMinutes} total late mins</span>
                    </span>
                  </div>
                </div>
                <div className="text-xs text-muted-foreground mt-2">
                  <div>Data from {attendanceScore.breakdown.totalMonths} months of attendance tracking</div>
                </div>
                {/* Calculation breakdown */}
                <div className="mt-2 p-2 rounded bg-muted/50 border text-xs text-foreground/80">
                  <span className="font-semibold">Calculation: </span>
                  <span className="text-primary font-semibold">{formatNumber(attendanceScore.breakdown.attendanceRate)}%</span>
                  <span className="text-muted-foreground"> (Attendance) - </span>
                  <span className="text-red-700 dark:text-red-300 font-semibold">{formatNumber(attendanceScore.breakdown.punctualityPenalty)}%</span>
                                      <span className="text-muted-foreground"> (Lateness Penalty) = </span>
                    <span className="font-bold text-foreground">{formatNumber(attendanceScore.score)}%</span>
                </div>
              </div>
            ) : (
              <div className="text-xs text-muted-foreground">
                <div className="font-medium">Weight: 10%</div>
                <div>{attendanceScore.details}</div>
              </div>
            )}
          </div>
        </motion.section>

        {/* Work Summary / Work History (IT) */}
        <motion.section variants={staggerItem} className={panelClass}>
          <div className="flex items-center gap-2 mb-3">
            <Clock className="h-4 w-4 text-orange-600 dark:text-orange-400" />
            <h3 className="text-sm font-semibold tracking-tight">{isIt ? 'Work History' : 'Work Summary'}</h3>
          </div>
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <span className="text-2xl font-bold text-foreground">{formatNumber(workSummaryScore.score)}%</span>
              <Badge className={`${getPerformanceColorClasses(workSummaryScore.score)} font-semibold`}>
                {workSummaryScore.grade}
              </Badge>
            </div>
            <Progress value={workSummaryScore.score} className="h-2" />
            {/* KPI Breakdown */}
            <div className="space-y-2 text-xs">
              <div className="font-medium text-foreground/80">Weight: 50% | Details:</div>
              {isIt ? (
                /* IT Work History Breakdown */
                (() => {
                  const itBreakdown = workSummaryScore.breakdown as any;
                  return (
                    <div className="flex flex-col gap-2">
                      <div className="flex justify-between items-center p-2 bg-primary/10 rounded">
                        <span className="font-medium text-primary">Ticket Volume (50%)</span>
                        <span className="text-right">
                          <span className="font-bold text-primary">{formatNumber(itBreakdown.ticketVolumeScore)}%</span>
                          <span className="text-primary text-xs ml-2">{itBreakdown.totalTickets} / {itBreakdown.benchmark}</span>
                        </span>
                      </div>
                      <div className="flex justify-between items-center p-2 bg-emerald-500/10 rounded-md">
                        <span className="font-medium text-emerald-700 dark:text-emerald-300">Completion Rate (50%)</span>
                        <span className="text-right">
                          <span className="font-bold text-emerald-700 dark:text-emerald-300">{formatNumber(itBreakdown.completionScore)}%</span>
                          <span className="text-emerald-600 dark:text-emerald-400 text-xs ml-2">{itBreakdown.completedTickets} / {itBreakdown.totalTickets}</span>
                        </span>
                      </div>
                      <div className="grid grid-cols-3 gap-2 mt-2">
                        <div className="p-2 bg-emerald-500/10 rounded-md text-center">
                          <div className="text-emerald-700 dark:text-emerald-300 font-bold">{itBreakdown.completedTickets}</div>
                          <div className="text-emerald-600 dark:text-emerald-400 text-xs">Completed</div>
                        </div>
                        <div className="p-2 bg-amber-500/10 rounded-md text-center">
                          <div className="text-amber-700 dark:text-amber-300 font-bold">{itBreakdown.inProgressTickets}</div>
                          <div className="text-amber-600 dark:text-amber-400 text-xs">In Progress</div>
                        </div>
                        <div className="p-2 bg-red-500/10 rounded-md text-center">
                          <div className="text-red-700 dark:text-red-300 font-bold">{itBreakdown.pendingTickets}</div>
                          <div className="text-red-600 dark:text-red-400 text-xs">Pending</div>
                        </div>
                      </div>
                      <div className="text-xs text-muted-foreground mt-2">
                        <div>{itBreakdown.totalTickets} total tickets, {itBreakdown.recentActivity} in last 30 days</div>
                      </div>
                      {/* Calculation breakdown */}
                      <div className="mt-2 p-2 rounded bg-muted/50 border text-xs text-foreground/80">
                        <span className="font-semibold">Calculation: </span>
                        <span className="text-primary font-semibold">{formatNumber(itBreakdown.ticketVolumeScore * 0.5)}</span>
                        <span className="text-muted-foreground"> (Volume 50%) + </span>
                        <span className="text-emerald-700 dark:text-emerald-300 font-semibold">{formatNumber(itBreakdown.completionScore * 0.5)}</span>
                        <span className="text-muted-foreground"> (Completion 50%) = </span>
                        <span className="font-bold text-foreground">{formatNumber(workSummaryScore.score)}%</span>
                      </div>
                    </div>
                  );
                })()
              ) : (
                /* Regular Work Summary Breakdown */
                (() => {
                  const regularBreakdown = workSummaryScore.breakdown as any;
                  return (
                    <div className="flex flex-col gap-2">
                      <div className="flex justify-between items-center p-2 bg-primary/10 rounded">
                        <span className="font-medium text-primary">Logged Hours (50%)</span>
                        <span className="text-right">
                          <span className="font-bold text-primary">{formatNumber(regularBreakdown.loggedHoursPercent)}%</span>
                          <span className="text-primary text-xs ml-2">{regularBreakdown.totalHours}h / {regularBreakdown.expectedHours}h</span>
                        </span>
                      </div>
                      <div className="flex justify-between items-center p-2 bg-emerald-500/10 rounded-md">
                        <span className="font-medium text-emerald-700 dark:text-emerald-300">Projects (25%)</span>
                        <span className="text-right">
                          <span className="font-bold text-emerald-700 dark:text-emerald-300">{formatNumber(regularBreakdown.projectsPercent)}%</span>
                          <span className="text-emerald-600 dark:text-emerald-400 text-xs ml-2">{regularBreakdown.userProjects} / {regularBreakdown.projectBenchmark}</span>
                        </span>
                      </div>
                      <div className="flex justify-between items-center p-2 bg-primary/10 rounded-md">
                        <span className="font-medium text-primary">Tasks (25%)</span>
                        <span className="text-right">
                          <span className="font-bold text-primary">{formatNumber(regularBreakdown.tasksPercent)}%</span>
                          <span className="text-primary text-xs ml-2">{regularBreakdown.userTasks} / 150</span>
                        </span>
                      </div>
                      <div className="text-xs text-muted-foreground mt-2">
                        <div>{regularBreakdown.totalEntries} entries across {regularBreakdown.uniqueProjects} projects, {regularBreakdown.totalTasks} tasks</div>
                      </div>
                      {/* Calculation breakdown */}
                      <div className="mt-2 p-2 rounded bg-muted/50 border text-xs text-foreground/80">
                        <span className="font-semibold">Calculation: </span>
                        <span className="text-primary font-semibold">{formatNumber(regularBreakdown.loggedHoursPercent * 0.5)}</span>
                        <span className="text-muted-foreground"> (Logged Hours 50%) + </span>
                        <span className="text-emerald-700 dark:text-emerald-300 font-semibold">{formatNumber(regularBreakdown.projectsPercent * 0.25)}</span>
                        <span className="text-muted-foreground"> (Projects 25%) + </span>
                        <span className="text-primary font-semibold">{formatNumber(regularBreakdown.tasksPercent * 0.25)}</span>
                        <span className="text-muted-foreground"> (Tasks 25%) = </span>
                        <span className="font-bold text-foreground">{formatNumber(workSummaryScore.score)}%</span>
                      </div>
                    </div>
                  );
                })()
              )}
            </div>
          </div>
        </motion.section>
      </motion.div>

      {/* Strengths and Improvements */}
      <motion.div variants={staggerItem} className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Strengths */}
        <motion.section variants={staggerItem} className={panelClass}>
          <div className="flex items-center gap-2 mb-3">
            <Star className="h-4 w-4 text-amber-600 dark:text-amber-400" />
            <h3 className="text-sm font-semibold tracking-tight">Key Strengths</h3>
          </div>
          {strengths.length > 0 ? (
            <div className="space-y-3">
              {strengths.map((strength, index) => (
                <div key={index} className="flex items-center justify-between p-3 bg-emerald-500/10 rounded-lg border border-emerald-500/20">
                  <div className="flex items-center space-x-2">
                    <CheckCircle className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
                    <span className="font-medium text-emerald-700 dark:text-emerald-300">{strength.name}</span>
                  </div>
                  <Badge className="bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 border-emerald-500/20">
                    {strength.score}%
                  </Badge>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-muted-foreground text-sm">No standout strengths identified. Focus on improving all areas.</p>
          )}
        </motion.section>

        {/* Areas for Improvement */}
        <motion.section variants={staggerItem} className={panelClass}>
          <div className="flex items-center gap-2 mb-3">
            <AlertCircle className="h-4 w-4 text-red-600 dark:text-red-400" />
            <h3 className="text-sm font-semibold tracking-tight">Areas for Improvement</h3>
          </div>
          {improvements.length > 0 ? (
            <div className="space-y-3">
              {improvements.map((improvement, index) => (
                <div key={index} className="flex items-center justify-between p-3 bg-red-500/10 rounded-lg border border-red-500/20">
                  <div className="flex items-center space-x-2">
                    <AlertCircle className="h-4 w-4 text-red-600 dark:text-red-400" />
                    <span className="font-medium text-red-700 dark:text-red-300">{improvement.name}</span>
                  </div>
                  <Badge className="bg-red-500/15 text-red-700 dark:text-red-300 border-red-500/20">
                    {improvement.score}%
                  </Badge>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-muted-foreground text-sm">All areas performing well. Continue maintaining high standards.</p>
          )}
        </motion.section>
      </motion.div>

      {/* Detailed Breakdown */}
      <motion.section variants={staggerItem} className={panelClass}>
        <div className="flex items-center gap-2 mb-3">
          <FileText className="h-4 w-4 text-muted-foreground" />
          <h3 className="text-sm font-semibold tracking-tight">Score Calculation Breakdown</h3>
        </div>

        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 text-sm">
            <div className="bg-primary/10 p-4 rounded-lg">
              <div className="font-medium text-primary">Departmental KPIs</div>
              <div className="text-primary">{formatNumber(departmentalScore.score)}% × 30% = {formatNumber((departmentalScore.score * 30) / 100)} points</div>
            </div>
            <div className="bg-emerald-500/10 p-4 rounded-lg border border-border">
              <div className="font-medium text-emerald-700 dark:text-emerald-300">Personnel KPIs</div>
              <div className="text-emerald-700 dark:text-emerald-300">{formatNumber(personnelScore.score)}% × 10% = {formatNumber((personnelScore.score * 10) / 100)} points</div>
            </div>
            <div className="bg-primary/10 p-4 rounded-lg border border-border">
              <div className="font-medium text-primary">Attendance</div>
              <div className="text-primary">{formatNumber(attendanceScore.score)}% × 10% = {formatNumber((attendanceScore.score * 10) / 100)} points</div>
            </div>
            <div className="bg-orange-500/10 p-4 rounded-lg border border-border">
              <div className="font-medium text-orange-700 dark:text-orange-300">{isIt ? 'Work History' : 'Work Summary'}</div>
              <div className="text-orange-700 dark:text-orange-300">{formatNumber(workSummaryScore.score)}% × 50% = {formatNumber((workSummaryScore.score * 50) / 100)} points</div>
              <div className="text-xs text-orange-600 dark:text-orange-400 mt-2">
                {isIt ? (
                  <>
                    <div>{(workSummaryScore.breakdown as any)?.totalTickets || 0} tickets, {(workSummaryScore.breakdown as any)?.completionRate || 0}% completion rate</div>
                    <div>{(workSummaryScore.breakdown as any)?.completedTickets || 0} completed, {(workSummaryScore.breakdown as any)?.inProgressTickets || 0} in progress</div>
                  </>
                ) : (
                  <>
                    <div>{(workSummaryScore.breakdown as any)?.totalHours || 0}h logged / {(workSummaryScore.breakdown as any)?.expectedHours || 0}h expected</div>
                    <div>{(workSummaryScore.breakdown as any)?.totalEntries || 0} entries, {(workSummaryScore.breakdown as any)?.uniqueProjects || 0} projects, {(workSummaryScore.breakdown as any)?.totalTasks || 0} tasks</div>
                  </>
                )}
              </div>
            </div>
          </div>

          <div className="border-t border-border pt-4">
            <div className="flex justify-between items-center text-lg font-semibold">
              <span>Total Score:</span>
              <span className="text-2xl">{formatNumber(overallScore.score)}% ({overallScore.grade})</span>
            </div>
          </div>
        </div>
      </motion.section>

      {/* Recommendations */}
      <motion.section variants={staggerItem} className={panelClass}>
        <div className="flex items-center gap-2 mb-3">
          <Target className="h-4 w-4 text-muted-foreground" />
          <h3 className="text-sm font-semibold tracking-tight">Recommendations</h3>
        </div>

        <div className="space-y-3 text-sm">
          {overallScore.score >= 90 && (
            <div className="p-3 bg-emerald-500/10 border border-emerald-500/20 rounded-lg">
              <p className="text-emerald-700 dark:text-emerald-300">
                <strong>Excellent Performance!</strong> Continue maintaining these high standards and consider mentoring others.
              </p>
            </div>
          )}

          {overallScore.score >= 80 && overallScore.score < 90 && (
            <div className="p-3 bg-primary/10 border border-primary/20 rounded-lg">
              <p className="text-primary">
                <strong>Good Performance!</strong> Focus on consistency and look for opportunities to excel in weaker areas.
              </p>
            </div>
          )}

          {overallScore.score >= 70 && overallScore.score < 80 && (
            <div className="p-3 bg-amber-500/10 border border-amber-500/20 rounded-lg">
              <p className="text-amber-700 dark:text-amber-300">
                <strong>Satisfactory Performance.</strong> Identify specific areas for improvement and create action plans.
              </p>
            </div>
          )}

          {overallScore.score < 70 && (
            <div className="p-3 bg-red-500/10 border border-red-500/20 rounded-lg">
              <p className="text-red-700 dark:text-red-300">
                <strong>Performance Needs Improvement.</strong> Schedule regular check-ins with your manager and focus on priority areas.
              </p>
            </div>
          )}

          {improvements.length > 0 && (
            <div className="p-3 bg-muted/50 border border-border rounded-lg">
              <p className="text-foreground">
                <strong>Priority Focus Areas:</strong> {improvements.map(i => i.name).join(', ')}
              </p>
            </div>
          )}
        </div>
      </motion.section>
    </motion.div>
  );
}