// components/evaluation/evaluation-columns.tsx - 집계 모드 지원 업데이트

"use client";
import * as React from "react";
import { type ColumnDef } from "@tanstack/react-table";
import { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Pencil, Eye, MessageSquare, Check, X, Clock, FileText, Circle, Ellipsis, BarChart3, ChevronDown } from "lucide-react";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header";
import { PeriodicEvaluationView, PeriodicEvaluationAggregatedView } from "@/db/schema";
import { DataTableRowAction } from "@/types/table";
import { vendortypeMap } from "@/types/evaluation";

interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<PeriodicEvaluationView | PeriodicEvaluationAggregatedView> | null>>;
  viewMode?: "detailed" | "aggregated";
}

// 집계 모드용 division 배지
const getDivisionBadgeWithAggregation = (
  division: string, 
  evaluationCount?: number, 
  divisions?: string
) => {
  if (division === "BOTH") {
    return (
      <div className="flex items-center gap-1">
        <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200">
          통합
        </Badge>
        {evaluationCount && evaluationCount > 1 && (
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger>
                <Badge variant="secondary" className="text-xs">
                  {evaluationCount}개
                </Badge>
              </TooltipTrigger>
              <TooltipContent>
                <p>{divisions?.replace(',', ', ')} 평가 통합</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
        )}
      </div>
    );
  }
  
  return (
    <Badge variant={division === "PLANT" ? "default" : "secondary"}>
      {division === "PLANT" ? "해양" : "조선"}
    </Badge>
  );
};

// 기존 함수들은 그대로 유지...
const getStatusBadgeVariant = (status: string) => {
  switch (status) {
    case "PENDING_SUBMISSION": return "outline";
    case "SUBMITTED": return "secondary";
    case "IN_REVIEW": return "default";
    case "REVIEW_COMPLETED": return "default";
    case "FINALIZED": return "default";
    default: return "outline";
  }
};

const getStatusLabel = (status: string) => {
  const statusMap = {
    PENDING: "대상확정",
    PENDING_SUBMISSION: "자료접수중",
    SUBMITTED: "제출완료",
    IN_REVIEW: "평가중",
    REVIEW_COMPLETED: "평가완료",
    FINALIZED: "결과확정"
  };
  return statusMap[status] || status;
};

// 부서별 상태 배지 함수
const getDepartmentStatusBadge = (status: string | null) => {
  if (!status) return (
    <div className="flex items-center gap-1">
      <span className="text-xs text-gray-500">-</span>
    </div>
  );
  
  switch (status) {
    case "NOT_ASSIGNED":
      return (
        <div className="flex items-center gap-1">
          <span className="text-xs text-gray-600">미지정</span>
        </div>
      );
    case "NOT_STARTED":
      return (
        <div className="flex items-center gap-1">
          <div className="w-4 h-4 rounded-full bg-red-500 shadow-sm" />
        </div>
      );
    case "IN_PROGRESS":
      return (
        <div className="flex items-center gap-1">
          <div className="w-4 h-4 rounded-full bg-yellow-500 shadow-sm" />
        </div>
      );
    case "COMPLETED":
      return (
        <div className="flex items-center gap-1">
          <div className="w-4 h-4 rounded-full bg-green-500 shadow-sm" />
        </div>
      );
    default:
      return (
        <div className="flex items-center gap-1">
          <span className="text-xs text-gray-500">-</span>
        </div>
      );
  }
};

// 등급별 색상
const getGradeBadgeVariant = (grade: string | null) => {
  if (!grade) return "outline";
  switch (grade) {
    case "S": return "default";
    case "A": return "secondary";
    case "B": return "outline";
    case "C": return "destructive";
    case "D": return "destructive";
    default: return "outline";
  }
};

// 자재구분 배지  
const getMaterialTypeBadge = (materialType: string) => {
  return <Badge variant="outline">{vendortypeMap[materialType] || materialType}</Badge>;
};

// 내외자 배지
const getDomesticForeignBadge = (domesticForeign: string) => {
  return (
    <Badge variant={domesticForeign === "DOMESTIC" ? "default" : "secondary"}>
      {domesticForeign === "DOMESTIC" ? "D" : "F"}
    </Badge>
  );
};

export function getPeriodicEvaluationsColumns({
  setRowAction, 
  viewMode = "detailed"
}: GetColumnsProps): ColumnDef<PeriodicEvaluationView | PeriodicEvaluationAggregatedView>[] {
  
  const baseColumns: ColumnDef<PeriodicEvaluationView | PeriodicEvaluationAggregatedView>[] = [
    // ═══════════════════════════════════════════════════════════════
    // 선택 및 기본 정보
    // ═══════════════════════════════════════════════════════════════

    // Checkbox 
    {
      id: "select",
      header: ({ table }) => (
        <Checkbox
          checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && "indeterminate")}
          onCheckedChange={(v) => table.toggleAllPageRowsSelected(!!v)}
          aria-label="select all"
          className="translate-y-0.5"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(v) => row.toggleSelected(!!v)}
          aria-label="select row"
          className="translate-y-0.5"
        />
      ),
      size: 40,
      enableSorting: false,
      enableHiding: false,
    },

    // ░░░ 평가년도 ░░░
    {
      accessorKey: "evaluationYear",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가년도" />,
      cell: ({ row }) => <span className="font-medium">{row.original.evaluationYear}</span>,
      size: 100,
      meta: {
        excelHeader: "평가년도",
      },
    },

    // ░░░ 구분 ░░░ - 집계 모드에 따라 다르게 렌더링
    {
      accessorKey: "division",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="구분" />,
      cell: ({ row }) => {
        const division =viewMode === "aggregated"?"BOTH": row.original.division || "";
        
        if (viewMode === "aggregated") {
          const aggregatedRow = row.original as PeriodicEvaluationAggregatedView;
          return getDivisionBadgeWithAggregation(
            division, 
            aggregatedRow.evaluationCount, 
            aggregatedRow.divisions
          );
        }
        
        return (
          <Badge variant={division === "PLANT" ? "default" : "secondary"}>
            {division === "PLANT" ? "해양" : "조선"}
          </Badge>
        );
      },
      size: viewMode === "aggregated" ? 120 : 80,
      meta: {
        excelHeader: "구분",
      },
    },

    {
      accessorKey: "status",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="Status" />,
      cell: ({ row }) => getStatusLabel(row.original.status || ""),
      size: 80,
      meta: {
        excelHeader: "Status",
      },
    },

    // ═══════════════════════════════════════════════════════════════
    // 협력업체 정보
    // ═══════════════════════════════════════════════════════════════
    {
      header: "협력업체 정보",
      columns: [
        {
          accessorKey: "vendorCode",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="벤더 코드" />,
          cell: ({ row }) => (
            <span className="font-mono text-sm">{row.original.vendorCode}</span>
          ),
          size: 120,
          meta: {
            excelHeader: "벤더 코드",
          },
        },

        {
          accessorKey: "vendorName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="벤더명" />,
          cell: ({ row }) => (
            <div className="truncate max-w-[200px]" title={row.original.vendorName}>
              {row.original.vendorName}
            </div>
          ),
          size: 200,
          meta: {
            excelHeader: "벤더명",
          },
        },

        {
          accessorKey: "domesticForeign",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="내외자" />,
          cell: ({ row }) => getDomesticForeignBadge(row.original.domesticForeign || ""),
          size: 80,
          meta: {
            excelHeader: "내외자",
          },
        },

        {
          accessorKey: "materialType",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="자재구분" />,
          cell: ({ row }) => getMaterialTypeBadge(row.original.materialType || ""),
          size: 120,
          meta: {
            excelHeader: "자재구분",
          },
        },
      ]
    },

    // 집계 모드에서만 보이는 평가 개수 컬럼
    ...(viewMode === "aggregated" ? [{
      accessorKey: "evaluationCount",
      header: ({ column }) => (
        <div className="flex items-center gap-1">
          <BarChart3 className="h-4 w-4" />
          <DataTableColumnHeaderSimple column={column} title="평가수" />
        </div>
      ),
      cell: ({ row }) => {
        const aggregatedRow = row.original as PeriodicEvaluationAggregatedView;
        const count = aggregatedRow.evaluationCount || 1;
        
        return (
          <div className="flex items-center gap-1">
            <Badge variant={count > 1 ? "default" : "outline"} className="font-mono">
              {count}개
            </Badge>
            {count > 1 && aggregatedRow.divisions && (
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger>
                    <div className="text-xs text-muted-foreground cursor-help">
                      ({aggregatedRow.divisions.replace(',', ', ')})
                    </div>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>{aggregatedRow.divisions.replace(',', ', ')} 평가의 평균값</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            )}
          </div>
        );
      },
      size: 100,
      meta: {
        excelHeader: "평가수",
      },
    }] : []),
        
    {
      accessorKey: "finalScore",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="확정점수" />,
      cell: ({ row }) => {
        const finalScore = row.getValue<number>("finalScore");
        const isAggregated = viewMode === "aggregated" && (row.original as PeriodicEvaluationAggregatedView).evaluationCount > 1;
        
        return finalScore ? (
          <div className="flex items-center gap-1">
            <span className={`font-bold ${isAggregated ? 'text-purple-600' : 'text-green-600'}`}>
              {Number(finalScore).toFixed(1)}
            </span>
            {isAggregated && (
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger>
                    <Badge variant="outline" className="text-xs bg-purple-50">평균</Badge>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>여러 평가의 평균값</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            )}
          </div>
        ) : (
          <span className="text-muted-foreground">-</span>
        );
      },
      size: viewMode === "aggregated" ? 120 : 90,
      meta: {
        excelHeader: "확정점수",
      },
    },

    {
      accessorKey: "finalGrade",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="확정등급" />,
      cell: ({ row }) => {
        const finalGrade = row.getValue<string>("finalGrade");
        const isAggregated = viewMode === "aggregated" && (row.original as PeriodicEvaluationAggregatedView).evaluationCount > 1;
        
        return finalGrade ? (
          <Badge 
            variant={getGradeBadgeVariant(finalGrade)} 
            className={isAggregated ? "bg-purple-600" : "bg-green-600"}
          >
            {finalGrade}
          </Badge>
        ) : (
          <span className="text-muted-foreground">-</span>
        );
      },
      size: 90,
      meta: {
        excelHeader: "확정등급",
      },
    },

    // ═══════════════════════════════════════════════════════════════
    // 진행 현황 - 집계 모드에서는 최고 진행 상태를 보여줌
    // ═══════════════════════════════════════════════════════════════
    {
      header: "부서별 평가 현황",
      columns: [
        {
          accessorKey: "orderEvalStatus",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="발주" />,
          cell: ({ row }) => getDepartmentStatusBadge(row.getValue("orderEvalStatus")),
          size: 60,
          meta: {
            excelHeader: "발주",
          },
        },
        
        {
          accessorKey: "procurementEvalStatus", 
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="조달" />,
          cell: ({ row }) => getDepartmentStatusBadge(row.getValue("procurementEvalStatus")),
          size: 70,
          meta: {
            excelHeader: "조달",
          },
        },
        
        {
          accessorKey: "qualityEvalStatus",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="품질" />,
          cell: ({ row }) => getDepartmentStatusBadge(row.getValue("qualityEvalStatus")),
          size: 70,
          meta: {
            excelHeader: "품질",
          },
        },
        
        {
          accessorKey: "designEvalStatus",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="설계" />,
          cell: ({ row }) => getDepartmentStatusBadge(row.getValue("designEvalStatus")),
          size: 70,
          meta: {
            excelHeader: "설계",
          },
        },
        
        {
          accessorKey: "csEvalStatus",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="CS" />,
          cell: ({ row }) => getDepartmentStatusBadge(row.getValue("csEvalStatus")),
          size: 70,
          meta: {
            excelHeader: "CS",
          },
        },

        {
          accessorKey: "adminEvalStatus",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="관리자" />,
          cell: ({ row }) => getDepartmentStatusBadge(row.getValue("adminEvalStatus")),
          size: 120,
          meta: {
            excelHeader: "관리자",
          },
        },
      ]
    },

    {
      header: "평가상세",
      enableHiding: true,
      size: 80,
      minSize: 80,
      cell: ({ row }) => {
        return (
          <div className="flex items-center gap-1">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  className="size-8"
                  aria-label="평가 상세 메뉴"
                >
                  <Ellipsis className="size-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem
                  onClick={() => setRowAction({ row, type: "view" })}
                  className="flex items-center gap-2"
                >
                  <Eye className="h-4 w-4" />
                  평가 상세
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setRowAction({ row, type: "vendor-submission" as any })}
                  className="flex items-center gap-2"
                >
                  <FileText className="h-4 w-4" />
                  협력업체 제출 상세
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        );
      },
    },

    // ═══════════════════════════════════════════════════════════════
    // 제출 현황
    // ═══════════════════════════════════════════════════════════════
    {
      header: "협력업체 제출 현황",
      columns: [
        {
          accessorKey: "documentsSubmitted",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="문서제출" />,
          cell: ({ row }) => {
            const submitted = row.getValue<boolean>("documentsSubmitted");
            const isAggregated = viewMode === "aggregated" && (row.original as PeriodicEvaluationAggregatedView).evaluationCount > 1;
            
            return (
              <div className="flex items-center gap-1">
                <Badge variant={submitted ? "default" : "destructive"}>
                  {submitted ? "제출완료" : "미제출"}
                </Badge>
                {isAggregated && (
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger>
                        <Badge variant="outline" className="text-xs">통합</Badge>
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>모든 평가에서 제출 완료된 경우만 "제출완료"</p>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                )}
              </div>
            );
          },
          size: viewMode === "aggregated" ? 140 : 120,
          meta: {
            excelHeader: "문서제출",
          },
        },

        {
          accessorKey: "submissionDate",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="제출일" />,
          cell: ({ row }) => {
            const submissionDate = row.getValue<Date>("submissionDate");
            const isAggregated = viewMode === "aggregated" && (row.original as PeriodicEvaluationAggregatedView).evaluationCount > 1;
            
            return submissionDate ? (
              <div className="flex items-center gap-1">
                <span className="text-sm">
                  {new Intl.DateTimeFormat("ko-KR", {
                    month: "2-digit",
                    day: "2-digit",
                  }).format(new Date(submissionDate))}
                </span>
                {isAggregated && (
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger>
                        <Badge variant="outline" className="text-xs">최신</Badge>
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>가장 최근 제출일</p>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                )}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: viewMode === "aggregated" ? 110 : 80,
          meta: {
            excelHeader: "제출일",
          },
        },

        {
          accessorKey: "submissionDeadline",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="마감일" />,
          cell: ({ row }) => {
            const deadline = row.getValue<Date>("submissionDeadline");
            if (!deadline) return <span className="text-muted-foreground">-</span>;
            
            const now = new Date();
            const isOverdue = now > deadline;
            
            return (
              <span className={`text-sm ${isOverdue ? "text-red-600" : ""}`}>
                {new Intl.DateTimeFormat("ko-KR", {
                  month: "2-digit",
                  day: "2-digit",
                }).format(new Date(deadline))}
              </span>
            );
          },
          size: 80,
          meta: {
            excelHeader: "마감일",
          },
        },
      ]
    },

    // ═══════════════════════════════════════════════════════════════
    // 평가 점수 - 집계 모드에서는 평균임을 명시
    // ═══════════════════════════════════════════════════════════════
    {
      header: viewMode === "aggregated" ? "평가 점수 (평균)" : "평가 점수",
      columns: [
        {
          accessorKey: "processScore",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="공정" />,
          cell: ({ row }) => {
            const score = row.getValue("processScore");
            const isAggregated = viewMode === "aggregated" && (row.original as PeriodicEvaluationAggregatedView).evaluationCount > 1;
            
            return score ? (
              <span className={`font-medium ${isAggregated ? 'text-purple-600' : ''}`}>
                {Number(score).toFixed(1)}
              </span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 80,
          meta: {
            excelHeader: "공정",
          },
        },

        {
          accessorKey: "priceScore",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="가격" />,
          cell: ({ row }) => {
            const score = row.getValue("priceScore");
            const isAggregated = viewMode === "aggregated" && (row.original as PeriodicEvaluationAggregatedView).evaluationCount > 1;
            
            return score ? (
              <span className={`font-medium ${isAggregated ? 'text-purple-600' : ''}`}>
                {Number(score).toFixed(1)}
              </span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 80,
          meta: {
            excelHeader: "가격",
          },
        },
        
        {
          accessorKey: "deliveryScore",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="납기" />,
          cell: ({ row }) => {
            const score = row.getValue("deliveryScore");
            const isAggregated = viewMode === "aggregated" && (row.original as PeriodicEvaluationAggregatedView).evaluationCount > 1;
            
            return score ? (
              <span className={`font-medium ${isAggregated ? 'text-purple-600' : ''}`}>
                {Number(score).toFixed(1)}
              </span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 80,
          meta: {
            excelHeader: "납기",
          },
        },       
        
        {
          accessorKey: "selfEvaluationScore",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="자율평가" />,
          cell: ({ row }) => {
            const score = row.getValue("selfEvaluationScore");
            const isAggregated = viewMode === "aggregated" && (row.original as PeriodicEvaluationAggregatedView).evaluationCount > 1;
            
            return score ? (
              <span className={`font-medium ${isAggregated ? 'text-purple-600' : ''}`}>
                {Number(score).toFixed(1)}
              </span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 80,
          meta: {
            excelHeader: "자율평가",
          },
        },

        // ✅ 합계 - 4개 점수의 합으로 계산
        {
          id: "totalScore",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="합계" />,
          cell: ({ row }) => {
            const processScore = Number(row.getValue("processScore") || 0);
            const priceScore = Number(row.getValue("priceScore") || 0);
            const deliveryScore = Number(row.getValue("deliveryScore") || 0);
            const selfEvaluationScore = Number(row.getValue("selfEvaluationScore") || 0);
            
            const total = processScore + priceScore + deliveryScore + selfEvaluationScore;
            const isAggregated = viewMode === "aggregated" && (row.original as PeriodicEvaluationAggregatedView).evaluationCount > 1;
            
            return total > 0 ? (
              <span className={`font-medium px-2 py-1 rounded ${
                isAggregated ? 'bg-purple-50 text-purple-600' : 'bg-blue-50 text-blue-600'
              }`}>
                {total.toFixed(1)}
              </span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 80,
          meta: {
            excelHeader: "합계",
          },
        },

        {
          accessorKey: "participationBonus",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="참여도(가점)" />,
          cell: ({ row }) => {
            const score = row.getValue("participationBonus");
            const isAggregated = viewMode === "aggregated" && (row.original as PeriodicEvaluationAggregatedView).evaluationCount > 1;
            
            return score ? (
              <span className={`font-medium ${isAggregated ? 'text-purple-600' : 'text-green-600'}`}>
                +{Number(score).toFixed(1)}
              </span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 100,
          meta: {
            excelHeader: "참여도(가점)",
          },
        },

        {
          accessorKey: "qualityDeduction",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="품질(감점)" />,
          cell: ({ row }) => {
            const score = row.getValue("qualityDeduction");
            const isAggregated = viewMode === "aggregated" && (row.original as PeriodicEvaluationAggregatedView).evaluationCount > 1;
            
            return score ? (
              <span className={`font-medium ${isAggregated ? 'text-purple-600' : 'text-red-600'}`}>
                -{Number(score).toFixed(1)}
              </span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 100,
          meta: {
            excelHeader: "품질(감점)",
          },
        },

        // ✅ 평가점수 컬럼
        {
          id: "evaluationScore",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가점수" />,
          cell: ({ row }) => {
            const processScore = Number(row.getValue("processScore") || 0);
            const priceScore = Number(row.getValue("priceScore") || 0);
            const deliveryScore = Number(row.getValue("deliveryScore") || 0);
            const selfEvaluationScore = Number(row.getValue("selfEvaluationScore") || 0);
            const participationBonus = Number(row.getValue("participationBonus") || 0);
            const qualityDeduction = Number(row.getValue("qualityDeduction") || 0);
            
            const totalScore = processScore + priceScore + deliveryScore + selfEvaluationScore;
            const evaluationScore = totalScore + participationBonus - qualityDeduction;
            const isAggregated = viewMode === "aggregated" && (row.original as PeriodicEvaluationAggregatedView).evaluationCount > 1;
            
            return totalScore > 0 ? (
              <span className={`font-bold px-2 py-1 rounded ${
                isAggregated ? 'bg-purple-50 text-purple-600' : 'bg-blue-50 text-blue-600'
              }`}>
                {evaluationScore.toFixed(1)}
              </span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 90,
          meta: {
            excelHeader: "평가점수",
          },
        },

        {
          accessorKey: "evaluationGrade",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가등급" />,
          cell: ({ row }) => {
            const grade = row.getValue<string>("evaluationGrade");
            const isAggregated = viewMode === "aggregated" && (row.original as PeriodicEvaluationAggregatedView).evaluationCount > 1;
            
            return grade ? (
              <Badge 
                variant={getGradeBadgeVariant(grade)}
                className={isAggregated ? "bg-purple-600" : ""}
              >
                {grade}
              </Badge>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          minSize: 100,
          meta: {
            excelHeader: "평가등급",
          },
        },
      ]
    },
  ];

  return baseColumns;
}